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.
On a SQL Server instance, you're seeing heavy PAGELATCH_UP waits on tempdb under a parallel build-and-insert workload. Explain the root causes, how you'd diagnose whether this is allocation contention or latch contention, and what concrete mitigations you'd consider, spanning tempdb configuration, engine-level options, and schema or application changes.
Sample Answer
Direct answer
A storm of PAGELATCH_UP waits on tempdb almost never means rows are locked. It means many sessions are fighting over a small set of "traffic control" pages that tempdb uses to hand out space (or, on a different pattern, over the system catalog pages that track temporary-object metadata), and a latch (an in-memory, short-duration protection on a page's physical consistency) is a different animal from a lock (a transactional guarantee on a row or table that can be held for the life of a transaction), and a different animal again from a deadlock (two transactions each waiting on a lock the other one is holding, so neither can proceed until the engine detects the cycle and kills one of them), which is a lock-level phenomenon, not the latch queue described here. Under a parallel build-and-insert workload, this usually happens because many concurrent workers are each creating and dropping temporary tables, table variables, or spill work tables (for sorts, hashes, or cursors) fast enough that the pages coordinating space allocation, or the catalog rows describing those objects, become a single point of serialization. The fix path is: identify which page type is hot with the wait DMVs (dynamic management views, the built-in system views that expose live server state), then apply the mitigation that matches that specific cause, because the tempdb-file-count fix and the metadata fix solve two different problems that both surface as the same wait type.
Structured elaboration
Two distinct root causes behind the same wait type
tempdb is the shared scratch database SQL Server uses for temporary tables, table variables, sort/hash spill space, and version-store data for snapshot isolation. Two unrelated mechanisms inside it can both produce PAGELATCH_UP waits:
| Cause | What is actually contended | Typical trigger |
|---|---|---|
| Allocation-page contention | PFS (Page Free Space), GAM (Global Allocation Map), SGAM (Shared Global Allocation Map): pages that track which pages/extents (an extent is SQL Server's fixed-size 8-page, 64 KB block of storage, the actual unit space is handed out in) in the data file are free | Many small objects created and dropped concurrently, each needing a new page or extent handed out |
| Metadata contention | System catalog pages in tempdb (the tables tracking temp-object names, columns, and structure, e.g. the internal equivalents of sys.objects/sys.columns scoped to tempdb) | Many sessions running CREATE TABLE #t / DROP TABLE #t (or table variable creation) at high frequency, so the catalog rows themselves become hot |
PFS tracks free space on roughly every 8,000-page range of a data file; GAM and SGAM each track roughly 4 GB of space per page (GAM records which extents are already allocated, SGAM which mixed extents, extents whose 8 pages are shared across several different small objects rather than dedicated to just one, still have a free page). Because SQL Server's allocation scan always starts at a predictable page, when many sessions allocate at once they queue up on the same PFS/GAM/SGAM page even though they're allocating different, unrelated objects. That is allocation-page contention: real work is blocked on a bookkeeping page, not on each other's data.
Metadata contention is a separate mechanism: every temp table create/drop touches rows in tempdb's own system catalog, and those catalog pages can themselves become a latch hotspot under very high create/drop rates, independent of how much data space is available.
Diagnosing which one you have
First confirm the wait itself and who is waiting:
SELECT r.session_id, r.wait_type, r.wait_time, r.wait_resource,
t.text AS running_query
FROM sys.dm_exec_requests AS r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t
WHERE r.wait_type LIKE 'PAGELATCH%';
wait_resource (or resource_description in sys.dm_os_waiting_tasks) is formatted database_id:file_id:page_id, for example 2:1:88 (database_id 2 is always tempdb). To classify the page:
- If
page_idis evenly divisible by 8088, it is a PFS page. - If it is a low, fixed page number that recurs across many different waiting sessions on the same file (classically page 2 or page 3 of a file), it is a GAM or SGAM page.
- If neither pattern holds, or the page belongs to a system object, it is likely metadata contention rather than allocation contention.
To directly test for metadata contention, resolve the page to the object it belongs to:
SELECT OBJECT_NAME(dpi.object_id, dpi.database_id) AS system_table_name,
COUNT(DISTINCT r.session_id) AS session_count
FROM sys.dm_exec_requests AS r
CROSS APPLY sys.fn_PageResCracker(r.page_resource) AS prc
CROSS APPLY sys.dm_db_page_info(prc.db_id, prc.file_id, prc.page_id, 'LIMITED') AS dpi
WHERE dpi.database_id = 2
AND dpi.object_id IN (3, 9, 34, 40, 41, 54, 55, 60, 74, 75)
AND UPPER(r.wait_type) LIKE N'PAGELATCH[_]%'
GROUP BY dpi.object_id, dpi.database_id;
Those ten numbers in the object_id IN (...) list are SQL Server's fixed, built-in object IDs for its own system base tables that back the temp-object catalog (tables like sysschobjs and syscolpars); they're the same on every SQL Server instance, which is why they can be hardcoded here instead of looked up by name. If this query returns rows, sessions are contending on tempdb's own catalog tables (metadata contention). If instead you see the PFS/GAM/SGAM page pattern from the previous step and this query returns nothing, you have allocation-page contention. A key diagnostic tell either way: this is a latch queue, not a blocking lock chain, so it will not show up in a sys.dm_exec_requests blocking-session-id chain the way row-lock blocking does; if you go looking for blocking there and find nothing, that itself is a clue you're looking at the wrong mechanism.
Mitigations, by layer
| Layer | Allocation-page contention | Metadata contention |
|---|---|---|
| tempdb configuration | Multiple equally sized data files: start with one file per logical CPU up to 8, then add in groups of 4 if contention persists. Preallocate size (avoid autogrow storms) and keep growth increments identical across files, since uneven sizing breaks the proportional-fill algorithm the allocator relies on. | Same file-count guidance still helps baseline I/O, but does not address catalog-row contention directly. |
| Engine-level options | On SQL Server 2016 and later, mixed-extent allocation is already disabled and all files autogrow together by default (this is what trace flags 1118 and 1117 did on 2014 and earlier; they are unnecessary, and mostly no-ops, on modern versions). SQL Server 2019+ updates PFS pages under a shared rather than exclusive latch. SQL Server 2022+ adds further GAM/SGAM concurrency improvements. | Enable memory-optimized tempdb metadata (ALTER SERVER CONFIGURATION SET MEMORY_OPTIMIZED TEMPDB_METADATA = ON, SQL Server 2019+), which makes the temp-object system tables latch-free. Requires a service restart and should be bound to a resource pool (a defined slice of the server's CPU and memory that SQL Server's Resource Governor feature can cap a workload to) to cap memory use. |
| Schema / application changes | Reduce the rate of temp-object create/drop: batch parallel workers so each does fewer, larger units of work instead of many tiny ones; if the parallel job is an index rebuild, evaluate whether SORT_IN_TEMPDB (an index build/rebuild option that redirects the sort work needed to build the index into tempdb instead of the same database's own data files) is needed at all, or whether lowering MAXDOP (Maximum Degree Of Parallelism: how many CPU cores SQL Server is allowed to use for a single query) reduces the number of concurrent sort/hash spills. | Reuse a small number of longer-lived temp tables (or a permanent staging table partitioned by worker/session) instead of each parallel worker creating and dropping its own; SQL Server already caches simple temp-table definitions since 2016, but caching stops applying if the temp table has DDL like added constraints or triggers after creation, which forces a fresh metadata operation. |
Worked example
The PFS-page test and the tempdb-file-count recommendation are both concrete, checkable arithmetic. Running this reproduces both:
def is_pfs_page(page_id, interval=8088):
return page_id % interval == 0
print("905856 %% 8088 =", 905856 % 8088, "-> PFS page:", is_pfs_page(905856))
def recommended_tempdb_files(logical_cpus):
if logical_cpus <= 8:
return logical_cpus
return 8 # start at 8; add in groups of 4 if contention persists
for cpus in [4, 8, 16, 32]:
print(f"{cpus} logical CPUs -> start with {recommended_tempdb_files(cpus)} tempdb data files")
total_gb, n_files = 32, recommended_tempdb_files(16)
print(f"{total_gb} GB tempdb split across {n_files} equally sized files -> {total_gb/n_files} GB each")
Output (executed):
905856 % 8088 = 0 -> PFS page: True
4 logical CPUs -> start with 4 tempdb data files
8 logical CPUs -> start with 8 tempdb data files
16 logical CPUs -> start with 8 tempdb data files
32 logical CPUs -> start with 8 tempdb data files
32 GB tempdb split across 8 equally sized files -> 4.0 GB each
So on a 16-core box with a single 32 GB tempdb data file, the concrete first move is 8 files of 4 GB each, not one 32 GB file: each file gets its own GAM/SGAM page pair, so the allocator's round-robin scan across files spreads what used to be one hot page into eight independently-scanned ones.
For the DMV query shape itself, here is illustrative (not executed, since this workload runs on SQL Server and this sandbox has no SQL Server instance) output showing what the classification query would return if you were hitting metadata contention on the temp-object catalog:
system_table_name session_count
------------------ -------------
sysschobjs 14
syscolpars 9
A result like that, with zero hits for the PFS/GAM/SGAM page pattern, tells you memory-optimized tempdb metadata (or reducing create/drop rate) is the right lever, not adding more data files.
Trade-offs & pitfalls
- Do not reach for trace flags 1118/1117 on SQL Server 2016 or later: their behavior is the default already, so setting them is harmless but signals you're diagnosing from stale knowledge, and on genuinely old instances (2014 and earlier) 1118 has a real cost, wasting up to 56 KB per tiny object that never grows past one page.
- Memory-optimized tempdb metadata is not a default-on fix: it requires a restart, and its
MEMORYCLERK_XTPmemory consumer (SQL Server's internal name for the pool of memory the in-memory OLTP / memory-optimized engine uses) can grow unbounded under heavy load, so bind it to a resource governor pool with an explicit memory cap and only turn it on once the catalog-contention diagnostic query above has actually shown session buildup on system tables. Turning it on speculatively is treating a possible symptom as a confirmed diagnosis. - Adding tempdb files is not free either: more files past what CPU concurrency and I/O bandwidth justify just adds round-robin overhead without reducing real contention, and unequal file sizes defeat the fix outright because the proportional-fill allocator favors the file with more free space, funneling load right back onto one file.
- The highest-leverage fix is frequently on the application side, not the infrastructure side: cutting how many temp objects a parallel workload creates and drops per second (by batching, reusing tables, or lowering the degree of parallelism) is usually cheaper and more effective than any tempdb reconfiguration, because it removes the contention at its source instead of spreading it thinner.
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.
On a SQL Server instance, your transaction log is growing unexpectedly large and causing disk pressure. Explain how you'd diagnose the root cause, which DMVs or commands you'd run to investigate, and describe safe steps to reduce the log size without risking data loss.
Sample Answer
Direct answer
SQL Server transaction log growth almost always comes down to one of a short list of causes: a long-running or orphaned open transaction holding the log from being reused, a broken backup chain under the FULL recovery model (only a log backup, not a full or differential backup, actually lets the log truncate), replication or Change Data Capture (CDC) holding log records for a consumer that hasn't caught up, or a genuine spike in write volume from a bulk operation. SQL Server exposes the exact reason it currently won't reuse space through a single column, log_reuse_wait_desc on sys.databases; check that first, before running anything else.
Structured elaboration
Glossary
A DMV (Dynamic Management View) is SQL Server's term for a built-in system view exposing internal server or database state, queried like any ordinary view, directly analogous to Postgres's pg_stat_* views. The recovery model (SIMPLE, FULL, or BULK_LOGGED) determines whether the log can truncate automatically after each checkpoint (a periodic point where SQL Server writes all data changes currently held in memory out to the data files on disk, so the log records covering those changes are no longer needed for crash recovery), under SIMPLE recovery, or only after a log backup, under FULL or BULK_LOGGED; this single setting drives most "the log keeps growing" incidents on a database running FULL recovery without a working log-backup job.
Diagnosis
The single most important query:
SELECT name, log_reuse_wait_desc, recovery_model_desc
FROM sys.databases WHERE name = 'yourdb';
log_reuse_wait_desc names the exact reason SQL Server currently cannot reuse log space: common values include LOG_BACKUP (no log backup has run since FULL recovery started retaining log), ACTIVE_TRANSACTION (a long-running or orphaned open transaction), and REPLICATION (a replication consumer hasn't acknowledged), among others. This tells you directly which cause applies, rather than inferring it.
SELECT total_log_size_in_bytes, used_log_space_in_bytes,
used_log_space_in_percent, log_space_in_bytes_since_last_backup
FROM sys.dm_db_log_space_usage;
This gives current size and, specifically, how much log has accumulated since the last log backup, useful both for confirming severity and for quantifying whether a log backup would actually relieve it; a log_space_in_bytes_since_last_backup close to the total confirms LOG_BACKUP as the practical driver.
DBCC SQLPERF(LOGSPACE); is an older, simpler, server-wide command listing log size and percent used for every database on the instance in one call, useful for a quick sweep of whether the problem is isolated to one database or several.
If log_reuse_wait_desc = 'ACTIVE_TRANSACTION', find the actual open transaction by joining the active-transactions and session-transactions DMVs to the session and request DMVs; this identifies the specific session and how long its transaction has been open. An orphaned, forgotten open transaction, for example an application connection that began one and never committed or rolled back, sometimes from a connection-pool bug, is a very common finding here.
DBCC LOGINFO; shows the individual virtual log file (VLF) segments and their status, active versus reusable, useful when the concern is specifically VLF fragmentation: a log that grew in many small increments accumulates a large number of small VLFs, which itself can slow crash recovery and log-related operations, a separate but related operational concern from raw growth.
Safe steps to reduce log size without risking data loss
If the cause is LOG_BACKUP, the common case for a FULL-recovery database, take a log backup; this is the correct way to let SQL Server reclaim internal log space, and it's data-safe, since a log backup is a normal part of the FULL recovery model's backup chain, not a destructive operation. Then set up or fix a recurring log-backup job so this doesn't recur. If the cause is ACTIVE_TRANSACTION, commit or roll back the identified transaction, coordinating with whoever owns that session or application first where possible; killing a transaction mid-flight is always safe for data integrity (a rollback is transactionally consistent) but may have application-level consequences for whatever was in progress. Only after the underlying cause is resolved and log backups are flowing normally, if the log file is now genuinely oversized relative to steady-state need, shrink it once to reclaim disk space and let it regrow naturally to a size that accommodates normal peak activity; shrinking repeatedly as routine maintenance is an anti-pattern, since it just forces the file to grow again on the next busy period, and growth events themselves briefly pause writes while the OS allocates space.
Never switch the database to SIMPLE recovery as a quick fix for log growth without confirming with whoever owns the backup and recovery strategy first: SIMPLE recovery breaks point-in-time restore and invalidates the existing backup chain, a durability and recoverability decision, not a storage-management knob.
Worked example
SQL Server isn't available to execute directly in this environment; the DMV and column names above were verified against Microsoft's current documentation rather than presented from memory (sys.dm_db_log_space_usage reports database_id, total_log_size_in_bytes, used_log_space_in_bytes, used_log_space_in_percent, and log_space_in_bytes_since_last_backup). The arithmetic that view reports is not a black box; given pinned example values it computes directly:
total_log_size_in_bytes = 8_589_934_592 # 8 GiB
used_log_space_in_bytes = 6_764_573_492
used_log_space_in_percent = round(100 * used_log_space_in_bytes / total_log_size_in_bytes, 2)
print(used_log_space_in_percent)
78.75
used_log_space_in_percent is exactly used_log_space_in_bytes / total_log_size_in_bytes * 100; a log at 78.75% used, on an 8 GiB log, is the kind of reading that should already have triggered an alert well before hitting LOG_BACKUP as the confirmed log_reuse_wait_desc cause and taking the corrective backup.
Trade-offs and pitfalls
- Killing the
ACTIVE_TRANSACTIONsession without checking what it was doing is always safe for the database itself, but can be disruptive for whatever application flow was mid-transaction; understand the blast radius before killing it under pressure. - Repeated
DBCC SHRINKFILEas routine maintenance is the single most common SQL Server log anti-pattern: it treats a capacity symptom with a maintenance operation instead of fixing the actuallog_reuse_wait_desccause, and the resulting grow-shrink cycle causes more VLF fragmentation and more autogrowth pauses than simply leaving the file at a stable, appropriately sized value would have. - Switching to
SIMPLErecovery genuinely stops the symptom, the log truncates automatically after each checkpoint, but it silently gives up point-in-time recovery capability. Treat it exactly like disabling WAL archiving on another engine: a durability decision disguised as a quick fix, requiring the same sign-off a backup-strategy change would.
You're on call and get paged for "high CPU and slow queries" on a production relational database. Walk through your first diagnostic steps: what you'd check first, which system and database-level commands you'd run to gather evidence, what you'd correlate against a recent deploy or config change, and how you'd package what you found for whoever picks up the deeper investigation.
Sample Answer
Direct answer
Before touching anything, I spend sixty seconds orienting: what changed recently, and which of three buckets does this look like (database-level, infrastructure-level, or application-level)? Then I run one focused command sweep that covers sessions, locks, and I/O in a single pass, form a hypothesis, apply only the fixes that carry no downside if I'm wrong, and hand off a written timeline to whoever picks up the deeper work. The goal of the first five minutes is triage and evidence collection, not a permanent fix.
Structured elaboration
Step 0: pick a bucket before you start clicking around. A single noisy customer's query going slow could be a database-level problem (bad query plan, lock wait), an infrastructure-level problem (the underlying host or cloud volume is degraded), or an application-level problem (a new code path sends 50x more of that query, or a connection pool misconfiguration is serializing requests that used to run in parallel). Naming the bucket up front stops you from reflexively reaching for EXPLAIN (the command that shows the execution plan the database chose for a query, i.e. which indexes or scans it actually used) when the real problem is a saturated disk.
Step 1: correlate against the timeline, not just the symptom. Pull up whatever change history the team has (deploy log, config management history, database driver/ORM version in the last release, a recent schema migration, an autoscaling event) and line it up against when the pages started. A page that starts within minutes of a deploy is a different investigation than one that started three hours after the last deploy with no correlated change. If nothing correlates, that itself is a data point: it points toward a data-volume or traffic-driven cause rather than a code or config change.
Step 2: one sweep, not five separate lookups. I run a single investigative pass instead of jumping between five different consoles:
-- 1. What's running right now, and for how long
SELECT pid, state, wait_event_type, wait_event, now() - query_start AS running_for,
left(query, 80) AS query
FROM pg_stat_activity
WHERE state <> 'idle' AND pid <> pg_backend_pid()
ORDER BY query_start;
-- 2. Who's blocked, and by whom (idiomatic form)
SELECT pid, wait_event_type, wait_event, pg_blocking_pids(pid) AS blocked_by
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
-- 3. Buffer cache health (is this a memory or an I/O problem?)
SELECT round(100.0 * sum(heap_blks_hit) /
nullif(sum(heap_blks_hit) + sum(heap_blks_read), 0), 2) AS cache_hit_ratio_pct
FROM pg_statio_user_tables;
-- 4. Table-level activity shape (sequential scans vs index use, dead-row buildup)
SELECT relname, seq_scan, seq_tup_read, idx_scan, n_live_tup, n_dead_tup
FROM pg_stat_user_tables
ORDER BY seq_tup_read DESC
LIMIT 10;
I ran this exact sweep against a seeded PostgreSQL 16 instance (2 million rows in an orders table, a separate sessions table carrying deliberate dead-row bloat from unvacuumed updates) and got real numbers back:
cache_hit_ratio_pct: 99.59
relname | seq_scan | seq_tup_read | idx_scan | n_live_tup | n_dead_tup
----------+----------+--------------+----------+------------+------------
orders | 18 | 12000000 | 515 | 2500000 | 2
sessions | 14 | 2400072 | 0 | 200000 | 1200000
That last row is a real finding, not a hypothetical one: sessions has 1.2 million dead rows sitting on top of 200,000 live ones (a 6x dead-to-live ratio), and every one of its 14 sequential scans is walking past all of that dead weight. A 99.59% cache hit ratio tells you this isn't a memory-pressure problem (the working set fits in shared buffers); the CPU and latency cost here is from scanning bloat, not from disk fetches.
Step 3: apply only the fixes with no downside if your hypothesis is wrong. Three moves are safe to make live, before the deeper investigation is done:
SET statement_timeout = '5s'(session- or role-scoped) so a single runaway query can't hold a lock or a connection slot indefinitely while you investigate; it doesn't fix the cause but it caps the blast radius.CREATE INDEX CONCURRENTLYif the sweep points at a genuinely missing index; it builds without taking the exclusive lock a plainCREATE INDEXwould, so it doesn't add a second incident on top of the first. I ran this against the same instance (CREATE INDEX CONCURRENTLY idx_orders_created_at ON orders (created_at);) and it completed cleanly withindisvalid = true, no blocking.ANALYZEon the specific table you suspect, ifn_dead_tupor query plans suggest stale statistics; it's a read of the table's rows plus a metadata write, not a schema change, so it's low-risk even under load (though on a very large table it does cost real I/O, so don't run it against ten tables at once during an active incident).
Step 4: name the shape of the root cause, including the ones you can't fix right now. Two shapes come up constantly: a query that used to be fine and now runs against 10x the data (data growth outpacing the original index or query design), or a table that was never really tuned, growing steadily, now hitting frequent full-table scans as it crosses a size threshold where the planner's old assumptions stop holding. Both are real and worth naming in your handoff, but neither is a five-minute fix: redesigning indexes or partitioning a monolithic table is medium-term (weeks-to-months) prevention work that belongs to query and schema tuning, not to this incident. Say so explicitly rather than trying to solve it while paged.
Step 5: check blast radius and communicate before you're fully done investigating. Don't wait for a root cause to tell people what you know. Check whether this is surfacing as errors in dependent services (application-side 500 responses, timeouts in a downstream queue consumer, elevated retry rates) so you can scope the incident correctly, and post a short, factual status update: what's affected, what you've ruled out, what you're checking next. Silence during an active incident is worse than an update that says "still narrowing it down."
Step 6: package the handoff. Whoever picks up the deeper investigation should get, in writing: the timeline of what changed and when, the raw output of your sweep (not just your interpretation of it), which of the three buckets you believe this is and why, what you've already ruled out, and the safe mitigations you already applied (so they don't get re-applied or accidentally reverted).
Worked example
Page comes in: "high CPU and slow queries" on the orders database. Bucket check: dashboard shows CPU climbing steadily over two hours, no step-function jump, so I lean database-level or data-volume-driven rather than infrastructure (no VM eviction or noisy-neighbor signature) or a single bad deploy. Timeline check: no deploy in the last six hours, but the on-call channel shows a bulk data-import job that landed 400,000 new rows into orders four hours ago. Sweep: pg_stat_user_tables shows orders at 18 sequential scans reading 12 million tuples total against a 2.5 million row table (the scans are individually cheap over a small table but expensive now that data grew 5x), and the cache hit ratio is a healthy 99.59%, ruling out a memory problem. Hypothesis: the import shifted the table's statistics enough that a query the planner used to route through an index is now taking a sequential-scan path, or an index that existed pre-import is no longer selective enough. Safe action: ANALYZE orders; to refresh statistics (cheap relative to the problem, no schema change), then re-check whether the hot query's plan changes. I'd hand off with: "CPU climbing over 2h, correlates with a 400k-row bulk import 4h ago, no recent deploy, cache hit ratio rules out memory pressure, ran ANALYZE as a safe first step, here's the sweep output, next person should pull EXPLAIN on the top three queries from pg_stat_statements to confirm the plan actually flipped."
Trade-offs and pitfalls
Tunnel vision on the first metric you see (usually CPU, because that's what paged you) is the single most common mistake: CPU is often a symptom of something else (a bad plan doing far more work than necessary, or the buffer cache thrashing) rather than the root cause itself. ANALYZE and CREATE INDEX CONCURRENTLY are low-risk but not free: ANALYZE on a huge table does real I/O and can itself add load during an already-strained window, and CREATE INDEX CONCURRENTLY can fail partway through and leave behind an invalid index that needs to be dropped and retried, so check pg_index.indisvalid afterward rather than assuming success. statement_timeout protects you from one runaway query but will also kill a legitimate long-running batch job if you set it too aggressively or forget to scope it to a role instead of applying it globally, so scope it narrowly and remove it once the incident is over rather than leaving it as an accidental permanent change.
You've just inherited on-call ownership of a production relational database that's never had real monitoring set up. What would you actually put on a dashboard and watch, and how would you go about setting alert thresholds so the on-call rotation gets paged for real problems without drowning in noise?
Sample Answer
Direct answer
I'd put four categories on the dashboard: request-level health (queries per second, latency at the p50 and p99 percentiles, error rate), resource saturation (connections in use, cache hit ratio, lock wait time), replication and durability (replication lag, write-ahead log queue depth, backup freshness), and the specific failure modes that have actually paged people before. For alerting, I set thresholds using rolling windows and a warn/page split, not single static numbers, and I map every page to a first remediation step so the on-call engineer isn't starting from zero at 3am.
Structured elaboration
What goes on the dashboard, and why each one.
| Metric | What it tells you | Why it matters here |
|---|---|---|
| Queries per second (QPS) / transactions per second (TPS) | Overall load level | Baseline for everything else; a latency spike at 2x normal load means something different than the same spike at flat load |
| Latency, p50 and p99 | Typical vs. tail experience | The average hides the pages: a p50 of 5ms with a p99 of 4s tells you a subset of queries or users are badly served even while the average looks fine |
| Active connections vs. max_connections | Headroom before the pool is exhausted | This is a leading indicator: connection exhaustion is usually visible minutes before it causes outright rejected connections |
| Cache (buffer) hit ratio | Whether the working set fits in memory | A drop here often precedes a latency spike, because the database starts going to disk for data it used to serve from memory |
| Lock wait time / count of blocked sessions | Contention, not raw load | High QPS with low lock wait is a scaling problem; low QPS with high lock wait is a code or transaction-design problem |
| Replication lag (time and bytes) | Read-replica freshness, failover readiness (failover: promoting a replica to take over as primary if the current one fails) | Determines whether reads from a replica are stale and whether a failover right now would lose data |
| Write-ahead log (WAL) queue / replication send lag | Whether the primary is generating writes faster than a replica or backup process can consume them | Rising WAL queue depth with flat replication lag on other metrics is often a network or replica-I/O problem, not a primary-side one |
| Backup completion and validation freshness | Whether your last known-good restore point is real | A backup job that "succeeds" but was never test-restored is not actually a safety net; track age since last validated restore, not just last backup run |
If the cluster runs on a storage engine with background compaction (an LSM-tree, log-structured merge-tree: a storage design that buffers writes in memory and periodically merges, or compacts, them into new sorted files on disk instead of updating in place; or a columnar engine, one that stores each column's values together instead of each row, common for BI, business intelligence, and analytics workloads) sitting next to the OLTP (online transaction processing: the primary's regular small, latency-sensitive reads and writes) primary, such as a Citus columnar table (Citus is primarily PostgreSQL's distributed sharding extension; Citus columnar is one table access method within it, added for compressed, append-mostly storage of historical partitions, not the extension's main purpose) or a ClickHouse/TimescaleDB continuous-aggregate sidecar (a separate analytics-oriented database kept in sync with the primary specifically to serve rollup queries without loading the OLTP primary), add compaction backlog and table bloat (wasted, dead space that accumulates in a table or index and isn't automatically shrunk back down) to the list; a growing compaction backlog degrades read latency the same way index bloat does on a classic B-tree engine, just through a different mechanism.
Setting thresholds without drowning in noise.
Three techniques matter more than picking the "right" number:
- Use rolling windows, not instantaneous values. A single 5-second latency spike from garbage collection or a checkpoint is normal; the same value sustained for 5 minutes is not. Alert on "p99 latency over 500ms for 5 consecutive minutes," not on any single sample crossing 500ms.
- Split warn from page. Warn (visible on a dashboard, maybe a low-priority ticket) catches trend problems early; page (wakes a human) is reserved for things that are both urgent and actionable right now. Example: cache hit ratio dropping below 95% is a warn (the working set is starting to outgrow memory, worth planning around); dropping below 85% is a page (you're now taking a meaningfully worse I/O hit on a large fraction of reads).
- Prefer relative and anomaly-aware thresholds over hardcoded absolutes where the baseline varies by time of day or by deployment size. A fixed "QPS > 10,000" alert is wrong for a service whose normal peak is 50,000; a threshold expressed as a deviation from the same hour last week, or a simple rolling z-score, survives normal traffic-shape changes without needing to be hand-tuned every time the service grows.
Concrete threshold examples, with the reasoning attached (not just the numbers):
- Cache hit ratio: warn under 95%, page under 85%. Reasoning: below 95% you're starting to lose the benefit of memory caching on a meaningful slice of reads; below 85% the marginal cost of each additional point drops is large, because you've moved from "occasional disk read" to "disk read is now common."
- Replication lag: warn over 30 seconds, page over 300 seconds (5 minutes). Reasoning: 30 seconds of staleness is tolerable for most read-replica use cases and often self-heals; 5 minutes means a failover right now risks losing up to 5 minutes of committed writes on an asynchronous replica, and reads from that replica are stale enough to be user-visible.
- Long-running transactions: page anything open longer than 10 minutes holding row or table locks. Reasoning: a transaction open that long is either a bug (forgotten
COMMIT), a batch job that should be broken into smaller pieces, or actively blocking other work; none of those are things you want to discover only when something else pages. - I/O operations per second (IOPS) on the storage volume, if the cluster runs on cloud block storage (a virtual disk volume attached to the database server, such as AWS EBS or GCP Persistent Disk, as opposed to object storage): page at 90% of the provisioned IOPS ceiling, sustained for 5 minutes. Reasoning: cloud volumes throttle hard at the ceiling rather than degrading gracefully, so you want the page before you hit the wall, not after latency has already spiked.
Map every page to a first action, not just a threshold. An alert without a next step trains people to acknowledge and go back to sleep. Two of the most common:
- High I/O wait alert fires: first action is to check whether it's a specific query (via the active-session view) versus a broad pattern across all queries (pointing at the underlying storage), and whether a recent deploy or backfill job correlates.
- Replication lag alert fires: first action is to check whether the primary's write volume actually increased (a load-driven cause you may just need to ride out) versus the replica itself being resource-starved (a replica-side problem you can act on directly, like resizing or restarting a stuck apply process).
Worked example
Say the team's baseline is 2,000 QPS with p99 latency normally around 40ms. I'd set: p99 latency warn at 150ms sustained 5 minutes, page at 400ms sustained 5 minutes (roughly 4x and 10x baseline, chosen because a load test showed the application's own request timeout is 500ms, so 400ms is the last point where paging still gives someone time to act before users see timeouts, not after). Connections in use: warn at 70% of max_connections, page at 90%, because pool exhaustion is a hard cliff, not a gradual degradation, so you want the warning well before the cliff. If, after a week of this configuration, the warn-level connection alert has fired forty times with no corresponding incident, that's a signal the threshold is miscalibrated for this workload's normal variance, not that the metric is useless; the fix is widening the window or raising the threshold, not deleting the alert.
Trade-offs and pitfalls
The most common failure mode isn't missing an important metric, it's alerting on too many of them with static thresholds tuned for a different traffic level than the service has grown into, which trains the on-call rotation to ignore pages. The opposite failure, cutting alerts down to "just the essentials," risks the exact regression this question is trying to avoid: rediscovering a real incident an hour late because nothing caught it. Anomaly-aware and relative thresholds reduce false positives but are harder to reason about at 3am ("why did this page, the number doesn't look that bad") than a simple static threshold, so pair them with a runbook line that explains, in plain language, what the alert is actually detecting. A backup-freshness check that only verifies "the job ran" rather than "the resulting backup restores cleanly" is a common blind spot: it will show green right up until the day you actually need it and discover the backup was silently corrupt.
Unlock Full Question Bank
Get access to all 8 Database Monitoring, Troubleshooting, and Diagnostics interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.