Sample diagnostic · PostgreSQL

Sample PostgreSQL diagnostic: inconsistent query latency across tenant accounts

Illustrative PostgreSQL diagnostic. Synthetic scenario; no customer data or measured performance result.

PostgreSQL · Version 1.0 ·

Have a question like this about your own system? See how the diagnostic works, or tell me about it.

Also available: the MySQL sample report.

Illustrative PostgreSQL diagnostic. Synthetic scenario; no customer data or measured performance result. The schema, query, indexes and symptoms were written for this example. No query was executed against data to produce this report, and no plan output, timings or row counts are quoted because none were measured.

This is what a PostgreSQL diagnostic report from me looks like: the same sections and the same level of detail. A real report fills them with the evidence that was actually supplied or collected.

Scroll horizontally to see all columns when needed.

Report detailValue
Engagement typePerformance diagnostic (PostgreSQL) (fixed scope)
Principal questionWhy is the recent-orders query fast for some tenant accounts and slow for others, and what should the team test before changing anything?
EnginePostgreSQL 16 (assumed for this example)
Prepared byKrzysztof Książek, DB-Ex
StatusIllustrative sample, version 1.0

1. Provenance and limits

This is an illustrative report. The scenario is synthetic: there is no customer, no production system and no collected evidence behind it. Its purpose is to show how a diagnostic separates what the evidence establishes from what still needs testing.

What this means for the content below:

  • The schema, indexes and query are scenario inputs, written to be technically coherent.
  • The symptom descriptions are scenario inputs, not measurements.
  • Recommendations describe what a team would test next. None of them has been shown to improve performance.

2. Question investigated

The application’s “recent orders” screen shows the latest 50 orders for one tenant account, filtered by order status and limited to the last 90 days. The team reports that it is consistently quick for some accounts and slow for others, and that some accounts became slow without any deployment.

Principal question: why is the recent-orders query fast for some tenant accounts and slow for others, and what should the team test before changing anything?

3. Scope

In scope:

  • One environment: production, reviewed through read-only evidence supplied by the team.
  • One statement: the recent-orders query below, with its existing indexes.
  • The written report and a one-hour technical handover.

Assumptions: PostgreSQL 16, a single primary with one streaming replica, and an application driver that uses server-side prepared statements.

Excluded: changing configuration or indexes in production, other queries and screens, vacuum and bloat review beyond what bears on this question, replication, upgrades and capacity planning.

Scenario schema, reduced to the relevant columns:

CREATE TABLE orders (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  account_id  bigint        NOT NULL,
  status      text          NOT NULL,
  created_at  timestamptz   NOT NULL,
  total       numeric(12,2) NOT NULL
);

CREATE INDEX orders_account_id_idx ON orders (account_id);
CREATE INDEX orders_created_at_idx ON orders (created_at);

The statement as the application sends it. $1, $2 and $3 are application placeholders (account, status, date boundary), so the text is not directly executable in psql:

SELECT id, status, created_at, total
FROM orders
WHERE account_id = $1
  AND status = $2
  AND created_at >= $3
ORDER BY created_at DESC, id DESC
LIMIT 50;

4. Evidence supplied

Scroll horizontally to see all columns when needed.

EvidenceProvenanceStatus
Table and index definitionsSupplied by the teamScenario input
The statement and its placeholdersSupplied by the teamScenario input
Description of symptoms: which accounts, since whenTeam interviewScenario input; qualitative
Driver configuration (server-side prepared statements)Team interviewScenario input; not verified
pg_stat_statements entry for the statementRequestedNot available: the extension is not installed
EXPLAIN (ANALYZE, BUFFERS) for a slow and a fast accountRequestedNot available
Per-account row counts, or pg_stats for account_idRequestedNot available
Autovacuum and ANALYZE history for ordersRequestedNot available

No execution plans for slow accounts were supplied, so the plan PostgreSQL actually chooses in the slow cases is unknown. Sections 5 and 6 are written with that limit in mind.

5. Observations

These follow directly from the scenario inputs:

Scroll horizontally to see all columns when needed.

#ObservationBasis
O1No index serves the account filter and the sort togetherorders_account_id_idx covers only account_id; orders_created_at_idx covers only created_at. Neither can return one account’s rows already in created_at DESC, id DESC order
O2The planner therefore has two broad strategies, and which one is cheaper depends on the accountEither fetch the account’s rows through orders_account_id_idx and sort them, or walk orders_created_at_idx from the newest entry and discard rows for other accounts until 50 match
O3The ordering is deterministicid breaks ties on equal created_at, so repeated calls return the same page. Any change must preserve this
O4The statement is sent as a prepared statement with parametersFrom the driver configuration described by the team

6. Hypotheses and uncertainty

Scroll horizontally to see all columns when needed.

#HypothesisWhy it is plausibleWhat would confirm or rule it out
H1Accounts with many orders are slow when the plan fetches and sorts all their matching rowsWith the account-only index, the work grows with the number of the account’s rows inside the date windowEXPLAIN (ANALYZE, BUFFERS) for a large account: rows read before the sort, and time in the sort
H2Accounts with few recent orders are slow when the plan walks orders_created_at_idxThe walk stops only after 50 matching rows. For a small or inactive account it may read a large part of the window, discarding other accounts’ rowsThe same plan capture for a small account: rows removed by the filter
H3Behaviour that changes after repeated executions points to plan cachingAfter several executions of a prepared statement, PostgreSQL may switch from plans built for each set of values to one generic plan, which cannot adapt to how many rows a particular account hasCompare the plan for the same account at the first execution and after several, or compare plan_cache_mode settings on a copy
H4Accounts became slow “without a deployment” because statistics changedNew tenants or bulk imports change the distribution of account_id; the planner’s estimates follow ANALYZEpg_stats for account_id and the last ANALYZE time, compared with when the slowness began

Uncertainty. Without plans for slow accounts, none of H1–H4 can be established, and more than one may apply to different accounts. The query may also not be the main cause: lock waits or connection-pool queueing would produce similar symptoms and are not covered by the evidence supplied.

7. Prioritised recommendations

First step. Capture plans for a small, a median and a large account on a non-production copy, before choosing any change. The recommendations below depend on what those plans show.

Scroll horizontally to see all columns when needed.

PriorityRecommendationRationalePrerequisitesTrade-offs
R1Capture EXPLAIN (ANALYZE, BUFFERS) for three representative accounts (small, median, large), both at the first execution and after repeated executionsDistinguishes H1, H2 and H3, which call for different changesA non-production copy with a realistic distribution, or an approved window on a replica. EXPLAIN ANALYZE executes the statementLow effort; the copy must resemble production for the result to transfer
R2Make the per-account distribution visible: row counts per account in the window, or pg_stats for account_id, plus the last ANALYZE timeNeeded to choose representative accounts for R1 and to assess H4Read access to a replica or copyNegligible
R3Consider installing pg_stat_statements for ongoing evidenceWould show the statement’s call count and the spread of execution timesAdding it to shared_preload_libraries requires a restart; plan that as a separate, approved changeSmall overhead and a restart; not a prerequisite for R1
R4Only if R1 supports H1 or H2: test the index below on the copyLets PostgreSQL read one account’s rows for one status already in the required order and stop after 50R1 evidence; realistic data; insert-rate figures for ordersExtra write cost and storage; must be built without blocking writes
R5Only if R1 supports H3: test statement-level plan behaviour on the copyA generic plan that suits neither small nor large accounts is a different problem from a missing indexR1 evidence; the ability to change the driver setting or statementChanging plan caching affects planning cost on every call

Candidate index for R4. Equality columns come first, then the sort columns; PostgreSQL can scan a B-tree backwards to satisfy ORDER BY created_at DESC, id DESC:

CREATE INDEX CONCURRENTLY orders_account_status_created_idx
  ON orders (account_id, status, created_at, id);

If the index is adopted, check afterwards whether orders_account_id_idx is still used before deciding whether to drop it. Do not drop it as part of the same change.

8. Validation plan

On a non-production copy with a realistic distribution of orders per account:

  1. Select test accounts: at least one small, one median and one large account, and the status values the screen actually uses.
  2. Run the statement as the application does, as a prepared statement, so that plan caching behaves the same way:
PREPARE recent_orders (bigint, text, timestamptz) AS
  SELECT id, status, created_at, total
  FROM orders
  WHERE account_id = $1
    AND status = $2
    AND created_at >= $3
  ORDER BY created_at DESC, id DESC
  LIMIT 50;

EXPLAIN (ANALYZE, BUFFERS) EXECUTE recent_orders (42, 'shipped', now() - interval '90 days');
  1. Record the plan shape, rows read and removed by filters, buffers and execution time for each account, at the first execution and after at least six executions.
  2. Apply one candidate change (R4 or R5), repeat step 3 with the same accounts and parameters, and compare.
  3. Check correctness: the result for each test account must be exactly the same rows in the same order as before the change.
  4. Measure write cost for R4 with the team’s own insert workload, and record the index size.

Accept a change only if the slow accounts improve in the recorded measurements, the fast accounts do not get worse, and the results are identical.

9. Operational considerations

  • Evidence collection. EXPLAIN ANALYZE runs the statement. For this read-only query that is safe for the data but still uses resources, so run it on a copy or a replica in an agreed window, not ad hoc on a busy primary.
  • Building the index. CREATE INDEX CONCURRENTLY avoids blocking writes, but it takes longer, cannot run inside a transaction block and, if it fails, leaves an invalid index that has to be dropped before retrying.
  • Plan caching. Changing plan_cache_mode globally affects every prepared statement. Test at the level of one statement or one connection first.
  • Statistics. If H4 is confirmed, a manual ANALYZE orders after bulk imports may be part of the fix. Raising the statistics target for account_id is an option to test, not a default.
  • Approval. Every production change above needs the team’s normal review and change approval. This report does not authorise any of them.

10. Handover questions

Before implementing a candidate change, the team needs to resolve:

  1. Which copy or replica can be used for R1, and who can run the captures?
  2. Which accounts represent small, median and large tenants for this screen?
  3. Is the driver’s prepared-statement behaviour configurable per statement or per connection?
  4. What response time does the team consider acceptable for this screen, so that validation has a target?
  5. Who approves a CREATE INDEX CONCURRENTLY on orders, and when can it run?
  6. Is installing pg_stat_statements, with its restart, acceptable as a separate change?

Outside this investigation: other queries, instance sizing, vacuum and bloat review, replication and failover, upgrades, and implementing any of the recommendations. DB-Ex can review the R1 evidence under a follow-up scope if the team wants a second look.

Have a question like this in your own system?

A real diagnostic follows the same structure with the evidence your team provides. Scope, fee and schedule are agreed before work begins.