Skip to content
ImagineWorld

Database Bottlenecks

node_idnode-book_mastering-distributed-observability-in-rust_chapter-11-database-bottlenecks
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleDatabase Bottlenecks
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In Chapter 5, we followed the request into SQL and made the database work visible in our traces. For the first time, the checkout path in OpenTel E-Commerce stopped being a black box. We could see the SELECT reserve_stock span in the Inventory service, the INSERT orders and INSERT order_items spans inside the Orders transaction, and the exact point where time disappeared.

That visibility was a major step forward, but it came with a new problem: once a span is slow, what exactly does “slow” mean?

A trace that shows a 900 millisecond database span tells you where the time was spent, but not necessarily why it was spent there. Was PostgreSQL actually executing the query for 900 milliseconds? Was the application waiting 850 milliseconds for a free connection from the pool and only 50 milliseconds to run the query? Was the statement blocked by a long running transaction holding a row lock? Or did a previously healthy query suddenly switch from an index scan to a sequential scan after a batch import changed the data distribution?

All four of those situations look similar in a distributed trace: one child span gets bigger, and overall request latency rises with it. But the fixes are completely different.

This is why database bottlenecks are among the most deceptive performance failures in production systems. They often present as “the database is slow,” but that phrase is too vague to be useful. A real diagnosis begins when you can distinguish three broad failure modes: the query is executing slowly, the query is waiting for a connection, or the query is waiting for a lock.

A database bottleneck is harder to isolate than a CPU hot path or a memory allocation spike because a single span duration combines multiple hidden phases: waiting for a free connection from the application pool, sending the query over the network, waiting in PostgreSQL for a lock or scheduler slot, executing the query itself, and returning rows back to the application. In Jaeger, those phases are collapsed into one span. If that span is 800 milliseconds, you need more evidence before you can say what went wrong.

That ambiguity creates one of the most common operational mistakes in backend systems: teams optimize the wrong thing. A team sees SELECT reserve_stock rising from 40 milliseconds to 700 milliseconds and immediately starts rewriting SQL, adding indexes, or debating schema changes. But if the actual execution time in PostgreSQL logs is still only 8 milliseconds, none of those fixes matter. The problem is not execution. It is pool saturation. The reverse is also true. A team sees num_idle() drop to zero and increases max_connections, but the real issue is a fragmented index that causesevery reservation query to scan too much data. Increasing the pool size only allows slower queries to execute concurrently, which can worsen the database load instead of improving latency.

The first lesson of this chapter is therefore diagnostic discipline:

A slow database span is a symptom, not a root cause.

In this chapter, we will use the telemetry foundation built across Chapters 4 through 8 to make those distinctions precise. We will extend the instrumentation from Chapter 5 with pool and wait-state signals, build practical Grafana panels on top of the metrics in Chapter 6, use the structured logging strategy from Chapter 7 to add context, and continue the incident-driven workflow from Chapter 8 to connect database latency to SLO impact and business cost.

Our main story begins with a familiar symptom: checkout latency suddenly rises on a Tuesday afternoon. The error rate remains near zero. Customers can still complete their purchases, but many requests now exceed the 2-second latency threshold from our SLO chapter. Burn-rate alerting fires. The trace points directly at SELECT reserve_stock in the Inventory service.

That much sounds familiar because in Chapter 8*,* we already saw the outline of this incident. Here, we go deeper. We will not stop at “the database span is slow.” We will prove exactly what changed, verify the database execution plan, compare application-side span time with database-side execution time, and distinguish this incident from two similar-looking impostors: connection pool starvation and lock contention.

By the end of this chapter, you will be able to answer the most important database performance question in production engineering:

When a trace says the database is slow, how do you know what is actually wrong**?**

What this chapter covers:

  • Why slow database spans are ambiguous by default
  • How to instrument pool saturation and wait time in Rust with SQLx
  • How to distinguish slow execution from connection waiting
  • How to diagnose lock contention and long-running transactions
  • How to use EXPLAIN ANALYZE and database-native views alongside traces and metrics
  • How to build a practical “database bottlenecks” dashboard in Grafana
  • How to fix the issue and verify recovery through the same observability signals

Unlike previous chapters, this chapter does not ship pre-built instrumentation in the OpenTel E-Commerce repository. The diagnostic patterns here, pool wait timing, execution timing, threshold logging, and dashboard queries, are designed for you to implement as a hands-on exercise. The code snippets are complete and ready to add to your fork. By building this instrumentation yourself, you will reinforce the patterns from Chapters 4 through 8, span attributes, metrics, structured logging, and SLO-driven diagnosis, while adding the wait-time separation that makes database bottleneck classification possible.

The Incident: Checkout Is Slow, but Nothing Is Failing

Section titled “The Incident: Checkout Is Slow, but Nothing Is Failing”

It is Tuesday at 2:15 PM. The CheckoutLatencyBurnCritical alert fires. The page states that the latency error budget is burning at 14.4 times the sustainable rate over the short and long windows. Availability is still healthy. Correctness is still healthy. The problem is not failed checkouts. It is a degraded checkout speed.

The on-call engineer opens Grafana. The dashboard shows three immediate signals: revenue per hour has dropped, conversion rate has fallen from the normal range, and latency SLI compliance has dropped below target.

This is exactly the kind of incident SLOs were designed to catch. Threshold alerts might have stayed silent because the error rate is close to zero. But the business impact is already visible.

The engineer clicks into Jaeger and filters traces for slow checkout requests during the incident window. The pattern emerges quickly:

otelmart: POST /api/checkout [=======] 5.4s
└─ orders: POST /orders [======] 5.2s
├─ validate_product (HTTP GET products/...) [=] 35ms
├─ HTTP POST inventory/reserve [=====] 4.6s
│ └─ inventory: POST /reserve [=====] 4.5s
│ └─ SELECT reserve_stock [====] 3.8s
└─ TRANSACTION checkout [=] 420ms

Figure 11.1 – Initial incident trace: checkout at 5.4 seconds with SELECT reserve_stock consuming 3.8 seconds inside the Inventory service

The trace points to the Inventory service. More specifically, it points to SELECT reserve_stock, the same operation we instrumented in Chapter 5.

At this point, many teams make a dangerous jump from evidence to assumption:

“The query is slow. Let’s tune the query.”

But the trace alone does not prove that. The span could still include pool wait time or lock wait time. We need more evidence.

So the engineer asks four questions in order:

  1. Is the application waiting for a connection before the query starts?
  2. Is the statement blocked by another transaction?
  3. Is PostgreSQL actually executing this query for several seconds?
  4. Did anything change recently in the schema, index health, or data distribution?

That question order matters. It prevents us from jumping straight to SQL tuning before we have ruled out the two most common impostors.

Use this as your on-call triage sequence: pool wait - > lock wait - > execution plan - > recent change. Keep the order fixed during incident response to avoid premature optimization.

Before we begin the investigation, we need to improve the instrumentation.

Extending the Instrumentation: Making Wait Time Visible

Section titled “Extending the Instrumentation: Making Wait Time Visible”

Chapter 5 deliberately focused on database visibility rather than optimization. We instrumented spans around repository functions and transaction boundaries to make SQL no longer hidden. That foundation remains correct, but it is not sufficient for bottleneck diagnosis because the span duration still blends together multiple phases.

To solve that, we will add three types of telemetry: connection pool gauges, connection wait histograms, and lock and transaction context logs.

SQLx already exposes pool-level information we can query in-process. The OpenTelemetry database semantic conventions define a set of connection pool metrics that we should align with:

Semconv MetricInstrumentSourceWhat It Tells You
db.client.connection.countUpDownCounterpool.size(), pool.num_idle()Connections by state (idle or used)
db.client.connection.maxUpDownCounterpool.options().get_max_connections()Configured ceiling
db.client.connection.pending_requestsUpDownCounterapplication trackingRequests waiting for a connection
db.client.connection.wait_timeHistogramInstant around pool.acquire()Time spent waiting for a connection

Table 11.1 – OpenTelemetry semantic convention metrics for database connection pools

The db.client.operation.duration metric (introduced later in this section and used by the dashboard in Section 11.7) is stable in the current OpenTelemetry semantic conventions. The connection pool metrics above are still experimental and may change in future releases. We use them here because they are well-established across OpenTelemetry implementations and represent the community’s agreed-upon naming direction. If the names change before your deployment, the diagnostic patterns remain the same.

IMPORTANT: In SQLx 0.8, PgPool exposes size() and num_idle(), but not a built-in num_waiters() method. For db.client.connection.pending_requests, register the observable counter once at startup**,** and track the count in application code around every pool.acquire() call:

Startup registration (called once when initializing telemetry):

use std::sync::atomic::{AtomicI64, Ordering};
static DB_PENDING_REQUESTS: AtomicI64 = AtomicI64::new(0);
// Register the observable instrument once at startup — never inside the hot path.
meter
.i64_observable_up_down_counter("db.client.connection.pending_requests")
.with_callback(|observer| {
observer.observe(DB_PENDING_REQUESTS.load(Ordering::Relaxed), &[]);
})
.build();

Per-acquire tracking (hot path, called on every pool.acquire()):

DB_PENDING_REQUESTS.fetch_add(1, Ordering::Relaxed);
let result = pool.acquire().await;
DB_PENDING_REQUESTS.fetch_sub(1, Ordering::Relaxed);
let mut conn = result?;

IMPORTANT: The decrement must run on both the success and failure paths. The ? operator is an early return — if pool.acquire() fails; anything written after? is skipped, so a naive pool.acquire().await? followed by fetch_sub leaks one count per failed acquisition. Capturing the result first and decrementing before the? keeps the gauge balanced. During a connection-refusal incident, where failures are frequent, the leaky version drifts upward and reports far more waiters than actually exist — exactly when the metric needs to be trustworthy. For code with multiple ? operators, an RAII guard that decrements in Drop is more robust.

In Rust, an observable callback publishes the pool state to OpenTelemetry metrics at the time of collection. Add this to inventory/src/telemetry.rs. The key lines are:

pub fn register_pool_metrics(
meter: &opentelemetry::metrics::Meter,
pool: PgPool,
pool_name: &'static str,
) {
let pool_for_count = pool.clone();
meter
.i64_observable_up_down_counter("db.client.connection.count")
.with_callback(move |observer| {
let total = pool_for_count.size() as i64;
let idle = pool_for_count.num_idle() as i64;
// db.client.connection.pool.name is required by the current semconv to
// uniquely identify which pool each metric belongs to. Without it,
// multiple pools aggregate together in dashboards.
observer.observe(idle, &[
KeyValue::new("db.client.connection.state", "idle"),
KeyValue::new("db.client.connection.pool.name", pool_name),
]);
observer.observe(total - idle, &[
KeyValue::new("db.client.connection.state", "used"),
KeyValue::new("db.client.connection.pool.name", pool_name),
]);
})
.build();
let pool_for_max = pool.clone();
meter
.i64_observable_up_down_counter("db.client.connection.max")
.with_callback(move |observer| {
observer.observe(pool_for_max.options().get_max_connections() as i64, &[
KeyValue::new("db.client.connection.pool.name", pool_name),
]);
})
.build();
}

If your existing code uses ObservableGauge instruments for pool state (for example, db.pool.connections.active / db.pool.connections.idle), the diagnostic interpretation in this chapter remains the same. The key requirement is capturing accurate snapshots of idle, used, and wait behavior over time.

This is not glamorous instrumentation, but it is essential. Without it, your traces cannot tell you whether the pool is the bottleneck.

The next signal is more powerful. We want to measure how long it takes to acquire a connection from the pool, separately from how long the query takes to execute.

Because SQLx typically hides acquisition inside helper methods, we explicitly acquire a connection in the hot path for the operations we care about most. The critical pattern is timing the pool.acquire() call independently from the query execution:

#[instrument(
name = "SELECT reserve_stock",
skip(pool),
fields(
db.system.name = "postgresql",
db.namespace = "inventory",
// ... semantic convention fields ...
otelmart.db.pool.wait_ms = tracing::field::Empty,
otelmart.db.exec.duration_ms = tracing::field::Empty
)
)]
pub async fn reserve_stock(
pool: &PgPool,
db_connection_wait_time: &Histogram<f64>,
db_operation_duration: &Histogram<f64>,
product_uuid: Uuid,
qty: i32,
) -> Result<bool, sqlx::Error> {
// Phase 1: Connection acquisition
let wait_start = Instant::now();
let acquire_result = pool.acquire().await;
let wait_secs = wait_start.elapsed().as_secs_f64();
let wait_ms = wait_secs * 1000.0;
tracing::Span::current().record("otelmart.db.pool.wait_ms", wait_ms);
// Record wait time even if acquisition failed; failures are themselves a
// signal of pool pressure and should appear in the histogram.
db_connection_wait_time.record(wait_secs, &[KeyValue::new("db.namespace", "inventory")]);
let mut conn = acquire_result?;
// Phase 2: Query execution
let exec_start = Instant::now();
let query_result = sqlx::query_scalar::<_, bool>(r#"SELECT reserve_stock($1, $2)"#)
.bind(product_uuid)
.bind(qty)
.fetch_one(&mut *conn)
.await;
let exec_secs = exec_start.elapsed().as_secs_f64();
let exec_ms = exec_secs * 1000.0;
tracing::Span::current().record("otelmart.db.exec.duration_ms", exec_ms);
// Record duration on both success and error paths. Failed operations such as
// deadlocks (SQLSTATE 40P01) and lock timeouts appear only in the error path
// and are often the most valuable signal during a lock-contention incident.
let mut attrs = vec![
KeyValue::new("db.system.name", "postgresql"),
KeyValue::new("db.namespace", "inventory"),
KeyValue::new("db.operation.name", "reserve_stock"),
];
if let Err(sqlx::Error::Database(db_err)) = &query_result {
let code = db_err.code().unwrap_or(std::borrow::Cow::Borrowed("unknown"));
attrs.push(KeyValue::new("error.type", code.to_string()));
attrs.push(KeyValue::new("db.response.status_code", code.to_string()));
}
db_operation_duration.record(exec_secs,&attrs);
// ... threshold logging ...
query_result
}

Where both histograms are initialized once at startup:

let db_connection_wait_time = meter
.f64_histogram("db.client.connection.wait_time")
.with_unit("s")
.build();
// Stable OTel semantic convention: separates per-statement execution time
// from connection acquisition time. Powers the query-duration heatmap in
// the dashboard built in Section 11.7.
let db_operation_duration = meter
.f64_histogram("db.client.operation.duration")
.with_unit("s")
.build();

Keep the db.operation.name label strictly low-cardinality (e.g., reserve_stock, insert_order). Never attach SQL text, UUIDs, or request parameters to a histogram label.

If you only adopt one new instrumentation pattern from this chapter, make it this one. Separating otelmart.db.pool.wait_ms from otelmart.db.exec.duration_ms transforms a vague, slow span into a diagnosable event. Implement the full pattern, including histogram recording and threshold-based warning logs, in inventory/src/db/repository.rs.

We intentionally use otelmart.db.* fields on spans for request-level diagnosis, while using OpenTelemetry semantic-convention names such as db.client.connection.wait_time for metrics. Keeping these namespaces distinct makes it easier to query traces and metrics without label ambiguity.

This separation is the breakthrough. Once you have both values, you can answer questions that the original Chapter 5 spans could not: Was the request slow because it waited for a connection? Was the database execution actually expensive? Are we seeing both problems at once?

Apply this two-phase pattern selectively. In a large system with hundreds of repository operations, wrapping every query with explicit acquire timing and dedicated histograms creates unnecessary telemetry volume, storage costs, and increased metric cardinality. Focus the detailed instrumentation on hot paths and SLO-critical operations: the checkout transaction, the inventory reservation, and any query that appears in your latency SLO definition. For low-value read queries that rarely appear in incident investigations, the standard span-level timing from Chapter 5 is sufficient. Treat telemetry itself as an operational design concern with real cost, and instrument deliberately rather than uniformly.

Structured logs remain useful here, not as a replacement for traces, but as context. For statements above a threshold, add a warning log that includes both wait time and execution time:

if wait_ms > 100.0 || exec_ms > 250.0 {
tracing::warn!(
product.uuid = %product_uuid,
otelmart.db.pool.wait_ms = wait_ms,
otelmart.db.exec.duration_ms = exec_ms,
"Stock reservation slow"
);
}

That single log line becomes extremely powerful in Loki. If the warning shows otelmart.db.pool.wait_ms=420.0 and otelmart.db.exec.duration_ms=7.5, the problem is almost certainly the pool. If it shows otelmart.db.pool.wait_ms=2.0 and otelmart.db.exec.duration_ms=3180.0, the problem is almost certainly the query. If both are small, but the overall request is still huge, another dependency is the culprit.

For lock-contention analysis, long transaction duration is a leading indicator. We add a transaction-level warning when any transaction exceeds a safe threshold:

if tx_duration_ms > 500.0 {
tracing::warn!(
transaction.name = "inventory_reservation",
otelmart.db.transaction.duration_ms = tx_duration_ms,
"Long database transaction"
);
}

This does not identify the blocker on its own, but it gives us the context we need to correlate long transactions with blocked reservation calls.

Keep span names low cardinality (SELECT reserve_stock, INSERT orders, TRANSACTION checkout). Do not put UUIDs, literal SQL parameters, or user identifiers into span names. Emit warning logs only when thresholds are crossed, not on every successful query. Observable pool gauges are collected at the SDK’s metric collection interval (configurable via OTEL_METRIC_EXPORT_INTERVAL; the default is 60 seconds). This is usually sufficient to identify saturation patterns; lower the interval during incidents if you need finer resolution.

With these new signals in place, we are ready to properly investigate the incident.

Before walking through each scenario, here is a compact diagnostic cheat sheet, and the full evidence table with supporting detail appears in Section 11.6. Use it as a guide while reading: each incident is a case for collecting evidence to classify one of these three failure modes.

SignalQuery Plan RegressionPool StarvationLock Contention
otelmart.db.pool.wait_msLowHighLow
otelmart.db.exec.duration_msHighLowHigh (blocked writes)
Pool idle connectionsNormalZeroNormal
First investigation toolEXPLAIN ANALYZEPool metricspg_stat_activity

Table 11.2 – Diagnostic cheat sheet: the signals that distinguish the three database failure modes at a glance

The first thing the engineer checks is the pool dashboard. Idle connections are not zero. Wait times are slightly elevated, but not dramatically. That makes pool starvation less likely.

Next, she checks the database session view. There are no large clusters of blocked sessions and no obvious lock chains. That makes lock contention less likely.

Now she compares the new instrumentation on the slow query.

A representative log line reads:

{
"timestamp": "2026-01-16T14:18:32.147Z",
"level": "WARN",
"message": "Stock reservation slow",
"product.uuid": "a7f3c5d2-1234-5678-9abc-def012345678",
"otelmart.db.pool.wait_ms": 3.4,
"otelmart.db.exec.duration_ms": 3678.8,
"trace_id": "1ec2f9dd2eaf4a1f83cbe3db3f6af0df"
}

That is the critical clue. The request did not spend several seconds waiting for a connection. It spent several seconds executing the statement.

The engineer queries Loki:

{service_name="inventory"} |= "Stock reservation slow" | json

The logs show slowness across many products, not a single SKU. That suggests the issue is structural, not data-specific to a single record. In Grafana, the p95 and p99 query duration panels for SELECT reserve_stock have both climbed sharply. Other inventory queries are only mildly affected.

WARNING: EXPLAIN ANALYZE executes the query. Unlike plain EXPLAIN, which only estimates the plan, ANALYZE runs the statement against live data. For an expensive query, this can add load to a database that is already under pressure and worsens an active incident. Write queries and stored procedures with side effects (inserts, updates, deletes), and execute those side effects. Prefer running EXPLAIN ANALYZE against a staging replica or read replica rather than the production primary. Use representative parameters carefully, avoid repeating the analysis in a tight loop during an outage, and consider plain EXPLAIN (without ANALYZE) as a safer first pass when the system is actively degraded.

Now we move to PostgreSQL. Because reserve_stock is a PL/pgSQL function, running EXPLAIN on the function call itself shows only the outer function wrapper — not the SQL statements inside the function body. To see the actual execution plan, run EXPLAIN (ANALYZE, BUFFERS) on the underlying SQL directly. If you need inner statement visibility for complex functions without modifying them, PostgreSQL’s auto_explain extension can log inner plans automatically. Using a representative product UUID:

EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM product_inventory
WHERE product_uuid = 'a7f3c5d2-1234-5678-9abc-def012345678'
FOR UPDATE;

The output reveals the problem:

Generated ASCII Image

Figure 11.2 – EXPLAIN (ANALYZE, BUFFERS) output revealing a degraded index: 8,412 page reads to locate a single row

Three numbers tell the story. The index scan is correctly targeting a single row (rows=1), so the plan itself has not switched to a sequential scan. But Buffers: shared read=8412 reveals the real problem: PostgreSQL is reading 8,412 pages from disk (roughly 65MB) to locate one row. Under normal conditions, the same index scan requires only 3-4 page reads. The index has become severely fragmented following the batch import.

Engineers often think of indexes as binary: either an index exists, or it does not. In production systems, index health also matters. Large imports, skewed updates, and changing data distribution can degrade performance without any code change in the Rust services. From the application perspective, nothing changed. The same SQL function is still being called. The same trace name still appears. But the physical work inside the database has increased.

The DBA runs a REINDEX on the affected index. Once the index is rebuilt, new traces begin to normalize. If the root cause had been stale statistics rather than index fragmentation (for example, a bulk import that doubled the row count without triggering autovacuum), the fix would be to run ANALYZE on product_inventory, which refreshes the planner’s row count estimates and allows it to choose the correct execution plan.

otelmart: POST /api/checkout [===] 760ms
└─ orders: POST /orders [==] 700ms
├─ HTTP POST inventory/reserve [=] 180ms
│ └─ inventory: POST /reserve [=] 165ms
│ └─ SELECT reserve_stock [=] 54ms
└─ TRANSACTION checkout [=] 360ms

Figure 11.3 – The same checkout trace after REINDEX, with SELECT reserve_stock dropping from 3.8 seconds to 54 milliseconds

The SLO dashboard stabilizes. Burn-rate drops. Revenue per hour recovers.

The post-mortem should not say merely, “database was slow.” It should say: slow span identified in Inventory SELECT reserve_stock; pool wait ruled out via wait histogram and idle-connection metrics; lock contention ruled out via session inspection; query execution confirmed slow via otelmart.db.exec.duration_ms and EXPLAIN ANALYZE; root cause was a degraded index after large batch import; mitigation was to rebuild the index and review maintenance strategy for future imports.

That level of precision is what distinguishes an observability-driven post-mortem from guesswork.

The index degradation scenario described above is form of query plan regression, but it is not the only one. A more common variant in growing systems is a query that shipped without an index.

Consider a new product search endpoint added to the Products service: GET /products/search?q=keyword. The developer writes a query: WHERE name LIKE '%keyword%' OR description LIKE '%keyword%'. In development with 200 rows, it returns in 3ms. In production with 500,000 products, the trace shows the SELECT products (search) span at 4+ seconds.

The EXPLAIN output makes the cause immediately visible:

Seq Scan on products (cost=0.00..18547.00 rows=1012
actual time=0.045..3842.123 rows=12 loops=1)
Filter: ((name ~~ '%wireless%') OR (description ~~ '%wireless%'))
Rows Removed by Filter: 499988
Buffers: shared read=8547
Planning Time: 0.089 ms
Execution Time: 3842.456 ms

Seq Scan means every row was examined. Rows Removed by Filter: 499988 means 99.99% of the work was wasted. Buffers: shared read=8547 means PostgreSQL read roughly 66MB of data to find 12 matching rows. The leading % in the LIKE pattern defeats B-tree indexes because the planner cannot seek to a position in the index when the search term can appear anywhere in the string.

The fix depends on the query pattern. For full-text search, replacing LIKE with PostgreSQL’s to_tsvector / to_tsquery functions leverages the GIN index that Chapter 3 already created on the Products table. For prefix matching (LIKE 'keyword%' without the leading wildcard), a standard B-tree index is sufficient. For exact lookups, a B-tree on the filtered column is the default choice.

The key diagnostic difference from the index degradation scenario is that EXPLAIN shows a Seq Scan (wrong plan type) here, rather than an Index Scan with excessive buffer reads (right plan type, degraded index). Both produce high otelmart.db.exec.duration_ms and low otelmart.db.pool.wait_ms, but the fix for a missing index is CREATE INDEX, while the fix for a degraded index is REINDEX.

A second incident produces an almost identical trace shape but requires a completely different fix.

It is Friday afternoon. Traffic rises during a promotional campaign. Checkout latency starts creeping up again. Traces once more show slow database spans in the Inventory and Orders services. A less experienced engineer, remembering the previous incident, immediately suspects another regression in the database plan.

But this time the evidence tells a different story.

A representative trace shows:

otelmart: POST /api/checkout [======] 2.7s
└─ orders: POST /orders [=====] 2.5s
├─ HTTP POST inventory/reserve [===] 1.6s
│ └─ inventory: POST /reserve [===] 1.5s
│ └─ SELECT reserve_stock [===] 1.3s
└─ TRANSACTION checkout [==] 620ms

Figure 11.4 – Connection pool starvation trace: 2.7-second checkout with the same SELECT reserve_stock symptom, but caused by pool wait rather than execution

At first glance, it resembles the query regression incident. But the new instrumentation reveals the difference.

{
"timestamp": "2026-01-23T16:11:07.212Z",
"level": "WARN",
"message": "Stock reservation slow",
"product.uuid": "9b8c6a10-4d2d-4f89-8c5c-4c650ea6dcf4",
"otelmart.db.pool.wait_ms": 1180.6,
"otelmart.db.exec.duration_ms": 11.3,
"trace_id": "238f7c1b0e234f96b56ea0e4f2cdbfb7"
}

This is not a slow query. The query itself still executes in about 11 milliseconds. The request is slow because it waited over a second for a free connection.

The Grafana pool panels confirm the diagnosis:

MetricNormalDuring Incident
db.client.connection.count{state=idle}4-60
db.client.connection.count{state=used}4-610 (maximum)
db.client.connection.wait_time p99< 5ms1,200ms
Operations affectednoneall database spans

Table 11.3 – Connection pool metrics under healthy load versus during pool starvation

This cross-query inflation is one of the strongest signatures of connection starvation. If a single index degrades, one operation usually dominates. If the pool is empty, many unrelated operations look slow together because they are all queued before execution.

Pool starvation usually comes from one of four causes: the pool size is too small for current concurrency, transactions hold connections longer than necessary, slow downstream queries reduce turnover and back up the pool, or the service performs too many database round-trips per request.

Notice how those causes can interact. A genuine slow query can create pool pressure, which can then inflate other queries. That is why separating wait and execution time is so important.

The fourth cause, too many round-trips per request, deserves special attention because it is one of the most common contributors to pool pressure and one of the easiest to identify in Jaeger.

Consider a handler that validates each order item individually rather than in a batch. In the trace waterfall, the pattern is unmistakable: a staircase of identical spans where there should be a single bar.

Generated ASCII Image

Figure 11.5 – The N+1 staircase pattern: five sequential product lookups expanding what should be a single batched request

Five sequential HTTP calls, each making a database round-trip. The individual queries are fast (3-5ms each), but the total wall time for product validation is 319ms compared to the 45ms a single batched call takes. Each round-trip also acquires a database connection from the Products service. Under load with 50 concurrent checkouts, that is 250 connection acquisitions per second instead of 50. The N+1 pattern is a connection pool amplifier: it multiplies the pressure on every shared resource along the path.

Logs would show five SELECT queries, but would not reveal that they are sequential and causally linked to the same checkout. Metrics would show elevated query count per second, but not the per-request multiplication. Only the trace waterfall exposes the staircase.

The fix is batching. A single POST /products/validate with all product UUIDs in the request body, executing one SELECT * FROM products WHERE uuid = ANY($1) query, collapses the staircase back to a single bar.

When the root cause genuinely requires a larger pool, or when connection lifetimes need adjustment, the following SQLx settings control the pool behavior:

SettingPurposeRecommended (OLTP)
max_connectionsHard ceiling on concurrent connections(2 x CPU cores) + 1
min_connectionsWarm baseline to avoid cold-start latency2-5
acquire_timeoutMaximum wait time before returning an error3-5 seconds
idle_timeoutClose idle connections to free server resources5-10 minutes
max_lifetimeRotate connections to pick up DNS/config changes30 minutes

Table 11.4 – SQLx connection pool configuration settings with recommended starting values for OLTP workloads

WARNING: Each PostgreSQL connection consumes roughly 5-10MB of server memory. At 100 connections, that is 500MB-1GB of RAM unavailable for shared_buffers or OS page cache. Beyond a threshold, additional connections cause contention at PostgreSQL’s internal synchronization points, and throughput decreases. The widely cited rule of thumb from the PostgreSQL community: connections = (2 x CPU_cores) + effective_spindle_count. Note that max_connections in SQLx is a per-service-instance pool setting. The total connection load on PostgreSQL is max_connections × number_of_service_replicas × number_of_distinct_services. Size each service pool with the database-wide connection budget in mind and divide that budget across services and replicas rather than applying the formula independently to each pool.

Do not respond to a pool starvation incident by adding indexes. The query was already fast. The evidence proved that. This scenario is exactly why Chapter 5 ‘s warning mattered: a slow database span may mostly be connection waiting, not query execution.

The third lookalike is lock contention.

Like the other two incidents, it often appears first as latency in a database span. But unlike pool starvation, it may be intermittent and bursty. Unlike an index issue, the same query can be fast one minute and painfully slow the next, depending on what another transaction is doing.

A subset of checkout requests becomes slow. Others complete normally. The latency distribution gets wide and ugly: p50 remains acceptable, but p95 and p99 spike hard.

That shape is your first clue. Pool starvation tends to drag many requests up together. Lock contention often produces a more uneven tail.

A slow trace might look like this:

Generated ASCII Image

Figure 11.6 – Lock contention trace: 3.1-second checkout with SELECT reserve_stock blocked rather than executing

Again, the trace alone does not tell us why.

This time, the warning log shows something different:

{
"timestamp": "2026-01-29T11:42:19.881Z",
"level": "WARN",
"message": "Stock reservation slow",
"product.uuid": "a7f3c5d2-1234-5678-9abc-def012345678",
"otelmart.db.pool.wait_ms": 4.8,
"otelmart.db.exec.duration_ms": 1988.4,
"trace_id": "67f7e6f89e534cad8d31f1f30a4decc1"
}

Execution looks slow, which could mislead us toward another plan issue. But when we inspect active sessions in PostgreSQL, we find blocked backends waiting on locks.

A practical query for active and blocked sessions is:

SELECT
pid,
state,
wait_event_type,
wait_event,
now() - query_start AS query_age,
now() - xact_start AS tx_age,
left(query, 80) AS query_snippet
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY query_start;

For lock chains, the built-in pg_blocking_pids() function is the simplest and most reliable starting point:

SELECT
blocked.pid AS blocked_pid,
blocked.query AS blocked_query,
blocking.pid AS blocking_pid,
blocking.query AS blocking_query
FROM pg_stat_activity blocked
JOIN pg_stat_activity blocking
ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;

For advanced inspection: for example, to see specific lock types and granularity, you can join pg_locks with pg_stat_activity. Be aware that a simple locktype + relation join misses non-relation locks (tuple locks, advisory locks, transaction ID locks). pg_blocking_pids() handles these edge cases correctly and is the safer default for incident response.

During the incident, this query produces a clear picture of who is blocking whom:

blocked_pidblocked_queryblocking_pidblocking_query
142SELECT reserve_stock('a7f3c5d2‑...', 1)87UPDATE product_inventory SET stock_quantity...
143SELECT reserve_stock('b8d4e7f1‑...', 2)87UPDATE product_inventory SET stock_quantity...

Table 11.5 – pg_blocking_pids() output during the lock contention incident: two reservation queries blocked by a single maintenance transaction

Both reservation queries are blocked by the same maintenance transaction (PID 87). That single long-running transaction is the root cause of the entire tail latency spike.

Even if you do not memorize the exact SQL, the operational habit matters: when execution looks slow, but plan analysis is inconclusive, inspect the database waits for events before changing the query.

Running the first query during the incident reveals the problem immediately:

pidstatewait_event_typewait_eventtx_agequery_snippet
142activeLocktransactionid00:00:01.8SELECT reserve_stock('a7f3c5d2‑...', 1)
143activeLocktransactionid00:00:02.1SELECT reserve_stock('b8d4e7f1‑...', 2)
87idle in transaction00:00:12.4UPDATE product_inventory SET stock_quantity...

Table 11.6 – pg_stat_activity snapshot showing the maintenance transaction in idle in transaction state holding row-level locks

PIDs 142 and 143 are reservation queries from concurrent checkouts. Both are blocked, waiting on a transactionid lock. PID 87 is the maintenance transaction: it has been idle inside a transaction for over 12 seconds, holding row-level locks that the reservations need. The idle in transaction state, combined with a long tx_age is the signature of a transaction that has done its database work but has not committed because the application is performing non-database work (validation, HTTP calls, file I/O) within the transaction boundary.

When contention is severe enough to create a deadlock cycle, the affected checkout trace will carry the PostgreSQL error code we instrumented in Chapter 5:

SELECT reserve_stock [======] 1012ms ERROR
otel.status_code: ERROR
db.response.status_code: 40P01
exception.message: "deadlock detected"

Figure 11.7 – Deadlock-detected span carrying PostgreSQL error code 40P01 propagated through Chapter 5 ‘s error instrumentation

In our scenario, an inventory-maintenance path was expanded in a recent release. The original code performed a focused, narrow transaction:

// Before: tight transaction scope
let updated = with_transaction(pool, "stock_adjustment", |tx| {
Box::pin(async move {
db::update_stock(tx, product_uuid, new_quantity).await
})
}).await?;
// Validation and logging happen AFTER the transaction releases locks
validate_adjustment(&updated)?;
log_stock_change(&updated).await;

The refactored code widened the transaction to include validation and logging inside the boundary:

// After refactor: wide transaction scope (the problem)
let updated = with_transaction(pool, "stock_adjustment", |tx| {
Box::pin(async move {
let result = db::update_stock(tx, product_uuid, new_quantity).await?;
validate_adjustment(&result)?; // holds locks while validating
log_stock_change(&result).await; // holds locks during async I/O
notify_warehouse(&result).await?; // holds locks during HTTP call
Ok(result)
})
}).await?;

Under concurrency, the reservation query is forced to wait for the locks held by the longer transaction. The validate_adjustment call, the log_stock_change call, and especially the notify_warehouse HTTP call all extend the lock duration by seconds.

Nothing is wrong with the index. Nothing is wrong with the pool. The query is blocked.

Developers often widen transaction scope for reasonable business reasons: to make a workflow more atomic, to ensure two writes happen together, or to reuse a single connection across several steps. But every extra line in a transaction increases the time locks are held for. Under concurrent traffic, that turns correctness-minded code into a latency problem.

The best fix is usually to move non-essential work out of the transaction:

Only keep the minimal set of SQL operations required for atomicity inside the transaction.

Validation, logging, expensive transformations, and remote calls should not happen while locks are held.

Code fixes address the immediate problem. Server-side settings act as safety nets for the next one.

idle_in_transaction_session_timeout tells PostgreSQL to terminate any session that has been idle within a transaction for longer than a threshold. If a transaction opens and then stalls (application crash, forgotten COMMIT, slow I/O), PostgreSQL kills the session and frees the connection:

ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';

statement_timeout kills individual statements that exceed a duration threshold, preventing a single runaway query from monopolizing a connection:

ALTER SYSTEM SET statement_timeout = '10s';

Both settings are strongly recommended guardrails for any connection pool serving OLTP traffic. ALTER SYSTEM sets them globally and requires a SELECT pg_reload_conf() to take effect (some parameters require a server restart); teams often prefer to scope them per database, per role, or per application connection string instead. Choose the scope and threshold values based on your workload characteristics and deployment environment.

When multiple transactions touch shared rows in different orders, contention and deadlocks become more likely. Consistent lock ordering, where all transactions acquire locks on the same rows in the same sequence, eliminates deadlock cycles. For transient lock-related failures, bounded retries with jitter may improve resilience. But retries are not a substitute for fixing the long transaction scope.

After refactoring the long transaction, the blocked-session view clears. The p99 tail collapses. Transaction-duration warnings disappear. Reservation spans return to their baseline.

The third major lesson of this chapter:

A query can be slow because it is blocked, not because it is inefficient.

The three scenarios produce similar traces but require different evidence and different fixes. This table summarizes the diagnostic fingerprints:

Query Plan RegressionConnection Pool StarvationLock Contention
otelmart.db.pool.wait_msLow (< 10ms)High (hundreds of ms to seconds)Low (< 10ms)
otelmart.db.exec.duration_msHigh (seconds)Low (< 50ms)High (seconds)
Latency distributionUniformly elevatedUniformly elevated across all operationsBimodal: fastest, long tail on writes
Pool idle connectionsNormalZeroNormal
pg_stat_activityNormal executionNormal execution, many are waiting for the poolBlocked sessions, Lock wait events
Primary diagnosis toolEXPLAIN (ANALYZE, BUFFERS)Pool metrics + wait histogramspg_locks + pg_stat_activity
Fix categoryIndex maintenance, query rewrite, ANALYZEReduce hold time, batch queries, and resize poolNarrow transaction scope, order locks

Table 11.7 – Full comparison of the three database failure modes: signal signature, primary diagnosis tool, and fix category

The two columns that cleanly separate the failure modesare otelmart.db.pool.wait_ms and otelmart.db.exec.duration_ms. If pool wait is high and execution is low, the problem is pool starvation, regardless of what the overall span duration says. If both pool wait and execution are high, you are likely to have a compound incident where a slow query is causing pool pressure. And if pool wait is low, execution is high, but EXPLAIN ANALYZE shows a fast plan, the missing piece is almost always lock contention visible in pg_stat_activity.

The “latency distribution” row is useful as a secondary signal. A uniformly elevated latency profile (every request is slower) points a systemic cause, such as a plan change or a drained pool. A bimodal profile (most requests are fine, but a tail spikes hard) is characteristic of lock contention, in which only requests that collide with the blocking transaction are affected.

Building the Database Bottlenecks Dashboard in Grafana

Section titled “Building the Database Bottlenecks Dashboard in Grafana”

Now that we have the right telemetry, we need a dashboard designed for diagnosis. A good database bottlenecks dashboard answers three questions immediately: Is the pool saturated? Is the query actually slow? Is something blocked?

Start with the user-facing context from Chapter 8: checkout latency percentiles, latency SLI compliance, current burn rate, and revenue per hour. This top row keeps the investigation grounded in business impact.

# p99 query execution duration by operation, service, and namespace
histogram_quantile(0.99,
sum(rate(db_client_operation_duration_seconds_bucket[5m])) by (le, service_name, db_namespace, db_operation_name)
)

A heatmap visualization of this histogram makes plan regressions immediately visible: a concentrated band at the bottom during normal operation, with a new high band appearing when an index degrades. During pool starvation, this row stays flat because the queries themselves are fast. During lock contention, Row 2 spikes only for the specific write operations that are blocked — reads and uncontended writes remain healthy. Row 3 (pool health) stays normal because lock waits are database-internal and do not consume pool slots. Row 4 (lock and transaction health) is the confirming signal: long-transaction warnings and deadlock counts will rise while Rows 2 and 3 stay otherwise healthy.

Keep db_operation_name strictly low-cardinality (for example: reserve_stock, insert_order). Never attach SQL text, UUIDs, or request parameters to this label, especially on histogram metrics.

# Idle connections (should stay above zero)
db_client_connection_count{service_name="inventory", db_client_connection_state="idle"}
# In-use connections (should stay below max)
db_client_connection_count{service_name="inventory", db_client_connection_state="used"}
# Connection wait time p99
histogram_quantile(0.99,
sum(rate(db_client_connection_wait_time_seconds_bucket{service_name="inventory"}[5m])) by (le)
)

Display as a stacked area chart. Healthy: green (idle) dominates, blue (in_use) fluctuates below the max. Unhealthy: blue fills the entire area, green disappears, and wait time climbs. During a query plan regression, this row may show mild pressure (slow queries hold connections slightly longer), but idle connections do not drop to zero. During lock contention, this row typically stays healthy because locks are a database-internal wait, not a pool-level wait.

Apply this same row to every service that owns a database pool (inventory, orders, and any other SQL-backed service). Limiting pool panels to one service can hide cross-service saturation.

# Long transaction count (from structured log warnings)
sum(count_over_time(
{service_name="inventory"} |= "Long database transaction" [5m]
))

For PostgreSQL-level lock metrics, a postgres_exporter sidecar can expose pg_stat_database_deadlocks and pg_locks counts:

# Deadlocks per minute
rate(pg_stat_database_deadlocks{datname="inventory"}[1m]) * 60

If you use the chapter Docker stack, add postgres_exporter to docker‑compose.yml and configure Prometheus to scrape it so these lock metrics are available in Grafana.

During a plan regression or pool starvation, this row stays quiet. During lock contention, long-transaction warnings spike, and the deadlock counter may begin ticking. If this row is the only one in alarm state while Rows 2 and 3 look healthy, lock contention is almost certainly the cause.

Add focused alerts alongside SLO burn-rate alerts:

# Pool saturation: no idle connections for 2 minutes
max_over_time(db_client_connection_count{service_name="inventory", db_client_connection_state="idle"}[2m]) == 0
# Pool wait p99 above 1 second
histogram_quantile(0.99,
sum(rate(db_client_connection_wait_time_seconds_bucket{service_name="inventory"}[5m])) by (le)
) > 1
# Deadlock activity
rate(pg_stat_database_deadlocks{datname="inventory"}[5m]) > 0

Build the cross-pillar workflow that connects the dashboard to the investigation tools. Configure Grafana’s data links so that clicking a spike in the query duration panel opens Loki with the operation name and time range prefilled. In Loki, the structured warning logs we added in Section 11.2 show otelmart.db.pool.wait_ms and otelmart.db.exec.duration_ms for every outlier, immediately classifying the failure mode. Each log entry carries a trace_id that links directly to Jaeger, where the full distributed trace reveals the request context: the customer hash or order ID, which products were involved, and which service hop was responsible.

After the incident is resolved, annotate the time window in Grafana. That annotation becomes permanent documentation: the next on-call engineer who sees a similar pattern can click into the annotation and read exactly what happened, which dashboard row signaled first, and what the fix was.

The dashboard should not be a pretty summary. It should be an investigative surface.

With all three incident patterns resolved, the combined effect on the checkout path is substantial.

During the worst period, all three failure modes were active simultaneously: the index was degraded by the batch import, the promotional campaign had elevated traffic beyond the pool’s capacity, and the recently widened maintenance transaction was holding locks amid that elevated concurrency. Each problem amplified the others.

The dashboard told the story across all four rows. Row 1 showed the checkout P99 at 8.2 seconds and SLI compliance latency at 74.2%, well below the 99.5% target. Row 2 showed SELECT reserve_stock execution duration at 3.8 seconds (the degraded index). Row 3 showed idle connections at 0 and a pool wait time of 1.2 seconds (the pool backed up because slow queries were holding connections longer). Row 4 showed 14 long-transaction warnings per minute and sporadic deadlocks (the wide maintenance transaction compounding with the elevated concurrency).

The three problems formed a feedback loop: the degraded index made queries slow, slow queries held connections longer, longer connection hold times exhausted the pool, pool exhaustion queued more requests, queued requests overlapped with the maintenance transaction’s lock window, and lock contention added yet more latency on top of an already degraded path.

otelmart: POST /api/checkout [===========] 8.2s
└─ orders: POST /orders [==========] 7.9s
├─ HTTP POST inventory/reserve [========] 6.1s
│ └─ inventory: POST /reserve [========] 5.9s
│ └─ SELECT reserve_stock [=======] 5.4s
└─ TRANSACTION checkout [==] 1.3s

Figure 11.8 – The compound incident before remediation: all three failure modes active simultaneously, checkout at 8.2 seconds

After rebuilding the index, restructuring the maintenance transaction to move validation and I/O outside the transaction boundary, and tuning the pool configuration, the same checkout under comparable load:

otelmart: POST /api/checkout [==] 340ms
└─ orders: POST /orders [=] 290ms
├─ HTTP POST inventory/reserve [=] 90ms
│ └─ inventory: POST /reserve [=] 75ms
│ └─ SELECT reserve_stock [=] 12ms
└─ TRANSACTION checkout [=] 140ms

Figure 11.9 – The same checkout path after rebuilding the index, narrowing the maintenance transaction, and tuning the pool: checkout drops to 340 milliseconds

MetricBeforeAfter
Checkout P998,200ms340ms
SELECT reserve_stock P995,400ms12ms
Pool pending count (peak)80
db.client.connection.wait_time P991,200ms3ms
Long transaction warnings/min140
Deadlocks/min20
Latency SLI compliance74.2%99.94%
Revenue impact-$2,400/hr estimatedrecovered

Table 11.8 – Before-and-after metrics for the compound incident, including SLI compliance and revenue impact recovery

None of the fixes required changing the database schema, upgrading hardware, or adding caching layers. Every improvement was guided by the instrumentation: traces identified the area, the otelmart.db.pool.wait_ms / otelmart.db.exec.duration_ms separation classified the failure mode, EXPLAIN ANALYZE, and pg_stat_activity identified the root cause, and the same signals verified recovery.

The feedback loop that made the compound incident so severe also explains why the recovery was dramatic. Fixing the index reduced query execution time, which reduced connection hold time, which freed pool capacity, which reduced queueing, which reduced the overlap window with the maintenance transaction’s locks. Each fix amplified the effect of the others.

In Chapter 5, we made database operations visible in our traces. That solved one major observability gap, but it also introduced a new challenge: once a database span slows, the trace alone does not explain why.

In this chapter, we closed that gap.

We learned that a slow database span can represent three fundamentally different problems: a query that is genuinely executing slowly, a query that is waiting for a free connection from the application pool, or a query that is blocked by another transaction inside the database.

We extended our Rust instrumentation to expose pool size, idle connections, connection wait duration, and transaction duration. We separated wait time from execution time, which transformed a vague symptom into a diagnosable signal. We used structured logs to surface outliers and Grafana dashboards to visualize differences among pool saturation, plan regressions, and lock contention.

Most importantly, we applied that telemetry to realistic incidents. In the first scenario, the SELECT reserve_stock span was slow because the query itself had become expensive after index degradation following a batch import. In the second, the same-looking symptom was actually connection-pool starvation during a traffic surge. In the third, the culprit was lock contention caused by a transaction that held database locks too long.

The diagnostic sequence that emerged is worth internalizing: check the SLO and service-level impact first, then look at pool idle counts and wait histograms, compare otelmart.db.pool.wait_ms with otelmart.db.exec.duration_ms, inspect database wait events and active transactions, run EXPLAIN ANALYZE only after ruling out queueing and blocking, ask what changed in data, schema, release, or traffic, apply the smallest fix that matches the proven failure mode, and verify recovery across traces, metrics, logs, and the SLO dashboard.

The lesson is not just technical. It is operational. When a trace says “the database is slow,” your job is not to guess the fix. Your job is to correctly classify the latency. That discipline is what turns telemetry into engineering judgment.