Database Monitoring, Troubleshooting, and Diagnostics Questions
Observing and fixing databases in production: health checks, metrics and alerting, and diagnosing common failures like slow queries, lock contention, replication lag, resource exhaustion, and data-integrity incidents such as duplicate keys or lost updates after a crash or migration. Covers a systematic troubleshooting method under incident pressure. Tests operational instincts distinct from design knowledge.
You'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 observe growing lock contention and many blocked transactions causing user-visible slowdowns. Walk through diagnostic steps to identify blocking chains and the root blocking session in PostgreSQL or MySQL. Include example SQL or commands to find blockers, how to interpret the lock types you find, and safe remediation steps to resolve the blocking without violating data consistency.
Sample Answer
Direct answer
I find the root blocking session first, because in a chain of blocked transactions everyone downstream is just waiting on the one at the top; fixing anyone else does nothing. In PostgreSQL, pg_blocking_pids(pid) does that lookup directly for you. Once I know which session actually holds the lock, I look at what it's doing and how long it's been doing it before choosing between letting it finish, canceling its current statement, or terminating the connection outright, in that order of preference, because each option gets more disruptive.
Structured elaboration
Finding the blocking chain in PostgreSQL. The built-in function pg_blocking_pids(pid) returns the process IDs currently blocking a given session, which is simpler and more reliable than hand-writing a self-join against pg_locks:
SELECT pid,
application_name,
wait_event_type,
wait_event,
pg_blocking_pids(pid) AS blocked_by,
state,
left(query, 60) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
For a manual look at the underlying locks (useful when you want to see the lock mode, not just who's blocked):
SELECT locktype, relation::regclass, mode, granted, pid
FROM pg_locks
WHERE relation = 'orders'::regclass
ORDER BY granted, pid;
Finding the blocking chain in MySQL. InnoDB (MySQL's default storage engine) exposes the same shape of information through information_schema (or performance_schema on modern MySQL): SELECT * FROM sys.innodb_lock_waits; in the sys schema view gives a ready-made blocked-versus-blocking pair, and SHOW ENGINE INNODB STATUS includes a TRANSACTIONS section listing the most recent deadlock (a cycle where two or more sessions are each waiting on a lock the other one already holds, so neither can proceed without help, unlike the one-directional chain this whole example is built around) if InnoDB had to resolve one automatically.
Finding the blocking chain in SQL Server. The dynamic management views (DMVs, system views exposing live server state) sys.dm_exec_requests and sys.dm_tran_locks carry the same information under different names: sys.dm_exec_requests.blocking_session_id directly names the blocking session (0 or null means not blocked), and joining to sys.dm_tran_locks on the transaction ID shows the specific lock resource in contention, the same way pg_locks does for PostgreSQL.
Interpreting the lock types you find. A relation-level lock (PostgreSQL) or table-level lock blocks broadly; a tuple or row-level lock is narrower and usually the more common, less disruptive case in day-to-day OLTP (online transaction processing, meaning many small concurrent reads and writes rather than long-running analytical scans) traffic. transactionid as the wait type in PostgreSQL means one transaction is waiting for another to commit or roll back entirely, which is what a plain row-level UPDATE conflict looks like: the second UPDATE isn't waiting on the row's storage, it's waiting on the first transaction's outcome.
Telling a deadlock apart from ordinary blocking. Ordinary blocking, like the chain this whole example walks through, is one-directional: B is stuck behind A, but A itself isn't waiting on anything, so it can sit that way indefinitely, for as long as A holds the lock. A deadlock is a cycle instead: A waiting on a lock B holds while B is simultaneously waiting on a lock A holds, so neither can finish without outside help. PostgreSQL checks for that cycle automatically on a timer (deadlock_timeout, one second by default) and, if it finds one, aborts one of the participating transactions itself with a deadlock detected error. That's the practical tell from pg_stat_activity: a session sitting in pg_blocking_pids() behind a single, non-waiting blocker for more than a second or two is ordinary contention, not a deadlock, because a real deadlock would not survive that long on its own, PostgreSQL would already have broken it. To confirm a deadlock actually happened, look at the logs for the deadlock detected error rather than expecting to catch the cycle live in pg_stat_activity; by the time you query it, the database has usually already resolved it.
Safe remediation, in order of preference.
- Wait, if the blocking transaction is short-lived and near completion. Most blocking resolves itself in normal operation within milliseconds to a few seconds; only intervene once you've confirmed it's stuck, not just momentarily busy.
- Cancel the blocking session's current statement, not the connection:
SELECT pg_cancel_backend(pid);in PostgreSQL,KILL QUERY <id>;in MySQL. This asks the running statement to stop and roll back, leaving the connection itself alive so the application can retry over the same connection if it's built to do so. - Terminate the connection outright only if canceling doesn't clear it (a session can be stuck in a state where it won't respond to a cancel, most commonly waiting on a client-side network read):
SELECT pg_terminate_backend(pid);in PostgreSQL,KILL <id>;(as opposed toKILL QUERY) in MySQL. This forcibly closes the connection, which the application will see as a connection error.
Neither option violates data consistency by itself: canceling or terminating a session rolls back its open transaction, exactly the same guarantee the database already gives you for any aborted transaction. The actual risk is application-level, not data-level: whatever partial work that transaction represented needs to be safely retryable, and whoever is holding a connection pool slot (application code borrows an already-open database connection from a shared pool rather than opening a fresh one per request) on that session needs to notice it disappeared and recover cleanly rather than hanging.
Worked example
I reproduced a real blocking chain end to end on a seeded PostgreSQL 16 instance. Session A ran, inside one transaction: BEGIN; UPDATE orders SET status = 'paid' WHERE id = 1; SELECT pg_sleep(15); (holding the row lock open via the sleep, simulating an application that opened a transaction and got stuck before committing). One second later, session B ran UPDATE orders SET status = 'shipped' WHERE id = 1; against the same row. Querying from a third session while both were active:
pid | application_name | wait_event_type | wait_event | blocked_by | state | query
-----+------------------+------------------+---------------+------------+--------+-------------------------------
92 | order-updater-A | Timeout | PgSleep | {} | active | ...UPDATE orders SET status='paid'...
99 | order-updater-B | Lock | transactionid | {92} | active | ...UPDATE orders SET status='shipped'...
pg_blocking_pids(99) returned {92} directly: session B is blocked by session A, full stop, no manual join required. Session A's wait_event_type is Timeout/PgSleep, meaning it isn't blocked on anything else, it's just sitting in pg_sleep(), which is exactly the "stuck application code that forgot to commit" pattern this scenario is modeling. I then ran SELECT pg_cancel_backend(92);. One second later, session 92 had disappeared from pg_stat_activity (its transaction rolled back, since UPDATE plus pg_sleep inside BEGIN never reached COMMIT), and session B's blocked UPDATE went through immediately: querying orders afterward showed status = 'shipped' for that row, confirming B's write landed cleanly with no data corruption, exactly as the "safe remediation" claim above predicts. Note that pg_cancel_backend was sufficient here: A was blocked on its own pg_sleep, which responds to a cancel request, so I never needed the more disruptive pg_terminate_backend.
Trade-offs and pitfalls
Killing the wrong session in a multi-way chain (canceling B instead of A in the example above) accomplishes nothing: B was never holding anything, it was waiting, so the real blocker keeps blocking and you've just added an unnecessary rollback. Canceling a session that's deep into a large multi-statement transaction throws away all of that transaction's work, which is correct from a consistency standpoint but can be expensive in wasted effort if it was 90% done; check how much work is likely to be lost before you cancel, not just how long it's been blocking others. A session that repeatedly shows up as a blocker is a symptom worth escalating past the immediate incident: if the same code path keeps opening a transaction and doing something slow (an external API call, a large batch update) before committing, the fix is shortening that transaction's scope in the application, not learning to cancel it faster every time it recurs.
An 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.
List and explain five key metrics you would monitor to assess the health and performance of a production relational database. For each metric, describe one alert condition you might set and why.
Sample Answer
Direct answer
Five metrics cover the core questions a responder needs answered first: is the database slow (a high-percentile query or write latency), is it actually serving load correctly (throughput and error rate), is it running out of room (connection and CPU or memory saturation), is its working set still fitting in memory (buffer or cache hit rate), and, if replicas exist, is it falling behind (replication lag). Pick alert thresholds relative to the workload's own historical baseline and its SLO (service-level objective, an internal target for how the system should perform), not a generic industry number, and expect an OLTP workload (online transaction processing, many small, fast operations) and an OLAP workload (online analytical processing, fewer, larger, longer-running queries) to need different baselines for the same metric.
Structured elaboration
| Metric | What it tells you | Example alert condition | Why that condition |
|---|---|---|---|
| p99 query or write latency | The tail experience, the slowest 1% of operations, catches problems an average hides | p99 latency more than 3x its trailing 7-day baseline for 5 consecutive minutes | Relative-to-baseline avoids one fixed number being wrong for every workload; 5 minutes filters transient blips from real degradation |
| Throughput and error rate (queries or transactions per second, and error or rollback rate) | Whether the database is serving load, and serving it correctly | Error rate above 1% of transactions over a rolling 5-minute window | A latency-only view can miss a database that's fast because it's failing fast, for example rejecting connections outright |
| Connections in use (percent of max) and CPU or memory saturation | Whether the instance is running out of room to accept more work | Connections in use above 80% of the configured maximum for 5 minutes, or CPU above 85% sustained for 10 minutes | Headroom-based thresholds catch the problem before the hard ceiling (connection refusals, out-of-memory) rather than after |
| Buffer or cache hit rate (percent of reads served from memory rather than disk) | Whether the working set still fits in memory; a falling hit rate predicts rising I/O-driven latency before it fully arrives | Hit rate drops more than 10 percentage points below its 30-day baseline | A sudden drop usually means a growing working set or a large one-off query evicting the cache, both worth knowing early |
| Replication lag (if replicas exist) | How far behind a replica is, and how much recent data a failover would risk losing | Lag exceeds the defined RPO (recovery point objective, the maximum acceptable amount of recently written data you could afford to lose), or a fixed threshold like 30 seconds absent a stated RPO | Lag is meaningless without a target; the condition should be "will this violate our stated data-loss tolerance," not an arbitrary number |
On a managed database
A managed relational database service typically removes OS shell access, but the same five categories are still visible, just organized through the provider's own console or API instead of OS commands: host-level metrics (CPU, memory, disk, network, exposed as instance-level monitoring), database-level metrics (connections, buffer hit ratio, via the engine's own views proxied through the console), query-level metrics (top SQL by load, via a performance-insight feature layered on top rather than raw direct access to the engine's own statistics views), and replication metrics (lag, as a first-class console metric since the provider manages the replica topology). Losing shell access doesn't mean losing observability; it means the same five things live in a different namespace. Know where each one lives before an incident, not during one.
OLTP versus OLAP baselines
The same five metrics need structurally different thresholds depending on workload shape. An OLTP system, many small, fast, latency-sensitive operations, should alert tight on p99 latency, since milliseconds matter, and treat connection saturation as urgent, since a starved OLTP system fails user-facing requests immediately; its throughput baseline is usually fairly steady and predictable. An OLAP system, fewer, larger, longer-running analytical queries, should alert loose on p99 latency, since a single query legitimately taking minutes is normal, but tight on sustained resource saturation, CPU, memory, or I/O held near capacity for an extended period is the actual OLAP health signal, since a single slow query is expected but the whole system staying pinned means queuing is building, and on queue depth (how many queries are waiting to run) rather than on individual query latency. Applying an OLTP-shaped p99-latency alert to a warehouse would page constantly on completely normal behavior, and applying an OLAP-shaped hourly-average view to an OLTP system would miss a real user-facing latency spike entirely.
Worked example
Turning the p99-latency alert condition into concrete numbers, showing why a baseline-relative threshold rather than a fixed one is the right shape:
p99_baseline_ms = 42 # trailing 7-day baseline
multiple = 3
threshold_ms = p99_baseline_ms * multiple
print(threshold_ms)
126
At a 42ms trailing baseline, the alert fires above 126ms. If legitimate growth naturally moves the baseline to, say, 55ms next quarter, the threshold recalculates to 165ms automatically, whereas a fixed ">100ms" rule set today would already be uncomfortably close to normal, healthy behavior by then and would need someone to remember to revisit it.
Trade-offs and pitfalls
- A fixed threshold copied from a blog post or another team's dashboard, rather than derived from this workload's own baseline, is the most common reason alerts are either constantly noisy (too tight for this workload's normal variance) or dangerously quiet (too loose, so real incidents don't page). Baseline-relative thresholds avoid this, but need enough historical data to compute a meaningful baseline; don't set them from one week of a system still finding its steady state right after launch.
- Alerting only on averages instead of a high percentile hides exactly the tail-latency problems users actually feel; a p99 spike can coexist with a perfectly healthy-looking average if it affects a small fraction of requests, which is often the fraction most likely to matter most.
- Five metrics is a floor, not a ceiling. This is the minimum viable health picture, not a complete observability strategy; deeper investigation, specific slow-query identification, lock waits, log growth, still needs its own dedicated tooling once one of these five flags a problem.
Given a MySQL slow query log entry, explain what each field means and how you'd use those logs to prioritize tuning work. Describe how to enable slow query logging safely in production, what pitfalls to watch out for, and how to correlate slow log entries with application traces.
Sample Answer
Direct answer
Each slow query log entry in MySQL carries a header with four numbers that matter for prioritization: how long the statement took to execute, how long it spent waiting to acquire locks, how many rows it sent back to the client, and how many rows it had to examine internally to produce that result. The gap between rows examined and rows sent is usually the single most useful number in the entry, since a query that examines a million rows to return ten is telling you almost exactly where the missing index is.
Structured elaboration
Reading the entry. A typical header looks like:
# Query_time: 0.500000 Lock_time: 0.000100 Rows_sent: 42 Rows_examined: 10000
SET timestamp=1234567890;
SELECT * FROM users WHERE status='active';
Query_time: total wall-clock time the statement took, in seconds (fractional, down to microsecond precision on modern MySQL). This is what actually determines whether the query crossed the logging threshold.Lock_time: how much of that total time was spent waiting to acquire a lock, as opposed to doing real work. A query withLock_timeclose toQuery_timeis a contention problem (something else is holding a lock this query needs), not a query-design problem; a query withLock_timenear zero and all its time elsewhere is the opposite.Rows_sent: how many rows actually went back to the client.Rows_examined: how many rows the storage engine had to read through internally to produce that result, before anyWHEREfiltering orLIMITcut it down. This is the number that most directly indicates whether an index is missing or not being used: a huge gap betweenRows_examinedandRows_sent, as in the example above (10,000 examined to send 42), usually means the storage engine is scanning far more of the table than it needs to, either a missing index on the filter column or an existing index the planner isn't using.
Prioritizing tuning work from the log. I don't prioritize by Query_time alone, because a query that's slow purely due to Lock_time needs a completely different fix (resolve the contention, don't touch the query) than one that's slow due to a large Rows_examined-to-Rows_sent gap (add or fix an index). I'd bucket entries into those two categories first, then within the Rows_examined-heavy bucket, prioritize by how frequently that same query shape recurs in the log (a query that's individually only moderately slow but appears constantly is often worth more effort than a rare, one-off slow query).
Enabling slow query logging safely in production. Set the threshold and destination deliberately rather than accepting defaults:
-- how many seconds a query must take to be logged; default is 10s, often too loose to catch real problems
SET GLOBAL long_query_time = 2;
-- write to a file, not the mysql.slow_log table; writing to a table under load risks its own contention and open-file-descriptor pressure
SET GLOBAL log_output = 'FILE';
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow-query.log';
SET GLOBAL slow_query_log = 1;
-- ignore queries that only touch a handful of rows even if they're slow for other reasons (lock waits mostly), keeps the log focused on genuine scan problems
SET GLOBAL min_examined_row_limit = 100;
Persist these with SET PERSIST (MySQL 8.0+) or in the server's configuration file so they survive a restart rather than silently reverting.
Worked example
Given the entry above (Query_time: 0.5, Lock_time: 0.0001, Rows_sent: 42, Rows_examined: 10000) for SELECT * FROM users WHERE status='active': Lock_time is negligible relative to Query_time, so this isn't a contention problem, it's a scan problem. 10,000 rows examined to return 42 is a 238-to-1 ratio, strongly suggesting status has no usable index, or the table is small enough that the optimizer decided a full scan was cheaper than an index lookup anyway (worth confirming with EXPLAIN (the command that shows the execution plan the database chose, i.e. which index or scan strategy it actually used) before assuming an index is missing, since sometimes it exists but isn't selective enough to be worth using). If this same query shape shows up dozens of times across a day's log with a similar ratio each time, that's a strong, low-risk case for adding an index on status: CREATE INDEX idx_users_status ON users (status);, built with ALGORITHM=INPLACE, LOCK=NONE where the storage engine supports it, to avoid locking the table during the build on a production system.
Correlating with application traces. Log entries carry a timestamp and the raw SQL text, but not, by default, any application-side request ID or trace context; the most reliable way to correlate a slow log entry with the specific application code path that issued it is to have the application inject an identifying SQL comment into the query itself (many object-relational mapping libraries and query builders support this directly, or it can be added manually), since that comment survives into the slow log verbatim and gives you a direct link back to the originating request or endpoint, rather than trying to line up timestamps after the fact.
Trade-offs and pitfalls
Enabling the slow query log is not free on a busy production server: writing each entry is an additional disk write per slow query, and under log_output = 'TABLE' specifically, each entry opens the internal mysql.slow_log table, which under high slow-query volume can itself contribute to file-descriptor pressure, one of the reasons FILE output is the safer production default. log_queries_not_using_indexes looks tempting (it logs every query that doesn't use an index, regardless of long_query_time) but is genuinely dangerous to turn on without log_throttle_queries_not_using_indexes set alongside it, since on a large, poorly-indexed table it can flood the log fast enough to itself become a performance and disk-space problem. MySQL writes each entry to the log only after the statement finishes executing and all its locks are released, so log order can differ from actual execution order; don't use log timestamps alone to reconstruct the precise sequence of events during an incident.
Unlock Full Question Bank
Get access to all 9 Database Monitoring, Troubleshooting, and Diagnostics interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.