A five-query PostgreSQL report's totals don't reconcile on a busy database — fix it
A month-to-date sales report runs five queries on the PostgreSQL 18 primary while the shop takes about 300 orders a second. Each run, the summary's revenue differs from the sum by region, and its order count from the sum by status. Constraints: the report must not block order writes; it takes about three minutes.
BEGIN; -- the server's default isolation level
SELECT count(*), sum(amount) AS revenue
FROM orders WHERE created_at >= date_trunc('month', now());
SELECT region, sum(amount)
FROM orders WHERE created_at >= date_trunc('month', now()) GROUP BY region;
SELECT status, count(*)
FROM orders WHERE created_at >= date_trunc('month', now()) GROUP BY status;
-- two more GROUP BY queries of the same shape: by channel, by day
COMMIT;Find and fix the bug.
Under Read Committed each statement takes its own snapshot, so orders committed between the queries land in some totals only. Run the report as one REPEATABLE READ READ ONLY transaction: one MVCC snapshot, writers never blocked. It holds back VACUUM.
- Assuming a BEGIN … COMMIT block alone gives every statement the same view of the data
- Reaching for table locks to get consistent totals and blocking the application's writes
- Running a long snapshot on the OLTP primary without noticing it holds back VACUUM
- What happens to dead row versions on the primary while a three-minute snapshot is open?
- How would you make the report consistent if it ran as five separate jobs instead of one session?
Cause. BEGIN … COMMIT groups the statements into one transaction but does not give them a common view of the data. At the default level, Read Committed, each SELECT takes a fresh snapshot when it starts. In the three minutes between the first and last query, tens of thousands of orders commit: some reach the summary, some only the per-region breakdown. The date_trunc('month', now()) bound is stable, because now() is the transaction's start time.
Fix. One snapshot for the whole report:
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT count(*), sum(amount) AS revenue
FROM orders WHERE created_at >= date_trunc('month', now());
-- ... the other four queries unchanged ...
COMMIT;In PostgreSQL, Repeatable Read sees the data as of the transaction's first statement and shows no phantoms, so all five totals are computed over the same rows. Thanks to MVCC the reader blocks no writers: new orders write new row versions that the report's snapshot simply does not see. READ ONLY guards against an accidental write and removes any risk of a serialization error on update.
Cost. While the snapshot is open, VACUUM cannot remove row versions that died after it started — on a table taking 300 orders a second that is noticeable bloat. Keep the report short, and once it grows, move it to a replica or to a warehouse fed by CDC or batch loads.