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.
You observe growing lock contention and many blocked transactions causing user-visible slowdowns. Walk through diagnostic steps to identify blocking chains and the root blocking session in PostgreSQL or MySQL. Include example SQL or commands to find blockers, how to interpret the lock types you find, and safe remediation steps to resolve the blocking without violating data consistency.
Sample Answer
Direct answer
I find the root blocking session first, because in a chain of blocked transactions everyone downstream is just waiting on the one at the top; fixing anyone else does nothing. In PostgreSQL, pg_blocking_pids(pid) does that lookup directly for you. Once I know which session actually holds the lock, I look at what it's doing and how long it's been doing it before choosing between letting it finish, canceling its current statement, or terminating the connection outright, in that order of preference, because each option gets more disruptive.
Structured elaboration
Finding the blocking chain in PostgreSQL. The built-in function pg_blocking_pids(pid) returns the process IDs currently blocking a given session, which is simpler and more reliable than hand-writing a self-join against pg_locks:
SELECT pid,
application_name,
wait_event_type,
wait_event,
pg_blocking_pids(pid) AS blocked_by,
state,
left(query, 60) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
For a manual look at the underlying locks (useful when you want to see the lock mode, not just who's blocked):
SELECT locktype, relation::regclass, mode, granted, pid
FROM pg_locks
WHERE relation = 'orders'::regclass
ORDER BY granted, pid;
Finding the blocking chain in MySQL. InnoDB (MySQL's default storage engine) exposes the same shape of information through information_schema (or performance_schema on modern MySQL): SELECT * FROM sys.innodb_lock_waits; in the sys schema view gives a ready-made blocked-versus-blocking pair, and SHOW ENGINE INNODB STATUS includes a TRANSACTIONS section listing the most recent deadlock (a cycle where two or more sessions are each waiting on a lock the other one already holds, so neither can proceed without help, unlike the one-directional chain this whole example is built around) if InnoDB had to resolve one automatically.
Finding the blocking chain in SQL Server. The dynamic management views (DMVs, system views exposing live server state) sys.dm_exec_requests and sys.dm_tran_locks carry the same information under different names: sys.dm_exec_requests.blocking_session_id directly names the blocking session (0 or null means not blocked), and joining to sys.dm_tran_locks on the transaction ID shows the specific lock resource in contention, the same way pg_locks does for PostgreSQL.
Interpreting the lock types you find. A relation-level lock (PostgreSQL) or table-level lock blocks broadly; a tuple or row-level lock is narrower and usually the more common, less disruptive case in day-to-day OLTP (online transaction processing, meaning many small concurrent reads and writes rather than long-running analytical scans) traffic. transactionid as the wait type in PostgreSQL means one transaction is waiting for another to commit or roll back entirely, which is what a plain row-level UPDATE conflict looks like: the second UPDATE isn't waiting on the row's storage, it's waiting on the first transaction's outcome.
Telling a deadlock apart from ordinary blocking. Ordinary blocking, like the chain this whole example walks through, is one-directional: B is stuck behind A, but A itself isn't waiting on anything, so it can sit that way indefinitely, for as long as A holds the lock. A deadlock is a cycle instead: A waiting on a lock B holds while B is simultaneously waiting on a lock A holds, so neither can finish without outside help. PostgreSQL checks for that cycle automatically on a timer (deadlock_timeout, one second by default) and, if it finds one, aborts one of the participating transactions itself with a deadlock detected error. That's the practical tell from pg_stat_activity: a session sitting in pg_blocking_pids() behind a single, non-waiting blocker for more than a second or two is ordinary contention, not a deadlock, because a real deadlock would not survive that long on its own, PostgreSQL would already have broken it. To confirm a deadlock actually happened, look at the logs for the deadlock detected error rather than expecting to catch the cycle live in pg_stat_activity; by the time you query it, the database has usually already resolved it.
Safe remediation, in order of preference.
- Wait, if the blocking transaction is short-lived and near completion. Most blocking resolves itself in normal operation within milliseconds to a few seconds; only intervene once you've confirmed it's stuck, not just momentarily busy.
- Cancel the blocking session's current statement, not the connection:
SELECT pg_cancel_backend(pid);in PostgreSQL,KILL QUERY <id>;in MySQL. This asks the running statement to stop and roll back, leaving the connection itself alive so the application can retry over the same connection if it's built to do so. - Terminate the connection outright only if canceling doesn't clear it (a session can be stuck in a state where it won't respond to a cancel, most commonly waiting on a client-side network read):
SELECT pg_terminate_backend(pid);in PostgreSQL,KILL <id>;(as opposed toKILL QUERY) in MySQL. This forcibly closes the connection, which the application will see as a connection error.
Neither option violates data consistency by itself: canceling or terminating a session rolls back its open transaction, exactly the same guarantee the database already gives you for any aborted transaction. The actual risk is application-level, not data-level: whatever partial work that transaction represented needs to be safely retryable, and whoever is holding a connection pool slot (application code borrows an already-open database connection from a shared pool rather than opening a fresh one per request) on that session needs to notice it disappeared and recover cleanly rather than hanging.
Worked example
I reproduced a real blocking chain end to end on a seeded PostgreSQL 16 instance. Session A ran, inside one transaction: BEGIN; UPDATE orders SET status = 'paid' WHERE id = 1; SELECT pg_sleep(15); (holding the row lock open via the sleep, simulating an application that opened a transaction and got stuck before committing). One second later, session B ran UPDATE orders SET status = 'shipped' WHERE id = 1; against the same row. Querying from a third session while both were active:
pid | application_name | wait_event_type | wait_event | blocked_by | state | query
-----+------------------+------------------+---------------+------------+--------+-------------------------------
92 | order-updater-A | Timeout | PgSleep | {} | active | ...UPDATE orders SET status='paid'...
99 | order-updater-B | Lock | transactionid | {92} | active | ...UPDATE orders SET status='shipped'...
pg_blocking_pids(99) returned {92} directly: session B is blocked by session A, full stop, no manual join required. Session A's wait_event_type is Timeout/PgSleep, meaning it isn't blocked on anything else, it's just sitting in pg_sleep(), which is exactly the "stuck application code that forgot to commit" pattern this scenario is modeling. I then ran SELECT pg_cancel_backend(92);. One second later, session 92 had disappeared from pg_stat_activity (its transaction rolled back, since UPDATE plus pg_sleep inside BEGIN never reached COMMIT), and session B's blocked UPDATE went through immediately: querying orders afterward showed status = 'shipped' for that row, confirming B's write landed cleanly with no data corruption, exactly as the "safe remediation" claim above predicts. Note that pg_cancel_backend was sufficient here: A was blocked on its own pg_sleep, which responds to a cancel request, so I never needed the more disruptive pg_terminate_backend.
Trade-offs and pitfalls
Killing the wrong session in a multi-way chain (canceling B instead of A in the example above) accomplishes nothing: B was never holding anything, it was waiting, so the real blocker keeps blocking and you've just added an unnecessary rollback. Canceling a session that's deep into a large multi-statement transaction throws away all of that transaction's work, which is correct from a consistency standpoint but can be expensive in wasted effort if it was 90% done; check how much work is likely to be lost before you cancel, not just how long it's been blocking others. A session that repeatedly shows up as a blocker is a symptom worth escalating past the immediate incident: if the same code path keeps opening a transaction and doing something slow (an external API call, a large batch update) before committing, the fix is shortening that transaction's scope in the application, not learning to cancel it faster every time it recurs.
An urgent rollback was required because a query plan produced by a recent statistics update caused severe latency. Describe how you'd identify which statistics change led to the plan regression, how you'd reproduce the regression, and what your options would be to fix it without introducing a new one.
Sample Answer
Direct answer
I look for what specifically changed the planner's row-count estimates right before the regression started, since a query plan regression from a statistics update is almost always an estimate that got worse, not better, for one particular predicate. I reproduce the exact query against a copy of the data with the pre-change statistics to confirm the plan actually flips, then choose a fix based on whether the underlying estimate itself was wrong (fix the statistics) or the plan the optimizer picked was fragile given any reasonable estimate (fix the query or add a plan-stabilizing hint), because those two situations call for different, non-overlapping fixes.
Structured elaboration
Identifying which statistics change caused it. Three common triggers, each with a different fingerprint:
- A lowered per-column statistics target (
ALTER TABLE ... ALTER COLUMN ... SET STATISTICS n, or a lowereddefault_statistics_target), often done deliberately to speed upANALYZEon a huge table, which coarsens the column's most-common-value list and histogram and degrades row-count estimate accuracy for anything not in the now-smaller sampled set. - A routine autovacuum-triggered
ANALYZElanding right after a data-shape change (a bulk load, a large delete, a schema migration), where the new statistics are individually accurate but represent a genuinely different data distribution than the plan the optimizer had been using before. - A schema migration that dropped or renamed an index as a side effect, where the regression isn't really about statistics changing at all, it's that the plan the optimizer had been quietly relying on is no longer available, and the "statistics update" that ran right after the migration is coincidental timing, not the actual cause; checking whether the previously-used index still exists under its expected name is a cheap, early check worth doing before assuming the cause is statistical.
Reproducing the regression. Pull the exact query text and parameter values from the slow-query log or application trace at the time of the incident, run EXPLAIN (ANALYZE, BUFFERS) against it now, and compare the plan and actual timing to what a known-good baseline looked like (either from before the change, if you have historical EXPLAIN output or a CI-based performance benchmark, or by temporarily reverting the specific statistics change and re-analyzing to reconstruct the old estimate). If a continuous integration (CI) benchmark already caught this as an automated regression (for example, a scheduled benchmark run flagging a 20% jump in median query latency) rather than a live production symptom, that benchmark's own before/after EXPLAIN output is often the fastest path to a reproduction, since it already isolated the change; treat that CI finding the same way you'd treat a production page, with a written runbook trail (what changed, what was tried, who was notified) rather than a quiet fix with no record, since the next person to touch statistics targets on this table needs to be able to find out this already happened once.
Worked example
I reproduced a real statistics-driven plan regression end to end on a seeded PostgreSQL 16 instance (2 million rows, a source_id column with a deliberately skewed distribution: one dominant value covering about 15% of rows, a second, moderately common value, source_id = 20 (the one this query actually filters on), covering a little under 0.4% of rows, which is what the accurate-statistics estimate below (7,667 rows out of 2 million) reflects, and a long tail of the remaining values covering under 0.02% each, plus a supporting index on the column itself, CREATE INDEX idx_events_source_id ON events(source_id);, since a paginated feed filtered by this column would have one in real production, and the coarsened-statistics plan below specifically depends on that index existing: without any index other than the primary key, PostgreSQL cannot build a bitmap from source_id at all, no matter how badly the row estimate degrades). The query, representative of a paginated feed: SELECT id FROM events WHERE source_id = 20 ORDER BY id LIMIT 50;.
With ALTER TABLE events ALTER COLUMN source_id SET STATISTICS 100; (accurate statistics, ANALYZE freshly run), the real plan:
Limit (cost=0.43..442.31 rows=50 width=8) (actual rows=50 loops=1)
-> Index Scan using events_pkey on events (cost=0.43..67758.43 rows=7667 width=8) (actual rows=50 loops=1)
Filter: (source_id = 20)
Execution Time: 0.767 ms, Buffers: shared hit=105
The optimizer correctly estimates roughly 7,667 matching rows and picks a cheap plan: scan the primary key in id order (already in the required sort order), filtering as it goes, stopping as soon as 50 matches are found, even though a source_id index exists, because at this estimate the pkey-order scan is cheaper than paying for a bitmap build plus an explicit sort. Fast, and correct.
I then ran ALTER TABLE events ALTER COLUMN source_id SET STATISTICS 1; ANALYZE events; (coarsened statistics, simulating someone lowering the target to speed up ANALYZE on a large table) and reran the identical query:
Limit (cost=640.08..640.20 rows=50 width=8) (actual rows=50 loops=1)
-> Sort (cost=640.08..640.51 rows=174 width=8) (actual rows=50 loops=1)
-> Bitmap Heap Scan on events (cost=5.78..634.30 rows=174 width=8) (actual rows=7709 loops=1)
Recheck Cond: (source_id = 20)
Execution Time: 6.702 ms, Buffers: shared hit=5567
Same query, same data, only the statistics target changed: the estimate for this predicate degraded from 7,667 to 174 (the coarsened statistics could no longer represent source_id = 20 accurately), and the optimizer's chosen plan flipped entirely, from the primary-key-order scan to a bitmap scan (built from the source_id index) plus an explicit sort. Real, measured cost: 8.7 times slower (6.702ms versus 0.767ms) and 53.0 times more buffer touches (5,567 versus 105), on identical data with nothing changed except one statistics-target setting. This flip is only available because a source_id index exists at all; on a table with only the primary key, I confirmed separately that the exact same statistics degradation leaves the optimizer stuck on the primary-key-order scan (just a costlier, slower version of it), because there is nowhere else for it to go.
I confirmed why the plan flipped by deriving the optimizer's own cost formula for this shape of query and checking it against the actual reported costs:
costlimit≈cstartup+(ctotal−cstartup)×rowsestlimit
Plugging in the accurate-statistics estimate (7,667 rows, limit 50): 442.31≈0.43+(67758.43−0.43)×766750, which matches the real reported cost exactly. With the degraded estimate (174 rows), the same formula predicts a much higher cost for that same plan shape, roughly proportional to the smaller denominator, which is precisely why the optimizer abandoned it in favor of the bitmap-scan alternative once it believed the value was much rarer than it actually is: a smaller believed row count makes the "scan in sort order, stop at the limit" strategy look like it needs to scan much further to find each match, flipping the cost comparison against it.
Fixing it without introducing a new regression. Since the actual cause here is the statistics degradation, not a fundamentally bad query, the fix is restoring an adequate statistics target on the affected column (SET STATISTICS 100 or higher, back to at least the previous value) rather than rewriting the query, and re-running ANALYZE to regenerate accurate statistics immediately, rather than waiting for the next scheduled autovacuum-triggered analyze to happen on its own. If the original motivation for lowering the target was genuinely slow ANALYZE times on a huge table, the correct fix addresses that specific problem (a higher autovacuum_analyze_scale_factor threshold so ANALYZE runs less often but stays accurate when it does, or analyzing during a low-traffic maintenance window) rather than trading query-plan correctness for ANALYZE speed.
Trade-offs and pitfalls
A fix that raises the statistics target back up solves this specific regression but reintroduces whatever cost problem motivated lowering it in the first place (typically, ANALYZE itself taking longer on a very large table), so a real fix has to address both sides, not just revert the symptom-causing change. If the actual trigger was a migration that dropped an index rather than a statistics change, restoring the statistics target does nothing and burns a rollback cycle on the wrong fix, which is exactly why checking for an index that disappeared is a cheap, fast, early step before assuming the cause is purely statistical. Structured runbook practice for this class of incident: capture the before/after EXPLAIN plans, the specific statistics or schema change identified as the trigger, the fix applied, and a named stakeholder update at each stage (detected, root-caused, fixed, verified), since "a query got slow and we made it fast again" without that record makes the same regression indistinguishable from a new one the next time a statistics target gets tuned for a different, unrelated reason.
An application started throwing intermittent 'duplicate key value violates unique constraint' errors after a migration. Outline how you'd determine whether this is due to an application-level race condition, a migration script bug, or genuinely inconsistent data. Include SQL queries to locate the duplicates, checks you'd run on the migration script, and steps to mitigate impact in production while you investigate.
Sample Answer
Direct answer
The database's own error text, "duplicate key value violates unique constraint," looks identical whether the cause is a genuine two-writer race, a re-run migration script, or real pre-existing duplicate data, because the constraint's whole job is to make all three collisions look the same at the SQL layer. Distinguishing them means bringing in evidence the database itself doesn't retain: an independent request log correlated against the failing key, a direct query against the source data for pre-existing duplicates, and a read of the migration script for idempotency. Mitigate the live impact by treating the race case as an expected, catchable outcome rather than an error, without touching the constraint itself.
Structured elaboration
Race condition check
Correlate an application-level log of every write attempt (not just successful writes) against the failing key. That log must be committed in its own transaction, separate from the risky write attempt; logging it inside the same transaction as the write means a failed write rolls the log entry back too, destroying the exact evidence the investigation needs. If two different client or session identifiers attempted the same key within a tight window (milliseconds to low tens of milliseconds), that's the race signature. One client retrying after a long gap and hitting an already-committed row is a normal, correct idempotent retry, not a bug, and should be treated as success by the caller.
Migration script bug check
Read the migration for whether reruns are idempotent (INSERT ... ON CONFLICT DO NOTHING or MERGE, versus a plain INSERT that fails loudly, or worse silently double-inserts, on a partial rerun after a timeout), whether it deduplicates the source data before inserting rather than assuming it's already unique, and whether its own execution log shows any sign it ran twice (two rows in a migration ledger, or overlapping time ranges in its own job log).
Genuinely inconsistent data check
Query the source (legacy or pre-migration) table directly for existing duplicates on the column the new constraint enforces: SELECT key_col, count(*) FROM legacy GROUP BY key_col HAVING count(*) > 1. If duplicates already existed upstream, the constraint is correctly surfacing a pre-existing data-quality problem the old system silently tolerated, not a migration bug or a race.
Immediate mitigation while investigating
For the race case specifically, catch the unique-violation and treat it as expected: re-select the row that already exists, and if its content matches what you intended to write, return success rather than an error to the caller. This is the standard idempotent-upsert pattern (INSERT ... ON CONFLICT (key) DO NOTHING followed by a SELECT, or DO UPDATE if a merge is genuinely safe). It doesn't fix the underlying cause, but it stops user-visible errors for the likely-majority-benign race case while the migration-bug and bad-data hypotheses, which need a human decision, get investigated.
Worked example
Real output from Postgres 16. First, the genuinely-inconsistent-data check against a legacy table that already has a duplicate before any migration touches it:
SELECT idempotency_key, count(*) AS dup_count, max(created_at) - min(created_at) AS time_spread
FROM legacy_payments
GROUP BY idempotency_key
HAVING count(*) > 1;
idempotency_key | dup_count | time_spread
------------------+-----------+-------------
idem-7001 | 2 | 00:00:04
Then, a real unique constraint and two genuinely concurrent sessions racing to insert the same new key:
CREATE TABLE payments (
id bigserial PRIMARY KEY,
idempotency_key text NOT NULL,
amount numeric NOT NULL,
CONSTRAINT payments_idempotency_key_uq UNIQUE (idempotency_key)
);
Session A and session B, started 20 milliseconds apart, both attempt INSERT INTO payments (idempotency_key, amount) VALUES ('idem-9002', 25.00);. Session B wins; session A gets:
ERROR: duplicate key value violates unique constraint "payments_idempotency_key_uq"
DETAIL: Key (idempotency_key)=(idem-9002) already exists.
The exact same error text as the pre-existing-duplicate case above; nothing in it says which cause produced it. The request-log correlation query, run against attempts logged in their own committed transactions before each insert was tried, is what actually distinguishes them:
SELECT idempotency_key, count(*) AS attempts, count(DISTINCT client_request_id) AS distinct_clients,
max(received_at) - min(received_at) AS spread
FROM request_log GROUP BY idempotency_key HAVING count(*) > 1 ORDER BY spread;
idempotency_key | attempts | distinct_clients | spread
------------------+----------+-------------------+-----------------
idem-9002 | 2 | 2 | 00:00:00.022678
Two distinct clients, 22.6 milliseconds apart: the race signature, versus the legacy duplicate's 4-second spread above, which is far too slow to be a race and instead reflects a real pre-existing double-submit the old system accepted. The order-of-magnitude difference in spread is itself diagnostic.
While building this, logging the request attempt inside the same transaction as the risky insert made the log entry for the losing session vanish entirely when that transaction rolled back on the constraint violation, taking the very evidence needed for this investigation with it. That's exactly the pitfall stated above, discovered by hitting it directly: log attempts in their own committed transaction, always, before the risky write is attempted.
Trade-offs and pitfalls
- Don't disable or drop the constraint to stop the errors; that removes the only thing currently preventing real duplicate business records, even while it's noisy.
- The idempotent-catch mitigation is for the race case only. Applying it blindly to the inconsistent-data case would silently paper over real duplicate business records that need a human decision about which of the conflicting rows is actually correct.
- The transaction-boundary mistake above (logging inside the same transaction as the write it's meant to explain) is easy to make and destroys exactly the evidence a race-versus-bug investigation depends on.
You're operating a RocksDB-backed OLTP service (LSM). Query and write latencies spike during compaction windows. Describe the debugging steps, key metrics to collect, and immediate mitigations you can apply without changing client behavior. Include long-term changes you might make.
Sample Answer
Direct answer
Latency spiking specifically during compaction windows on an LSM (log-structured merge tree) engine like RocksDB is close to the textbook symptom of write amplification (writing more total bytes to physical storage than the original logical write required) competing with foreground I/O, and for a JVM-embedded deployment, garbage collection (GC) pauses layering on top of that. Debug by first separating "is this disk contention from compaction" from "is this a JVM GC pause that happens to correlate with compaction," since they can look identical from a client but need different fixes, using RocksDB's own compaction statistics plus OS-level I/O stats for the first and GC logs for the second. Apply immediate mitigations that don't touch client behavior (I/O throttling, thread-pool tuning, GC pause-time goals), and treat memtable sizing, compaction strategy, level sizing, and large-partition splitting as the longer-term structural changes.
Structured elaboration
Glossary
RocksDB is an embedded LSM-tree key-value store: writes land first in an in-memory memtable, backed by a write-ahead log (WAL) for durability; once a memtable fills, it's flushed to disk as an immutable SST (sorted string table) file. Compaction periodically merges SST files from one level into the next, bounding how many files a read must check and physically removing overwritten or deleted data. Write amplification is writing more total bytes to disk, across the flush and every compaction pass a piece of data goes through, than the original logical write required.
Debugging steps, in order
- Confirm compactions are actually running during the spike windows (
rocksdb.num-running-compactions, the compaction stats dump), the same "confirm correlation before assuming causation" discipline as any other coincidence-shaped investigation. - If confirmed, check OS-level disk queue depth and await time during the compaction window versus outside it. Compaction competing for the same disk queue as foreground reads and flushes is the most common direct mechanism; it's real I/O volume, reading multiple SST files and writing a merged one, not free.
- For a JVM-embedded deployment specifically (RocksDB accessed via JNI from a JVM process, such as a Kafka Streams state store or a Flink RocksDB state backend), pull GC logs for the same windows and check for stop-the-world pause events or safepoint stalls (a JVM mechanism that briefly pauses all threads to reach a consistent state for GC or other coordinated operations). An extreme p99.99 tail latency spike (the response time experienced by the slowest 0.01% of requests) that looks like it's caused by compaction can actually be a GC pause that merely correlates with it, since compaction's native buffer allocations for reads and merges can themselves trigger GC. Check both signals for the same window rather than assuming compaction alone explains it once it's confirmed to be involved at all.
- Check specifically for write-amplification-driven causes: compare
rocksdb.compact.write.bytesagainst the application's own logical write-rate metric to get the observed amplification factor directly, and check whether writes concentrate on a small number of wide partitions or large keys, since a hot, large row forces its containing SST region through compaction more often and at a larger size per pass than a workload with more evenly distributed smaller rows.
Immediate mitigations that don't change client behavior
Throttle compaction's own I/O rate (RocksDB's rate_limiter option caps total background bytes per second across flush and compaction), at the cost of compaction, and space reclamation, falling further behind temporarily: a deliberate, reversible trade. Tune the split between flush and compaction thread pools once step 2 confirms whether the bottleneck is I/O-bound or CPU-bound. If GC is confirmed as a co-equal or primary cause, tune the collector's max-pause-time goal (most current collectors expose one) or add heap headroom to reduce collection frequency, without touching client behavior at all.
Long-term changes
- Memtable sizing: a larger memtable means fewer, larger flushes, which means less write amplification from frequent small flushes triggering excess low-level compaction. But it's a real trade, not a free win: a larger unflushed memtable means a longer WAL replay on crash recovery, and if the deployment uses an async or disabled WAL policy on any write path for throughput, it also widens the actual data-loss window on a crash, since more recent writes exist only in memory. If the WAL is kept enabled and synced, durability itself doesn't change, only recovery time does; treat memtable size purely as a write-amplification-versus-recovery-time trade, and be explicit about which case applies to your deployment.
- Compaction strategy and level sizing: leveled compaction favors read performance and space efficiency at the cost of higher write amplification than a size-tiered approach. For an analytics-style, ingestion-heavy workload (bulk, mostly-append writes with less latency-sensitive point-read need), a size-tiered-leaning configuration, a wider
level0_file_num_compaction_trigger, a larger base level size, or RocksDB's universal compaction style, trades some read amplification (having to check more SST files to find a key's current value) and space overhead for meaningfully less write amplification, matching the workload's actual shape instead of defaulting to leveled compaction for everything. - Wide-row and large-partition mitigation: if a small number of very large keys drive disproportionate compaction cost, split that logical entity across multiple keys (a suffix range or hash bucket) so no single compaction pass moves as much data for one outlier, shrinking the SST rewrite scope rather than tuning the whole engine around one hot entity's shape.
Worked example
The classic analytic bound for leveled-compaction write amplification, per-key write amplification on the order of the number of levels multiplied by the size ratio between them, computed explicitly for two configurations:
L = 6 # number of levels
T = 10 # size ratio between adjacent levels (a common default order of magnitude)
leveled_amp = L * T
T2 = 4 # a gentler, more size-tiered-leaning ratio
leveled_amp2 = L * T2
print(leveled_amp, leveled_amp2)
60 24
At a size ratio of 10 across 6 levels, the theoretical per-key write amplification bound is on the order of 60x; narrowing the ratio to 4 (leaning the configuration toward a size-tiered shape) brings that bound down to roughly 24x. This is exactly the mechanism behind the analytics-ingestion recommendation above: a workload that's mostly appending, rather than doing frequent point reads that benefit from leveled compaction's tighter file-count bound, can trade some of that read benefit for a meaningfully lower write-amplification ceiling by choosing a smaller level-size ratio or a size-tiered-leaning strategy.
Trade-offs and pitfalls
- Diagnosing "it's compaction" and stopping there, without checking GC for a JVM-embedded deployment, is exactly the failure mode step 3 exists to catch. Throttling compaction's I/O alone won't fix a GC-driven tail if GC was the actual (or co-equal) cause, and the conclusion "the fix didn't work" will be right for the wrong reason.
- A bigger memtable is a common reflex fix for compaction pressure that quietly trades away crash-recovery time and, if the WAL isn't fully durable on some write path, a wider data-loss window; state the trade explicitly rather than treating it as a free win.
- Splitting a wide partition helps compaction cost but changes the read pattern: a single logical entity now needs a scatter-read across the split keys. Verify the read path can absorb that before making the change purely to relieve compaction pressure.
Given a MySQL slow query log entry, explain what each field means and how you'd use those logs to prioritize tuning work. Describe how to enable slow query logging safely in production, what pitfalls to watch out for, and how to correlate slow log entries with application traces.
Sample Answer
Direct answer
Each slow query log entry in MySQL carries a header with four numbers that matter for prioritization: how long the statement took to execute, how long it spent waiting to acquire locks, how many rows it sent back to the client, and how many rows it had to examine internally to produce that result. The gap between rows examined and rows sent is usually the single most useful number in the entry, since a query that examines a million rows to return ten is telling you almost exactly where the missing index is.
Structured elaboration
Reading the entry. A typical header looks like:
# Query_time: 0.500000 Lock_time: 0.000100 Rows_sent: 42 Rows_examined: 10000
SET timestamp=1234567890;
SELECT * FROM users WHERE status='active';
Query_time: total wall-clock time the statement took, in seconds (fractional, down to microsecond precision on modern MySQL). This is what actually determines whether the query crossed the logging threshold.Lock_time: how much of that total time was spent waiting to acquire a lock, as opposed to doing real work. A query withLock_timeclose toQuery_timeis a contention problem (something else is holding a lock this query needs), not a query-design problem; a query withLock_timenear zero and all its time elsewhere is the opposite.Rows_sent: how many rows actually went back to the client.Rows_examined: how many rows the storage engine had to read through internally to produce that result, before anyWHEREfiltering orLIMITcut it down. This is the number that most directly indicates whether an index is missing or not being used: a huge gap betweenRows_examinedandRows_sent, as in the example above (10,000 examined to send 42), usually means the storage engine is scanning far more of the table than it needs to, either a missing index on the filter column or an existing index the planner isn't using.
Prioritizing tuning work from the log. I don't prioritize by Query_time alone, because a query that's slow purely due to Lock_time needs a completely different fix (resolve the contention, don't touch the query) than one that's slow due to a large Rows_examined-to-Rows_sent gap (add or fix an index). I'd bucket entries into those two categories first, then within the Rows_examined-heavy bucket, prioritize by how frequently that same query shape recurs in the log (a query that's individually only moderately slow but appears constantly is often worth more effort than a rare, one-off slow query).
Enabling slow query logging safely in production. Set the threshold and destination deliberately rather than accepting defaults:
-- how many seconds a query must take to be logged; default is 10s, often too loose to catch real problems
SET GLOBAL long_query_time = 2;
-- write to a file, not the mysql.slow_log table; writing to a table under load risks its own contention and open-file-descriptor pressure
SET GLOBAL log_output = 'FILE';
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow-query.log';
SET GLOBAL slow_query_log = 1;
-- ignore queries that only touch a handful of rows even if they're slow for other reasons (lock waits mostly), keeps the log focused on genuine scan problems
SET GLOBAL min_examined_row_limit = 100;
Persist these with SET PERSIST (MySQL 8.0+) or in the server's configuration file so they survive a restart rather than silently reverting.
Worked example
Given the entry above (Query_time: 0.5, Lock_time: 0.0001, Rows_sent: 42, Rows_examined: 10000) for SELECT * FROM users WHERE status='active': Lock_time is negligible relative to Query_time, so this isn't a contention problem, it's a scan problem. 10,000 rows examined to return 42 is a 238-to-1 ratio, strongly suggesting status has no usable index, or the table is small enough that the optimizer decided a full scan was cheaper than an index lookup anyway (worth confirming with EXPLAIN (the command that shows the execution plan the database chose, i.e. which index or scan strategy it actually used) before assuming an index is missing, since sometimes it exists but isn't selective enough to be worth using). If this same query shape shows up dozens of times across a day's log with a similar ratio each time, that's a strong, low-risk case for adding an index on status: CREATE INDEX idx_users_status ON users (status);, built with ALGORITHM=INPLACE, LOCK=NONE where the storage engine supports it, to avoid locking the table during the build on a production system.
Correlating with application traces. Log entries carry a timestamp and the raw SQL text, but not, by default, any application-side request ID or trace context; the most reliable way to correlate a slow log entry with the specific application code path that issued it is to have the application inject an identifying SQL comment into the query itself (many object-relational mapping libraries and query builders support this directly, or it can be added manually), since that comment survives into the slow log verbatim and gives you a direct link back to the originating request or endpoint, rather than trying to line up timestamps after the fact.
Trade-offs and pitfalls
Enabling the slow query log is not free on a busy production server: writing each entry is an additional disk write per slow query, and under log_output = 'TABLE' specifically, each entry opens the internal mysql.slow_log table, which under high slow-query volume can itself contribute to file-descriptor pressure, one of the reasons FILE output is the safer production default. log_queries_not_using_indexes looks tempting (it logs every query that doesn't use an index, regardless of long_query_time) but is genuinely dangerous to turn on without log_throttle_queries_not_using_indexes set alongside it, since on a large, poorly-indexed table it can flood the log fast enough to itself become a performance and disk-space problem. MySQL writes each entry to the log only after the statement finishes executing and all its locks are released, so log order can differ from actual execution order; don't use log timestamps alone to reconstruct the precise sequence of events during an incident.
Unlock Full Question Bank
Get access to all 37 Database Monitoring, Troubleshooting, and Diagnostics interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.