A summary table for an operational grid

A collections queue that joined the ledger on every page view. How a one-row-per-lease summary table, a single page-and-total query and a few partial indexes made it fast, and why the refresh needs a budget.

The first two posts in this series were about a grid of properties. This one is about a second screen in the same product: the list of leases that staff use for collections work. Who is past due, who has autopay, who was last emailed, whose balance does not match an external ledger. It is the screen people open when money is late, which makes it the one that most needs to be quick.

The naive version

The first implementation did what the data model suggested. It joined leases, companies, properties, payment accounts, a daily balance snapshot, and an aggregation of open charges. It then applied the filters, sorted, and counted the same join a second time for the pager.

The product needed a lot from this screen: filters on ids, enums, ranges and booleans, a global search, and sorts on amounts and dates. Doing that in memory after a wide SELECT does not survive tens of thousands of leases, and doing it in SQL over the charge ledger meant that every page view paid for aggregating charges it did not display.

One row per lease

The design is a summary table with one row per lease. The list query reads the summary and joins to a few small tables for names. It does not touch the charge ledger at all.

The columns worth denormalizing are exactly the ones the grid sorts or filters on:

  • a past-due flag, the past-due amount and the days past due
  • autopay status, the last result and the next charge date
  • the dunning stage
  • statement-delivery status and when the lease was last emailed
  • a contact-log count
  • the live unpaid balance, which is the sum of amount minus paid over the charge statuses that count toward the balance
  • whether a payment account exists

The unpaid balance is stored on the summary and recomputed when the summary is refreshed, with its own sort index. The rule we apply is simple: if the grid sorts or filters on it, it is a column on the summary. If it is only displayed, it can come from a join on the current page.

The summary is refreshed when the underlying facts change, and by an explicit backfill. How that refresh is run turned out to matter a great deal, and the final post in this series is what happened when we got it wrong.

Query habits that mattered

One round trip for the page and the total. We replaced the second count query with COUNT(*) OVER() on the filtered set, next to the LIMIT. The separate count had been repeating every join and was often the slowest part of the request.

SELECT s.*, l.code, c.name,
       COUNT(*) OVER () AS total
FROM lease_summary s
JOIN leases l ON l.id = s.lease_id
LEFT JOIN companies c ON c.id = l.company_id
WHERE s.is_past_due
ORDER BY s.past_due_amount DESC
LIMIT 25 OFFSET 0;

Start from the summary when the sort lives there. If the sort column is on the summary, start the query from the summary and inner-join leases. The planner can then walk the summary’s index. Starting from leases and sorting on a coalesced expression across several tables usually produces a sequential scan and a sort.

Partial indexes for the hot predicates. Active leases that have not ended. Past-due rows. Rows with no payment account. Most rows are not in the queue the operator is looking at, so a partial index covering only the interesting rows stays small, and stays cache-resident.

Every filter is SQL, and every input is bounded. Array filters are capped at 50 ids. Enum values are whitelisted. An unknown sort field falls back to the lease id, as in the pagination post. Exports use the same filter contract as the list and read 500 rows at a time into the spreadsheet, so memory tracks the batch size and not the number of matches.

Keep downstream hops out of the query timing. Contact details come from another service. We time that enrichment separately and can switch it off with a parameter, includeContacts=false, so a slow downstream call is never mistaken for a slow query, or the reverse. The targets we set were: a list of 25 under 500ms at p95 excluding that hop, the past-due queue under 800ms at p95, and no sequential scan of the charge table anywhere in the list plan.

The same disease in a smaller screen

A lease list scoped to a single property had the same problem in miniature. For every row it ran subqueries for last charged, last paid, unpaid total and next due. Those became a join to a pre-aggregated stats row, with the same endpoint and the same pagination envelope, and a good deal less work per row. If you read the first post, this is the stats table mentioned there for the properties grid. The pattern is identical at both levels.

Be honest about small data

At a few thousand leases, a sequential scan plus a sort of the summary can still take a handful of milliseconds, and the planner will ignore your new index. That is the planner being right. The index earns its place at around ten thousand rows and up, so we publish the EXPLAIN habit and not a claim that every index is used on day one. Check plans on data the size of your largest customer.

The pitfall: a summary is a cache with a product contract

Once the grid reads from a summary, the summary is a promise. Operators will make decisions on it. If the numbers are stale or missing, the grid is wrong, and wrong in the direction of “this tenant owes nothing”.

The temptation is to recompute on read: if a row is missing or old, compute it inside the list request. Do not. If recompute is synchronous inside the list request, the grid is only fast when the cache is warm, and a cold tenant becomes an outage. The first user to open the screen after a deploy pays for the whole tenant.

Recompute belongs on the write path, where the fact changes, and in a rate-limited background job for repair and backfill. The read path should be allowed to see a missing row and say so, but not to fix it while someone waits.

What we would tell another team

Precompute the numbers a grid sorts and filters on. Keep one row per entity the grid lists. Return the page and the total in one query. Index only the slices operators actually look at. And treat the refresh as a first-class piece of the system, with its own limits, because the performance of every read depends on it.

The next post leaves queries behind and looks at what happens when a scheduled job does the wrong amount of work in the wrong place: a connection storm that took down services that had nothing to do with payments.

Previous: Leading-wildcard search without a sequential scan. Next: The job that opened the database six thousand times.