Relational databases: collection tree

Relational databases

Diagnosing a database incident

Deep diveAbout 11 minutes AI-generated

A slow application request does not tell you that its SQL needs a faster plan. It may be waiting to borrow a connection, waiting for a lock after reaching the database, or competing for a processor or storage with other work. Each can leave the same spinning page in front of the customer. A useful diagnosis connects that symptom to the work or dependency holding it up.

We will follow Mina asking the shop for her order history. Order 103 already exists, pending, with its two lines worth 29.00 and no payment. Her ordinary history read changes nothing. Separate branches introduce a pool queue, a PostgreSQL table lock and shared resource pressure; they are alternatives, not one accumulating incident. The schedules and timings are illustrative.

The aim is to choose one action whose effect you can predict and check. Native evidence and intervention commands belong to Operating and diagnosing PostgreSQL; the same reasoning needs the appropriate evidence on another engine.

Start with the request

Mina should receive her newest orders. The small starting records return 103, pending, followed by 101, paid. The query asks for the order explicitly:

SELECT order_id, placed_at, status
FROM orders
WHERE customer_id = 1
ORDER BY placed_at DESC, order_id DESC
LIMIT 10;

Suppose the page now takes a second where comparable requests previously completed promptly. Record when the request arrived and when it asked for a connection. Then record when it acquired that connection, sent its statement and consumed the result.

For an illustrative breakdown, suppose these stages happen in sequence. Connection acquisition takes 600 ms. The statement takes another 300 ms. Receiving, processing and returning its result takes the final 100 ms.

Figure 1 One request, several intervals

Illustrative elapsed time · 0 to 1,000 ms

Request
1,000 ms
Get connection
600 ms
Statement
300 ms
Return result

Return result: final 100 ms. Statement time can itself include waits.

600 + 300 + 100 = 1,000 ms. The statement’s 300 ms is already inside the request’s 1,000 ms.

A simplified request with consecutive stages. The first interval begins when the application asks its pool for a connection; the last includes receiving, processing and sending the result. Real tracing boundaries and overlapping work depend on the application.

The 600 ms acquisition wait accounts for most of this invented request. Making its statement instantaneous would still leave at least those 600 ms. Conversely, a trace that wraps the whole connection call in a span named “database” can make a pool queue look like slow execution. Record what each interval actually includes.

The request’s total already contains its statement’s time. Adding both would count the statement twice. The same applies inside the database: a statement’s elapsed time can contain lock waits, storage waits and result delivery. A long elapsed time is a place to investigate, not a processor-use measurement.

Compare the same work before and after

Establish the incident window and the affected work. Are all history requests slow, only one customer’s, or every endpoint using the same pool? Count arrivals, successful useful completions and errors as well as latency. An average for successful requests can improve while more callers time out or are refused.

Keep a small evidence window spanning the onset. Collect request traces (handling parameters appropriately), pool measurements, database activity and wait samples, and resource trends. Add the times of releases, migrations and report starts. Compare equivalent inputs and traffic. Mina’s ten-row history lookup and a year-long report are different work even when they read the same tables.

A release just before the slowdown is a candidate explanation. It becomes stronger when it accounts for a changed query rate, a longer transaction or the actual blocking operation. Timing alone does not tell you which. A missing database reply also establishes only what the caller heard; in a writing request it would not establish whether a commit happened.

Waiting for a connection

A connection pool lends a limited set of database conversations to application work. A caller waiting to borrow one has not sent its statement on that connection. Correlate its acquisition interval with the number of borrowed clients, available clients and queued callers in that same pool. A quiet database cannot show a statement the application has not sent.

Then follow the borrowers. A client can stay occupied while its query executes, waits for a database lock, delivers a large result or waits for application code to finish a transaction. Code can also forget to return it. A full pool establishes where the later callers wait; it does not yet explain why the earlier borrowers remain there. Check each application instance’s pool rather than assuming one total describes them all.

Consider a pool with three clients. A separate session, H, holds an ACCESS EXCLUSIVE lock on orders in an open transaction that changes no business rows. Three history readers borrow all the clients and wait for that lock. Two later callers queue for a client, so they have not yet sent a database statement.

A database wait becomes a pool queue
Figure 2. A lock-only schedule: H changes no rows. Pool waiting and database waiting are different parts of the same chain.
Figure as text

A separate holder H keeps an ACCESS EXCLUSIVE orders lock. Three readers borrow all pool clients and wait for H. Two later callers queue; one leaves without freeing a client or the lock. H rolls back. The readers finish and release their clients, then the remaining caller can proceed.

The first three callers borrowed clients and reached PostgreSQL. The two later callers did neither. Both groups can report slow history requests, but only the first group has a current database statement to inspect. A request identifier, connection identity and statement interval let you connect those observations without inventing five database waiters.

Increasing this pool’s limit would let more history statements reach the same lock. It would not release H. Under resource pressure it could instead admit more competing work. First explain what keeps clients occupied; Connections, overload and capacity develops the limits, queue budgets and overload behaviour after that diagnosis.

Waiting inside the database

Once a request has a connection and an outstanding statement, match that statement to its database session and sample what it is waiting for. A session described as active need not be using a processor. In PostgreSQL, activity state and wait information answer different questions: a query can be active while blocked.

The lock branch uses an ACCESS EXCLUSIVE lock on orders. Mina’s ordinary SELECT needs a conflicting table lock, so it waits. An ordinary row-update lock would not explain this read waiting: PostgreSQL’s ordinary snapshot reads do not wait for those row locks. The kind of lock and the requested operation have to fit the explanation.

H’s lock statement has finished, but its transaction is still open. That is why looking only for a long-running current statement can miss the cause. Follow the blocked statement to its blocker, then inspect that transaction’s lifetime, owner and remaining work. If the blocker also waits, follow the next edge. A chain ending at an idle holder has no cycle; it need not be a deadlock and can outlast a deadlock detector’s checking interval.

If one queued caller gives up, it frees no borrowed client and releases no database lock. Cancelling one of the three database waiters would end that selected statement, but would still leave H holding the lock. The useful intervention depends on who can release the resource, not simply which waiting request looks oldest.

For an actual incident, retain the statement identity, requested resource, blocking relationship and transaction state together. One sample can catch a brief wait that explains little of a long request; repeated samples and the request’s interval make the case stronger. Locks, contention and deadlocks develops repairs to the protected interval, lock scope and acquisition order. Native monitoring and selected cancellation remain with the operations article.

When execution is expensive

If acquisition is prompt and the statement spends its time doing work rather than waiting for the identified lock, investigate that work. The shop’s paid-order report adds agreed line values for paid orders in October and groups them by customer. Its two-row teaching result, Tariq 40.00 and Mina 39.50, says little about the work of finding those totals in a large history.

Query execution and performance follows that report through scans, joins, repeated line lookups, grouping and sorting. Here the incident question comes first: did its work grow, did the same work start happening more often, or did it begin overlapping with foreground requests?

Follow the change within the incident window
Possible changeEvidence to compareWhat it would explain
More inputParameters and rows examined per executionA wider reporting range does more work even with the same plan.
More repetitionCall counts and overlapping executionsAn acceptable report can consume a shared resource when run repeatedly.
A changed routePlans for comparable inputs, including repeated inner workEach invocation now performs more searches or carries more rows onwards.
Temporary workSpill evidence and temporary reads or writesA sort or hash operation has added storage work.

Use changes in cumulative counters over the window, checking their reset times and coverage. A statement with the largest lifetime total may have been cheap throughout this incident. A single slow sample can be unusual, and a quick isolated execution does not reproduce the traffic competing with Mina.

Connect statement work to resource use in the same period: processor demand, storage activity, temporary work and memory pressure. Absence of a recorded wait does not by itself prove processor saturation. A measured plan can locate the work, but collecting one with EXPLAIN ANALYZE runs the statement again. An overloaded service may not have room for that experiment. Preserve existing evidence and use a suitable copy or a bounded diagnostic run.

Pausing an optional reporting schedule is a testable containment when the evidence points there. Predict that new report executions stop, resource demand falls and history completions improve. Already running reports require their own decision; switching off their scheduler does not cancel them. Plan analysis and testing a lasting SQL or index repair belong to the execution article.

Storage delay and running out of space

Storage pressure has two different forms. A statement can wait too long for a read, a temporary write or a durable log flush while plenty of space remains. A volume can also run out of space while its latency still looks acceptable. Measure latency and available space separately.

For delay, match the affected operation’s waits with storage activity and latency during the incident. Database page visits include cached work; a page reported as read by PostgreSQL can still come from the operating system’s cache. A full buffer pool is normal cache use, not proof that the drive is saturated. Storage and durability follows those boundaries.

Other work can share the same device: reports reading pages or spilling, background page writes, and log writes needed by transactions. Find which operation and which storage location account for the change. More demand on a shared volume can delay a small history read whose own plan has barely changed.

For space, examine the relevant volumes, quotas and growth trends. Then identify what is growing. It may be data, indexes, temporary files, retained row versions, recovery logs or unrelated files. Suppose a volume’s free space falls from 12 GiB to 8 GiB over five minutes, then to 4 GiB after another five. A proposed repair needs 6 GiB of extra peak space. Its available window closes before the volume becomes full.

Figure 3 The repair needs space too
Free space falls from 12 to 4 GiB in ten minutes Synthetic observations at minute zero, five and ten show 12, 8 and 4 GiB free. A dashed line at 6 GiB shows the extra space assumed necessary for a proposed repair. The trajectory crosses it before minute ten. It is not safe to assume the repair fits just because some space remains. 128400510GiB freeminutes Repair: 6 GiB extra

At minute 10, 4 GiB remains. A repair needing 6 GiB of extra peak space already does not fit.

Invented free-space observations on one volume. The 6 GiB requirement is an assumed repair estimate, not a database threshold. At the same net growth rate the remaining 4 GiB would last five more minutes; the workload and the rate can change.

At minute ten, “four GiB left” sounds less urgent than “the six-GiB repair no longer fits”. The estimate must also leave room for ongoing writes and cleanup. Extrapolating the recent slope gives a warning horizon, not a promise: a new report or retained log can change it abruptly.

Deleting rows need not return their file space to the operating system. Rebuilding a table can require another copy and take an excluding lock; on PostgreSQL, VACUUM FULL does both. A near-full volume is therefore a poor place to start an unbudgeted rewrite. Do not remove database or recovery-log files by hand. Use the operations, vacuum and WAL procedures to establish safe relief. A full WAL volume can shut PostgreSQL down, so preserving recovery headroom is part of containment.

Choose a bounded intervention

Turn the explanation into one action with a predicted effect, a scope and a stopping condition. In the lock case, the evidence identifies H as a lock-only transaction with no business changes to preserve. Its owner can end it with rollback. The scope is that transaction; the first predicted effect is release of the table lock, followed by the readers finishing and clients returning.

Choose an observation period long enough to see those stages, bounded by the service’s remaining deadline and risk. If H has ended but the expected lock waits remain, check the current blockers. If the lock waits disappear but the queue keeps growing, follow the remaining execution or result-consumption delay. Do not broaden the action merely because the first graph has not returned to normal.

For the report branch, the bounded action might be to stop new optional report runs and observe the foreground workload while existing work finishes. Record when it took effect and what actually stopped. If the supported resource demand falls without history recovery, the report was not the whole explanation. Keep the evidence and revise the hypothesis.

Cancellation and recovery still do work

A caller giving up, a statement being cancelled and a session ending are different events. An application deadline does not prove a cancellation reached the database. A cancellation request does not prove the statement has already stopped. Confirm its terminal result and the transaction’s state before reusing the client; a failed transaction must be ended cleanly.

Ending a session discards its connection and aborts unfinished transaction work. It can therefore affect more than the statement currently visible. Recovery costs depend on the engine and the work: InnoDB can spend substantial time undoing a large transaction, while PostgreSQL hides aborted row versions and reclaims their space later. Neither promises that every resource becomes available the instant a cancellation is requested.

A lost connection during commit leaves a separate uncertainty. The transaction might already have committed. Preserve its request identity and reconcile through the operation’s recovery protocol; do not turn a missing reply into a new purchase. Retries and uncertain commit outcomes develops that distinction.

A restart has a wider scope again. It interrupts other sessions, can trigger crash recovery, loses the database’s warm cache and may bring a rush of reconnecting clients and retries. A restart that removes today’s holder can still leave tomorrow’s workload producing the same queue. Estimate that recovery work before using it as relief.

When a live change triggered the incident

A schema operation may explain the table exclusion in the lock branch. A backfill, which gradually writes existing rows into a new form, may instead explain increased execution, page writing or log growth. Correlate the particular change’s state with the waits or resource demand; “a migration is running” does not identify which mechanism is delaying Mina.

Pausing the migration launcher does not establish that its current database operation ended. Reverting the application release does not undo committed backfill work or prove that older callers still accept the current schema and values. Contain the demonstrated pressure, preserve the change’s state, and check which callers and database operations remain active.

Live schema changes and backfills develops the compatible sequence of schema, data and caller states, including when a change can safely pause or return. During the incident, that compatibility is a condition on the proposed intervention, not something a healthier latency graph can establish.

Verify that useful service recovered

The lock release is only the first predicted change. Confirm that the waiting readers finish, their clients return to the pool, and queued requests can borrow them and complete. Each consequence needs its own observation: a cleared database lock does not establish that the application has recovered.

Figure 4 Follow the predicted recovery
End lock-only holder HConfirmed transaction end
History lock waits disappearStatements can proceed
Readers finish and return clientsPool acquisition queue drains
Mina’s history requests succeedUseful completions, errors and latency recover

A prediction to test for Figure 2, not a guarantee. If the lock disappears but clients remain occupied, follow the unfinished statements or result consumers. If the queue drains only because every caller fails, the service has not recovered.

Observe useful completions, errors, latency and queue drainage under the relevant arrivals. Check requests already queued as well as newly arriving ones. A quiet database after refusing every caller is not a recovered history service. Nor does one successful probe establish that the original request mix is healthy.

Restore paused reporting gradually within the available headroom and watch whether the cause returns. If foreground service degrades again, retain the bound while the lasting repair is tested. Record the incident window, supported cause, intervention, predicted effects and observed recovery so that the next owner can reproduce the reasoning.

The lasting work follows what you found: shorter protected intervals or a different lock protocol, less query work, explicit admission budgets, storage relief or a compatible change procedure. The diagnosis is complete enough to act when it explains both where Mina waited and what had to change for her request to finish.

Sources and further reading

Checked on 25 October 2026. Request durations, pool occupancy, schedules and space trends are illustrative models, not production measurements. The history SQL was checked in PGlite 0.5.8, a WebAssembly build of PostgreSQL 18.3. PostgreSQL lock and intervention details follow its version-18 documentation.