Study guide · System design

Study guide: observability and operations

Measure user outcomes, connect metrics, logs and traces, respond to alerts, release safely, and verify capacity and recovery.

Contents
  1. ·Learning objectives
  2. §1Core concepts
  3. §2Define outcomes and reliability targets
  4. §3Connect metrics, logs, and traces to the request path
  5. §4Keep the telemetry pipeline useful and affordable
  6. §5Detect problems and make alerts actionable
  7. §6Release and change the system safely
  8. §7Plan capacity and prove recovery
  9. §8Coordinate incidents and learn from them
  10. ·Common mistakes
  11. ·Practice questions
  12. ·Review checklist

· · Start here

Learning objectives

  1. Explain how observability supports operating a system and distinguish a user-visible failure from a healthy-looking component.
  2. Define a service level indicator, a service level objective, and an error budget for a named user journey, then calculate the budget from traffic and target.
  3. Choose metrics, structured logs, and distributed traces to answer different diagnostic questions across a request path.
  4. Design a telemetry pipeline that preserves useful detail while controlling label cardinality, sampling, retention, and sensitive data.
  5. Choose actionable alerts, external checks, health probes, and runbooks that connect a detected problem to a response.
  6. Compare staged release methods and plan compatible configuration and schema changes that can be reversed safely.
  7. Use capacity tests, recovery objectives, restoration drills, and incident reviews to verify and improve operational promises.

§1 · Definitions

Core concepts

This section defines observability, operations, telemetry, and a user journey. These terms connect system signals to the outcomes that users actually experience.

A design becomes observable when the signals let an operator connect an affected journey to the component or data transition responsible for it. Operations then uses that evidence to choose an action: stop a rollout, reduce admission, repair an integration, or restore data. A component's CPU graph can be normal while an order is paid but never confirmed, so operational design must start from the required outcome and trace inward to the resources that support it.

The useful unit of operation is a promise about a user journey. A product search can be available while checkout is failing; checkout can return quickly while its confirmation worker falls hours behind. A single service-level graph cannot represent both outcomes unless it records the event that completes each one. Start with what the user attempted, the latest time at which the result remains useful, and the durable state that proves completion. Then identify the entry point, dependencies, queued work, and stored records that can break that promise. This produces an operational map instead of a catalogue of machines.

Observable behaviour also requires a distinction between cause, symptom, and impact. A growing queue is a symptom; a slow consumer or an upstream burst may be its cause; orders that remain unconfirmed are the impact. The distinction changes the response. Adding consumers may help a capacity shortage but can worsen database contention. Pausing new work may protect completed orders during a corrupted downstream integration. A dashboard should let an operator move from impact to likely cause while preserving uncertainty until the evidence supports a choice.

Operations is continuous because the workload, code, data, and dependencies change. A signal that explained yesterday's synchronous request may not explain tomorrow's background job. Written response steps for one version may direct an unsafe action after a schema migration. Each release therefore changes both the system and the evidence needed to operate it. Useful operational work includes rehearsing rollback, testing a restore, reviewing alert ownership, and retiring measurements that no longer answer a question. These activities protect the same user journey that feature tests exercise before deployment.

The common confusion is to equate observability with collecting every possible log. Large volumes of records can still leave a failure unexplained if they lack a shared request identity, omit the decisive state transition, or measure only internal health. Useful signals answer a question and lead to an action; collection volume alone does neither.

§2 · Outcomes and targets

Define outcomes and reliability targets

An SLI needs a population and a good-event rule. For checkout, a good event might mean that an eligible attempt reaches a durable order confirmation within a stated duration; merely returning HTTP 200 would not prove that the order exists. The measurement point matters too. A server-side SLI can miss failures at the edge or in a client, while a scheduled test journey can cover only the path it exercises. Define exclusions narrowly so a dependency outage is not hidden by removing its failed requests from the denominator.

The diagram shows how the outcome rule is applied before the target is evaluated.

System flow
Eligible user attempts → outcome and latency check → good / not good
                                              ↓
                                  SLI over a window → compare with SLO

Read left to right: first decide which attempts count, then classify each result, then aggregate over the same window used by the objective. A service dashboard can display the resulting ratio, but the rule that classifies an event must be specified before the dashboard is trusted.

Worked examplea request-based error budget

Consider an API with 50 million eligible requests in a 30-day window and an SLO that 99.9% are good. The allowed bad fraction is 1 − 0.999 = 0.001. The error budget is 50,000,000 × 0.001 = 50,000 bad requests. Check: 50,000,000 − 50,000 = 49,950,000 good requests, and 49,950,000 ÷ 50,000,000 = 0.999.

Assume 20,000 bad requests have already occurred in that window. The spent share is 20,000 ÷ 50,000 = 0.40, or 40%, leaving 50,000 − 20,000 = 30,000 bad requests before the target is missed. This arithmetic is specific to a request-based SLI; a time-based availability objective needs a time denominator instead.

Write the event rule before choosing a target

A reliable SLI states who is counted, when an attempt begins, what evidence marks success, how long success may take, and how missing measurements are treated. For an order journey, a rule might count each valid checkout submission once and mark it good only if a durable order with the expected items appears within two minutes. A retry of the same submission should not create another eligible attempt if the product treats it as the same checkout. A payment provider timeout is not automatically an exclusion: from the customer's point of view, the outcome may remain unknown or delayed. The rule should name that case and its deadline.

Server responses, client measurements, and synthetic probes each see different populations. A server can count only requests that reach it; a browser can see DNS, connection, and rendering failures; a synthetic probe tests a controlled path from selected locations. If a mobile application stores work offline, the moment at which it presents the operation as submitted may differ from the moment the server receives it. Choose the observation point that matches the promise, and document blind spots. Where no one signal sees the whole journey, join an entry event with a completion event using a stable operation identifier and measure the age of unmatched entries. Missing completion events must count as failures after the deadline, not disappear from the denominator.

Targets should reflect the point at which users notice harm and the cost of improving reliability. A 99.99% target is not automatically better than 99.9%; it permits one tenth as many bad events for the same traffic and therefore changes release freedom and engineering cost. Separate journeys when they have different consequences. Browsing recommendations might tolerate a fallback that checkout payments cannot. Averages across regions or customer groups can hide a consistently failing minority, so the overall SLI should be accompanied by segment views where routing or dependency differences make them meaningful. Keep the segment labels bounded enough to measure reliably.

Google's SRE treatment of service level objectives separates indicators, targets, and agreements. A service level agreement is a commitment with consequences specified outside the measurement itself; an internal SLO can guide engineering without making that commitment. The two should use compatible definitions if both exist. An error budget is a decision input rather than permission to ignore failures: a fast burn may justify freezing a risky rollout, while a nearly untouched budget may allow a carefully staged change. A policy needs an owner, a window, and explicit actions so the same budget position produces a predictable response.

Worked exampletime and request denominators

Consider a 30-day window and a 99.9% availability target. Assume availability is measured by eligible one-minute intervals. There are 30 × 24 × 60 = 43,200 intervals. The allowed bad fraction is 1 − 0.999 = 0.001, giving 43,200 × 0.001 = 43.2 bad minutes. Because whole one-minute intervals are counted, at most 43 bad intervals keep the result at or above the target. Check: (43,200 − 43) ÷ 43,200 ≈ 0.9990046, while 44 bad intervals give 43,156 ÷ 43,200 ≈ 0.9989815. If instead the SLI counts one million eligible requests in that window, the budget is 1,000,000 × 0.001 = 1,000 bad requests. Neither budget can be converted to the other without knowing when traffic occurs and how the one-minute rule classifies a partial outage.

Keep the denominator and window honest

A short fixed window is responsive but volatile; a long window gives a steadier product view but can hide a fresh severe failure inside earlier good traffic. Rolling windows move with the current time and avoid an abrupt reset, while calendar windows align with reporting periods. The choice affects how much budget appears to remain on a given day. Record the window in every dashboard and alert. Do not compare a seven-day burn with a monthly remaining budget without explaining the conversion and the current traffic volume.

Low traffic changes the meaning of percentages. In a window with 100 eligible requests, one failure produces 99% success; in a window with one million requests, the same single failure produces 99.9999% success. A low-traffic journey may need a longer window, synthetic checks, or an invariant such as “no paid order remains unconfirmed beyond the deadline.” Always display numerator and denominator next to the ratio. Otherwise, an apparently dramatic percentage change may represent one event, while a modest change at high volume may represent thousands of affected users.

Some promises cannot be reduced to a request response. For a delayed export, measure completion within an agreed time from acceptance, as well as correct file generation and delivery. For freshness, compare the age of the newest usable data with the allowable age; for durability, check whether an accepted write remains recoverable after a relevant failure. The metric may come from state transitions rather than HTTP status codes. The same discipline applies: state the eligible population, success rule, deadline, observation point, and treatment of missing evidence before announcing a target.

§3 · Diagnostic signals

Connect metrics, logs, and traces to the request path

Metrics show whether a problem is widespread and when it began. Logs explain discrete decisions and failures, such as a payment result being marked unknown. A trace shows where one slow or failed request spent time across the dependency graph. The correlation ID joins these views. Instrument entry points and asynchronous handoffs so the ID survives a queue; record the outcome of important state transitions, not only incoming requests.

This comparison helps select the signal that answers a particular question.

Signal Question it answers well Limitation to plan for
Metric How often and how broadly is a condition occurring? Aggregation can hide one affected key or one incorrect transition.
Structured log What decision or state change occurred for this operation? Searching high-volume records can be expensive and slow.
Distributed trace Which calls and waits shaped this operation's latency? Sampling may omit the particular failed request.

The signals complement rather than replace one another. A rising checkout tail latency can lead to a trace of a slow database call, then to a log explaining which lock or query failed; the metric still shows whether the issue affects all checkouts or one route.

The diagram follows a request and its identifiers through two services and a queue.

System flow
Client → API span ────────→ inventory span → database span
            │                    │
            ├→ request metric    └→ decision log
            └→ queued event with correlation ID → worker span → outcome log

Follow the top line for synchronous calls and the lower line for delayed work. The queued event carries the correlation ID because a later worker is part of the same logical journey even though it runs in a different process and at a different time.

A high percentile should be calculated from the combined request distribution for the chosen window. Averaging the p99 values of individual hosts does not produce a fleet p99, because each host may have different traffic volume and latency shape.

Instrument the operation, not merely its entry point

For each journey, mark its start, decisive state transitions, and terminal outcome. An asynchronous order might move from accepted to payment pending, paid, allocated, and confirmed. A log at the API entry proves that a request arrived; it cannot prove that the worker later completed it. Count transitions and age the unfinished work, then connect the transition records by operation identity. A request metric should classify the server's response; a separate outcome metric should classify the eventual order result. Keeping both prevents an apparently healthy API from masking a stalled workflow.

Dimensions should explain differences that change an operational decision. Route, region, version, dependency, and bounded outcome class can distinguish a canary defect from a regional outage. Values with many distinct possibilities, such as order IDs, belong in protected event records. Record a common timestamp convention and enough identity to join signals without logging credentials or full payloads. Clock differences between hosts can make a trace appear to run backward; duration measured with a monotonic clock is safer for elapsed time, while wall-clock timestamps help place events on an incident timeline. Inspect both when the two disagree.

Use a counter for completed requests and derive a rate from its change over time, accounting for process resets. Use a gauge for current backlog, but do not infer a completion rate from its change alone: the backlog can stay flat while arrivals and completions are both high. A latency histogram preserves counts across duration ranges so data from instances can be combined, subject to the histogram format and bucket resolution. A single average discards the slow tail; a percentile computed independently on each instance cannot simply be averaged into a fleet percentile. Prometheus instrumentation guidance explains these metric types and their operational use.

Worked examplewhy a stable queue is not idle

Consider a queue with 5,000 jobs at the start and end of a ten-minute interval. Assume 12,000 jobs arrive and 12,000 complete during that interval. The backlog change is 5,000 + 12,000 − 12,000 = 5,000, so a queue-depth gauge alone looks unchanged. The arrival and completion rates are each 12,000 ÷ 600 = 20 jobs/s. If arrivals rise to 25 jobs/s while completions remain 20 jobs/s for the next ten minutes, the backlog grows by (25 − 20) × 600 = 3,000 to 8,000. Check: 5,000 + 15,000 arrivals − 12,000 completions = 8,000. Queue age and oldest-item age add another view: a flat depth can still conceal an old stuck job while newer work passes it.

Join traces across synchronous and delayed work

A trace begins at an entry point, then spans represent meaningful work such as an outgoing request, database operation, or queue publish. Propagate context over supported request headers or message metadata, and create a new span when a worker handles the message. For delayed or fan-out work, the new activity may need a link to the originating trace rather than pretending the original request stayed open. The choice should represent the actual causal relation. A correlation ID can connect logs across longer lifetimes even when sampled traces are absent. OpenTelemetry's concepts documentation describes context propagation and its role in relating signals.

Instrument errors as events with a meaningful outcome, not only as exceptions. A timeout after a payment request may leave the result unknown; recording it as “payment failed” would lead an operator or retry worker to the wrong action. Distinguish a rejected request, a dependency timeout, a confirmed downstream failure, and an ambiguous result. Add the relevant operation identifier and bounded status class so the event can be reconciled later. Avoid recording raw request bodies, tokens, or sensitive response contents as a substitute for a useful state label.

Measure spans and queues at boundaries where time can disappear. A trace that includes only application method calls may omit network wait, connection-pool wait, queue residence, or client rendering. A slow user journey can then appear to contain only fast spans. Compare the end-to-end duration with the sum and gaps of observed steps; a large unexplained gap is itself an instrumentation finding. Attach resource attributes such as service and version consistently, so a trace from the old version can be distinguished from one from the canary during a release.

§4 · Telemetry design

Keep the telemetry pipeline useful and affordable

Instrumentation sends events through collectors and processing stages to storage. This path has its own failure modes: buffers can fill, sampling can discard the only evidence of a rare event, and high-cardinality labels can overwhelm a metrics store. Keep labels bounded, reserve request IDs for logs and traces rather than metric labels, and choose a retention period from diagnosis and audit needs. Avoid putting secrets or personal data into telemetry; access and deletion rules apply to these stores as well as to primary data.

The diagram shows where volume and privacy controls belong.

System flow
Service signals → collector → filter / redact / sample → metric, log, trace stores
                       │                    │
                       └→ bounded buffer    └→ retention and access policy

Read left to right: the service emits the evidence, the collector limits and routes it, and each store keeps only what its use requires. If this pipeline fails, the service should have a defined behaviour, and loss of operational evidence should itself be visible through an independent signal.

Worked examplelabel combinations

Consider a request metric labeled by 3 methods, 5 routes, 4 status classes, and 10 instances. Assume every combination occurs. Its upper-bound series count is 3 × 5 × 4 × 10 = 600. If a user identifier with 100,000 distinct values is added and, as a worst-case assumption, each user occurs in every existing combination, the bound becomes 600 × 100,000 = 60,000,000 series. Check: the new dimension multiplies the original count by 60,000,000 ÷ 600 = 100,000. Real counts depend on which combinations occur, but a per-user metric label is still an unbounded growth path; put the identifier in a protected log or trace field when it is genuinely needed.

Budget the pipeline as part of the service

Telemetry has production costs at three points: instrumented processes spend CPU and memory to create it, collectors buffer and transform it, and stores ingest, index, and retain it. A log line that is cheap to emit can be expensive to search when repeated for every request. A metric with a small payload can be expensive when its labels create many series. Decide which operational question each signal answers, then estimate volume before adding it to a hot path. A useful budget states acceptable telemetry overhead, ingest rate, active series, storage duration, and query latency for incident investigations.

Choose bounded labels from controlled vocabularies. A route template such as /orders/{id} groups all orders under one label; the concrete path /orders/84927 grows with every order. Treat arbitrary exception messages, URLs, tenant IDs, and user IDs as unbounded unless there is a proven cap. Even bounded dimensions multiply when combined. If every instance is removed from a high-level service metric, the service view becomes cheaper but instance-specific diagnosis still needs a separate, deliberately scoped metric. Design both views for their jobs instead of attaching every dimension to every measurement.

Worked exampleestimating ingest and retention

Consider a service producing 2,000 requests per second. Assume it emits one 500-byte structured log for every request and a second 500-byte log for 5% of requests. The average is 500 + 0.05 × 500 = 525 bytes/request, so raw application log output is 2,000 × 525 = 1,050,000 bytes/s. In one day that is 1,050,000 × 86,400 = 90,720,000,000 bytes, or about 90.72 GB in decimal units. Thirty days of raw output would be about 90.72 × 30 = 2,721.6 GB. Check: the daily figure divided by 86,400 returns 1,050,000 bytes/s. Indexes, replicas, compression, and transport overhead change actual storage; the calculation is a planning baseline, not a bill. Reducing the per-request log by 200 bytes saves 2,000 × 200 × 86,400 = 34.56 GB of raw output per day under the same traffic assumption.

Sample with the question in mind

Uniform random sampling can reduce high-volume traces while retaining a representative view of ordinary requests, provided the sample probability is known. It can still miss rare failures. A policy that keeps all known errors and a small fraction of successes improves failure diagnosis, but the retained set no longer represents the original traffic mix. Use unsampled counters for rates and SLOs; use sampled traces to explain examples. If a collector selects traces after seeing their outcomes, it needs enough buffer time and capacity to hold complete traces before deciding. If the collector drops data under pressure, record that loss separately so a sudden decline in traces is not mistaken for recovery. OpenTelemetry's sampling guidance describes the trade-off between volume and representative detail.

Sampling decisions should propagate consistently across a trace where possible. If a parent is retained but a critical downstream span is missing because each service sampled independently, the trace can appear to blame the wrong step. At asynchronous boundaries, preserve enough correlation to connect the message and worker even if they enter different trace lifetimes. Maintain a deliberate path for rare but high-value evidence, such as a failed payment reconciliation, while limiting the sensitive content that path can carry. “Keep every error” still needs a bounded policy during an error storm.

Protect and monitor the evidence path

Redaction should occur as close to emission as practical, before data reaches broad collectors or third-party stores. Prefer an allowlist of safe fields over a blocklist of secret patterns, since new credentials and payload fields may not match old patterns. Protect access to traces and logs because correlation identifiers and transaction metadata can reveal behaviour even without a password. Retention needs a reason for each store, including short-lived buffers, search indexes, archives, and exports. Deletion rules for personal data must include telemetry copies where applicable.

The telemetry pipeline requires its own health signals: received versus exported record counts, queue length, drop count, exporter errors, storage lag, and freshness of the latest usable sample. If the application is healthy but the collector stops exporting, an incident could become invisible. Monitor the monitoring system from an independent path where possible, such as an external synthetic check or a separate heartbeat. Decide whether an exporter outage may delay user requests; most user paths should not block indefinitely on telemetry. A bounded buffer and explicit drop behaviour make that trade-off visible and testable.

§5 · Detection and response

Detect problems and make alerts actionable

An alert should identify an actionable condition, an owner, and a response. User-visible errors, sustained SLO burn, and broken invariants are stronger paging signals than an isolated CPU threshold. Resource saturation remains useful for diagnosis and capacity planning. A synthetic journey catches a failed path at low traffic and can cover the public edge; it must use safe test data and be excluded from business volume. Liveness probes should not restart every instance because one shared database is slow, and readiness should answer whether an instance can usefully accept traffic rather than test every possible dependency.

The diagram connects detection to response and verification.

System flow
Real traffic + synthetic checks + invariants → alert → owner and runbook
                                                  ↓
                                   contain → repair → verify outcome
                                                  ↓
                                          update signals and procedure

Read the top line as the detection path. The lower loop closes only when the operator confirms the user outcome has recovered and updates the runbook or instrumentation so the next incident is easier to diagnose.

Worked exampleinterpreting error-budget burn

Consider a 99.9% request-success SLO. Its allowed bad fraction is 1 − 0.999 = 0.001, or 0.1%. Assume a recent interval has 10,000 eligible requests and 100 bad results, so the observed bad fraction is 100 ÷ 10,000 = 0.01, or 1%. The burn rate is 0.01 ÷ 0.001 = 10. Check: 1% is ten times 0.1%.

If the request rate and bad fraction remain constant, a fresh 30-day budget would be consumed in 30 ÷ 10 = 3 days. This is a projection under the constant-rate assumption, not a promise about how much budget remains now. An alert can use burn measured over more than one window so a brief spike and a sustained failure are treated differently.

Choose a response before a threshold

An alert should state what user promise is at risk, the evidence that triggered it, its owner, and the first safe action. A page is appropriate when delay would increase harm and a responder can act now. A ticket or scheduled review is better for capacity trends that allow planning. If an alert has no clear response, change the measurement or remove the page. Repeated nonactionable pages train responders to ignore the channel, increasing the chance that a real failure is missed. Route alerts by service ownership, test the route, and identify a backup when the primary responder is unavailable.

Alerts on symptoms and causes serve different roles. An SLO burn alert says users are being harmed; a database connection-pool saturation signal suggests a cause. The latter can be useful as context or an early warning, but it should not automatically page if it routinely rises without impact. Conversely, a regional edge failure can harm users while every internal instance is healthy. Pair user-facing indicators with diagnostic views and an external check. For delayed work, alert on the age of the oldest eligible item and missed completion deadlines, not only a high queue count; a queue can be large and healthy if it drains within the promised time.

Multi-window burn alerts combine a short window that notices fast damage with a longer window that confirms persistence, and a second pair can catch slower sustained loss. The exact windows and thresholds depend on the SLO period, traffic, and response cost. Before enabling a page, replay historical incidents and normal peaks through the rule. Check how many pages it would have sent, how long it would have taken to fire, and whether the named responder could have changed the outcome. Include a minimum event count or other low-traffic guard where a single failure would otherwise create an unstable ratio, without hiding a severe one-off event that deserves a separate invariant alert.

Worked examplebudget consumed during an alert

Consider a 99.9% good-request SLO over 30 days and an assumed constant load of 1,000 eligible requests per minute. The window has 30 × 24 × 60 = 43,200 minutes and 43,200 × 1,000 = 43,200,000 eligible requests. Its error budget is 43,200,000 × 0.001 = 43,200 bad requests. Assume a fault makes 10% of requests bad for 30 minutes. It causes 1,000 × 0.10 × 30 = 3,000 bad requests, spending 3,000 ÷ 43,200 ≈ 0.0694, or about 6.94% of the monthly budget. Check: the fault's bad fraction is 0.10 ÷ 0.001 = 100 times the allowed fraction; 30 minutes at 100-fold burn consumes the budget equivalent of 3,000 normal minutes, and 3,000 ÷ 43,200 ≈ 6.94%. This calculation ignores any bad requests outside the fault interval and assumes traffic remains constant.

Separate probe meanings

A liveness probe should answer whether restarting this instance is likely to help. A readiness probe should answer whether it can accept new work now. A startup probe, where supported, can give slow initialization time to complete before liveness begins to enforce restarts. Avoid placing a shared database query in every instance's liveness probe: a database outage would restart all instances and add load just when the dependency is struggling. Readiness may need to reflect an indispensable local dependency, but probe failure should be chosen with an understanding of whether removing every instance leaves any path for graceful degradation. Health checks are control inputs, not merely dashboards; a faulty check can cause its own outage.

Synthetic checks complement real-traffic indicators. A test that enters through the public edge can reveal DNS, TLS, routing, or login issues the application metric never sees. It can also give a false sense of coverage if it tests only a static page while checkout is failing. Define which journey and location each probe represents, use controlled accounts and safe test transactions, clean up artifacts, and keep its traffic out of commercial reporting. Compare synthetic failure with real-user signals: a synthetic-only failure may be a test fixture issue, while real-user-only failure may reflect a path, device, or population the probe never exercises.

Make the runbook executable

A runbook begins with confirmation: the alert query, affected journey, scope by region or version, and nearby deployment or dependency changes. It then gives a low-risk containment action, the conditions for taking it, the expected effect, and a way to verify that effect. It names escalation contacts and the evidence to preserve before changing state. Commands that rotate credentials, replay jobs, or restore data need clear preconditions and a rollback or stop condition. A procedure that says only “investigate logs” leaves the responder to invent a method under time pressure. Rehearse the runbook when the service changes, and remove steps that no longer match the deployed system.

Alert quality is measured by what happens after it fires. Record whether the alert preceded user reports, whether it named the correct owner, whether the first action helped, and whether it repeated after containment. A page that arrives late may need a better SLI or shorter evaluation window; a page that fires early but on every harmless burst may need a persistence rule or a different severity. Treat missed incidents and noisy alerts as design feedback, then update both detection and response. Prometheus alerting guidance also notes that the alerting infrastructure itself needs monitoring.

§6 · Change safety

Release and change the system safely

Release design is part of operations because a bad change can affect every healthy component at once. A canary limits initial exposure and compares user outcomes, latency, and correctness signals with the old version. A rolling deployment limits how many instances are replaced together but still requires old and new code to share data safely. Blue-green can make traffic reversal quick, but a single switch to all users does not limit the initial blast radius. Feature flags separate deployment from activation; an emergency flag must be reachable when the affected dependency is failing. Infrastructure as code makes the intended environment reviewable, and emergency manual changes must be reconciled back into it.

The diagram shows a staged release with a measured decision before widening traffic.

System flow
Old version ←──── 99% of traffic       New version ← 1% of traffic
       │                                    │
       └──────── compare outcomes ─────────┘
                           ↓
             widen, hold, or route back to old version

The two branches see different shares of the same live workload. Compare like-for-like routes and users where possible, and include business outcomes: a version returning HTTP 200 with a missing order is not a successful canary. Schema and message changes need compatibility across both versions; expand–migrate–contract delays irreversible removal until older instances and data are accounted for.

Worked exampleinitial canary exposure

Consider a service receiving 20,000 requests per second. Assume the canary receives exactly 1% for five minutes and every canary request is affected by a new defect. Its rate is 20,000 × 0.01 = 200 requests/s; five minutes is 5 × 60 = 300 s, so at most 200 × 300 = 60,000 requests follow the faulty version during that interval. Check: the full service receives 20,000 × 300 = 6,000,000 requests, and 60,000 ÷ 6,000,000 = 0.01. The cap holds only if routing really stays at 1%, and the defect must produce a signal the comparison can detect before traffic widens.

Measure a canary against a comparable baseline

A canary decision needs a question, a baseline, enough observations, and a stop rule before traffic is sent. Compare the same route, region, client type, and time period where practical. If the canary receives only internal users or one low-risk endpoint, its clean result says little about checkout. A rare failure may not appear in a small sample even when the version is defective. Track sample counts with rates; a zero observed failure rate in ten requests is weak evidence. Use bounded guardrails for obvious regressions such as crash loops or missing confirmations, and allow a longer observation period for delayed outcomes that cannot fail within the first minute.

Rollout stages should increase exposure only after the previous stage has completed its observation window and any queued work has reached a meaningful outcome. A background worker can keep processing old messages after the frontend has moved on, and a client application may remain on an older version for weeks. A rollback plan must therefore account for code, schema, messages, and state written by the new version. Reversing the traffic route does not remove new-format records already stored. If old code cannot read those records, the nominally fast rollback may fail exactly when needed.

Make data changes compatible with both versions

Expand–migrate–contract separates a data change into safe stages. First add a nullable field or new structure that old code can ignore. Next deploy readers that accept both old and new representations, then writers that produce the new one. Backfill old records in bounded batches with progress and correctness measurements. Only after readers, writers, stored data, and delayed messages have converged should the old representation be removed in a later release. The safe order depends on the actual contract: a new required field cannot be introduced while an old producer still omits it, and a column cannot be dropped while any old process reads it.

Backfills are operational workloads. They consume database capacity, may compete with user traffic, and can fail halfway through. Make each batch restartable, record a cursor or completion state, and measure rows scanned, changed, rejected, and remaining. Check a sample of results and an invariant across the full dataset. If the backfill is paused, new writes must still produce a representation that both versions understand. A migration should have a stop condition for rising latency or replication lag, not only a success message when the script exits.

Worked exampleestimating a backfill window

Consider 12 million existing records. Assume a migration safely updates 2,000 records per second while production traffic continues. Its ideal processing time is 12,000,000 ÷ 2,000 = 6,000 seconds, or 6,000 ÷ 60 = 100 minutes. Assume it pauses for 20 minutes during a traffic peak and spends another 10 minutes retrying rejected batches. The planned elapsed window is at least 100 + 20 + 10 = 130 minutes. Check: 2,000 records/s for the 100 active minutes processes 2,000 × 100 × 60 = 12,000,000 records. This estimate assumes uniform processing cost; a skewed partition or slow index update can extend it. The rollout should retain the old format until verification shows all required records and delayed messages are compatible.

Control configuration and flags as changes

Configuration can change behaviour faster than code. Review and stage changes to timeouts, retry budgets, connection pools, routing, and feature flags with the same attention given to deployments. A timeout that is too short can cause retries and amplify load; a concurrency increase can saturate a shared database. Record who changed a value, when, and what outcome was expected. Reconcile emergency console edits into the version-controlled definition afterward so the next deployment does not silently undo the fix. Test whether a kill switch remains reachable when the very service it controls is impaired.

Flags also create combinations that tests may miss. A flag may be enabled for a small group, then left on for months while its old path rots. Give each flag an owner and retirement condition. During a staged activation, compare outcomes for the enabled and disabled groups and account for users moving between them. A flag can stop new requests but cannot necessarily retract a queued job or reverse a completed write; the runbook must say what happens to work already in flight. Release safety is achieved by measuring and containing effects, not merely by having a switch.

When a canary is stopped, preserve enough evidence to learn from it. Record the version, configuration, traffic share, affected route, first and last bad events, and the observed state of queued or durable work. Verify that routing has returned, that error-budget burn has slowed, and that delayed failures are no longer arriving. Then decide whether affected data needs reconciliation. This makes “rollback complete” a claim about user outcomes rather than only a deployment status.

§7 · Capacity and recovery

Plan capacity and prove recovery

Operations closes the design loop by comparing actual traffic with the assumptions used to size the system. Forecast peak demand, include work caused by retries and recovery, and load-test the same traffic mix and key skew that production sees. The capacity limit is the rate at which the user-visible target still holds, not the rate at which a process merely remains alive. Keep room for a node or zone loss if that fault is within the availability goal.

Backups and replicas solve different problems. A replica can take traffic after a node failure but also copies a mistaken deletion. A protected backup and retained change history make recovery from corruption possible, while a restoration drill establishes how long it actually takes and which writes survive. RTO and RPO must be stated for a named scenario and compared with measurements from drills, not inferred from the existence of backups.

The diagram shows the operating loop from measurement to verified recovery.

System flow
Measured demand → forecast → load test → capacity decision → running service
       ↑                                              │
       └──── outcome and saturation measurements ─────┘

Backup → isolated restore → correctness checks → measured RTO and RPO

The upper loop revises capacity as demand changes. The lower path tests whether stored recovery material can become a working service within the required time and data-loss bounds.

Worked examplecapacity after one instance fails

Consider a forecast peak of 900 requests per second. Assume a tested instance meets the latency target at no more than 350 requests per second, and assume one instance may fail while the peak continues. With all instances healthy, the arithmetic minimum is ceil(900 ÷ 350) = 3. To keep serving after one fails, provision 3 + 1 = 4 instances. Each of the three survivors then receives 900 ÷ 3 = 300 requests/s, below the tested 350. Check: 3 × 350 = 1,050 requests/s, above the 900 target, whereas two survivors would offer only 2 × 350 = 700 requests/s. This assumes traffic can be redistributed evenly and the shared dependencies can handle the same peak.

Measure the bottleneck under representative demand

A useful load test specifies the request mix, payload sizes, client concurrency, key distribution, and duration. A service that handles 1,000 cached reads per second may fail at a much lower rate when writes require a database transaction. A uniform key distribution can hide one popular account or product that concentrates work on a partition. Include background tasks, retries, scheduled jobs, and telemetry overhead. Warm-up matters because caches, connection pools, and just-in-time compilation can change behaviour after startup. Run long enough to expose queue growth and resource leaks rather than reporting only a brief peak throughput.

Observe both offered load and completed useful work. If clients send requests faster than the service can finish them, an open-loop test reveals queueing and latency growth. A closed-loop test in which each client waits for a response before sending another may reduce its offered rate as the service slows, making overload look deceptively stable. Record in-flight work, queue age, saturation, timeouts, and actual completion rate alongside response latency. Define the capacity point as the highest sustained load at which the user-visible SLO and correctness invariants still hold. The point where the process stops responding is too late to guide safe operation.

Shared resources constrain scaling. Adding API instances does not help if each adds a connection pool that exceeds the database's connection limit. More workers can make a lock hot spot or downstream rate limit worse. Test the entire path after a node or zone is removed, including load balancer convergence, cache misses, replica promotion, and retries. Headroom should cover the largest specified failure while maintaining acceptable latency, not only the average utilization on a normal day. Forecasts should be revised against actual traffic and new product behaviour, especially after a launch changes the request mix.

Worked examplepool growth after scaling out

Consider a database that can safely serve 600 concurrent application connections. Assume each API instance is configured with a pool of 80 connections. Six instances can open up to 6 × 80 = 480 connections, leaving 600 − 480 = 120 for other clients and failure recovery. If autoscaling adds four instances without changing the pool, the potential becomes 10 × 80 = 800, exceeding the safe level by 800 − 600 = 200. Check: a per-instance cap of 50 at ten instances would produce 10 × 50 = 500, leaving 100 for other uses under the same assumptions. The actual safe setting also depends on query cost and the connections needed by workers or administrators; pool size alone is not throughput.

State the failure scenario behind recovery targets

RTO and RPO have meaning only with a named disruption. Restoring one accidentally deleted row, recovering from a corrupted database, and losing a whole region require different procedures and may have different targets. RTO begins at the specified failure or detection point and ends when the required function is verified for users, not when a new database process starts. RPO compares the latest recoverable committed state with the state at the failure time. A replica that shares corrupt writes can have a very small replication lag and still be unsuitable for corruption recovery. Protected, independently retained backups and change history address that different failure mode.

Restoration drills should use the same access, keys, network paths, and backup catalogue that a real incident would require. Restore into an isolated environment to avoid overwriting healthy production data. Verify counts, checksums or application-level invariants, a representative read, and a representative write where safe. Then measure how long routing, dependencies, credentials, and client access take to restore. Record the timestamp of the latest recovered write. A backup job's successful exit confirms that bytes were stored; it does not establish that the service can use them, that the snapshot is recent enough, or that the recovery procedure fits the target.

Worked examplemeasuring a restore

Consider a disruption at 14:00. Assume the last recoverable committed write is timestamped 13:52 and the restored service passes user-journey checks at 14:47. The measured RPO is 14:00 − 13:52 = 8 minutes; the measured RTO is 14:47 − 14:00 = 47 minutes. Check: if the targets for this scenario are RPO at most 10 minutes and RTO at most 60 minutes, this drill passes both by 2 and 13 minutes respectively. Those margins are small if detection, authorization, or routing takes longer in a real incident. If the drill started its timer only when restoration began at 14:15, reporting 32 minutes as RTO would omit 15 minutes of outage and misstate the user impact.

Recovery design should also say how to handle writes accepted during a degraded period. If a service switches to read-only mode, that is a visible change to the user promise and belongs in the incident communication and SLI classification. If writes are buffered for later replay, they need durable storage, deduplication, ordering rules, and a test of reconciliation after the main store returns. A recovery plan that restores infrastructure but leaves ambiguous or duplicated business actions unresolved has not restored the journey. Measure completion of those delayed actions separately from the initial return of the request path.

§8 · Incident management

Coordinate incidents and learn from them

Detection and diagnosis are only part of operating a service. During an incident, several people may investigate different components, change configuration, and communicate with users at once. Without coordination, two well-meant actions can conflict: one responder restores a database while another replays jobs against it, or a release continues while a dependency is failing. Assign one coordinator, one place for the current status and timeline, and explicit owners for containment, investigation, and communication. These roles can be held by a small number of people, but the responsibilities should remain distinct.

Start with impact: which journeys are failing, where, when the failure began, how many users or operations are affected, and whether the scope is growing. State what is known and what remains uncertain. Avoid committing to a root cause before testing the evidence. A recent deployment is a useful clue, yet a provider outage or traffic shift may have started at the same time. Choose a containment action that reduces harm while preserving enough evidence to investigate. A rollback, rate reduction, read-only mode, or disabling an optional feature may be appropriate; each has a different effect on users and queued work.

The diagram shows how incident work moves from impact to verified recovery while maintaining a shared timeline.

System flow
Detect impact → assign coordinator → contain → diagnose → repair → verify
       │                 │                       │                 │
       └→ shared timeline┴→ status updates       └→ preserve evidence
                                                      ↓
                                             review and follow-up

Read the upper line as the response sequence, not a strict one-way pipeline. Diagnosis can lead to a new containment decision, and verification can reveal that the first repair was incomplete. The lower paths keep decisions and evidence available to other responders and to the later review.

Record a timeline that supports decisions

Record when the first user-visible bad event occurred, when detection fired, when someone acknowledged it, which actions were taken, and when each outcome recovered. Use a consistent time zone and distinguish event time from the time a person discovered it. Preserve links to dashboards, trace examples, release identifiers, and relevant log queries. A timeline helps identify detection delay, coordination delay, and repair time separately. If the latest successful synthetic check was at 10:00 and the first failed check was at 10:05, the onset is within that interval unless another signal narrows it; do not report 10:05 as exact onset without evidence.

Keep a decision log beside the timeline. It should explain why a risky action was chosen, its expected effect, who owns it, and the observation that would cause reversal. This prevents a later shift from repeating a failed experiment or assuming an earlier rollback completed. During a long incident, hand off unresolved questions, temporary mitigations, and the state of queued or partially processed work. A responder joining later should be able to tell which facts are confirmed and which are hypotheses.

Communicate the user impact

Status updates should describe the affected function and current mitigation in plain language, with a next update time if the issue continues. Internal detail such as a database lock or failing collector may be useful to responders but may not describe the user's experience. Avoid claiming full recovery because an error rate has fallen while a backlog still contains delayed orders. Conversely, a checkout path may be restored while an optional recommendation feature remains impaired; distinguish the two. Keep customer-facing and internal timelines consistent, and correct earlier statements when later evidence changes the assessment.

Worked exampleseparating response intervals

Consider a checkout incident whose first confirmed bad event is at 09:02. Assume an alert fires at 09:07, a responder acknowledges it at 09:10, a containment switch takes effect at 09:22, and the final affected order is reconciled at 10:05. Detection delay is 09:07 − 09:02 = 5 minutes; acknowledgement delay is 09:10 − 09:07 = 3 minutes; time from acknowledgement to containment is 09:22 − 09:10 = 12 minutes. The path stops creating new failures after 09:22 − 09:02 = 20 minutes, but complete outcome recovery takes 10:05 − 09:02 = 63 minutes. Check: 5 + 3 + 12 = 20, and the remaining reconciliation period is 63 − 20 = 43 minutes. Reporting only the 20-minute containment time would omit the users still waiting for correct orders.

Verify recovery and improve the system

Recovery requires more than the disappearance of the triggering alert. Confirm a fresh user journey succeeds from the relevant edge, the error or latency indicator has returned within its objective, the backlog drains, and the affected data is reconciled. Verify that temporary flags, routing changes, credentials, and extra capacity are tracked for cleanup. If a dependency is still degraded, state the remaining risk. An incident should close only when the required outcome is restored or a documented, accepted degraded mode is in place.

A postmortem reconstructs the incident from evidence and asks why the system allowed the impact and why detection or response took its measured time. Focus on conditions that can be changed: a missing confirmation invariant, a shared timeout that amplified retries, a canary without the affected route, or a restore process that lacked a key. Separate the triggering event from these contributing conditions. Assign follow-up changes to owners with a way to verify completion; “be more careful” is not testable. Review whether the same pattern could affect another journey. Google's SRE Workbook discussion of postmortems describes using incident records to find recurring system weaknesses.

Incident work creates operational data of its own. Track detection delay, time to containment, time to full outcome recovery, repeat incidents, and the share of follow-up actions that were actually verified. These numbers are useful only with context: a complex data corruption may take longer than a failed deployment even when the response is effective. Use trends and individual reviews to improve signals and procedures, not to rank responders by a single stopwatch value. The next release, alert rule, or restoration drill should reflect what the incident taught about the user's journey.

· · Review

Common mistakes

Each entry below names a mistake, explains why it arises, and gives the correction. The entries follow the order of the sections they relate to, from §2 through §8.

Defining success as an HTTP 200 response

Why it happens
Server status is easy to count, while completion of a business transition, such as a durable order confirmation, may occur later and elsewhere.
Correction
Define the good event at the user outcome, including latency and correctness, and measure it from a point that sees the relevant failures.

Labeling a metric with a user or request identifier

Why it happens
The label makes a dashboard filter convenient for one investigation, but it multiplies the number of stored series by a large and growing population.
Correction
Keep bounded dimensions on metrics and record individual identities in protected log or trace fields.

Paging on symptoms without a response policy

Why it happens
Thresholds on every resource spike or nonzero invariant count are easy to set, but a transient fluctuation or an expected in-flight state may not need a person.
Correction
Alert on sustained user impact or a genuinely broken invariant, assign an owner, and link a tested runbook.

Trusting a canary's clean HTTP error rate

Why it happens
The new code may return plausible but incorrect data, or the canary's small traffic share may not exercise the affected route.
Correction
Compare business outcomes and route coverage between versions, and keep old and new data formats compatible until the rollout is complete.

Treating backups as verified recovery

Why it happens
A backup's existence is easy to confirm, but a snapshot may be unreadable, incomplete, inaccessible during an outage, or too slow to restore.
Correction
Restore into an isolated environment, check application invariants, and measure the actual RTO and RPO.

· · 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)

A checkout alert shows a rising bad-request ratio. What different questions should a metric, a trace, and a structured log answer during diagnosis?

Answer

The metric shows how many eligible checkouts fail, when the increase began, and which bounded route or region dimensions are affected. A trace follows one affected checkout through its services and shows where time or failure occurred. A structured log records the decision or state transition at that point, using the same correlation ID so the event can be tied to the trace and the original request.

Question 2 (calculation)

An API receives 8 million eligible requests in a measurement window and has a 99.95% good-request SLO. How many bad requests can it tolerate, and what fraction of the budget has been used after 1,200 bad requests?

Answer

The bad fraction is 1 − 0.9995 = 0.0005. The budget is 8,000,000 × 0.0005 = 4,000 bad requests. After 1,200, the used fraction is 1,200 ÷ 4,000 = 0.30, or 30%; 4,000 − 1,200 = 2,800 remain. Check: 8,000,000 − 4,000 = 7,996,000 good requests, and 7,996,000 ÷ 8,000,000 = 0.9995.

Question 3 (calculation)

A metric has 6 route labels, 3 status classes, 4 regions, and 5 instances. Assuming every combination occurs, how many series does it produce? What happens if a label with 20,000 distinct customer IDs is added and every combination occurs?

Answer

The original count is 6 × 3 × 4 × 5 = 360 series. The customer label raises the upper bound to 360 × 20,000 = 7,200,000 series. Check: 7,200,000 ÷ 360 = 20,000, the factor introduced by that label. Actual counts depend on which combinations occur, but the risk follows from the multiplicative bound.

Question 4 (application)

A canary returns HTTP 200 and has normal latency, but some orders are missing their confirmation event. Which release signals and response should change?

Answer

Count durable order confirmations and missing confirmation events as outcome or invariant signals, segmented by version so the canary can be compared with the old version. Stop widening the canary and route its traffic back if the missing-event condition is confirmed. Preserve the event records or repair path needed to reconcile affected orders, and do not remove old schema or message support until both versions and the backlog are accounted for.

Question 5 (open-ended)

An online shop expects a seasonal traffic peak, sometimes loses its recommendations service, and needs to deploy a new order schema without stopping checkout. Describe the observability, alerting, rollout, capacity, and recovery decisions that should be made together.

Answer

Define good checkout and browsing events, their measurement window, and the permitted bad-event budget. Emit request rate, error and duration metrics; bounded resource saturation metrics; a correlated trace across checkout; and structured logs for order state changes. Alert on user impact and broken order invariants, with an owner and a runbook. Keep recommendations optional with a visible fallback signal, and test the missing dependency under peak load. Forecast the seasonal peak, load-test its traffic mix and one-instance loss, and leave capacity headroom for that failure. Add the new schema compatibly, backfill and verify it, then canary new code while comparing order outcomes against the old version; remove the old structure only after every instance has moved. Maintain protected backups, rehearse a restore, and measure recovery time and surviving writes against scenario-specific RTO and RPO targets.

Question 6 (application)

A checkout alert fires after a canary release. Traffic is routed back to the old version within 15 minutes, but some accepted orders remain unconfirmed in a queue. What should the incident team record, communicate, verify, and change before closing the incident?

Answer

Record the first bad user outcome, alert and acknowledgement times, canary version and traffic share, rollback time, affected order identifiers in protected records, and any uncertain cases. Coordinate containment and reconciliation under one incident owner. Communicate that new failures have stopped while previously accepted orders may still be delayed; give a next update time. Verify fresh checkouts through the public path, check SLO recovery and the age of queued work, then reconcile or safely replay each affected order without duplicating payment or confirmation. Close only when the required outcome is restored or a documented degraded mode is accepted. In the review, test why the canary comparison missed delayed confirmations and add an outcome or invariant signal, a stop rule, and a regression test for the queued path.

· · Finish

Review checklist

Without consulting notes, a reader should be able to define observability and operations from user outcomes; specify an SLI, SLO, and error budget and recompute the budget; choose metrics, logs, traces, and correlation fields for a distributed journey; estimate metric cardinality and plan sampling and retention; connect external checks and invariant alerts to an actionable runbook; stage a release and compatible schema change with outcome-based comparison; plan capacity and verify recovery with load and restoration tests; and coordinate an incident from first impact through verified recovery and a useful postmortem. A reader who can do all of these has covered the material.