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 detail | Value |
|---|---|
| Engagement type | Performance diagnostic (PostgreSQL) (fixed scope) |
| 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? |
| Engine | PostgreSQL 16 (assumed for this example) |
| Prepared by | Krzysztof Książek, DB-Ex |
| Status | Illustrative 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.
| Evidence | Provenance | Status |
|---|---|---|
| Table and index definitions | Supplied by the team | Scenario input |
| The statement and its placeholders | Supplied by the team | Scenario input |
| Description of symptoms: which accounts, since when | Team interview | Scenario input; qualitative |
| Driver configuration (server-side prepared statements) | Team interview | Scenario input; not verified |
pg_stat_statements entry for the statement | Requested | Not available: the extension is not installed |
EXPLAIN (ANALYZE, BUFFERS) for a slow and a fast account | Requested | Not available |
Per-account row counts, or pg_stats for account_id | Requested | Not available |
Autovacuum and ANALYZE history for orders | Requested | Not 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.
| # | Observation | Basis |
|---|---|---|
| O1 | No index serves the account filter and the sort together | orders_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 |
| O2 | The planner therefore has two broad strategies, and which one is cheaper depends on the account | Either 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 |
| O3 | The ordering is deterministic | id breaks ties on equal created_at, so repeated calls return the same page. Any change must preserve this |
| O4 | The statement is sent as a prepared statement with parameters | From the driver configuration described by the team |
6. Hypotheses and uncertainty
Scroll horizontally to see all columns when needed.
| # | Hypothesis | Why it is plausible | What would confirm or rule it out |
|---|---|---|---|
| H1 | Accounts with many orders are slow when the plan fetches and sorts all their matching rows | With the account-only index, the work grows with the number of the account’s rows inside the date window | EXPLAIN (ANALYZE, BUFFERS) for a large account: rows read before the sort, and time in the sort |
| H2 | Accounts with few recent orders are slow when the plan walks orders_created_at_idx | The 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’ rows | The same plan capture for a small account: rows removed by the filter |
| H3 | Behaviour that changes after repeated executions points to plan caching | After 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 has | Compare the plan for the same account at the first execution and after several, or compare plan_cache_mode settings on a copy |
| H4 | Accounts became slow “without a deployment” because statistics changed | New tenants or bulk imports change the distribution of account_id; the planner’s estimates follow ANALYZE | pg_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.
| Priority | Recommendation | Rationale | Prerequisites | Trade-offs |
|---|---|---|---|---|
| R1 | Capture EXPLAIN (ANALYZE, BUFFERS) for three representative accounts (small, median, large), both at the first execution and after repeated executions | Distinguishes H1, H2 and H3, which call for different changes | A non-production copy with a realistic distribution, or an approved window on a replica. EXPLAIN ANALYZE executes the statement | Low effort; the copy must resemble production for the result to transfer |
| R2 | Make the per-account distribution visible: row counts per account in the window, or pg_stats for account_id, plus the last ANALYZE time | Needed to choose representative accounts for R1 and to assess H4 | Read access to a replica or copy | Negligible |
| R3 | Consider installing pg_stat_statements for ongoing evidence | Would show the statement’s call count and the spread of execution times | Adding it to shared_preload_libraries requires a restart; plan that as a separate, approved change | Small overhead and a restart; not a prerequisite for R1 |
| R4 | Only if R1 supports H1 or H2: test the index below on the copy | Lets PostgreSQL read one account’s rows for one status already in the required order and stop after 50 | R1 evidence; realistic data; insert-rate figures for orders | Extra write cost and storage; must be built without blocking writes |
| R5 | Only if R1 supports H3: test statement-level plan behaviour on the copy | A generic plan that suits neither small nor large accounts is a different problem from a missing index | R1 evidence; the ability to change the driver setting or statement | Changing 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:
- Select test accounts: at least one small, one median and one large account, and the status values the screen actually uses.
- 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');
- 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.
- Apply one candidate change (R4 or R5), repeat step 3 with the same accounts and parameters, and compare.
- Check correctness: the result for each test account must be exactly the same rows in the same order as before the change.
- 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 ANALYZEruns 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 CONCURRENTLYavoids 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_modeglobally affects every prepared statement. Test at the level of one statement or one connection first. - Statistics. If H4 is confirmed, a manual
ANALYZE ordersafter bulk imports may be part of the fix. Raising the statistics target foraccount_idis 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:
- Which copy or replica can be used for R1, and who can run the captures?
- Which accounts represent small, median and large tenants for this screen?
- Is the driver’s prepared-statement behaviour configurable per statement or per connection?
- What response time does the team consider acceptable for this screen, so that validation has a target?
- Who approves a
CREATE INDEX CONCURRENTLYonorders, and when can it run? - 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.