Database Monitoring, Troubleshooting, and Diagnostics Questions
Observing and fixing databases in production: health checks, metrics and alerting, and diagnosing common failures like slow queries, lock contention, replication lag, resource exhaustion, and data-integrity incidents such as duplicate keys or lost updates after a crash or migration. Covers a systematic troubleshooting method under incident pressure. Tests operational instincts distinct from design knowledge.
Write a PostgreSQL SQL query that lists the top 5 queries by average duration in the last 24 hours using pg_stat_statements. Include columns: query, calls, total_time, mean_time, and max_time. Provide the SQL and a short explanation of how you'd interpret the results to prioritize optimization work.
Sample Answer
Direct answer
pg_stat_statements tracks cumulative statistics per normalized query (the same query shape with different literal values counted as one entry), so ranking by mean execution time surfaces queries that are consistently slow every time they run, which is a different and often more actionable signal than ranking by total time, which is dominated by whatever runs most often rather than whatever is individually worst.
Structured elaboration
One important correction before the query itself: the column names in the question, total_time, mean_time, and max_time, are the pre-PostgreSQL-13 names. As of PostgreSQL 13, they were renamed to total_exec_time, mean_exec_time, and max_exec_time (with separate total_plan_time/mean_plan_time columns added alongside them, splitting out query-planning time from execution time, which didn't exist as a separate measurement before). I ran this against a real PostgreSQL 16 instance and confirmed the old names no longer exist; the query below uses the current names and aliases the output to match what was asked for, so the result still has the requested column labels.
SELECT query,
calls,
round(total_exec_time::numeric, 2) AS total_time_ms,
round(mean_exec_time::numeric, 2) AS mean_time_ms,
round(max_exec_time::numeric, 2) AS max_time_ms
FROM pg_stat_statements
WHERE query NOT ILIKE '%pg_stat_statements%'
ORDER BY mean_exec_time DESC
LIMIT 5;
The WHERE clause filters out the extension's own bookkeeping query from the results, since otherwise this query would show up ranking itself. pg_stat_statements must be loaded via shared_preload_libraries and its extension created (CREATE EXTENSION pg_stat_statements;) before it will collect anything; it's not on by default.
Interpreting the results. The query column shows the normalized query text with literal values replaced by placeholders ($1, $2, and so on), because pg_stat_statements groups executions of the same query shape together regardless of which specific values were passed; this is different from pg_stat_activity, which shows the literal text of whatever is currently running. calls tells you how many times that shape has executed since the last stats reset, which matters for prioritization: a query with a high mean_exec_time but only 3 calls total is a very different priority than one with a similarly high mean but 50,000 calls. max_exec_time catches queries whose average looks fine but that occasionally spike badly, often a sign of a plan that's sensitive to the specific parameter values passed (a classic cause is a skewed data distribution where one particular value matches far more rows than the planner's cached plan expected).
Prioritizing the ranked list. Ranking by mean_exec_time alone finds individually slow queries, but the actual optimization priority should weigh mean time against call volume: a query at 60ms mean called 50,000 times a day is consuming roughly 50 minutes of cumulative database time daily, while a query at 500ms mean called only 10 times a day costs about 5 seconds cumulative; the first is very likely the better use of tuning effort even though it ranks lower on mean time alone, so I'd look at both this query's mean_exec_time-ranked list and a separate total_exec_time-ranked list before deciding where to spend effort, not just the one the question asked for.
Worked example
I generated real, varied query activity against a seeded 2 million row orders table (a mix of an indexed point lookup, a full-table GROUP BY, an unindexed range scan with an ORDER BY and LIMIT, and a self-join), reset pg_stat_statements, ran each query a realistic number of times, then ran the query above. Actual output:
query | calls | total_time_ms | mean_time_ms | max_time_ms
------------------------------------------------------------------------------------------------------------------------+-------+---------------+--------------+-------------
SELECT count(*) FROM orders o1 JOIN orders o2 ON o1.customer_id = o2.customer_id WHERE o1.id < o2.id AND o1.id < $1 | 1 | 110.08 | 110.08 | 110.08
SELECT status, count(*), avg(amount_cents) FROM orders GROUP BY status | 2 | 126.62 | 63.31 | 64.05
SELECT * FROM orders WHERE amount_cents > $1 ORDER BY created_at DESC LIMIT $2 | 1 | 27.72 | 27.72 | 27.72
SELECT id, status FROM orders WHERE id = $1 | 5 | 2.59 | 0.52 | 1.22
SELECT count(*) FROM orders WHERE customer_id = $1 | 3 | 1.05 | 0.35 | 0.75
Reading this: the self-join tops the list by mean time at 110ms, but it was only called once, so on its own this doesn't say much about production priority, it says this specific shape of query is expensive per-call, worth knowing if it's on a hot path. The GROUP BY query is second at 63ms mean but was called twice, both calls close to the mean (64.05ms max versus 63.31ms mean), so this one is consistently, not occasionally, expensive, a more confident signal that it needs a covering index (an index that already includes every column the query needs, so the database can answer it from the index alone without a separate trip to the table) or a materialized rollup (a precomputed, stored summary table that's refreshed periodically, so the GROUP BY is computed once and then just read) if it runs often in production. The point lookup by id and the count by customer_id are both fast and unremarkable, exactly what you'd expect from indexed equality lookups against a 2 million row table.
Trade-offs and pitfalls
pg_stat_statements numbers are cumulative averages since the last reset (or since the extension was created), so a query that was fast for months and only recently started degrading will still show an overall mean pulled down by its historical fast runs, masking a real, recent regression; for that, look at max_exec_time alongside the mean, or better, sample the view periodically and diff it over time rather than treating one snapshot as the full picture. mean_time ranking, as the direct answer notes, can mislead if read without call volume: it will surface a rarely-run, individually expensive report query above a frequently-run query whose cumulative cost to the system is actually far higher, so treat this ranked list as one input to prioritization, not the final answer.
On a SQL Server instance, your transaction log is growing unexpectedly large and causing disk pressure. Explain how you'd diagnose the root cause, which DMVs or commands you'd run to investigate, and describe safe steps to reduce the log size without risking data loss.
Sample Answer
Direct answer
SQL Server transaction log growth almost always comes down to one of a short list of causes: a long-running or orphaned open transaction holding the log from being reused, a broken backup chain under the FULL recovery model (only a log backup, not a full or differential backup, actually lets the log truncate), replication or Change Data Capture (CDC) holding log records for a consumer that hasn't caught up, or a genuine spike in write volume from a bulk operation. SQL Server exposes the exact reason it currently won't reuse space through a single column, log_reuse_wait_desc on sys.databases; check that first, before running anything else.
Structured elaboration
Glossary
A DMV (Dynamic Management View) is SQL Server's term for a built-in system view exposing internal server or database state, queried like any ordinary view, directly analogous to Postgres's pg_stat_* views. The recovery model (SIMPLE, FULL, or BULK_LOGGED) determines whether the log can truncate automatically after each checkpoint (a periodic point where SQL Server writes all data changes currently held in memory out to the data files on disk, so the log records covering those changes are no longer needed for crash recovery), under SIMPLE recovery, or only after a log backup, under FULL or BULK_LOGGED; this single setting drives most "the log keeps growing" incidents on a database running FULL recovery without a working log-backup job.
Diagnosis
The single most important query:
SELECT name, log_reuse_wait_desc, recovery_model_desc
FROM sys.databases WHERE name = 'yourdb';
log_reuse_wait_desc names the exact reason SQL Server currently cannot reuse log space: common values include LOG_BACKUP (no log backup has run since FULL recovery started retaining log), ACTIVE_TRANSACTION (a long-running or orphaned open transaction), and REPLICATION (a replication consumer hasn't acknowledged), among others. This tells you directly which cause applies, rather than inferring it.
SELECT total_log_size_in_bytes, used_log_space_in_bytes,
used_log_space_in_percent, log_space_in_bytes_since_last_backup
FROM sys.dm_db_log_space_usage;
This gives current size and, specifically, how much log has accumulated since the last log backup, useful both for confirming severity and for quantifying whether a log backup would actually relieve it; a log_space_in_bytes_since_last_backup close to the total confirms LOG_BACKUP as the practical driver.
DBCC SQLPERF(LOGSPACE); is an older, simpler, server-wide command listing log size and percent used for every database on the instance in one call, useful for a quick sweep of whether the problem is isolated to one database or several.
If log_reuse_wait_desc = 'ACTIVE_TRANSACTION', find the actual open transaction by joining the active-transactions and session-transactions DMVs to the session and request DMVs; this identifies the specific session and how long its transaction has been open. An orphaned, forgotten open transaction, for example an application connection that began one and never committed or rolled back, sometimes from a connection-pool bug, is a very common finding here.
DBCC LOGINFO; shows the individual virtual log file (VLF) segments and their status, active versus reusable, useful when the concern is specifically VLF fragmentation: a log that grew in many small increments accumulates a large number of small VLFs, which itself can slow crash recovery and log-related operations, a separate but related operational concern from raw growth.
Safe steps to reduce log size without risking data loss
If the cause is LOG_BACKUP, the common case for a FULL-recovery database, take a log backup; this is the correct way to let SQL Server reclaim internal log space, and it's data-safe, since a log backup is a normal part of the FULL recovery model's backup chain, not a destructive operation. Then set up or fix a recurring log-backup job so this doesn't recur. If the cause is ACTIVE_TRANSACTION, commit or roll back the identified transaction, coordinating with whoever owns that session or application first where possible; killing a transaction mid-flight is always safe for data integrity (a rollback is transactionally consistent) but may have application-level consequences for whatever was in progress. Only after the underlying cause is resolved and log backups are flowing normally, if the log file is now genuinely oversized relative to steady-state need, shrink it once to reclaim disk space and let it regrow naturally to a size that accommodates normal peak activity; shrinking repeatedly as routine maintenance is an anti-pattern, since it just forces the file to grow again on the next busy period, and growth events themselves briefly pause writes while the OS allocates space.
Never switch the database to SIMPLE recovery as a quick fix for log growth without confirming with whoever owns the backup and recovery strategy first: SIMPLE recovery breaks point-in-time restore and invalidates the existing backup chain, a durability and recoverability decision, not a storage-management knob.
Worked example
SQL Server isn't available to execute directly in this environment; the DMV and column names above were verified against Microsoft's current documentation rather than presented from memory (sys.dm_db_log_space_usage reports database_id, total_log_size_in_bytes, used_log_space_in_bytes, used_log_space_in_percent, and log_space_in_bytes_since_last_backup). The arithmetic that view reports is not a black box; given pinned example values it computes directly:
total_log_size_in_bytes = 8_589_934_592 # 8 GiB
used_log_space_in_bytes = 6_764_573_492
used_log_space_in_percent = round(100 * used_log_space_in_bytes / total_log_size_in_bytes, 2)
print(used_log_space_in_percent)
78.75
used_log_space_in_percent is exactly used_log_space_in_bytes / total_log_size_in_bytes * 100; a log at 78.75% used, on an 8 GiB log, is the kind of reading that should already have triggered an alert well before hitting LOG_BACKUP as the confirmed log_reuse_wait_desc cause and taking the corrective backup.
Trade-offs and pitfalls
- Killing the
ACTIVE_TRANSACTIONsession without checking what it was doing is always safe for the database itself, but can be disruptive for whatever application flow was mid-transaction; understand the blast radius before killing it under pressure. - Repeated
DBCC SHRINKFILEas routine maintenance is the single most common SQL Server log anti-pattern: it treats a capacity symptom with a maintenance operation instead of fixing the actuallog_reuse_wait_desccause, and the resulting grow-shrink cycle causes more VLF fragmentation and more autogrowth pauses than simply leaving the file at a stable, appropriately sized value would have. - Switching to
SIMPLErecovery genuinely stops the symptom, the log truncates automatically after each checkpoint, but it silently gives up point-in-time recovery capability. Treat it exactly like disabling WAL archiving on another engine: a durability decision disguised as a quick fix, requiring the same sign-off a backup-strategy change would.
You've observed intermittent Elasticsearch cluster issues: shard imbalance, long GC pauses, and slow merges causing query timeouts. Walk through your diagnostic steps and the metrics you'd examine to isolate the cause, propose remediation strategies you'd consider, and describe longer-term design changes you'd make to avoid recurrence.
Sample Answer
Direct answer
Shard imbalance, garbage collection (GC) pauses, and slow segment merges are three distinct root causes bundled into one symptom, query timeouts, and each needs a different metric to confirm rather than being assumed from the others. They interact (an imbalanced shard concentrates both indexing load and heap pressure on fewer nodes, which then triggers more GC), so diagnose each independently before assuming one caused the rest, remediate the confirmed cause with a matched lever, and fix the underlying design decision, almost always shard count and sizing, that let the imbalance happen in the first place.
Structured elaboration
Glossary
A shard is Elasticsearch's unit of horizontal partitioning; each index is split into shards distributed across nodes. A segment is Lucene's (the search library Elasticsearch is built on) immutable on-disk unit of an inverted index (a lookup structure mapping each search term to the list of documents containing it, the core data structure behind full-text search); new documents create new small segments, which are periodically merged in the background into fewer, larger ones, reducing the number of files a query must check, similar in purpose to LSM-tree compaction (the equivalent background merge process in log-structured-merge-tree storage engines such as RocksDB or Cassandra, which periodically consolidate many small on-disk files into fewer, larger ones). The JVM heap is the memory pool the Java Virtual Machine manages; Elasticsearch relies on both JVM heap (for query and aggregation working memory) and OS page cache (for the actual segment files on disk), so heap pressure and disk-cache pressure are separate things to check.
Diagnostic steps and the metric each confirms
- Shard imbalance: a cluster-wide shard listing shows document count and disk usage per node and per shard. A node carrying meaningfully more shards, or shards from an unusually write-heavy index, for example today's index in a time-series setup where shards aren't rotated or sized evenly, carries disproportionate load. A "what are this node's threads doing right now" view (merge, search, or indexing) turns "this node looks busy" into "this node is busy doing X."
- GC pauses: node-level JVM statistics report garbage-collection count and cumulative time per collector. Correlate pause times against the exact query-timeout timestamps, not just "GC happens sometimes"; a genuine GC-caused timeout shows a stop-the-world pause overlapping the exact timeout window. Also check the heap usage trend: sawtooth-but-recovering is normal collector behavior, while a heap trending upward across collections (not fully reclaimed each cycle) points at either a working set genuinely too large for the configured heap, or a memory-pressure source like oversized aggregations or eagerly loaded field data (an older Elasticsearch structure that pulls an entire field's values into JVM heap memory at once to support sorting or aggregating on it).
- Slow merges: the merge thread pool's queue and rejection counts, plus per-index merge time and count, show whether merges are backed up. If they are, foreground search threads compete with them for disk I/O and, since merge work is CPU-intensive too, for CPU: the same shape of contention as the compaction-versus-foreground-traffic problem in log-structured-merge engines, even though the underlying engine is different.
Remediation, matched to the confirmed cause
- Imbalance: rebalance explicitly, or correct the allocator's settings: allocation awareness (telling Elasticsearch to spread shards across specific node attributes, such as availability zone or rack, instead of just balancing by count) or weighting (biasing the allocator toward or away from specific nodes when it decides where a new shard lands), and address the underlying design issue: revisit shard count and sizing. A well-known Elasticsearch operational guideline is keeping individual shard size in a moderate range, commonly cited as roughly tens of gigabytes, avoiding either many tiny shards, which waste per-shard overhead, or a few huge ones, which each become a hot spot and are slow to relocate or recover.
- GC pauses: tune the collector's max-pause-time goal (most current deployments default to a collector that exposes a configurable pause-time target), and check whether heap size is actually undersized for the real working set versus needing more nodes to shard that working set smaller, rather than reflexively growing the heap on the same number of nodes.
- Slow merges: temporarily throttle the indexing rate, giving merges room to catch up by reducing the rate new segments are created, or increase merge thread-pool capacity if CPU headroom actually exists, the opposite lever from the GC and imbalance cases, so confirm which resource is genuinely free before choosing.
Longer-term design changes
Right-size shard count relative to node count and expected growth up front; over-sharding is the single most common root cause of both imbalance and excess merge or GC overhead, since more, smaller shards mean more total segments and more per-shard bookkeeping across the cluster than the data volume actually needs. For time-series-style data, use an index-rollover policy based on size or age so shards stay in a healthy range automatically, rather than one ever-growing index eventually developing hot, oversized shards. Separate hot and warm node tiers, dedicated hardware profiles for actively indexed data versus older, read-mostly data, so indexing and merge load on hot data doesn't share heap and disk I/O with query load on older data.
Worked example
Elasticsearch isn't available to execute directly here, so this is a pinned, computed illustration of the shard-sizing guideline rather than a live measurement: a projected ingestion volume, and a target shard size range, turned into a concrete shard count.
daily_volume_gb = 300
target_shard_gb_low, target_shard_gb_high = 20, 50
shards_low = daily_volume_gb / target_shard_gb_high # fewer, bigger shards
shards_high = daily_volume_gb / target_shard_gb_low # more, smaller shards
print(shards_low, shards_high)
6.0 15.0
At 300 GB a day and a 20 to 50 GB target shard size, a reasonable daily index should use somewhere between 6 and 15 shards. Provisioning far outside that range in either direction (2 giant 150 GB shards, or 60 tiny 5 GB shards) is exactly the kind of sizing mistake that produces the imbalance-and-merge-overhead pattern this investigation methodology exists to catch, computed directly from the guideline rather than picked arbitrarily.
Trade-offs and pitfalls
- Adding more heap to fix a GC problem without checking whether the working set (aggregations, doc values, Elasticsearch's on-disk, per-field structure built at index time for sorting and aggregating without pulling the whole field into heap) is the actual driver can make pauses worse, not better: a larger heap is a larger space to collect, so an individual major collection can take longer even if it happens less often. Verify the actual cause before choosing this lever.
- Reducing the indexing rate to relieve merge pressure genuinely works, but it directly delays how fresh newly indexed data is for search, a real cost to name explicitly, not a free fix.
- Over-correcting shard count downward after an imbalance incident, going to fewer, bigger shards, trades one failure mode for another: too few shards limits how much a query can be parallelized across nodes and makes each shard's recovery and relocation slower and more disruptive. There's a genuine sweet spot here, not a monotonic "fewer is always better" direction.
A production RocksDB-backed key-value store uses a Bloom filter to cut down on unnecessary SST file lookups, but observability shows its false-positive rate has crept an order of magnitude higher than expected. Walk through how you'd debug this: what you'd look at first, what the plausible root causes are given how a Bloom filter actually works, and what you'd do immediately to limit the impact on latency and disk I/O while you dig further.
Sample Answer
Direct answer
Check first whether the Bloom filter is actually being consulted for the queries that are failing to benefit from it (whole-key filtering can be silently disabled for prefix-only lookups), then check the configured bits_per_key and filter format version against what's actually deployed, and finally check whether the query key distribution itself has shifted, since a Bloom filter's real-world false-positive rate assumes queries resemble the filter's own key population and a workload change can raise the effective rate even with unchanged configuration.
Structured elaboration
What's happening, in plain terms
RocksDB stores data in immutable, sorted on-disk files called SST files (sorted string tables). Before reading an SST file from disk to check whether it holds a key, RocksDB first checks a small in-memory Bloom filter for that file: a probabilistic structure that can say "definitely not in this file" (skip the disk read) or "maybe in this file" (must actually read it to check). A false positive is when the filter says "maybe" but the key isn't actually there, wasting a disk read (or a block-cache lookup) that should have been skippable. When the false-positive rate rises, more of those reads that should have been avoided now happen for nothing, which is exactly why it shows up as extra latency and I/O.
What to look at first
Pull the actual statistics RocksDB tracks: rocksdb.bloom.filter.useful (true negatives, the filter correctly avoided a lookup), rocksdb.bloom.filter.full.positive (every "maybe" result), and rocksdb.bloom.filter.full.true.positive (of those "maybe"s, how many actually held the key). The observed false-positive rate is (full.positive - full.true.positive) / (full.positive - full.true.positive + useful). Compute this from both current and a recent historical baseline to confirm the magnitude and pin down when it actually changed.
Plausible root causes, given how the filter actually works
bits_per_keymisconfiguration: this directly sets the theoretical false-positive rate (roughly: 1.5 bits per key gives about a 50% false-positive rate, 9.9 bits per key gives about 1%, 15.5 bits per key gives about 0.1%; more bits means fewer false positives at the cost of more filter memory). If a config or deploy change accidentally lowered this value, that alone explains an order-of-magnitude jump.whole_key_filtering=false: when a workload wants prefix-only Bloom filters (to speed up prefix scans), point lookups that don't share the configured prefix length get little or no filter benefit at all. From the outside this looks exactly like "the false-positive rate went up," when actually the filter is barely being consulted for full-key lookups in the first place. It's an easy root cause to miss because it's a configuration semantics change, not a data or hardware change.- Filter format version and mixed-version SST files: the original "full filter" implementation topped out around a 0.1% floor even at very high
bits_per_key; newer format versions (5 and later, using 64-bit hashing) do meaningfully better at the same memory budget. A rollback, or a partial rolling deploy that leaves some SST files written under an old format version, can leave part of the dataset with structurally worse filters than the rest. Check whether the regression correlates with a specific deploy window and whether it's uniform across files or concentrated in ones written in a particular period. - A shift in the query key distribution: the filter's theoretical false-positive rate is an average over a well-distributed key population, not a per-subset guarantee. A workload change, for example queries clustering on a narrow hot key range, or a burst of structurally similar keys (long shared prefixes, under a prefix extractor) can raise the effective collision rate with the same
bits_per_keyon paper.
Immediate mitigations to limit latency and I/O impact while investigating further
- Pin index and filter blocks in the block cache and increase cache size (
cache_index_and_filter_blocksplus a larger cache), so even with more filter checks needed, the resulting extra SST-block fetches are more likely served from memory rather than disk, capping the latency cost without a code change. - If
whole_key_filtering=falseturns out to be the cause, that's typically fixable with an option change: existing SST files keep their old filters until naturally compacted, so this is a controlled fix, not an emergency full rewrite. - If it's a
bits_per_keyor format-version regression, avoid an emergency full re-compaction (RocksDB's background process that rewrites SST files into fewer, cleaner ones) under load, which would multiply I/O and CPU on an already-degraded system. Let normal compaction rewrite files with the corrected setting over time, or schedule an explicit re-compaction during a low-traffic window.
Worked example
Computing the observed false-positive rate from raw counters, and comparing it against a 1% target implied by a bits_per_key of roughly 9.9:
useful = 940_000 # rocksdb.bloom.filter.useful (true negatives)
full_positive = 115_000 # rocksdb.bloom.filter.full.positive
full_true_positive = 1_500 # rocksdb.bloom.filter.full.true.positive
false_positives = full_positive - full_true_positive
observed_fp_rate = false_positives / (false_positives + useful)
target_fp_rate = 0.01
print(round(observed_fp_rate * 100, 2), round(observed_fp_rate / target_fp_rate, 1))
10.77 10.8
From these counters, the observed false-positive rate is 10.77%, 10.8 times the roughly 1% target for a 9.9-bits-per-key configuration: a genuine order-of-magnitude jump, computed from the same raw tickers RocksDB exposes rather than eyeballed off a dashboard, and exactly the kind of check that turns "the false-positive rate crept up" from an impression into a number you can act on.
Trade-offs and pitfalls
- Raising
bits_per_keyto "just fix it" without knowing which of the causes above is actually responsible burns memory for no benefit if the real cause waswhole_key_filtering=falseor a workload shift; diagnose before tuning. - Ribbon filters trade CPU for memory (roughly 3 to 4 times more CPU per lookup for about 30% less space, per RocksDB's own documented figures), so switching filter type to chase a memory budget can move the bottleneck to CPU if there isn't headroom there.
- SST files are immutable: an option change to
bits_per_keyorwhole_key_filteringonly affects newly written files going forward, not the ones already on disk. Don't expect an instant global fix from a config change alone, and expect the false-positive rate to improve gradually as compaction naturally touches more of the dataset, not immediately.
A database replica, same-region or cross-region, is falling further and further behind the primary, and clients reading from it are seeing stale data. Walk through how you'd diagnose the lag: what you'd check first, the commands or queries you'd run to see how far behind it is and why, the most likely root causes, and how you'd decide between waiting it out, intervening, or resyncing from the primary.
Sample Answer
Direct answer
I start by separating "is the replica receiving data slowly" from "is the replica applying data slowly," because those point at completely different root causes, network versus replay, and PostgreSQL's replication view lets you tell them apart directly rather than guessing. Once I know which stage is behind, I look for the matching cause (network saturation, a long-running query holding back replay, single-threaded apply falling behind write volume, or replica-side disk contention), and only after that do I decide whether to wait, intervene, or resync from scratch.
Structured elaboration
Check first: how far behind, and where in the pipeline. On the primary, pg_stat_replication gives you the full picture per connected replica:
SELECT application_name,
state,
sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn) AS unsent_bytes,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS unapplied_bytes,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
The three LSN-diff (log sequence number, PostgreSQL's monotonically increasing position in the write-ahead log) columns tell you where in the pipeline the lag actually is: sent_lsn is how far the primary has streamed; write_lsn is how far the replica has written that stream to its own disk (not yet durable); flush_lsn is how far it's durably fsynced; replay_lsn is how far it's actually applied those changes into the visible database state. A gap between pg_current_wal_lsn() and sent_lsn means the primary itself isn't managing to send fast enough (rare, usually a primary-side network or WAL-generation problem). A gap between sent_lsn and replay_lsn with sent_lsn current means the replica has the data but hasn't applied it yet, the most common real-world case, and it splits further into "hasn't written it" (disk-write bound), "wrote but hasn't flushed" (fsync/durability bound), and "flushed but hasn't replayed" (apply-thread bound).
Most likely root causes, by which stage is behind.
- Replay-lag only, write/flush current: a long-running query on the replica is holding back WAL replay (PostgreSQL by default won't apply a change that would conflict with an open read query, up to
max_standby_streaming_delay), or the replay process itself is CPU- or I/O-starved on the replica. - Write/flush lag: the replica's local disk can't keep up writing the incoming stream, usually an under-provisioned replica or a genuinely I/O-saturated one.
- Send lag on the primary: network bandwidth between primary and replica, or the primary itself is generating WAL faster than the connection can carry it (a real write-volume spike).
- MySQL-specific angle, since replication mechanics differ: MySQL replication runs two separate threads on the replica, an IO thread that pulls changes from the source's binary log and writes them to a local relay log, and a SQL thread that reads that relay log and applies the changes, historically on a single thread (unless multi-threaded replication via
replica_parallel_workersis configured). A single large transaction or a workload with poor parallelism on the source can leave the (single-threaded) SQL/apply side unable to keep up even when the network and I/O are both fine.SHOW REPLICA STATUS(the current name; the olderSHOW SLAVE STATUSsyntax is deprecated as of MySQL 8.0.22 but still common on older installs) exposesSeconds_Behind_Source,Replica_IO_Running, andReplica_SQL_Runningto make the same read/write-vs/apply split PostgreSQL's LSN columns give you: an IO thread that'sYes(still running, receiving data into the relay log fine) paired with a largeSeconds_Behind_Sourcepoints at the same single-threaded SQL-thread apply bottleneck, not a receive-side problem.
Deciding between waiting, intervening, and resyncing. If the primary's own write throughput is normal (ruling out an overall load spike as the cause) and the gap is growing rather than holding steady, that already tells you this isn't going to self-heal and is a replica-side or network problem worth acting on directly, not primary-side load to ride out. Wait it out when the lag is bounded and shrinking, or it's a known, temporary cause (a large batch job you know is running). Intervene (kill the blocking read query on the replica, resize the replica, check the network path) when the lag is growing and you've identified a specific, fixable cause. Resync from the primary (rebuild the replica from a fresh base backup) only when the replica has fallen so far behind that the primary has already recycled the write-ahead log segments it would need to catch up (it hits wal_keep_size or a replication slot's retained WAL runs out; a replication slot is a marker the primary keeps for one specific replica, telling itself not to discard WAL that replica hasn't received yet, even while the replica is disconnected), because at that point incremental catch-up is no longer possible and the replica is not just lagged, it's actually broken.
Worked example
I set up real streaming replication between two PostgreSQL 16 containers to reproduce this rather than describe it abstractly. Steady state, replica caught up: pg_stat_replication showed write_lag around 22ms, flush_lag around 24ms, both effectively "current." I then paused WAL replay on the replica (SELECT pg_wal_replay_pause();, simulating a stuck apply process) and inserted 500,000 rows on the primary. Querying the primary immediately after:
application_name | state | sync_state | send_lag_bytes | replay_lag_bytes | replay_lag
-------------------+-----------+------------+-----------------+-------------------+------------------
walreceiver | streaming | async | 0 | 133342800 | 00:00:01.411261
send_lag_bytes is 0: the primary has successfully streamed everything, so this is not a network or primary-side problem. replay_lag_bytes is about 127 MB and climbing, isolating the cause to the replica-side apply stage, exactly the paused-replay scenario I created. On the replica side, pg_stat_wal_receiver confirmed the receiver itself was healthy and current (status: streaming, flushed_lsn matching latest_end_lsn), reinforcing that the data had arrived, it just hadn't been applied. Resuming replay (SELECT pg_wal_replay_resume();) and checking two seconds later: replay_lag_bytes back to 0, and a row count on the replica (SELECT count(*) FROM orders;) matched the primary's 2,500,000 rows exactly, confirming a full, correct catch-up with no resync required.
Trade-offs and pitfalls
Seconds_Behind_Source in MySQL is a genuinely useful number but has a known weakness: on multi-threaded replication it's computed from the coordinator's position and can understate lag relative to the most recently committed transaction, so don't treat it as exact under parallel apply; check Last_SQL_Error and, if available, the performance_schema.replication_applier_status_by_worker table for a truer per-worker picture. Deciding to resync is expensive (a full base backup and re-stream, during which that replica serves nothing), so confirm the WAL/binlog retention has actually been exceeded, not just that the lag number looks alarmingly large, before committing to it; a replica with a large but still-shrinking lag rarely needs a resync. Killing a long-running read query on the replica to unblock replay is a real trade-off, not a free fix: you're trading that read's progress for replication currency, which is the right call if the lag itself is now causing bigger problems (stale reads app-wide, or risking replication slot bloat on the primary, the slot holding on to a growing pile of WAL the primary can no longer reclaim because nothing has consumed it), but it's worth naming explicitly rather than reflexively killing every long query you see.
Unlock Full Question Bank
Get access to all 38 Database Monitoring, Troubleshooting, and Diagnostics interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.