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.
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.
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."
Your database is intermittently hitting its connection limit and starting to refuse new connections. Walk through how you'd figure out whether this is a connection leak, a genuine traffic spike, or pool starvation from a few slow queries hogging connections, and what you'd do immediately to relieve the pressure while you find the real cause.
Sample Answer
Direct answer
I look at the shape of the connection count over time before I look at anything else, because a leak, a genuine spike, and starvation each leave a different fingerprint. A leak climbs steadily and never comes back down even when traffic drops. A genuine spike rises and falls roughly in step with request volume. Starvation from a few slow queries shows a connection count that's high but the active-versus-idle split is unusual, most of those connections are sitting there holding a slot without doing real work. Immediately, regardless of which it turns out to be, I relieve pressure by raising the ceiling slightly if there's headroom, or by killing the specific sessions holding connections hostage, while I confirm the actual cause.
Structured elaboration
Distinguishing the three causes from what's visible in the database itself.
SELECT state, count(*), max(now() - state_change) AS oldest_in_state
FROM pg_stat_activity
GROUP BY state
ORDER BY count(*) DESC;
- Genuine traffic spike: most connections show
state = 'active', actually executing queries, and the pattern started at the same time as a visible increase in request volume upstream (from an application-side metric, not the database). Connections are doing real work; there are just more of them than usual. - Connection leak: connections accumulate in
state = 'idle'and never return to the pool. This is an application bug, not a database problem: code that opened a connection (or checked one out of a pool) and never returned it, often on an exception path that skips the cleanup step. The database-side fix is temporary; the real fix is in the application. - Pool starvation from a few slow queries: a small number of connections show
state = 'active'with an unusually longnow() - query_start, while many other application instances or threads are stuck waiting for a connection to free up (visible on the application side as connection-pool checkout timeouts, not visible in the database at all, since a request that never got a connection never became a database session). The database-side signature is: total connection count is at or near the ceiling, but the count of connections actually doing work is small relative to the total, and the ones doing work have been running far longer than typical for this workload.
Immediate relief, matched to which of the three it looks like.
- If it looks like starvation from a few slow queries: cancel the specific offending sessions (
SELECT pg_cancel_backend(pid);for the ones with the longestnow() - query_start) rather than doing anything broader; this directly frees the connections they were holding without touching anyone else's legitimate work. - If it looks like a leak: this can't be fixed live in the application code during the incident, so the immediate relief is bouncing the affected application instances (which forces their connections closed and lets the pool rebuild cleanly) while you fix the actual leak afterward. A database-side connection limit increase does not fix a leak, it just delays the same wall by a bit, so treat it as a stopgap, not a resolution.
- If it looks like a genuine spike: this is the one case where temporarily raising
max_connectionsor, better, adding read replicas or a connection pooler in front of the database (a separate piece of infrastructure that multiplexes many client connections onto fewer actual database connections) is a legitimate response rather than a band-aid, because the underlying demand is real and needs to be served somehow. Note that raisingmax_connectionsitself has a real cost: each PostgreSQL connection holds a meaningful amount of backend memory whether or not it's doing anything, so this isn't free headroom, it's trading memory pressure for connection-slot pressure.
Confirming the real cause while relief is in effect. Correlate the connection-count graph against an application-side deploy timeline (a leak often starts exactly at a specific deploy) and against an upstream traffic graph (a spike correlates with real demand, a leak and starvation usually don't). If canceling a handful of long-running sessions immediately drops the total connection count back to normal, that's strong confirmation it was starvation, not a leak or a genuine spike, because a real leak or real spike wouldn't be explained away by five sessions.
Worked example
Say a service normally runs around 40 of its 100 max_connections in use, and pages fire at 95 connections. First check: state breakdown shows 90 connections idle, 5 active. That single fact already rules out a genuine traffic spike (if this were real demand, most of those 90 would be active, not idle), narrowing it to a leak or starvation. Second check: of the 5 active, now() - query_start shows they've been running between 40 seconds and 3 minutes, well outside normal for this workload's typical sub-100ms queries; those 5 look like the starvation candidates. But the 90 idle connections are the bigger number and need their own explanation: checking state_change on those (how long they've sat idle) shows they've been idle for hours, spanning well before the 5 slow queries started, which points toward this actually being a leak that's been slowly accumulating, with the 5 slow queries being a separate, coincidental problem rather than the root cause of the exhaustion. This is exactly why checking the shape (how long has each connection been in its current state, not just the current count) matters more than the raw number: a snapshot of "95 connections" alone doesn't tell you which of the three you're looking at, or, as here, that you might be looking at two problems at once.
Trade-offs and pitfalls
The three causes aren't mutually exclusive, as the worked example shows, and treating the first plausible-looking cause as the whole answer risks fixing 5% of the problem and declaring victory. Raising max_connections as a first response, before distinguishing the three, is the most common mistake: it can mask a genuine leak for hours or days by giving it more room to leak into, turning a fast, cheap-to-diagnose incident into a slow, expensive one. Killing sessions to relieve starvation is safe from a data-consistency standpoint (it just rolls back their open transaction) but only actually helps if those sessions were the real bottleneck; killing the wrong sessions while a leak continues accumulating elsewhere buys you a few minutes at best.
You see frequent 'authentication failed' entries in the database logs. Outline step by step how you'd diagnose the connection/authentication problem across the application, the connection pooler, the network, and the database itself, including the commands or queries you'd use at each layer and how you'd narrow down which layer is actually at fault.
Sample Answer
Direct answer
I work outward from the database, since that's where the error surfaced, but the actual cause is just as likely to live in the application, the connection pooler (a lightweight proxy that sits between the application and the database and multiplexes many client connections onto a smaller, reused set of actual database connections instead of opening a fresh one per client), or the network in between. I check each layer for what it would look like if it were the culprit, ruling layers out with direct evidence rather than guessing, and I specifically avoid assuming "authentication failed" means a wrong password, since a handful of other things produce the identical error text.
Structured elaboration
Layer 1: the database itself. Read the full log entry, not just the summary line; PostgreSQL's DETAIL line often names exactly which authentication rule matched. I reproduced this directly: attempting a connection with a wrong password against a real PostgreSQL 16 instance produced
FATAL: password authentication failed for user "postgres"
DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
That DETAIL line is doing real diagnostic work: it confirms the connection reached the database, matched a specific client-authentication rule (pg_hba.conf line 128, requiring scram-sha-256 password authentication for this combination of database, user, and source), and failed specifically at the password-verification step, not earlier. That single line rules out several other possible causes at once: it's not a network reachability problem (the connection reached the server and matched a rule), it's not a missing pg_hba.conf entry (a rule did match), and it's not an authentication-method mismatch (the client attempted the method the rule required). What's left, given that DETAIL line alone, is either a genuinely wrong password or a wrong username presented as if it were a password problem (MySQL and PostgreSQL both report certain wrong-username cases through the same generic "authentication failed" message rather than a distinct "no such user" error, partly as a deliberate security choice to avoid confirming which usernames are valid to an attacker).
Layer 2: the connection pooler, if one sits between the application and the database (PgBouncer for PostgreSQL, ProxySQL for MySQL, or a managed service's built-in pooler). A pooler can produce the exact same "authentication failed" text for a cause that has nothing to do with the actual database credentials: its own separate copy of user credentials (poolers commonly maintain their own auth file, independent of the database's) going stale after a password rotation, while the database's own credentials are perfectly correct. Check the pooler's own logs separately from the database's; if the pooler logs a clean, successful connection to the database but the client sees an authentication failure against the pooler, the pooler's own credential store is the layer at fault, not the database.
Layer 3: the network. A firewall or security-group rule change, a database migrated to a new host without every client's allowlist being updated, or a source IP address that changed (a redeployed application instance getting a new address, a NAT gateway change) can all cause connections to arrive from an address the authentication rules don't expect, which some database configurations report as an authentication failure rather than a clearly separate "connection refused" or "no route" error, especially when the pg_hba.conf-style rule is matched by source address as part of the same rule that governs the auth method. Check what source address the failing connections are actually arriving from, in the log's DETAIL or equivalent, and compare it against what the connecting application believes its own address is.
Layer 4: the application. Check for a credential that's stale in exactly one place: a secret manager or environment variable that was rotated everywhere except one deployment target, a connection string cached in application memory from before a rotation and never refreshed without a restart, or, for a scheduled batch or extract-transform-load (ETL) job specifically, credentials baked into a config file that's on a different rotation schedule than the interactive application's credentials, so it silently breaks weeks after a password rotation that the interactive path already absorbed.
Narrowing down which layer is actually at fault. The fastest discriminator is trying the exact same credentials directly against the database, bypassing the application and the pooler entirely, from a machine you know can reach the database network-wise (a database client run from a bastion host or the database's own host). If that direct connection succeeds, the problem is in the application or the pooler, not the database's own credential store or pg_hba.conf rules, since you just proved those are correctly configured for this exact username and password. If the direct connection also fails with the same error, the problem is at the database or network layer, and the DETAIL line from that direct attempt tells you which.
Worked example
Errors are showing up for a scheduled nightly batch job specifically, not for the interactive application, which is itself the first useful clue: whatever changed, it changed for this one job's credential path and not the others, which already argues against a database-wide cause (a pg_hba.conf change affecting one rule for all users would hit everyone, not just this one job) and toward something scoped narrowly to this job. Direct connection test with the batch job's configured credentials, run manually from the batch host: succeeds. That single result rules out the database and the network entirely (a direct connection with the same credentials from the same host just worked), narrowing this to the application layer specifically: the batch job's own config, most likely a credential that was rotated in the secret manager but never refreshed in whatever cached copy the batch job reads at startup, since the job likely only reads its credentials once, at startup, and a password rotated after that keeps failing until the job process is restarted.
Trade-offs and pitfalls
The single biggest trap in this kind of triage is assuming the error text describes the actual cause precisely; "authentication failed" is, by design in most databases, deliberately vague about whether the username, the password, or the source address was the specific problem, because a more specific error would leak information useful to an attacker probing for valid usernames. Treat the error text as a starting point, not a diagnosis, and use the DETAIL line and direct reproduction, as above, to actually narrow it down. Jumping straight to "someone changed the password" without checking the pooler and network layers first wastes time on the wrong fix if the real cause is a stale pooler credential cache or a firewall rule, both of which look identical from the client's point of view.
A query is slow and you need to figure out whether it's CPU-bound or I/O-bound before you can pick the right fix. Which database-level and OS-level signals would you pull together to make that call, and how would you combine them into a confident diagnosis rather than a guess?
Sample Answer
Direct answer
I pull database-level wait information and operating-system-level resource utilization together, because neither alone is conclusive: the database can tell you what a specific query is waiting on right now, but only the operating system (OS) can tell you whether that wait reflects genuine system-wide resource pressure or is isolated to this one query. A confident diagnosis comes from both pointing the same direction, not from either signal in isolation.
Structured elaboration
Database-level signal: what is this specific query actually doing? In PostgreSQL, pg_stat_activity exposes wait_event_type and wait_event for the session running the query. This is the fastest, cheapest first check, and it splits into a genuinely three-way answer, not the two-way CPU-versus-I/O split the question implies:
- If
wait_eventis null whilestate = 'active', the backend isn't blocked on anything the database can name, it's actively executing, which points toward CPU-bound (or, less commonly, waiting on something outside the database's own accounting, like a slow client network read on a very large result set). - If
wait_event_type = 'IO'with a specific event likeDataFileRead,WALWrite(PostgreSQL keeps "WAL" fully capitalized in its wait-event names, unlike the "DataFile" family, so this isWALWritenotWalWrite), orDataFileExtend, the backend is directly waiting on a disk operation, which is the clean I/O-bound case. - If
wait_event_typeisLockorLWLock, the backend is waiting on contention with another session or on an internal shared data structure, which is neither CPU-bound nor I/O-bound in the sense this question means; it's a third category worth naming explicitly, because treating a lock wait as an I/O problem sends you looking in the wrong place entirely.
OS-level signal: is this isolated, or system-wide? A single query showing no wait_event tells you it's actively running, but not whether the whole machine is CPU-saturated or this is one query among many all fighting for the same core. top or vmstat at the host level fills that gap: high %us (user CPU time) system-wide, with load average tracking close to the core count, confirms genuine CPU saturation across the board, not just one query burning cycles while the rest of the system is idle. For the I/O side, iostat -x 1 shows per-device %util (how busy the device is) and await (average time each I/O request takes, including queueing), which distinguishes "the disk itself is the bottleneck" from "requests are queueing because too many things are asking for I/O at once, but the disk itself would be fast if less contended," a distinction that changes whether the fix is faster storage or fewer concurrent I/O-heavy operations.
Combining them into a confident diagnosis, not a guess. A single signal, taken alone, is genuinely ambiguous: wait_event being null could mean this query is CPU-bound, or it could mean it's waiting on something the database doesn't track as a formal wait event, like handing a large result set back to a slow client. Combining the database-level and OS-level signals resolves that ambiguity: if the query shows no wait_event (database says "actively running") and host-level CPU is elevated specifically on the core this backend's process is pinned to or system-wide, that's a confident CPU-bound diagnosis, both layers agree. If the query shows no wait_event but host-level CPU is idle and iostat shows high await on the underlying storage device, that mismatch is itself informative: it suggests the wait is happening somewhere the database's own instrumentation doesn't capture cleanly, which is worth investigating specifically (for example, a network-attached storage layer with its own queueing that doesn't map directly onto the database's IO wait-event categories) rather than accepting the database's report as conclusive on its own.
Worked example
Picture two queries. Query A: pg_stat_activity shows wait_event null, state = 'active', and it's been running 4 seconds against a table small enough to fit entirely in memory. Host-level top, checked at the same moment, shows the backend's specific process pinned near 100% of one core, with overall system load elevated in proportion to how many similar queries are running concurrently. Both layers agree: this is CPU-bound, likely a computationally expensive operation (a complex aggregate, a function call per row, a sort with a large working set) rather than data-fetching cost, and the fix path is query or computation redesign, not indexing.
Query B: same symptoms at the database level (wait_event null, active, 4 seconds), but top shows overall CPU largely idle, and iostat -x 1 shows the storage device's %util at 95% with await climbing well above its baseline. This is the case where the database-level signal alone (wait_event null) would have pointed toward CPU-bound, but the OS-level signal tells a different, more accurate story: the query is likely doing synchronous read-ahead or prefetching that PostgreSQL doesn't always surface as a formally tracked IO wait event in every code path, and the actual bottleneck is disk throughput, not computation. Without checking both layers, this one would have been misdiagnosed.
Trade-offs and pitfalls
Trusting the database's wait_event classification alone, without a corroborating OS-level check, is the most common way to get this wrong, precisely because (as in query B above) not every form of I/O wait is guaranteed to surface as a database-level IO wait event in every version and code path; the database's instrumentation is good but not exhaustive. Conversely, checking only OS-level tools without narrowing to the specific query first wastes time on system-wide noise when the actual problem is one query among many well-behaved ones; start at the database level to find the specific backend, then confirm at the OS level, rather than starting broad. Lock and LWLock waits are easy to misclassify as an I/O problem if you're not careful about reading wait_event_type specifically rather than assuming any wait means disk; they call for looking at what's holding the lock, not at storage metrics at all.
Unlock Full Question Bank
Get access to all 29 Database Monitoring, Troubleshooting, and Diagnostics interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.