Skip to content
dbexplore

The invoice names an instance, not a query

A cloud invoice names an instance. Postgres can name the queries. How to split a bill across them with pg_stat_statements, and where the split is wrong.

7 min read

The question from finance is always the same shape. The Aurora cluster cost more this quarter than last, so whose is it? The invoice has an answer and it is useless: the name of the cluster. RDS bills per DB instance-hour, Aurora Serverless bills in ACU-hours per instance, and every line item stops one level above the thing a DBA can actually change.

So the conversation goes sideways. The platform team says the workload grew. The application team says nothing shipped. Somebody opens the instance graphs, sees CPU at a respectable height, and the meeting ends with a ticket to look into it.

What the database can say that the bill cannot

pg_stat_statements keeps a running total, per normalised statement, of the three things a bill is made from. Time spent executing, blocks fetched from outside shared buffers, and bytes of WAL written. The columns are total_exec_time, shared_blks_read and wal_bytes. The extension has tracked WAL usage since PostgreSQL 13, and the query below was run on 16 and 18.

None of those is a dollar. Each is a reasonable stand-in for one pool of dollars. Execution time stands in for the compute you pay for by the hour, reads for the I/O charges if your platform meters them, and WAL for the write path, including every replica that has to replay it.

A share of a pool

The method is arithmetic you can do on a whiteboard. Take what a pool cost you last month, from your own bill. Take each statement’s share of the matching counter. Multiply.

WITH pools(compute_usd, io_usd) AS (
  VALUES (1000.0, 200.0)   -- hypothetical monthly rates, replace with yours
), totals AS (
  SELECT sum(total_exec_time) AS t, sum(shared_blks_read) AS r
  FROM pg_stat_statements
  WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
)
SELECT left(regexp_replace(s.query, '\s+', ' ', 'g'), 50)                   AS query,
       s.calls,
       round((100 * s.total_exec_time / totals.t)::numeric, 1)               AS time_pct,
       round((100 * s.shared_blks_read / nullif(totals.r, 0))::numeric, 1)   AS read_pct,
       round((pools.compute_usd * s.total_exec_time / totals.t
            + pools.io_usd * s.shared_blks_read / nullif(totals.r, 0))::numeric, 2) AS modeled_usd
FROM pg_stat_statements s
CROSS JOIN pools CROSS JOIN totals
WHERE s.dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY modeled_usd DESC NULLS LAST
LIMIT 10;

At those hypothetical rates, a statement responsible for 30 percent of execution time and 10 percent of reads is modeled at 320 dollars for the month: 300 from compute, 20 from I/O. Run it on every node, replicas included, and add the results. Physical replicas share queryid values for the same query, which is what makes the sum possible. Logical replicas do not promise that, and neither do major versions.

That is a useful afternoon. It turns “the cluster” into a ranked list, and the top of the list is usually a surprise to whoever owns it.

Where the split is wrong

The shares always add up to the pool. That is what makes the output look right, and it is also the reason the total can never contradict the bill. Everything that can be wrong is in the split, so that is where to look.

A cache hit is not a billed read. On Aurora, AWS documents that billed read operations accrue for queries that request pages not in the buffer cache and must be loaded from storage, so shared_blks_hit is free by construction. But shared_blks_read is not quite a billed read either. It counts blocks that were not in shared buffers, and PostgreSQL also relies on the operating system cache, so on a host with a page cache some of those never reach storage. Compare your summed shared_blks_read with the platform’s billed read metric for the same window. The two will not match, and the ratio between them is the calibration you actually want.

Average cost is not marginal cost. A statement at 30 percent of execution time does not mean 30 percent of the bill disappears if you remove it. Instances come in steps, and a cluster that is idle at three in the morning is billed for the idle. The method spreads that headroom over the busy statements pro rata, which is fair as an allocation and misleading as a forecast.

The cheap query can cause the cost somewhere else. An UPDATE that runs in a millisecond looks harmless in the time column. Its wal_bytes may tell a different story if the table has a lot of indexes, and replicas pay for that WAL later. Worse is the one that appears in no column. A session left idle inside a transaction can keep old row versions visible, so vacuum has to keep them, and every table it touches grows. The bloat shows up as extra reads under other people’s statements.

The view forgets. pg_stat_statements holds five thousand statements by default and discards the least-executed when it overflows, a count you can read in pg_stat_statements_info. Statistics reset when someone calls the reset function. By default only top-level statements are tracked, so what a function does inside is charged to the call. None of that is hidden. It is simply in a different place from the query you are staring at.

Rank with it, do not invoice with it

Here is the opinion we would defend in front of a finance team: use this for ranking and for conversation, and do not use it for chargeback. A ranked list lets two engineers agree in ten minutes which three statements deserve a look. A per-team invoice built on the same numbers invites a debate about whose shared buffer pool ate whose pages, and nobody wins that debate because the figure was never a measurement.

The honest label is on the number. This is a model, built from counters, priced with the rates you typed in. A bill is what the vendor charged. When the two disagree, the bill is right, and the useful question is why. It is never a reason to nudge the model until it matches. The same goes for any cost figure you show a colleague: say whether it rests on a list price, your own rate or your bill, as how Postgres cost works on a fleet lays out.

There is a real trade-off in how simple this is. Time and reads are blunt. A statement that burns CPU on a function call looks the same as one waiting on a lock for the same duration, and only one of them is a candidate for a smaller instance. You can refine the proxy, split waiting from running, weigh the I/O by platform, but every refinement is another assumption sitting inside a number that looks precise. We would rather start with the blunt version, publish its caveats next to it, and refine only where an experiment confirms the refinement.

The experiment is the one check available. Pick the top statement, change it or move it, and watch the real bill for the pool it was charged to. If the bill moves by about what the model said, you have learned something about this cluster. If it does not, you have learned something more valuable.

The meeting you will be in

Sooner or later someone will ask which team owns the number, and the answer will have to be a name rather than a cluster. The version of this you can defend is the one with the assumptions on the slide: the pools, the counters, the rates, and the line that says modeled.

If you have only ever shown the cluster graph, pull the top ten statements before that meeting and ask each owner whether they would have guessed it. The disagreements are where the money is.

Keep reading

· 6 min read

Your Aurora Serverless floor is billed all night

A minimum capacity set for the busiest hour is billed through the quiet ones too. How to see the floor you pay for, how to pick it, and what lowering it costs.

Read the post →

· 6 min read

Fail-open automation is not automation

When the policy check times out and the action runs anyway, nothing decided that it was safe. Something guessed, with a production primary as the stake.

Read the post →

· 6 min read

The slot was lost at the last checkpoint

Postgres says a replication slot is in danger long before it dies, in a column almost nothing reads. By the time it says lost, the subscriber is gone.

Read the post →

Run this on your own fleet.

DBExplore watches every Postgres you run and acts only inside the guardrails you set. Early access is open in small batches.