Study guide · System design

Study guide: robustness, fault tolerance, and high availability

Define reliability targets, contain failures, preserve correctness across retries and failover, and prove recovery works.

Contents
  1. ·Learning objectives
  2. §1Core concepts
  3. §2Set reliability targets and failure boundaries
  4. §3Preserve correctness at request boundaries
  5. §4Contain slow dependencies and overload
  6. §5Retry safely after uncertain outcomes
  7. §6Use redundancy and failover without losing data
  8. §7Restore, verify, and improve the recovery path
  9. ·Common mistakes
  10. ·Practice questions
  11. ·Review checklist

· · Start here

Learning objectives

  1. Distinguish robustness, fault tolerance, and high availability by the failure each addresses and the guarantee it preserves.
  2. Define availability, recovery time, and recovery point targets for a particular operation and failure scenario.
  3. Protect correctness when inputs are invalid, requests race, or an operation's outcome is unknown.
  4. Combine timeouts, bounded concurrency, circuit breaking, and load shedding to contain a slow dependency.
  5. Design retries so transient failures can recover without duplicating effects or overwhelming a service.
  6. Explain the detection, promotion, fencing, and routing steps of failover, including the data-loss trade-off in replication.
  7. Verify recovery and data safety with independent checks, fault injection, and backup restoration.

§1 · Definitions

Core concepts

This section defines a fault, a failure, robustness, fault tolerance, high availability, availability, and reliability. These terms separate the event that goes wrong from the behaviour the system promises when it does.

A malformed order should be rejected without corrupting stored orders: that is robustness. A server may crash while another takes over and preserves acknowledged orders: that is fault tolerance. If customers can still place orders within the stated response target through most of the measurement window, the service meets a high availability goal. These properties overlap, but a service can be available while returning incorrect answers, or preserve every write while taking hours to recover.

A fault is a cause or adverse condition; a failure is a user-visible breach of a stated requirement. A disk can fail without an observable service failure if another durable copy serves the same data and the replacement takes over in time. Conversely, a service can fail without a hardware fault when a valid request races another and breaks a rule that must always hold. The distinction directs investigation: identify the fault that occurred, the mechanism that was meant to contain it, and the particular promise that was broken. Counting component restarts alone does not measure whether users received the required result.

Reliability includes the correctness of completed work as well as the chance that work completes. For a checkout path, “available” should mean that an eligible order reaches a durable, unambiguous result within the promised time. Returning a quick success response for an order that later disappears is a failure under that definition. A browsing page may have a different promise: it can show an older recommendation while still displaying an authoritative price at the moment of purchase. Reliability requirements therefore belong to operations and data guarantees, rather than to a service name alone.

Fault tolerance always names the fault it tolerates. A service can tolerate one process crash while failing under a zone outage, a shared database error, a bad deployment or a long network partition. High availability is an observed service outcome across a defined window. A design may contain several independent copies yet miss an availability target because detecting a fault and switching to a replacement are slow. Equally, an operation may meet a measured availability target in a quiet month despite having no protection against a likely shared failure. Design and measurement answer related but different questions.

A common confusion is to assume that adding copies guarantees all three properties. A second server can take traffic after a crash, but it cannot correct invalid state, detect every failure, or guarantee that a write reached the replacement. Each guarantee needs its own mechanism and measurement.

§2 · Reliability targets

Set reliability targets and failure boundaries

An availability target must name the operation, success condition, response limit, measurement window, and excluded or included traffic. A target for browsing can differ from one for committing an order. RTO and RPO must also name the scenario: loss of one process, a database primary, an availability zone, or an entire region can require different recovery mechanisms. A target is a design input; a drill supplies the measured result.

Make the measured promise explicit

A request-based availability measure counts eligible attempts that finish correctly within a specified latency limit and divides by all eligible attempts in the window. A time-based measure counts the portion of the window in which a defined probe or service condition is available. The two measures can differ: a ten-minute interruption during a quiet period has a large time cost but may affect few requests, while a one-minute failure during a promotion can affect many requests. Neither convention is inherently correct for every operation. The choice should reflect what users need and be fixed before evaluating results.

An error budget converts a target into an allowance that can be compared with measured failures. It is not permission to lose data or break a safety rule. A response that completes inside the time limit but returns the wrong committed order state must count as a failure if correctness is part of the objective. Define which attempts are eligible, including treatment of client cancellation, malformed requests and dependency outages. If exclusions are vague, a dashboard can improve by removing difficult requests from its denominator rather than by improving the service.

Error-budget burn rate helps distinguish a brief but severe outage from normal variation. A service may appear to have many minutes left in a monthly time budget while a current failure is consuming those minutes rapidly. Short-window measurements prompt immediate response; longer windows show whether the service is repeatedly missing its target. For a request-based objective, the same idea applies to failed eligible attempts rather than elapsed minutes. Alerting should use the measure chosen for the objective and avoid hiding an incorrect response behind a successful transport status.

RTO and RPO answer different recovery questions. RTO measures how long the function may remain unavailable after a named disruption. RPO limits how far back the recovered state may be. A system can restore quickly from an older saved copy and meet a short RTO while missing its RPO. Another can preserve every acknowledged write by waiting for another copy to confirm it, yet take too long to promote a replacement. For an operation that cannot lose an acknowledged payment, a zero-loss requirement must be expressed as a data guarantee and tested at the acknowledgement boundary; a time-valued RPO alone can obscure what happens to individual writes.

Map the whole failure boundary

Redundancy helps only when the redundant components do not share the fault being planned for. Two API instances on one host tolerate one process crash but not host loss. Instances in two zones may still share a regional control plane, a database leader, a router, a cloud account or a software release. A dependency map should trace every component needed for the operation, including DNS, authentication, message delivery and write storage. The end-to-end path is unavailable if any required single component cannot be replaced or safely bypassed.

For each failure domain, ask three questions. Can the fault be detected without mistaking a temporary delay for permanent loss? Is there a replacement with enough capacity and the required state? Can traffic be moved to it without allowing the old owner to continue unsafe writes? These questions make a claim about switching to a replacement testable. A diagram of instances without their dependencies can look resilient while hiding a single database or router through which all successful requests must pass.

The target should also distinguish planned maintenance from unplanned faults. Draining an instance for an update can avoid user-visible interruption if the remaining fleet has capacity, but a database schema change or router update may still expose a shared dependency. Whether planned work consumes an availability budget is a policy choice that should be stated in the measurement rule. Excluding it from a dashboard does not remove its effect on users, so a separate view of all user-visible failures is useful even when the formal objective has exclusions.

The diagram shows why two instances in one failure domain do not protect against every outage.

System flow
                    ┌─ zone A: API 1 ─┐
Client → router ─────┤                 ├→ database in zone A
                    └─ zone A: API 2 ─┘
                         zone A fails → both APIs and database lost

Read across the shared zone label: adding API instances protects against one process failing, but a zone loss still removes the whole path. Spreading the required components across independent failure domains changes which faults can be tolerated; a shared router or database can remain a single point of failure.

Worked examplean availability budget

Consider a 30-day measurement window and assume an operation has a time-based availability target of 99.9%. The window contains 30 × 24 × 60 = 43,200 minutes. The unavailable fraction is 1 − 0.999 = 0.001, so the budget is 43,200 × 0.001 = 43.2 minutes. Check: 43,200 − 43.2 = 43,156.8 available minutes, and 43,156.8 ÷ 43,200 = 0.999.

If the target is 99.99%, the unavailable fraction is 1 − 0.9999 = 0.0001, giving 43,200 × 0.0001 = 4.32 minutes. This arithmetic does not by itself define how partial failures count; the SLO must say whether a slow or incorrect request consumes the budget.

Worked exampleavailability across unequal traffic periods

Consider a 24-hour period with 1,000,000 eligible requests. Assume a ten-minute outage occurs during a quiet interval and affects 2,000 of those requests; assume every other request succeeds within its latency limit. Request-based availability is (1,000,000 − 2,000) ÷ 1,000,000 = 0.998, or 99.8%. Time-based availability is (1,440 − 10) ÷ 1,440 = 1,430 ÷ 1,440 ≈ 0.99306, or about 99.31%. The check is that the unavailable fractions are 2,000 ÷ 1,000,000 = 0.002 and 10 ÷ 1,440 ≈ 0.00694, respectively. The different results follow from different measurement conventions, not a calculation error.

§3 · Correctness

Preserve correctness at request boundaries

Robustness starts before a machine fails. Validate incoming data at the boundary, enforce business invariants at the authoritative state change, and reject impossible transitions. Input validation alone is insufficient: two valid requests can race and both try to reserve the final item. An atomic conditional update or a group of changes committed together must make one succeed and the other receive a clear conflict. The database constraint remains useful even when application validation is present, because every write path must obey it.

Put the invariant at the state change

Boundary validation checks shape and meaning before work is attempted: required fields are present, quantities are within allowed ranges, and the caller may perform the action. It prevents invalid work from reaching deeper components, but it cannot prove that a value remains valid later. Between a stock read and a stock write, another request may reserve the last unit. The condition must therefore be checked at the same authoritative boundary that changes the stock. A database constraint or conditional update protects the invariant even if a new application path forgets a preliminary check.

Optimistic concurrency control can make conflicting updates explicit. A client reads a record with version 7, computes a change, and submits an update conditioned on the version still being 7. If another request has already written version 8, the conditional update changes nothing and the caller must re-read, resolve the conflict or report it. Retrying blindly with the stale calculation could overwrite the other writer's work. This mechanism is useful when conflicts are infrequent; under heavy contention, repeated conflicts can reduce throughput, so a single owner or queued update path may be more appropriate.

A transaction is needed when several changes must agree, such as creating an order and reserving its inventory. Its guarantee has a boundary: a local database transaction cannot atomically commit an unrelated payment provider's response or an email sent over the network. Holding the transaction open while waiting on a remote provider can also increase lock time and failure exposure. A workflow should identify which changes are in one storage transaction and which external effects need an explicit state machine, a way to make repeated requests safe, and later reconciliation. The user-facing response must match what has actually become durable.

A state machine makes uncertainty visible. An order can be pending, confirmed, rejected or awaiting reconciliation, with permitted transitions recorded explicitly. A timed-out payment should not automatically turn a pending order into a definite rejection because the provider may have charged it. Likewise, a second confirmation should not create a second shipment. The transition rule can be enforced with a conditional update on the current state, making concurrent callbacks and retries converge on one valid outcome. Record enough identifiers and timestamps to investigate an ambiguous transition without inferring success from the absence of an error.

The error contract matters to clients. A conflict caused by a stale version should tell the caller that its proposed change was not applied, allowing it to fetch current state and decide again. A validation rejection should identify the rejected field without exposing unrelated private data. If waiting for a write response ends after the write may have committed, preserve the operation identifier and communicate uncertainty. These outcomes should not all be collapsed into a generic error, because clients react differently: correcting input, resolving a conflict and checking an unknown outcome are different actions. Clear errors reduce unsafe retries.

Robustness also requires limits on valid-looking input. A request with a syntactically valid but enormous collection can exhaust memory or make a database query run longer than the caller can wait. Set bounds on payload size, collection length, nesting depth and work per request according to measured capacity and the product contract. Reject excess work before allocating large resources where possible. The same rule applies to internal messages: an upstream service can send a valid message at a rate the consumer cannot sustain. Validation, concurrency limits and admission control jointly protect correctness and availability at that boundary.

Worked exampletwo reservations for one item

Consider a product with exactly one unit available and two simultaneous valid requests, A and B, each asking for one unit. Assume the stock row begins at quantity 1. A separate read-then-write design lets both requests read 1, each calculate 1 − 1 = 0, and each write 0. It has acknowledged two reservations while the initial stock allowed only one; checking the final quantity alone misses the violation. With an atomic conditional update that decrements only when stock is positive, exactly one request changes the quantity from 1 to 0. The other observes that zero rows met the condition and receives a conflict. Check the conservation rule: one initial unit minus one successful reservation equals zero, and the count of successful reservations is one. The winner may vary with scheduling, but the invariant does not.

The diagram traces two valid requests racing for one remaining unit.

System flow
Request A ─┐
           ├→ atomic update: decrement only if stock > 0 → one success
Request B ─┘                                      └────────→ one conflict

The requests converge at one atomic decision. Checking stock in a separate read and then decrementing later would permit both requests to see the same unit; the protected transition makes the outcome depend on a single authoritative write.

An error response must also describe the state honestly. If a payment call times out after the remote side may have committed it, the result is unknown, not a confirmed failure. Recording that uncertainty and resolving it later is safer than declaring failure and starting an unrelated second charge. This leads to the rules for repeating a request below.

§4 · Failure containment

Contain slow dependencies and overload

A slow dependency holds caller resources even when it has not returned an error. A timeout bounds each wait, and a propagated deadline stops later services from doing work after the original request can no longer use the result. A bulkhead limits how many callers can be trapped at once. A circuit breaker then reduces traffic to a dependency already known to be unhealthy. Load shedding limits total admitted work before queues and latency grow without bound. These controls cover different quantities, so one does not replace the others.

Spend one end-to-end time budget

A timeout applies to one wait; a deadline covers the entire user operation. If three downstream calls each have a two-second timeout, the caller can wait close to six seconds even when its response target is only three seconds. Carry an absolute deadline or remaining budget through the call chain. Before starting a new attempt, check whether enough time remains for it to help the original request. A child call should receive no more time than its parent's remaining budget, including a reserve for response serialization and network travel. Cancellation should release local resources, although it cannot assume a remote operation was rolled back.

Timeout selection is a tradeoff. A very short timeout can convert normal slow responses into failures and retries. A very long timeout traps workers during a genuine fault. Use the dependency's latency distribution under representative load and the caller's own deadline to choose a bound. A connection-acquisition timeout should be separate from the remote-operation timeout so a full local pool is distinguishable from a slow server. Observe both timeouts and late responses. A timed-out write can still have completed remotely, which is why the caller must treat its outcome as uncertain.

Cap the blast radius of waiting

A bulkhead reserves a finite amount of concurrency for one class of calls. If recommendations can occupy at most 20 of 200 request workers, a recommendation outage cannot directly trap every worker. The remaining capacity is useful only if the application can return the core response without waiting for a permit or for the failed call. A shared queue in front of the bulkhead also needs a bound; otherwise requests can accumulate there and exhaust memory or miss their deadlines. The limit should be tested at peak traffic, because an overly small bulkhead can reject healthy calls unnecessarily.

A circuit breaker has a different purpose. It observes recent failures or excessive latency and temporarily avoids calls that are unlikely to succeed. After a pause, it admits a small number of probes to see whether the dependency has recovered. A breaker cannot protect a service if its threshold looks only at explicit errors while the dependency is returning slowly; slow-call rate and concurrency must be considered. It should also avoid opening because of a few failures in a tiny sample. A breaker is a short-term traffic control, not a replacement for a timeout, a bulkhead or an operational repair.

Backpressure acts before overload spreads. A full worker pool can reject new optional work, a bounded queue can stop accepting jobs, or a client can be told to retry later. Load shedding deliberately drops or rejects work that cannot meet the target; it should prioritize requests according to the service contract rather than arbitrary arrival order when some operations matter more. A fast explicit rejection can be more honest than accepting a request into a queue whose waiting time exceeds the deadline. Retry guidance should include limits and spacing so clients do not amplify the overload.

Worked examplea shared deadline across calls

Consider an API with a 600 ms end-to-end deadline. Assume it spends 80 ms validating and reading local state, then calls a required inventory service for 240 ms. The remaining budget is 600 − 80 − 240 = 280 ms. Assume the API reserves 40 ms to finalize and send its response, leaving 280 − 40 = 240 ms for any later work. An optional recommendation call with a standalone 500 ms timeout cannot be allowed to wait the full 500 ms. Its effective wait is at most 240 ms, and a shorter limit may preserve more margin. Check the total: 80 + 240 + 240 + 40 = 600 ms. If the optional call times out at its 240 ms cap, the API must omit that feature and still return a correct core response by the deadline.

The diagram shows an optional recommendation service isolated from an order path.

System flow
Client → API ───────────────→ order store → response
          └→ capped calls → recommendation service
                └→ timeout or open breaker → omit recommendations

The lower branch may fail or slow without taking every API worker. The fallback is valid because recommendations are optional. Authorisation, order totals, and payment status cannot be replaced by guesses merely to preserve a successful response.

Worked examplea slow dependency and a fixed pool

Consider an API offered 200 requests per second, each calling an optional dependency. Assume that dependency normally takes 50 ms = 0.05 s, and that the API has 200 request workers. For a stable system, Little's law gives required average in-flight calls as arrival rate times response time: 200/s × 0.05 s = 10 calls. If the dependency slows to an assumed 5 s while arrivals continue, sustaining that rate would require 200/s × 5 s = 1,000 concurrent calls. Check: 1,000 ÷ 10 = 100, matching the latency increase from 0.05 to 5 s.

The 200-worker pool cannot supply 1,000 concurrent calls, so throughput will fall and a queue will grow; the 1,000 figure is demand implied by the offered rate, not an observed steady state. A bulkhead of, say, an assumed 20 concurrent recommendation calls caps this optional branch at one tenth of the request-worker count, while a timeout releases permits and a fallback lets other requests proceed.

§5 · Safe retries

Retry safely after uncertain outcomes

Timeout does not prove that the remote operation failed. A request can commit just before the response is lost. Retry a write only when the operation is naturally idempotent or the receiver durably deduplicates attempts with the same idempotency key. The deduplication record and effect must be coordinated so two concurrent attempts cannot both pass a check. External effects, such as sending an email after a database commit, need their own duplicate protection.

Choose one layer to retry, distinguish transient failures from permanent rejections, cap attempts, and stop when the request deadline is exhausted. Backoff with jitter spreads retries in time; it does not create spare capacity. Under sustained overload, rejecting or deferring work is more useful than adding attempts.

Separate logical operations from attempts

One logical operation can have several network attempts. The idempotency key must remain stable across those attempts and change for a genuinely new operation. It should be scoped to the caller and operation type so two unrelated clients cannot accidentally share an identifier. The receiver must also decide how long it retains the result. If a key expires while a client still retries, the same request may be treated as new and repeat the side effect. That retention window must cover the maximum retry and reconciliation period promised by the API.

Deduplication needs an atomic boundary. A check-then-insert sequence is unsafe when two attempts with the same key arrive concurrently: both may observe no record and both perform the effect. Reserve the key with a unique constraint, or commit the key and effect in one transaction where the storage system supports it. The recorded outcome should include enough information to return the same result on a retry. If the first attempt is still running, a second attempt can wait within its deadline or receive a response indicating that the logical operation remains in progress.

Not every operation is naturally safe to repeat. Reading a product is usually repeatable, although it may return a newer value. Setting a record to a specified value can be idempotent under a clear versioning rule. Incrementing a counter, issuing a refund or sending an email is not naturally idempotent: a repeated call can apply the effect again. A retry policy must be chosen for the effect, not merely for the HTTP method or the status code. A timeout, connection reset or lost response gives no proof that the remote side did not commit.

A transactional outbox addresses the gap between a local commit and a later message. Without it, an order can commit and the process can crash before publishing the fulfillment event, leaving an order with no fulfillment work. If the order state and outbox record commit together, a separate publisher can retry delivery after a crash. The publisher may send an event more than once if it crashes after sending but before marking it delivered, so consumers still need stable event IDs and idempotent effects. The pattern prevents a lost event at the local boundary; it does not make external delivery exactly once.

Retry only while recovery is plausible

Transient connection failures or temporary unavailability may recover within a request's deadline. Invalid input, authorization denial and a business-rule conflict usually will not. Retrying a permanent rejection wastes capacity and can hide the actual problem. Even for transient failures, limit attempts and total time. Randomized backoff reduces synchronized retry waves after an outage, but a large population of clients can still overwhelm a recovering dependency. A retry budget can cap extra attempts as a fraction of original traffic, so the service does not spend most of its capacity repeating failed work.

When the outcome cannot be known from the response, reconciliation is a first-class path. Keep the operation identifier and the “unknown” state, query the authoritative provider or inspect a durable event, and move to confirmed or rejected only when evidence supports that transition. The user may see a pending status rather than an invented success or failure. Reconciliation itself needs a deadline for escalation and a way to surface unresolved cases. A durable record of attempts and provider references makes it possible to distinguish one logical payment from two independent payment requests.

Worked examplea bounded retry schedule

Consider one request with a 1,000 ms total deadline. Assume its first attempt uses 250 ms and fails transiently. Assume the client waits 100 ms before a second attempt, which then uses 250 ms and also fails. The elapsed time is 250 + 100 + 250 = 600 ms, leaving 1,000 − 600 = 400 ms. If the policy's next randomized wait is 200 ms and the client must reserve 50 ms to finish its response, at most 400 − 200 − 50 = 150 ms remains for a third attempt. A third attempt known to require about 250 ms is unlikely to help; stopping after two attempts is preferable. The check is that a 250 ms third attempt would bring total time to 600 + 200 + 250 + 50 = 1,100 ms, exceeding the deadline by 100 ms. The example illustrates budget accounting, not a universal retry schedule.

The diagram traces the uncertain outcome of a write and its safe retry.

System flow
Client ── key K, create order ──→ server ── commit ──→ order store
Client ←── response lost ──────── network
Client ── key K, retry ─────────→ server ── look up K ─→ original result

Read the second request as a query for the first attempt's outcome. It must not create another order. A new key would represent a new operation and could duplicate the effect.

Worked exampleretry amplification

Consider three sequential service layers, each configured for at most three attempts per call, including the first attempt. Assume every attempt fails in a way each layer considers retryable. The top layer makes 3 attempts to the middle layer; each middle attempt makes 3 attempts to the bottom layer's caller; each of those makes 3 attempts to the final dependency. The final dependency can receive 3 × 3 × 3 = 27 calls for one original request. Check by grouping: the first two layers produce 3 × 3 = 9 calls, and 9 × 3 = 27 at the bottom. Keeping retries at one chosen boundary caps this multiplication and makes the overall deadline easier to enforce.

§6 · Failover

Use redundancy and failover without losing data

Stateless application instances can usually fail over by stopping traffic to an unhealthy instance and routing it to another with spare capacity. Stateful failover also needs a replacement with suitable data. The transfer has four steps: detect that the old owner cannot serve, choose a successor, prevent the old owner from writing, and redirect clients. A slow or partitioned old owner may still be alive, so detection alone cannot make two writers safe. Fencing must be enforced where the protected state is changed.

Detection is a decision under uncertainty

A failed health probe does not prove that a node has stopped. The probe, the node or the network between them may be slow. Promoting too quickly can create two active owners; waiting too long extends the outage. Detection thresholds therefore trade recovery time against false promotion risk. The system should observe repeated probes and state progress, then use an ownership mechanism that stays safe even if the original node was only isolated. A router removing an unhealthy API instance is simpler than changing the owner of mutable database state, because two stateless API instances can often serve the same operation concurrently.

A standby must be able to carry the planned load after promotion. If the primary normally handles 800 writes per second and the standby has only been tested at 300, a successful role switch can still miss the service target. Warm caches, database connections, background replay and application routing all consume time after leadership changes. Include these stages in the measured RTO rather than stopping the clock when an election announces a new leader. Also test the common case in which clients hold stale connections or cached addresses and need time to discover the replacement.

A fencing token works only if the storage resource enforces it. When B becomes the new leader with token 12, the resource must reject any later write from A carrying token 11, even if A continues running. Telling A to stop is insufficient because it may be partitioned and unable to receive that instruction. The check must be tied to each protected write or to a connection whose authority cannot outlive the token. Routing and leadership election can eventually point all clients to B, but the fencing rule protects correctness during the transition.

Some systems use a quorum to choose one leader and to decide which replicated writes are committed. For three independent voters, requiring two votes means two disjoint groups cannot both elect a leader, because any two groups of two overlap. The arithmetic check is that 2 + 2 = 4 votes would be needed for two disjoint majorities, but only three voters exist. This intersection helps avoid conflicting decisions, yet it does not by itself stop a stale leader from writing to an unprotected external resource. Fencing is still needed at that resource. A quorum also affects availability: if two voters are unavailable, the remaining one cannot make new coordinated decisions under a two-vote rule.

The phrase "conflicting histories" in the definition of split brain refers to the history of a piece of state: the ordered sequence of writes that a node has accepted and applied to it, which is the same sequence a replication log records. Before failover, the leader and its standby share one history, because the standby replays the leader's writes in order. During split brain, A and B each accept writes independently, starting from the last state they had in common, so their histories branch from that point and neither contains the other's later writes. Consider the stock example from §3, with one unit remaining. A accepts order X and decrements stock to 0; B, unaware of X, accepts order Y and also decrements stock to 0; both clients receive a confirmation. When the two nodes can communicate again, no merge is correct: keeping both orders violates the invariant that stock cannot fall below zero, and discarding either one loses a write that a client was told had succeeded. Because the conflict cannot be repaired afterwards without breaking a guarantee, the design prevents the second history from being created, which is the job of fencing.

The diagram shows a leader replacement with a fenced old owner.

System flow
Clients → router → leader A ── replicated state ─→ standby B
                    │ failure suspected             │ promoted
                    └─ old writes rejected ← generation advances
Clients → router ───────────────────────────→ leader B

Follow the first line before failover and the last line after it. The generation change rejects writes from A even if it resumes; routing B without that guard would risk split brain. The router and the replacement's capacity also need independent failure protection.

How much data a promotion can lose depends on how the standby receives its copy. In a typical primary–standby database, each node keeps its own write-ahead log on its own disk; the name comes from the rule that a change is recorded durably in the log ahead of being applied to the data files, so the log can rebuild the data after a crash. The log is not shared storage. The leader appends each write to its local log, then streams those log records over the network to the standby, which appends them to its own log and replays them. The standby therefore does replay the log, but only the records that have arrived; the records the leader has written but not yet sent or the standby has not yet stored are the replication lag, measured in time or in log position.

Asynchronous replication means the leader acknowledges a write to the client as soon as the record is durable in its own log, without waiting for the standby to confirm that it has durably stored it; shipping the record happens afterwards, in the background. The consequence is narrower than “any acknowledged write can be lost at any promotion”. Writes durably stored on the promoted standby are safe under the assumed storage-failure model; a record merely received in memory is not enough. What is at risk is the acknowledged tail not durably present on the promoted standby when the leader fails. If the standby is promoted at that point, its history ends where its durable log ends, and it begins accepting new writes from there.

System flow
leader A log:   w1 w2 w3 w4 w5    ← clients told w4 and w5 succeeded
                         │ streamed in the background
standby B log:  w1 w2 w3          ← lag: w4 and w5 not yet received
A fails, B promoted → new history continues from w3; w4 and w5 are missing

Read the two logs as columns: everything up to w3 exists on both nodes and survives the promotion, while w4 and w5 exist only on A's disk. Those records are not necessarily destroyed; if A's disk survives they are still there, but they now form a second branch that conflicts with whatever B accepts next, which is the conflicting-history problem described under "Split brain" in this section. When A rejoins as a standby, its unshipped tail is normally rolled back to match B, and the orphaned writes are discarded or reconciled by hand. A planned switchover avoids the loss by stopping writes on A and waiting until B has caught up before promoting it; the risk applies to unplanned failover.

Synchronous replication closes the stated window when the standby's acknowledgement means the record is durable in its own log: every acknowledged write then exists on at least two nodes. The cost is a network round trip added to every write, and if the required standby is unavailable, writes stall until it returns or the requirement is relaxed. A different architecture places the log on a storage layer that is itself replicated across failure domains, so a replacement node reads the same log rather than a streamed copy; promotion then does not drop acknowledged writes, because the acknowledgement already waited for the storage layer's copies. Neither a replica nor automatic promotion protects against a mistaken delete or corrupting application write that is faithfully copied to every node.

The acknowledgement rule must match the failure it promises to survive. Waiting for one replica that shares a host or zone with the leader may not protect against loss of that shared domain. Waiting for a remote replica can increase write latency and make writes unavailable during a network partition. Relaxing the rule to restore availability changes the durability promise for writes accepted during that period. A design must state which side may accept writes when communication is lost, and must prevent both sides from accepting incompatible histories. The operational switch between modes is itself part of the correctness path and should be tested.

Worked examplerecovery time and potential data loss

Consider a primary failure. Assume detection takes 8 seconds, successor selection and fencing take 7 seconds, and client redirection plus warm-up take 20 seconds. Recovery takes 8 + 7 + 20 = 35 seconds. Check: the three stages account for the whole interruption, so a 30-second RTO would be missed by 5 seconds under these assumptions.

Assume the primary accepted 1,000 writes per second and its standby was 0.2 seconds behind when the primary failed. If that lag consists of acknowledged writes that exist only on the failed primary, the potential loss is 1,000/s × 0.2 s = 200 writes. The multiplication checks the units, but actual loss depends on which writes reached durable storage and which replica is promoted; a measured replication position is needed to establish the real RPO.

§7 · Recovery

Restore, verify, and improve the recovery path

Replication is for continued service after an infrastructure fault. A backup retained outside the affected failure domain is for recovering from deleted or corrupted data, including mistakes that replicas copy. A restoration test must prove that the data is readable, that the application can use it, and that the process completes within its RTO. For a time-based backup schedule, the interval since the last recoverable point informs the RPO; the duration of the restore informs the RTO.

Keep recovery data outside the failure

A replica follows current writes and therefore usually copies mistakes promptly. A backup provides an older recoverable point. Protect it from the same deletion credentials, software bug, storage failure or regional event that could damage the primary. Separate access controls and retention rules reduce the chance that an accidental or malicious deletion removes both live data and recovery copies. A backup inventory should show when each copy completed, what data it covers, where it lives and whether its restore procedure still works. A file that was written once but can no longer be decrypted or read by current software is not a usable recovery point.

Backup frequency and log retention determine the possible data-loss window. A daily snapshot alone can leave nearly a day of changes at risk just before the next snapshot. Retaining a continuous sequence of database changes permits point-in-time recovery to a later moment, but only if the sequence is complete and can be replayed from a compatible base backup. A missing segment breaks the chain after that point. Check continuity and restore a sample through the end of the retained log, rather than assuming that a successful backup job proves recoverability.

Worked examplebackup interval and restore duration

Consider a database with snapshots every six hours and no retained change log. Assume the last completed snapshot was at 06:00 and a destructive error occurs at 11:45. The latest recoverable state is 06:00, so the state gap is 5 hours 45 minutes. The maximum gap under a perfectly regular six-hour schedule is just under six hours, assuming each snapshot completes and remains usable. If the requirement permits no more than one hour of lost changes, this plan misses it by at least 5 hours 45 minutes − 1 hour = 4 hours 45 minutes for the stated event.

Assume restoring the snapshot takes 70 minutes, validating it takes 25 minutes and routing clients to the restored service takes 15 minutes. Total interruption is 70 + 25 + 15 = 110 minutes, or 1 hour 50 minutes. Check: 1 hour 10 minutes + 25 minutes + 15 minutes = 1 hour 50 minutes. A two-hour RTO would pass under these assumptions, while a one-hour RTO would miss by 50 minutes. These values describe one tested scenario; larger data volume or a different region may change the times.

Restore to a trustworthy point

For accidental deletion, the newest data is not necessarily the correct data. Recovery must identify a point before the harmful change, restore it into an isolated environment and verify which legitimate changes followed that point. Replaying every later log entry would reproduce the deletion. Stopping replay just before it avoids the bad operation but may omit valid changes that occurred afterwards. Those later changes may need selective replay, comparison or reconciliation with external systems. The recovery plan should say who decides the safe point and what evidence confirms that the restored state is suitable for service.

Validation must cover more than record counts. A restored database may have the expected number of rows while an index is corrupt, an encryption key is missing or a downstream service still points at the old primary. Verify representative reads and writes, application startup, schema compatibility, authentication, and the business invariants the service promises. If a payment or message was already sent outside the database, restoring an earlier database point can make local state disagree with that external effect. Reconcile durable external identifiers before resuming workflows that could repeat those effects.

Observe recovery from outside the affected path

Internal health checks can report that a process is running while users cannot reach it through DNS, routing, authentication or a shared network dependency. A synthetic check from an independent location can exercise a harmless end-to-end operation and measure its correctness and latency. Several checks may be needed for distinct functions: browsing can recover while checkout remains blocked. Pair them with server-side measurements of error rate, slow requests, replication lag, queue age and failover state. A single green process-level indicator does not prove that the service-level objective is being met.

Alerts should lead to a decision. A rising error rate may require shedding optional work, while replication lag may require pausing promotion or reducing write admission. An alarm that fires after the recovery time objective has already elapsed leaves no time to act. Define thresholds from the target and the time needed for the response, and verify that on-call operators can distinguish a noisy transient from a real user-visible failure. After an incident, compare the observed timeline with the planned detection, decision, restore and validation stages; improve the stage that consumed the time.

Exercise the fault, not only the diagram

Fault injection tests whether the promised mechanism works under controlled conditions. Remove an API instance and verify that remaining capacity handles traffic; delay a dependency and verify timeouts, bulkheads and fallbacks; isolate a primary and verify that the old owner cannot write after promotion. Tests should have a clear stop condition and expected result, including whether acknowledged writes survive. Begin with a limited scope that can be observed and reversed, then expand only after the recovery path has been demonstrated. Record the actual interruption and any data discrepancy, because a successful command to inject a fault does not prove that users experienced an acceptable outcome.

Software changes are frequent faults in otherwise redundant systems. A staged rollout limits how many requests see a bad version before the error is detected. Rolling back code may be quick, but a schema or data migration may not be reversible by simply starting old binaries. Use compatible transition stages for data changes, and test how both old and new versions behave while they coexist. A release plan should identify which metrics trigger a halt, how traffic returns to the known version, and how data written by the new version will be interpreted if rollback occurs.

Recovery drills should cover both common and severe scenarios. A process restart checks routing and local state; a zone loss checks independence and spare capacity; a mistaken delete checks backup isolation and the ability to select a safe restore point. Running only the easiest drill gives no evidence about the others. Preserve the timestamps of fault onset, detection, decision, restoration, validation and user-visible recovery. From those timestamps, calculate both the total interruption and which stage dominated it. Track whether every acknowledged operation survived, rather than relying only on a final “healthy” indicator.

Restore dependencies in a usable order

A restored database is not enough if application instances still connect to the failed endpoint or a message consumer resumes before its deduplication state is available. A recovery runbook should name the order of prerequisites: restore or promote authoritative storage, verify its durable position, bring required identity and configuration services into reach, route a small amount of traffic, and then resume background consumers that can safely process pending work. The exact order depends on the system, but each step should have a check that can halt the sequence when correctness is uncertain. A service that responds to health checks before these dependencies are ready can draw traffic into a partially recovered path and prolong the incident.

After service returns, recovery work may continue. Queued jobs, replica catch-up and cold caches can use capacity that normal traffic also needs. The RTO clock should stop only when the defined user operation is restored to its target; a process coming online is not sufficient. Separately track the time until backlog and replicas return to normal, because the system may remain vulnerable to a second fault during that period. Capacity reserved for recovery should be tested with realistic background work rather than inferred from an idle standby's specifications.

The diagram places the two recovery objectives on opposite sides of a disruption.

System flow
last recoverable state ── possible lost work ── failure ── detection and restore ── service resumes
                         ←────── RPO ──────→           ←──────── RTO ────────→

Read leftward from failure to the last recoverable state for the data-loss window, and rightward to restored service for the interruption. A fast restart can have a poor RPO, while a slow restore can retain every write.

Monitor actual successful operations, error and latency rates, replication position, failover progress, queue age, and correctness invariants. An external synthetic check can detect outages that internal monitoring misses because it shares the failing system. Exercise process loss, slow dependencies, duplicate requests, primary promotion, and backup restoration, then compare measured recovery and data loss with their targets. Changes to software are another failure source: a staged rollout limits the fraction of traffic exposed to a bad release, but a restore still needs to account for incompatible data changes.

· · Review

Common mistakes

Each card below names one mistake, the reason it is easy to make, what goes wrong as a result, and the fix, with a link to the section that explains the mechanism.

  1. Equating a fast response with a correct one

    Why it happens
    Availability dashboards often count only HTTP status and latency.
    What goes wrong
    A successful response that lost an acknowledged write or bypassed an invariant is counted as success, although it is a failure under a correctness-aware SLO.
    Fix
    Define success to include the required outcome, not only the status code and response time. §2
  2. Treating a second instance as complete failover

    Why it happens
    Redundancy is assumed to cover every fault, so shared dependencies go unexamined.
    What goes wrong
    Both instances may share a database, router, region, or bad release, and a standby may lack capacity or current data.
    Fix
    Map failure domains and test the whole path through detection, fencing, routing, and warm-up. §6
  3. Retrying every timeout

    Why it happens
    A timeout is read as a definite failure rather than an unknown outcome.
    What goes wrong
    The original attempt may have committed, so a retry can duplicate the effect; retries at several layers also multiply load.
    Fix
    Use one bounded retry point, a shared deadline, and idempotency for effects that could otherwise be duplicated. §5
  4. Letting a slow optional dependency occupy all request workers

    Why it happens
    The dependency is still returning success, so error-based alarms and circuit breakers may remain quiet.
    What goes wrong
    Waiting calls hold every worker, and requests that never needed the dependency queue behind them.
    Fix
    Apply a deadline and an independent concurrency cap, observe slow-call rate, and use a stated fallback for the optional function. §4
  5. Calling replicas a backup

    Why it happens
    A replica holds a full copy of the data, so it looks like a recovery source.
    What goes wrong
    Replicas reproduce deletes and corruption as well as valid writes.
    Fix
    Retain protected backups or change logs in a separate failure domain and practise restoring them to a usable state. §7

· · Exercises

Practice questions

These questions mix recall, calculation and application across the whole guide, and each answer is collapsed beneath its question to be opened once the reader has worked out an answer.

Question 1 (distinction)

An API rejects a malformed order without changing state, survives one API instance crashing, and serves checkout during that crash. Which observations demonstrate robustness, fault tolerance, and high availability?

Answer

Rejecting the malformed order without state change demonstrates robustness. Preserving the checkout function when an instance crashes demonstrates fault tolerance to that fault. Serving checkout during the crash contributes to high availability; whether the system meets a specific availability target still requires measurement over the stated window and latency limit.

Question 2 (calculation)

An operation has a time-based 99.95% availability target over 30 days. How many minutes of unavailability does that permit?

Answer

The window is 30 × 24 × 60 = 43,200 minutes. The unavailable fraction is 1 − 0.9995 = 0.0005, so the budget is 43,200 × 0.0005 = 21.6 minutes. Check: 43,200 − 21.6 = 43,178.4 available minutes, and 43,178.4 ÷ 43,200 = 0.9995.

Question 3 (calculation)

A primary accepts 2,000 writes per second, and a standby is 150 ms behind when the primary fails. Under the assumption that every write in that interval exists only on the primary, how many acknowledged writes could be lost by promoting the standby?

Answer

Convert 150 ms to 0.15 s. The potential loss is 2,000 writes/s × 0.15 s = 300 writes. The seconds cancel, leaving writes. This is an estimate under the stated assumption; inspect durable replication positions to determine actual loss.

Question 4 (application)

A payment request times out after the provider may have committed a charge. What should the service record and how can it retry safely?

Answer

Record the attempt as having an unknown outcome rather than as a definite failure. Reuse the same provider idempotency key when retrying or query the provider for that attempt's result. Keep local state tied to one logical payment and reconcile it against the provider's authoritative result before confirming a new charge or reporting success.

Question 5 (open-ended)

An online shop uses one database primary and two API instances in one zone. During a promotion, the old primary sometimes resumes, recommendations become slow, and a mistaken delete is copied to the standby. Propose changes that address correctness, availability, and recovery, and say how to test them.

Answer

Set separate success and recovery targets for browsing and checkout, including a rule for acknowledged orders. Place API capacity and a database standby across suitable independent failure domains, and verify that the router can move traffic with enough capacity left. Promote one primary at a time and enforce fencing at the write resource so the old primary cannot resume writes. Bound recommendation calls with timeouts, a bulkhead, and a breaker, and omit recommendations when the optional service fails; checkout correctness controls remain required. Keep protected backups and a change log for point-in-time recovery from the delete, because replication copies it. Test a slow recommendation dependency, an API loss, primary promotion while a request is in flight, attempted stale-primary writes, and a timed restore. Measure user-visible interruption and the set of acknowledged writes that survive each test.

Question 6 (application)

A database replica is current, but a mistaken deletion has been copied to it. The latest protected backup predates the deletion, and later legitimate orders also exist. Why is promoting the replica insufficient, and what should recovery verify before checkout resumes?

Answer

Promoting the replica preserves the same mistaken deletion because replication copied it. Restore an isolated copy to a point before the deletion, identify valid changes after that point, and reconcile them rather than replaying the harmful change blindly. Before resuming checkout, verify schema compatibility, representative reads and writes, inventory and order invariants, and external payment or fulfillment identifiers. Measure the time to restore usable service against the RTO and the age of the recoverable state against the RPO. A current replica helps with infrastructure failure, while the protected backup and change history address logical corruption.

· · Finish

Review checklist

Without consulting notes, distinguish faults from failures and explain robustness, fault tolerance, and high availability for a named operation. State a measurable success condition, calculate an availability budget, and set RTO and RPO for a specific disruption. Enforce invariants when requests race, and describe an uncertain remote outcome honestly. Bound waiting, concurrency, retries, and admitted load so a slow dependency cannot consume the whole service. Explain detection, promotion, durable replication, fencing, and routing during failover, including the potential data-loss window. Choose a recoverable point after logical corruption, verify the restored service and its external effects, and measure recovery with independent checks and a tested restore. A reader who can do all of these has covered the material.