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.
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.
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.
Intermittent P99 write latency spikes are impacting global users, and the spikes seem to correlate with heavy analytics jobs that run hourly. Design a methodical approach to isolate the root cause: what instrumentation and sampling would you add, how would you validate that the analytics jobs are actually causing the spikes rather than just coinciding with them, and how would you decide which mitigation to reach for once causality is confirmed?
Sample Answer
Direct answer
Don't start by assuming the analytics jobs cause the spikes just because they share an hourly schedule. Build a three-step methodology: instrument write latency and every candidate resource at fine enough granularity to catch a multi-minute spike, run a natural experiment (move or pause the job) to test causality rather than infer it from a coincidence, and only then pick a mitigation that matches the specific resource the job turns out to contend for.
Structured elaboration
Instrumentation and sampling
- Capture write latency as a percentile distribution (p50, p99, p99.9, meaning the value that only the slowest 50%, 1%, or 0.1% of requests respectively exceed), not an average, at 1-minute or finer resolution. Hourly or even 5-minute rollups can average a 90-second stall down to invisible.
- Tag every latency sample by region. P99 write latency spikes affecting "global users" can be driven by a single slow region pulling the global percentile up while every other region is healthy; segmenting by region rules that in or out before you even look at the analytics job.
- Instrument both client-perceived latency (including cross-region network round trip) and server-side commit latency separately, so a network routing problem doesn't get mistaken for a database problem.
- At the database layer, sample
pg_stat_activityandpg_locks(or your engine's equivalents) every 10 to 30 seconds during the analytics job's known window, and less frequently outside it, to catch lock waits or connection pressure in the act rather than after the fact. - At the OS/infrastructure layer, sample disk queue depth and I/O throughput, CPU run queue, and network egress on the primary's host at the same resolution.
Validating causality, not just coincidence
- Time-lag cross-correlation: compute the correlation between the job's on/off schedule and the p99 series at several time lags. A real causal relationship shows a clear correlation peak near a small, consistent lag (the time it takes contention to manifest as latency); a coincidental "same hour, different cause" pairing shows no clean peak.
- The strongest test is a natural experiment: deliberately shift or skip the analytics job's schedule for a few cycles and watch whether the latency spike moves with it. If the job moves 30 minutes and the spike doesn't move with it, causation is refuted right there, regardless of how well the original schedules lined up.
- Rule out confounders sharing the same "top of the hour" slot: backup jobs, log rotation, connection-pool recycling, and TLS certificate renewal are common hourly/cron neighbors that produce the exact same false-positive correlation.
- If causal, you should be able to find a resource-contention fingerprint that lines up with the spike window: for example, writer queries visibly waiting in
pg_lockson something the analytics job holds, or disk queue depth rising in lockstep with both.
Deciding the mitigation once causality is confirmed
The right fix depends entirely on which resource is actually contended, so diagnose that before picking one:
- I/O contention (the job reads or writes heavily and competes with OLTP, online transaction processing, meaning the primary's own regular small reads and writes, for write fsyncs): move the job to a read replica, or throttle its I/O.
- Lock contention (the job holds a long read lock, or triggers maintenance against a hot table): run it at a snapshot-isolated read level against a replica so it can't block writers at all.
- Connection-pool exhaustion (the job opens many connections and starves the OLTP pool): give it its own bounded connection pool or role.
- Replication-apply pressure (the job runs against a replica and its side effects add load back toward the primary): move it to a dedicated analytics replica or a change-data-capture-fed warehouse instead of querying anything in the primary's write path.
Reach for the fix that matches the confirmed mechanism. Throwing more hardware at the primary before you know which resource is contended just relocates the spike to whichever resource you didn't address.
Worked example
The technique for step two, testing whether the spike's timing actually tracks the job rather than just sharing an hour, is a lagged cross-correlation. Mechanically: pick a candidate lag, say 2 minutes, shift the job's on/off schedule by that many minutes, then compute the standard correlation coefficient (a single number between -1 and 1 measuring how closely two series move together) between the shifted job-schedule series and the latency series. Repeat that across a range of candidate lags and see which one produces the highest correlation; a sharp, high peak at one specific lag, one that stays at the same lag even after you deliberately move the job, is the signature of real causation rather than coincidence. Below is a small, fully pinned illustration of the method (a hand-built synthetic series, not real production data) showing how a genuine causal relationship keeps its correlation peak at the same lag even after the job's schedule is deliberately shifted, which is exactly the signature you'd look for in the real natural experiment.
import statistics
minutes = list(range(140))
# week 1: job runs minutes 60-74. week 2: job deliberately SHIFTED to minutes 90-104.
job_week1 = [1 if 60 <= m < 75 else 0 for m in minutes]
job_week2 = [1 if 90 <= m < 105 else 0 for m in minutes]
def synth_p99(job_on, lag=2, base=40, spike=260, decay=6):
out = []
start = job_on.index(1) + lag
end = len(job_on) - 1 - job_on[::-1].index(1)
for m in minutes:
if start <= m <= end:
out.append(base + spike)
elif m > end:
d = spike * (0.6 ** ((m - end) / decay))
out.append(base + d if d > 1 else base)
else:
out.append(base)
return out
def xcorr(job_on, p99, lags=range(-10, 11)):
jm, pm = statistics.mean(job_on), statistics.mean(p99)
js, ps = statistics.pstdev(job_on), statistics.pstdev(p99)
result = {}
for lag in lags:
num, cnt = 0.0, 0
for i in range(len(job_on)):
j = i - lag
if 0 <= j < len(job_on):
num += (job_on[j] - jm) * (p99[i] - pm)
cnt += 1
result[lag] = (num / cnt) / (js * ps) if js > 0 and ps > 0 else 0.0
return result
for label, job_on in [("week1 (job at :60-:74)", job_week1), ("week2 (job shifted to :90-:104)", job_week2)]:
p99 = synth_p99(job_on)
corr = xcorr(job_on, p99)
best = max(corr, key=lambda k: corr[k])
print(f"{label}: peak correlation r={corr[best]:.3f} at lag={best} min")
Running this prints:
week1 (job at :60-:74): peak correlation r=0.892 at lag=2 min
week2 (job shifted to :90-:104): peak correlation r=0.891 at lag=2 min
The peak stays at the same 2-minute lag both times, even though the job moved 30 minutes later in the second series. That consistency, the spike tracking the job wherever it goes, is the signature you're looking for in the real natural experiment; a coincidental hourly neighbor would not follow the job when it moves.
Trade-offs and pitfalls
- Dashboards built on hourly or coarse averages will hide the exact spike you're trying to find; insist on percentile latency at sub-minute resolution before trusting any "it looks fine" reading.
- Correlation from a shared schedule is the single most common false lead in this kind of investigation; treat "same hour" as a hypothesis to test, never as evidence on its own.
- Reacting with a broad mitigation (bigger instance, more replicas) before confirming causality wastes effort and can mask the real cause, which then resurfaces later under a different label.
- A global p99 can hide a single bad region; always confirm whether the spike is global or regional before designing a fix, since the two point at very different mitigations.
- Pausing the job "to see if it helps" without checking whether the deferred work simply lands later doesn't prove much; compare like-for-like windows, not just "did today's number improve."
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.
A recent migration inadvertently caused write amplification and IOPS spikes on your primary database, and performance has degraded severely. Walk through how you'd quickly diagnose the root cause, what immediate steps you'd take to protect the primary from further damage, and how you'd confirm your mitigation actually worked.
Sample Answer
Direct answer
Confirm this is genuine write amplification (more physical bytes written per logical write than before, not just more traffic) rather than assume it from the timing alone, then check the two most common migration-triggered causes: a newly added index on a frequently updated column defeating an existing update-in-place optimization, or a row-size change that broke existing free-space assumptions. Protect the primary immediately by removing or throttling whatever is generating the extra writes, not by tuning storage under fire, and confirm the fix worked by re-measuring the same ratio that flagged the problem, not just watching the IOPS (input/output operations per second) graph look better.
Structured elaboration
Glossary
Write amplification: writing more total bytes to physical storage than the logical write itself requires, for example one small UPDATE triggering writes to the table's heap plus several index structures plus the write-ahead log. IOPS (input/output operations per second): a measure of how many discrete disk read or write operations storage is asked to perform.
Confirming it's actually amplification
Compare the rate of logical writes (transactions per second, or rows changed per second) against the rate of physical bytes written (WAL bytes per second, or OS-level disk write throughput). If the logical write rate is flat but physical bytes written per logical write jumped, that's amplification, not simply more traffic.
Common migration-triggered causes, most likely first
- A newly added index on a column that's updated frequently: every update to an indexed column now has to write both the heap row and maintain every index touching it. In Postgres specifically, updating an indexed column disables the heap-only-tuple (HOT) optimization for that update, which otherwise lets an update skip touching indexes entirely when no indexed column changed and the page has free space. This is directly checkable: compare
n_tup_hot_updagainstn_tup_updinpg_stat_user_tables; a sudden drop in that ratio right after the migration is a strong, checkable signal, and it's demonstrated concretely below. - A column type or width change (widening a column, or adding several nullable columns) that increased average row size enough that rows no longer fit in their page's existing free space, forcing more page splits, and combined with a low fill factor, more full-page writes.
- A backfill migration still running in the background, generating sustained extra write-ahead-log volume on top of normal traffic; check whether the spike tracks the backfill's own progress rather than just the moment the schema change deployed.
- Full-page writes after a checkpoint: many engines write a full copy of a page to the log the first time it's touched after a checkpoint, to protect against a torn page on crash. If the migration spread writes over a wider, more random set of pages (for example, via a new index), more distinct pages hit this full-page-write cost following each checkpoint, amplifying log volume independent of any single row's size.
Immediate steps to protect the primary
If the cause is a specific new index that isn't yet load-bearing for query performance, consider dropping it (or marking it unused) as an emergency measure, an explicit, reversible trade made deliberately, not silently. If it's a backfill job, pause it rather than let it keep competing with foreground traffic for the same I/O budget; a well-built backfill should be resumable, and if this one isn't, that's a finding to fix on its own. If the amplification is coming from application write volume itself, throttle at the statement or connection level as a stopgap. Do not reach for "add more IOPS" as the first move; it treats the symptom and hides whether the underlying amplification is actually fixed.
Confirming the mitigation worked
Re-measure the same ratio used to confirm the problem (physical bytes per logical write, and the HOT-update ratio if that was the cause) back at its pre-migration baseline. A lower IOPS graph can simply mean traffic dropped for an unrelated reason (off-peak hours); the underlying amplification can still be broken and will resurface at the next traffic peak.
Worked example
A real, executed demonstration of the HOT-update mechanism specifically, since it's the most directly checkable and most common migration-triggered cause. Postgres 16, a table with free space reserved per page (fillfactor=70) so HOT updates are actually possible:
CREATE TABLE hot_demo (id bigint PRIMARY KEY, note text, counter int NOT NULL DEFAULT 0)
WITH (fillfactor=70);
3,000 random updates to counter, with no index on it yet:
n_tup_upd | n_tup_hot_upd | hot_pct
-----------+---------------+---------
2922 | 2271 | 77.7
77.7% of updates avoided touching any index, exactly what HOT is for. Then an index is added on counter, the very column being updated, statistics reset, and the same 3,000 random updates repeated:
CREATE INDEX idx_hot_demo_counter ON hot_demo (counter);
n_tup_upd | n_tup_hot_upd | hot_pct
-----------+---------------+---------
2969 | 0 | 0.0
The HOT-update rate drops from 77.7% to exactly 0.0%. Every single update now has to touch the new index too, because it's on the column changing, real, measured write amplification caused directly by adding an index, on identical data and an identical update pattern, changed by nothing except the index's existence.
Trade-offs and pitfalls
- Dropping a newly added index to relieve write pressure can silently reintroduce the slow-query problem the index was meant to fix. Only do this as a deliberate, communicated, temporary trade, with a plan to rebuild it (ideally online, off-peak) once the amplification's root cause is actually addressed.
- Lowering fill factor helps HOT-update eligibility going forward but does not retroactively fix already-full existing pages; a table that's already bloated usually needs a rebuild to benefit, which carries its own availability trade-offs.
- A backfill migration that isn't resumable and rate-limited is a recurring failure pattern; treat "can this be paused and resumed without redoing work" as a required property of any migration touching every row of a live table, not an afterthought.
Unlock Full Question Bank
Get access to all 27 Database Monitoring, Troubleshooting, and Diagnostics interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.