Debugging Production Incidents
local graph
Chapter 12 — Debugging Production Incidents
Section titled “Chapter 12 — Debugging Production Incidents”In Chapter 11, we learned to classify a slow database span into three failure modes: query plan regression, connection pool starvation, and lock contention. In Chapter 10, we learned to diagnose async starvation by separating I/O wait from scheduler contention. In Chapter 9, we used flamegraphs to find CPU hot paths and allocation-heavy code. In Chapter 8, we built SLO burn-rate alerts that fire before users complain. Each chapter solved one type of problem with one set of tools.
Real incidents do not arrive pre-classified.
The alert says “checkout is degraded.” The on-call engineer does not know whether the cause is a plan regression, pool starvation, executor contention, a deployment regression, or a combination of these. The trace points to one service. The metrics say something different. The root cause turns out to be in a background task that the engineer has never touched.
This chapter puts you in the on-call seat. One incident, multiple misleading signals, and the full toolkit from the book. The investigation pivots twice before reaching the root cause, which is three layers deep from where the symptom appeared. No new instrumentation is added. No new tools are introduced. Everything you need was built in Chapters 4 through 12.
The first half of this chapter is a case study: a compound production incident in the OpenTel E-Commerce system. The second half extracts a repeatable incident response workflow, a post-mortem template, and a runbook structure that you can adapt to your own systems.
What this chapter covers:
- How to triage a multi-service incident using SLO burn-rate alerts
- How to follow a distributed trace across services to narrow the investigation
- How to correlate metrics, logs, and traces to distinguish symptoms from causes
- How to identify a compound incident where multiple failure modes interact
- How to build a repeatable incident response workflow and runbook
- How to measure the operational return of the observability stack built across this book
The Incident: Checkout Degrades Under Load
Section titled “The Incident: Checkout Degrades Under Load”It is Friday afternoon. Traffic is elevated due to a promotional campaign that launched earlier in the week, roughly 2.5 times normal volume. The campaign offers discounted bundles and free gift messages, which have driven a sustained increase in checkout activity. The on-call engineer receives the CheckoutLatencyBurnCritical alert. The page states that the latency error budget is burning above the critical threshold over both the long and short windows (per the multi-window burn-rate method defined in Chapter 8).
The timing is not ideal. Friday afternoon means the team that deployed the most recent changes has already started winding down. The engineer will need to investigate with partial context about what changed recently.
The engineer opens Grafana and checks the dashboard (see Chapter 8). Four numbers tell the story:
| Signal | Normal | During Incident |
|---|---|---|
| Checkout P99 | 1.1s | 6.2s |
| Latency SLI compliance | 99.7% | 78.4% |
| Error rate | 0.1% | 2.1% |
| Revenue per hour | $4,200 | $2,730 (-35%) |
Table 12.1 – Checkout business signals at the start of the incident: P99 latency, SLI compliance, error rate, and revenue per hour
The classification is immediate, as latency is the primary symptom; errors are secondary. The 2.1% error rate is almost certainly timeout driven, checkouts that exceeded the client’s patience, not hard failures. This is a degradation, not an outage; availability is intact. Customers can still complete purchases, but at 5-6 seconds per checkout, a meaningful share are abandoning.
The engineer opens a shared incident channel, attaches the dashboard screenshot, and logs the initial classification: Checkout latency degradation, P99 at 6.2s, error rate 2.1%, likely timeout-driven, revenue impact down 35%. Investigating.
That classification matters because it determines where to look first. A latency incident without a matching error spike usually points to a saturated resource, not a broken one. Something in the checkout path is slow, not failing.
Step 1: Open Jaeger, Search for Slow Traces
Section titled “Step 1: Open Jaeger, Search for Slow Traces”The engineer opens Jaeger and filters for checkout traces in the incident window with a duration greater than 3 seconds — well above the normal 1.1s P99 but low enough to capture the full range of degraded traces, not just the worst outliers. The pattern emerges within a few traces. Here is a representative one:
otelmart: POST /api/checkout [==========] 6.2s +- orders: POST /orders [=========] 5.9s +- HTTP POST /products/validate [=] 38ms +- HTTP POST /inventory/reserve [========] 5.1s | +- inventory: POST /reserve [========] 5.0s | +- SELECT reserve_stock [=======] 4.6s +- TRANSACTION checkout [=] 580msFigure 12.1 – Initial incident trace: a 6.2-second checkout dominated by SELECT reserve_stock at 4.6 seconds (the misleading symptom)
The product validation call is fast (38ms). The checkout transaction is normal (580ms). The dominant span is SELECT reserve_stock in the Inventory service, with a duration of 4.6 seconds. That is where the time is going.
The engineer’s first hypothesis - this looks like a database plan regression. In Chapter 11, we saw exactly this pattern when an index degraded after a batch import. The same span, the same service, the same shape. The SELECT reserve_stock query slowed from milliseconds to seconds because PostgreSQL was scanning too many pages.
That hypothesis is reasonable. Whether the data supports it is worth a closer look, as the next section puts it to the test.
Step 2: Identify the Bottleneck (Not What It Seems)
Section titled “Step 2: Identify the Bottleneck (Not What It Seems)”The engineer opens the Chapter 11 database dashboard for the Inventory service. Three panels tell a different story than the trace suggested:
| Metric | Normal | During Incident |
|---|---|---|
db.client.connection.count{state=idle} | 4-6 | 0 |
db.client.connection.count{state=used} | 4-6 | 10 (maximum) |
db.client.connection.wait_time P99 | < 5ms | 3,200ms |
otelmart.db.exec.duration_ms P99 | 8ms | 45ms |
Table 12.2 – Inventory pool and execution metrics during the incident, showing pool drain rather than slow execution
The execution duration is 45 milliseconds. That is slightly elevated from the normal 8ms, but nowhere near the 4.6 seconds the trace showed. The query is not slow. The span is slow because it includes 3.2 seconds of pool wait time. The pool is drained: zero idle connections, all 10 connections in use, and new requests wait over 3 seconds for a free connection.
This is the pool starvation pattern from Chapter 11, Section 11.4. The trace looked like a plan regression because the span duration combines pool wait and execution into one number. Without the Chapter 11 instrumentation that separates otelmart.db.pool.wait_ms from otelmart.db.exec.duration_ms, the engineer might have spent the next several minutes analyzing query plans for a query that is perfectly healthy.
When a database span is slow but otelmart.db.exec.duration_ms is normal, stop investigating the query. The problem is upstream of execution. Check what is consuming or blocking the connection pool.
The engineer updates the incident channel: execution is healthy at 45ms; the pool is fully drained with zero idle connections and a wait time of 3.2 seconds. The next question is, what is holding those connections open?
Before diving deeper into the pool drain, the engineer also checks two other dashboards for negative evidence:
Chapter 10 async dashboard: healthy. Queue depth near zero, in-flight normal, queue wait flat. The Tokio runtime is not the bottleneck.
Chapter 9 profiling signals: CPU utilization and memory allocation are normal across all services, and no flamegraph anomaly. The bottleneck is not in the application code.
These healthy dashboards are as important as the unhealthy ones. They help narrow the investigation significantly, as async contention and application-level regression can both be ruled out, focusing attention squarely on the database layer.
Step 3: Trace the Pool Drain to Lock Contention
Section titled “Step 3: Trace the Pool Drain to Lock Contention”The pool is drained. All 10 connections are in use. But the queries are fast. So what is holding the connections?
A good starting point when the pool is drained, but queries appear healthy is pg_stat_activity (for PostgreSQL, other databases have similar views). It surfaces all active database sessions, their current wait states, and any lock-wait events, making it possible to identify exactly which sessions are holding connections and why. Running it here reveals a clear pattern:
SELECT pid, state, wait_event_type, wait_event, now() - xact_start AS tx_age, left(query, 80) AS query_snippetFROM pg_stat_activityWHERE state <> 'idle'ORDER BY xact_start;The output would reveal a clear pattern:
| pid | state | wait_event_type | tx_age | query_snippet |
|---|---|---|---|---|
| 201 | idle in transaction | 00:00:08.4 | UPDATE product_inventory SET stock_quantity... | |
| 202 | idle in transaction | 00:00:07.1 | UPDATE product_inventory SET stock_quantity... | |
| 203 | idle in transaction | 00:00:06.3 | UPDATE product_inventory SET stock_quantity... | |
| 204 | active | Lock | 00:00:04.6 | SELECT reserve_stock(...) |
| 205 | active | Lock | 00:00:03.9 | SELECT reserve_stock(...) |
| 206 | active | Lock | 00:00:02.7 | SELECT reserve_stock(...) |
| 207 | active | Lock | 00:00:01.8 | SELECT reserve_stock(...) |
| 208-210 | active | 00:00:00.x | Various checkout queries |
Table 12.3 – pg_stat_activity snapshot during the incident: three reconciliation sessions idle in transaction and four reservation queries blocked on lock waits
PIDs 201-203 are the root of the problem. They are in idle in transaction state with transaction ages of 6-8 seconds. Each one has executed an UPDATE product_inventory statement and is waiting for the application to commit the transaction. While they wait, they hold row locks on the product_inventory table.
The term “idle in transaction” can be misleading. It does not mean the work has stalled or that the transaction is doing nothing. PostgreSQL reports this state when the database has finished executing the last SQL statement, but the application has not yet sent the next statement or committed. In this case, the application thread is busy making an HTTP call to the warehouse API. The database session is idle from PostgreSQL’s perspective because no SQL is running, but the transaction remains open, and all row locks acquired by earlier statements are still held. This is the core of the problem: the application is doing useful work (the API call), but the database resources (locks and connections) are held hostage for the duration of that external I/O.
PIDs 204-207 are checkout reservation queries. They are blocked on Lock wait events, waiting for the rows held by PIDs 201-203. Each blocked reservation is also holding a database connection. Those connections cannot return to the pool until the lock clears.
To confirm the blocking relationship, joining pg_locks (see chapter 11) with pg_stat_activity is the recommended approach. This query reveals which sessions are actively blocking others, and which specific queries are caught in the wait chain:
SELECT blocked.pid AS blocked_pid, left(blocked.query, 40) AS blocked_query, blocking.pid AS blocking_pid, left(blocking.query, 40) AS blocking_queryFROM pg_stat_activity blockedJOIN pg_locks bl ON blocked.pid = bl.pid AND NOT bl.grantedJOIN pg_locks gl ON bl.locktype = gl.locktype AND bl.relation = gl.relation AND gl.grantedJOIN pg_stat_activity blocking ON gl.pid = blocking.pidWHERE blocked.pid != blocking.pid;| blocked_pid | blocked_query | blocking_pid | blocking_query |
|---|---|---|---|
| 204 | SELECT reserve_stock(...) | 201 | UPDATE product_inventory SET... |
| 204 | SELECT reserve_stock(...) | 202 | UPDATE product_inventory SET... |
| 205 | SELECT reserve_stock(...) | 201 | UPDATE product_inventory SET... |
| 206 | SELECT reserve_stock(...) | 203 | UPDATE product_inventory SET... |
| 207 | SELECT reserve_stock(...) | 201 | UPDATE product_inventory SET... |
Table 12.4 – pg_blocking_pids() output showing every blocked reservation waiting on one or more of the three reconciliation sessions
The blocking relationship is unambiguous. Every blocked reservation (204-207) is waiting on one or more of the reconciliation sessions (201-203). PID 201 alone is blocking three different checkout queries.
What is emerging is a compound failure of two patterns from Chapter 11 interacting. Lock contention from PIDs 201-203 triggers pool starvation in PIDs 204-207: blocked queries hold connections, held connections drain the pool, a drained pool queues new queries, and queued queries wait even longer. Each layer amplifies the next.
Structured logs in Loki are the next place to look. The transaction-duration warning instrumented in Chapter 11 can pinpoint exactly when the long transactions began, connecting a database-level symptom to an application-level timeline:
{ "timestamp": "2026-03-20T15:38:12.447Z", "level": "WARN", "message": "Long database transaction", "transaction.name": "inventory_reconciliation", "otelmart.db.transaction.duration_ms": 7842.3, "trace_id": "8b2c1d4e5f6a7b8c9d0e1f2a3b4c5d6e"}The transaction name inventory_reconciliation tells an important story. This is not a checkout transaction at all, but a background task responsible for reconciling stock levels with an external warehouse system. More significantly, the warnings started at 3:38 PM, a full seven minutes before the SLO alert fired. The problem was already underway before the engineer was even paged.
Now the engineer has two questions: why is this background task holding transactions for 8 seconds, and when did it start behaving this way?
The transaction.name field in the structured log connects a database-level symptom (long idle times in transaction sessions) to an application-level cause (a specific background task). Without that field, the engineer would see the UPDATE product_inventory query in pg_stat_activity but would have to search the code to figure out which application path generated it. This is why the structured logging strategy from Chapter 7 matters: context on logs bridges the gap between database views and application code.
Step 4: The Root Cause
Section titled “Step 4: The Root Cause”Checking the deployment annotations on the Grafana dashboard surfaces a critical data point: a deployment went out at 3:35 PM. That was ten minutes before the alert fired, and just three minutes before the first long-transaction warnings appeared in Loki. The release notes point directly to the inventory service, specifically a change to the inventory_reconciliation background task. The timeline is starting to connect.
The engineer pulls up the code diff. Before the deployment, the reconciliation task looked like this:
// Before: small batch, infrequent, but HTTP call inside transactionlet reconciled = with_transaction(pool, "inventory_reconciliation", |tx| { Box::pin(async move { let products = db::get_stale_products(tx, 50).await?; for p in &products { let actual = warehouse_api::get_stock_count(p.uuid).await?; if actual != p.stock_quantity { db::update_stock(tx, p.uuid, actual).await?; } } Ok(products.len()) })}).await?;// Scheduled every 30 minutesThe diff points to two specific changes. The batch argument in get_stale_products(tx, 50) was removed, so the task now fetches all stale products, roughly 2,000 in this system. The schedule comment changed from every 30 minutes to every 5 minutes. Critically, the warehouse_api::get_stock_count call remained inside the transaction boundary, so the architectural issue was always there, but the old parameters kept the lock window small enough to go unnoticed.
The engineer searches Jaeger for traces from the reconciliation task during the incident window. The trace confirms the problem:
inventory: inventory_reconciliation [===================] 7.8s +- TRANSACTION inventory_reconciliation [===================] 7.8s +- SELECT get_stale_products [=] 12ms +- HTTP GET warehouse/stock/a7f3c5d2 [====] 3.2s +- UPDATE product_inventory (a7f3c5d2) [=] 4ms +- HTTP GET warehouse/stock/b8d4e7f1 [===] 2.8s +- UPDATE product_inventory (b8d4e7f1) [=] 3ms +- HTTP GET warehouse/stock/9c451a99 [==] 1.9s +- ... (hundreds more HTTP + UPDATE pairs)Figure 12.2 – The inventory_reconciliation task trace showing wide transaction scope: hundreds of warehouse HTTP calls and UPDATE statements wrapped inside a single 7.8 second transaction
The transaction span wraps everything: the initial SELECT, all the HTTP calls to the warehouse, and all the UPDATE statements. The warehouse HTTP calls dominate the transaction duration. While each HTTP call is in flight, the transaction holds row locks on every product it has already updated. Those are the locks that block the checkout reservation queries.
The warehouse_api::get_stock_count call makes an HTTP request to an external warehouse system. Each call takes 2-8 seconds, depending on the warehouse’s response time. Under the old configuration (50 products every 30 minutes), the total transaction duration was short enough that it rarely overlapped with checkout reservations. The lock window was narrow and, with only 50 products per run, rarely overlapped with concurrent checkout traffic.
Under the new configuration (2,000 products every 5 minutes), the transaction holds row locks on the product_inventory table for the entire duration of the warehouse API calls. With 2,000 products and 2-8 seconds per call, the transaction can hold locks for minutes. During that window, every checkout reservation query that touches the same rows is blocked.
The compound effect forms a feedback loop. The reconciliation task opens a transaction and begins updating product inventory rows. The warehouse API call takes seconds, and during that time, the transaction holds row locks. Concurrent checkout reservations arrive and try to acquire locks on the same rows, but they are blocked. Each blocked query holds a database connection while it waits, so the connection pool drains to zero idle connections. New reservation requests then queue for pool connections, adding 3+ seconds of wait time on top of the lock wait. The checkout P99 climbs from 1.1 seconds to 6.2 seconds.
This is the “wide transaction scope” anti-pattern from Chapter 11, Section 11.5, triggered not by a code refactor but by a configuration change in a deployment. The code always had the HTTP call inside the transaction, but the old batch size and frequency masked the problem. The deployment removed that mask.
The root cause is not a traditional bug; the reconciliation task works correctly. The problem is operational: the transaction scope is too wide for the new batch size and frequency. Under low concurrency, wide transactions are harmless, but under elevated traffic, they create lock contention that cascades into pool starvation.
Step 5: Fix and Recovery
Section titled “Step 5: Fix and Recovery”At this point, the investigation has a clear answer: the deployment at 3:35 PM is the root cause. The fastest path to recovery is a rollback.
Immediate mitigation: roll back the deployment. The reconciliation task reverts to the old frequency (every 30 minutes) and batch size (50 products).
Rollback is appropriate here because the deployment was recent, limited to a single configuration change, and was clearly correlated with the incident timeline. That is not always the case. In many production systems, rollbacks can introduce their own risks: schema migrations that ran during deployment may not be backward-compatible, caches may hold data shaped by the new code, and downstream services may have already adapted to changed behavior. Before treating rollback as a default first response, verify that the previous version is still compatible with the current state of the database, caches, and dependent services. When rollback is not safe, other mitigations such as feature flags, configuration overrides, or targeted traffic shedding may be more appropriate.
The rollback goes out at 3:52 PM — seven minutes from alert to action. Recovery is visible almost immediately:
| Time After Rollback | Signal | Value |
|---|---|---|
| +30 seconds | Long transaction warnings | Stopped |
| +1 minute | Pool idle connections | Recovering (3-4) |
| +2 minutes | db.client.connection.wait_time P99 | Below 10ms |
| +3 minutes | Checkout P99 | 1.2s (near normal) |
| +5 minutes | Latency SLI compliance | Climbing toward 99% |
| +15 minutes | Revenue per hour | Recovered to $4,100 |
Table 12.5 – Recovery signals at increasing intervals after the rollback
The recovery is fast because the feedback loop works in reverse. Once the reconciliation task stops holding wide transactions, the locks clear. Blocked reservations are complete, connections return to the pool, and new reservations acquire connections immediately. The checkout path returns to normal.
Proper fix (post-incident): the rollback is a temporary mitigation, but the reconciliation task still needs to run with the larger batch size and higher frequency. The product team wants more accurate stock levels, and the old 30-minute cadence was creating customer-visible inventory discrepancies.
The fix applies the narrow-transaction-scope pattern from Chapter 11, Section 11.5: move everything not required for atomicity outside the transaction boundary. In this case, that means the warehouse API call:
// After: HTTP call outside transaction, narrow lock window// Step 1: Read current stock levels (no transaction needed)let products = db::get_all_stale_products(pool).await?;
// Step 2: Fetch actual counts from warehouse (slow HTTP, NO transaction)let actuals: Vec<i32> = warehouse_api::get_stock_counts_batch(&products).await?;
// Step 3: Compute differences (application logic, no database).// Collect owned (Uuid, i32) pairs so the update step does// not borrow from \`products\` / \`actuals\` across the await.let diffs: Vec<(Uuid, i32)> = products .iter() .zip(actuals.iter().copied()) .filter(|(p, actual)| p.stock_quantity != *actual) .map(|(p, actual)| (p.uuid, actual)) .collect();
// Step 4: Update only the differences (narrow transaction, fast)if !diffs.is_empty() { with_transaction(pool, "inventory_reconciliation", move |tx| { Box::pin(async move { for (uuid, actual) in &diffs { db::update_stock(tx, *uuid, *actual).await?; } Ok(diffs.len()) }) }).await?;}The transaction now holds locks only for the UPDATE statements, which take roughly 50 milliseconds for a batch of differences. The warehouse API calls (2-8 seconds) happen entirely outside the transaction boundary. Under concurrent checkout traffic, the lock window is 50ms instead of minutes.
As an additional guardrail (after fixing the transaction scope, not in place of it), consider setting idle_in_transaction_session_timeout = '30s' for the application role used by the inventory service. This caps how long any transaction can sit idle, limiting the blast radius of a future wide-transaction incident. Choose the threshold and the role carefully — applying it globally can disrupt legitimate maintenance work or interactive debugging sessions (see footnote 1).
Step 6: Verify with Traces
Section titled “Step 6: Verify with Traces”The same Jaeger query that showed 6.2-second checkouts now shows:
otelmart: POST /api/checkout [==] 420ms +- orders: POST /orders [=] 380ms +- HTTP POST /products/validate [=] 35ms +- HTTP POST /inventory/reserve [=] 52ms | +- inventory: POST /reserve [=] 42ms | +- SELECT reserve_stock [=] 8ms +- TRANSACTION checkout [=] 180msFigure 12.3 – The same checkout trace after the rollback: SELECT reserve_stock returns to 8 milliseconds and total checkout drops to 420 milliseconds
The SELECT reserve_stock span dropped from 4.6 seconds to 8 milliseconds. The pool wait time disappeared. The lock contention cleared. The checkout is back to normal.
The Chapter 11 database dashboard confirms:
| Metric | During Incident | After Rollback |
|---|---|---|
db.client.connection.count{state=idle} | 0 | 5 |
db.client.connection.wait_time P99 | 3,200ms | 3ms |
otelmart.db.exec.duration_ms P99 | 45ms | 8ms |
| Long transaction warnings/min | 12 | 0 |
Table 12.6 – Inventory pool and execution metrics during the incident versus after the rollback
The execution duration also improved from 45ms to 8ms. The slight elevation during the incident was a secondary effect: when many queries compete for the same rows, even the ones that eventually acquire locks take slightly longer due to PostgreSQL’s internal lock management overhead. Once the contention cleared, execution returned to its true baseline.
The SLO dashboard shows latency SLI compliance climbing back toward 99.5%. The burn rate has dropped below 1x. The error rate is back to 0.1%. The engineer annotates the incident window in Grafana and closes the incident channel.
(1) - Why Settings Like_session_timeout Can Be a Bad Idea: https://www.percona.com/blog/human-factors-behind-incidents-why-settings-like-idle_session_timeout-can-be-a-bad-idea/
Incident Response Workflow
Section titled “Incident Response Workflow”The case study followed a specific investigation path, but the method generalizes. Every production incident, regardless of root cause, flows through five phases. This section extracts those phases into a repeatable framework.
Detection (Metrics and Alerts)
Section titled “Detection (Metrics and Alerts)”SLO burn-rate alerts from Chapter 8 are the first signal. They tell you something is wrong and how fast the error budget is burning, but not what caused it. What they do provide is a symptom classification (latency, availability, or correctness) and a quantified impact (burn rate, revenue drop).
In this incident, the CheckoutLatencyBurnCritical alert, firing at a 6.8x burn rate, classified the problem as a latency degradation; not firing at a 6.8x burn rate classified the problem as a latency degradation rather than an availability outage. That single classification directed the investigation toward saturated resources rather than broken ones.
Action: Open the business dashboard, classify the incident (latency, availability, or correctness), start the incident channel, and post the impact summary.
Investigation (Traces and Logs)
Section titled “Investigation (Traces and Logs)”Distributed traces from Chapters 4 and 5 narrow the investigation from “checkout is slow” to “this specific span in this specific service is slow.” The trace is the roadmap — it shows the full request path and highlights exactly where time accumulates.
Structured logs from Chapter 7 fill in what traces do not carry: threshold warnings, transaction durations, error details, and application-level identifiers like transaction.name that bridge the gap between a database symptom and its application-level cause.
In this incident, the trace pointed to SELECT reserve_stock in the Inventory service, and the structured logs connected it further to a transaction.name: inventory_reconciliation with duration warnings that had been firing for seven minutes before the SLO alert triggered.
Action: Find representative slow or failed traces, identify the dominant span, and check structured logs for context around the incident window.
Diagnosis (Dashboard Correlation)
Section titled “Diagnosis (Dashboard Correlation)”Domain-specific dashboards classify the failure mode. Each dashboard answers a different question:
- Chapter 10 async dashboard: is the Tokio runtime the bottleneck? (In this incident: No)
- Chapter 11 database dashboard: is it a plan regression, pool starvation, or lock contention? (In this incident: Pool starvation caused by lock contention)
Negative evidence is as valuable as positive evidence. A healthy dashboard narrows the investigation by ruling out an entire failure category before deep analysis begins. In this incident, the healthy async dashboard and normal profiling signals ruled out executor contention and application-level regression, focusing the remaining investigation squarely on the database layer.
When dashboard data does not match the hypothesis, pivot rather than persist, and ask what is upstream of the symptom. Two common mismatches and where to look next:
Mismatch 1: Pool starvation, but queries are fast. The pool is drained, and execution duration is normal, this was the pattern in this incident. The drain has an external cause: lock contention (pg_stat_activity shows idle in transaction sessions), N+1 query patterns (the trace shows a staircase of sequential spans), or a connection leak (idle connections drop monotonically and never recover).
Mismatch 2: Async queue wait is high, but downstream spans are normal. The executor is contending (see Chapter 10), not the dependencies. Check the Tokio Console for tasks with high busy time and low yield behavior. The likely cause is blocking code on an async worker thread.
Correlate with deployment logs, traffic changes, and infrastructure events. The root cause often precedes the alert by minutes. In this incident, the deployment at 3:35 PM preceded the alert at 3:45 PM by 10 minutes.
Action: Check each domain dashboard in sequence; record both positive and negative findings; follow mismatches to their upstream causes; correlate mismatches with their upstream causes; and correlate findings with deployment history.
Resolution (Fix and Deploy)
Section titled “Resolution (Fix and Deploy)”Apply the smallest fix that matches the proven failure mode. For compound incidents, fix the root cause first. The downstream symptoms (pool starvation, lock contention) resolve automatically once the root cause (a wide transaction scope introduced by the deployment) is fixed.
Rollback is a valid first response. In this incident, rolling back the deployment was the fastest path to recovery. The proper fix (restructuring the reconciliation task) was implemented post-incident with the benefit of calm analysis and code review.
Action: apply the fix, monitor the recovery signals.
Verification (Observability Confirms Fix)
Section titled “Verification (Observability Confirms Fix)”Use the same signals that detected the problem to verify the fix. The trace should show the span returning to baseline. The metrics should show the pool recovering, the wait time dropping, and the SLI compliance climbing.
Do not close the incident until the SLI compliance has recovered and the burn rate has returned to sustainable levels. In this incident, the engineer waited until the burn rate dropped below 1x before closing the channel.
Action: compare before/after traces, confirm metric recovery on the domain dashboard, verify SLI compliance on the business dashboard, annotate the incident window in Grafana, and close the incident channel.
Post-Mortem: Root Cause Analysis
Section titled “Post-Mortem: Root Cause Analysis”The post-mortem uses the investigation evidence as its foundation, not memory. Walk through the trace waterfall, the dashboard screenshots, the Loki queries, and the deployment log. Each piece of evidence supports or refutes the hypothesis:
- Trace showed slow
SELECT reserve_stock(4.6s)****. Initial hypothesis: query plan regression. - Pool metrics showed fast execution (45ms) but high wait time (3.2s) and zero idle connections. Hypothesis revised: pool starvation. But queries are fast, so the pool drain has an external cause.
pg_stat_activityshowedidle in transactionsessions fromUPDATE product_inventory. Hypothesis revised: lock contention from a background task holding wide transactions.- Structured logs showed
transaction.name: inventory_reconciliationwith 7.8-second durations starting at 3:38 PM. Root cause narrowed further, the reconciliation task is the source of the lock contention. - The deployment log showed the reconciliation task was modified at 3:35 PM. Root cause confirmed that the deployment widened the lock window by changing batch size and frequency.
The root cause chain connects in a straight line. The deployment changed the reconciliation task’s batch size from 50 to 2,000 products and increased its frequency from every 30m to 5m. The task already had an HTTP call inside the transaction boundary, so the new parameters widened the lock window from a few seconds to minutes. Under elevated traffic, checkout reservations blocked behind those locks, blocked reservations held database connections, and the pool drained to zero. New reservations then queued for connections, stacking wait time on top of lock wait. Checkout latency climbed from 1.1s to 6.2s.
Every layer of this chain was visible in the telemetry. The observability stack did not just detect the problem. It classified it, distinguished it from two similar-looking failure modes (plan regression and pure pool starvation), and connected the timeline to a specific deployment.
Post-Mortem: Timeline Reconstruction
Section titled “Post-Mortem: Timeline Reconstruction”Build the incident timeline from telemetry, not from memory. Each row cites a specific signal source:
| Time | Signal | Source | What It Shows |
|---|---|---|---|
| 3:35 PM | Deployment | CI/CD annotation in Grafana | Reconciliation task change deployed |
| 3:38 PM | Long transaction warnings begin | Loki (inventory) | otelmart.db.transaction.duration_ms > 500 |
| 3:39 PM | Pool idle drops to 0 | Grafana (Ch11 dashboard, Row 3) | All connections in use |
| 3:40 PM | db.client.connection.wait_time rises | Grafana (Ch11 dashboard, Row 3) | Requests queuing for connections |
| 3:41 PM | Checkout P99 starts climbing | Grafana (Ch8 dashboard, Row 1) | User-visible impact begins |
| 3:43 PM | Revenue per hour drops | Grafana (Ch8 dashboard, Row 1) | Business impact |
| 3:45 PM | CheckoutLatencyBurnCritical fires | Alertmanager | SLO burn rate 6.8x |
| 3:47 PM | Error rate ticks up to 2.1% | Grafana (Ch8 dashboard, Row 1) | Some checkouts timing out |
| 3:52 PM | Rollback initiated | CI/CD | Engineer identified root cause |
| 3:53 PM | Long transaction warnings stop | Loki (inventory) | Reconciliation task reverted |
| 3:55 PM | Pool idle recovers | Grafana (Ch11 dashboard, Row 3) | Connections returning |
| 3:57 PM | Checkout P99 returns to normal | Grafana (Ch8 dashboard, Row 1) | User experience restored |
| 4:00 PM | Burn rate drops below 1x | Grafana (Ch8 dashboard) | Incident resolved |
Table 12.7 – Reconstructed incident timeline with each event tagged by its telemetry source
The root cause (3:35 PM deployment) preceded the alert (3:45 PM) by 10min. The engineer identified the root cause at 3:52 PM, 7m after being paged. Total time from alert to mitigation: 7m. Total time from alert to full recovery: 15m.
The 10m gap between deployment and alert is the detection lag. It exists because the SLO burn-rate alert requires sustained degradation before firing. The pool-drain alert recommended below would have fired at 3:39 PM, reducing the detection lag to 4m.
Post-Mortem: Lessons Learned
Section titled “Post-Mortem: Lessons Learned”A good post-mortem doesn’t just explain what happened, it changes how the system behaves tomorrow. This investigation yields five structural improvements:
- Annotate all deployments on Grafana dashboards automatically from CI/CD The 10m gap between deployment and alert would have been immediately visible if the deployment timestamp appeared as a vertical line on the dashboard. Most CI/CD systems can POST an annotation to Grafana’s API as a deployment step.
- Add a pre-deployment check for transaction scope changes touching hot tables. The
product_inventoryandorderstables are in the critical checkout path. Any PR that modifies a transaction touching these tables should include a review of lock duration under concurrent load. This is a code review rule, not a technical check. - Carefully configure
idle_in_transaction_session_timeout. A timeout would have terminated the runawayidle in transactionsessions before they drained the pool, limiting the blast radius. However, exercise caution: aggressive or global timeouts can abruptly drop legitimate long-running maintenance queries or disconnect engineers during manual incident debugging (1). Apply this setting selectively per-role (e.g., targeting the application user, not admins) rather than enforcing it globally. - Add a PromQL alert for pool idle connections reaching zero for more than 60 seconds. A pool hitting zero momentarily under bursty traffic is normal, but staying at zero for a full minute (spanning multiple metric scrape intervals) means requests are continuously queuing without relief. The pool drain was visible here at 3:39 PM, six minutes before the SLO alert fired.
max_over_time(db_client_connection_count{service_name="inventory", db_client_connection_state="idle"}[1m]) == 0
- Move all external API calls outside transaction boundaries. The reconciliation task’s HTTP call inside the transaction was the architectural root cause. Apply the narrow-transaction-scope principle from Chapter 11 as a team-wide convention: transactions should contain only the SQL statements required for atomicity. Validation, logging, HTTP calls, and other I/O should happen before or after the transaction, not during it.
Building an Incident Response Runbook
Section titled “Building an Incident Response Runbook”A good runbook is not a script meant to be followed blindly, it is a decision tree that guides the first 10 minutes of an incident, ensuring the investigation starts in the right place and wastes no time on incorrect hypotheses.
Here is the runbook for the OpenTel E-Commerce checkout path, based on the diagnostic patterns established across the book:
When CheckoutLatencyBurnCritical or CheckoutAvailabilityBurnCritical fires:
- Classify. Open the Chapter 8 business dashboard. Record the P99 latency, SLI compliance, error rate, and revenue impact. Is this a latency degradation, an availability outage, or a correctness issue?
- Trace. Open Jaeger. Filter for checkout traces in the last 15 minutes with duration > 3s (for latency) or status = error (for availability). Identify the dominant span and record the service name, span name, and span duration.
- Dashboard. Open the domain dashboard for the identified service:
- Inventory or Orders: Chapter 11 database dashboard. Check pool idle count, connection wait time, and execution duration.
- Any service with async handlers: Chapter 10 async dashboard. Check queue depth, in-flight count, and queue wait P95.
- Inventory or Orders: Chapter 11 database dashboard. Check pool idle count, connection wait time, and execution duration.
- Classify the failure mode using the established diagnostic patterns:
- High execution duration, normal pool: query plan regression. Run
EXPLAIN ANALYZE.- Normal execution, high pool wait*, zero idle:* pool starvation. Check what is holding connections (
pg_stat_activity). - Normal execution, lock wait events: lock contention. Check
pg_stat_activityforidle in transactionsessions. - High async queue wait, normal downstream: executor contention. Check
tokio‑console.
- Normal execution, high pool wait*, zero idle:* pool starvation. Check what is holding connections (
- High execution duration, normal pool: query plan regression. Run
- Correlate. Check Grafana annotations for recent deployments. Check Loki for warning logs in the 15 minutes preceding the alert. Check traffic graphs for unusual load patterns.
- Fix. Apply the smallest fix matching the proven failure mode. If a deployment is the root cause, roll it back.
- Verify. Compare before/after traces to validate the fix. Confirm metric recovery on the domain dashboard and verify SLI compliance on the business dashboard. Finally, annotate the incident window in Grafana and close the channel only after the burn rate drops below 1x.
Customize this runbook with your own dashboard URLs, alert names, and escalation contacts. Print it. Pin it to the incident channel. The value of a runbook is not in its sophistication; it is what the engineer reads at 3:45 PM on a Friday when the page actually arrives.
The ROI of Observability
Section titled “The ROI of Observability”This section is not a sales pitch. It is a measurement exercise using the incident we just diagnosed. The question is direct: did the observability investment made across this book produce a measurable operational return?
Time to Detection
Section titled “Time to Detection”Without SLO burn-rate alerts (Chapter 8), the team would have noticed when customers complained, when a manual dashboard check happened during business hours, or when a threshold alert on error rate eventually fired. Estimated detection time: 20-40 minutes.
With burn-rate alerts, detection happened at 3:45 PM, 10 minutes after the root cause. The alert fired automatically, with no human monitoring required.
The remaining 10 minutes are the lag between the deployment and the burn rate crossing the threshold. The pool-drain alert recommended in the post-mortem would reduce detection lag to approximately 4 minutes.
Time to Resolution
Section titled “Time to Resolution”Without the observability stack, the investigation would have followed a slower path. The engineer sees “checkout is slow” checks a correlation. The deployment connection might take 30-60 minutes to establish, as determined by manual log review. Total estimated time to resolution: 45-90 minutes.
With the stack, the investigation was evidence-driven at every step. The trace narrowed to Inventory in 2 minutes. Pool metrics reclassified the failure mode in 3 minutes. pg_stat_activity identified lock contention in 5 minutes. Deployment annotations connected the root cause in 7 minutes. Total time from alert to rollback: 7 minutes of investigation plus 5 minutes of deployment pipeline.
The difference is not speed. It is confidence. Each diagnostic step eliminated a hypothesis with evidence rather than guessing. The engineer never rewrote a query plan, never scaled pool connections unnecessarily, and never restarted a service, hoping the problem would resolve itself.
Business Impact Reduction
Section titled “Business Impact Reduction”The revenue-per-hour number on the Chapter 8 business dashboard is not an estimate. It is computed from the cumulative order amount counter introduced in Chapter 8:
sum(rate(orders_total_amount_sum[5m])) * 3600During the investigation window (3:45 PM to 3:52 PM), the checkout path was degraded. The dashboard showed revenue dropping from 2,730/hour, a 170 of reduced throughput.
Without the observability stack, the same incident would have lasted 45-90 minutes at the same degradation level. Revenue impact: 2,200.
The observability stack, traces, metrics, logs, dashboards, and alerts is an infrastructure that was built once across Chapters 4-12. It paid for itself in the first 7 minutes of this incident. Every subsequent incident compounds the return.
These cost calculations are directional estimates, not exact financial measurements. The revenue-per-hour metric captures order throughput, but it does not account for customer behavior that is harder to measure: abandoned carts that never become orders, customers who leave and do not return, or support costs triggered by the degradation. Conversely, not all lost throughput results in lost revenue; some customers may retry successfully after the incident is resolved. The value of these estimates is in establishing the order of magnitude of business impact and making the case for observability investment. Treat them as credible approximations rather than precise accounting, and present them that way to leadership.
These numbers are specific to this incident and this application’s revenue profile. The principle generalizes: instrument once, diagnose many times. The cost of instrumentation is paid during development. The return is collected during every incident throughout the system’s lifetime.
Summary
Section titled “Summary”This chapter used every tool built across the book to diagnose a single compound incident.
What initially appeared to be a database plan regression within a 4.6-second SELECT span due to pool starvation caused by lock contention. The root cause was operational: a deployment increased a background task’s batch size, widening its lock window and triggering a cascade which blocked reservations, which blocked reservations, which blocked reservations, which drained the pool, and pool exhaustion throttled checkout latency.
No new instrumentation was needed. The diagnostic power came entirely from correlation: SLO alerts proved impact, traces isolated the service, metrics classified the failure mode, database views found the blocker, and deployment annotations provided the timeline. No single dashboard told the whole story, but together they formed a straight line to the root cause.
The resulting incident workflow is repeatable — detect with alerts, investigate with traces, diagnose with metrics, correlate with events, fix, and verify — and is captured in a customizable runbook.
While the observability stack drastically reduced time-to-resolution, speed wasn’t the main triumph. The real victory was that every step was backed by evidence. The engineer never chased a wrong hypothesis for long because the next dashboard always forced a pivot. That is what this stack delivers: not faster guessing, but confident, evidence-driven diagnosis.
In the next chapter, we apply this same evidence-driven workflow to a different domain. Instead of diagnosing performance degradation, we use traces to detect security attacks, including credential stuffing, data exfiltration, and denial-of-service attacks. The investigation loop stays the same; the attributes change.