Scrivio Interview library
DesignAdvanced8 min read · updated 12 November 2026

Finance asks for account balances at any point in time from a ledger of 5 billion entries. A query with SUM(amount) OVER (PARTITION BY account ORDER BY posted_at) works on small accounts but not at scale. How would you design this?

Summing all history on every read costs time proportional to the account's history, so I would store balances instead of recomputing them. Each ledger entry gets a balance_after column written at insert time under a per-account lock, which makes a point-in-time balance a single index lookup on (account_id, posted_at); alternatively we keep daily snapshots and add the few entries since. Back-dated entries need recomputing later balances or a bitemporal model with separate effective and booking times, and a regular reconciliation checks that entries still add up to the stored balances.

Why this question is asked

Point-in-time balances are a core finance question: what was this account's balance at the end of the quarter, at the moment of this payment, on the date of this dispute. A window function answers it beautifully on a small table and falls over at 5 billion rows, because it recomputes history on every read. Interviewers ask this design question to see whether we can move work from read time to write time without losing correctness. In this answer, we will see why the window query does not scale, design a running balance stored at write time, compare it with periodic snapshots, deal with late and back-dated entries, and add reconciliation so we can trust the stored numbers.

1Why the Window Query Does Not Scale

The current query computes a running total over the whole history of an account and then picks the row at the requested time.

SQL
SELECT balance
FROM (SELECT posted_at,
SUM(amount) OVER (PARTITION BY account_id ORDER BY posted_at, id) AS balance
FROM ledger
WHERE account_id = :acc) t
WHERE posted_at <= :at
ORDER BY posted_at DESC
LIMIT 1;
-- small account, 200 entries: 1 ms
-- merchant account, 40 million entries: reads and sorts 40 million rows, many seconds

The work is proportional to the history of the account, not to the size of the answer. A merchant account with 40 million entries makes every balance request read and sum 40 million rows, and when finance runs a month-end report for 2 million accounts the database does this for every one of them. As the ledger grows, every read gets slower, forever. The fix is to compute each balance once, when the entry is written, and store it.

2Store the Running Balance at Write Time

We add a column balance_after to the ledger: the account's balance immediately after this entry. To compute it we need the previous balance, and two concurrent postings to the same account must not both read the same previous balance, or one of them will be lost. So the write path takes a per-account lock, for example by locking the account's row in an accounts table that also holds the current balance.

SQL
BEGIN;
SELECT balance FROM accounts WHERE id = :acc FOR UPDATE; -- 1500.00, and other postings to :acc now wait
INSERT INTO ledger (account_id, posted_at, amount, balance_after)
VALUES (:acc, now(), -200.00, 1500.00 - 200.00); -- balance_after 1300.00
UPDATE accounts SET balance = 1300.00 WHERE id = :acc;
COMMIT;
CREATE INDEX ledger_acc_time_idx ON ledger (account_id, posted_at DESC, id DESC);
-- Balance at any point in time: one index lookup
SELECT balance_after FROM ledger
WHERE account_id = :acc AND posted_at <= '2025-03-31 23:59:59'
ORDER BY posted_at DESC, id DESC
LIMIT 1; -- 1300.00
Step throughPosting an entry with a stored balance
Payment serviceaccounts rowledger
SELECT balance FOR UPDATE (lock account)
1500.00
INSERT amount -200.00, balance_after 1300.00
UPDATE balance = 1300.00
COMMIT, lock released

5 messages in order. Play them, or step through them one at a time.

The lock makes postings to one account happen one after another, so each balance_after builds on the previous one.

The read is now independent of the history length: the index takes us straight to the last entry before the requested time, so a 40-million-entry account answers as fast as a new one. The lock serialises writes per account, which is a real constraint for very hot accounts, such as a marketplace's settlement account receiving thousands of postings a second. For those, a serialized write path, a single consumer per account partition reading from a queue, achieves the same ordering without database lock contention.

Notice the tiebreaker id in both the ordering and the index. Many entries can share a posted_at timestamp, and the balance is only well defined if the order of entries is.

3Alternative: Periodic Snapshots

If changing the write path is not possible, for example because the ledger is fed by a legacy system, we can keep a separate table of daily snapshots: balance_snapshot(account_id, day, closing_balance). A nightly job computes each day's closing balance from the previous snapshot plus that day's entries. A point-in-time query then reads the latest snapshot before the requested time and adds the entries since.

SQL
SELECT s.closing_balance + COALESCE(SUM(l.amount), 0) AS balance
FROM balance_snapshot s
LEFT JOIN ledger l
ON l.account_id = s.account_id
AND l.posted_at >= s.day + 1
AND l.posted_at <= :at
WHERE s.account_id = :acc
AND s.day = (SELECT max(day) FROM balance_snapshot
WHERE account_id = :acc AND day < :at::date)
GROUP BY s.closing_balance;
-- reads one snapshot row and at most one day of entries
Two designs compared
Concernbalance_after on each entryDaily snapshots
Point-in-time readOne index lookupOne snapshot plus up to a day of entries
Write pathPer-account lock or serialized writerUnchanged
Extra storageOne numeric columnOne row per account per day
Back-dated entryUpdate every later balance_afterRecompute later snapshots
FreshnessImmediateImmediate (entries since snapshot are added)

This bounds the read cost to one day of entries rather than all history, and the write path is untouched. The costs are a nightly job, storage of one row per account per day (2 million accounts over 5 years is about 3.6 billion rows, so many teams snapshot only accounts with activity), and the need to recompute snapshots when an old entry arrives late.

4Late and Back-Dated Entries

Finance systems receive entries late: a card network settlement arrives two days after the purchase, or an accountant posts a correction dated last month. If an entry is inserted with a posted_at in the past, every stored balance after it is now wrong.

One option is to recompute: insert the entry and update balance_after for every later entry of that account, in the same transaction and under the same lock. For an account with a few thousand later entries this is fine; for a busy merchant it may update millions of rows, so we schedule such corrections in batches.

The more robust option is to separate two times. The booking time is when the entry was recorded in our system, which only moves forward, and the effective time (or value date) is when it counts for the balance. Running balances are kept in booking order, so they never need rewriting, and point-in-time questions are answered as of a booking time. A question such as 'what did we believe the balance was on 31 March, as we knew it on 5 April' then has a precise answer. Keeping both times is called a bitemporal model, and auditors usually want exactly that.

5Reconciliation: Trusting the Stored Numbers

Stored balances are derived data, so they can drift because of a bug, a manual fix or a failed migration. A reconciliation job checks them regularly: for each account, the sum of all entries must equal the current balance, and each snapshot must equal the previous snapshot plus the entries in between. The job can also spot-check that balance_after equals the previous balance_after plus amount, using LAG over a sample of accounts.

SQL
SELECT a.id
FROM accounts a
JOIN (SELECT account_id, SUM(amount) AS total FROM ledger GROUP BY account_id) l
ON l.account_id = a.id
WHERE a.balance <> l.total;
-- expected: no rows; any row raises an alert

On 5 billion entries this job is itself heavy, so it runs on a replica or the warehouse, incrementally by account range, and it alerts finance and engineering on any mismatch. That alert, rather than the design alone, is what lets us trust the fast path.

6Follow-up questions

Why not just cache balances in Redis?

A cache helps with current balances but not with arbitrary points in time, and finance needs answers that are auditable and consistent with the ledger. Storing balance_after in the same transaction as the entry gives a balance that can never disagree with the ledger at commit time, which a separate cache cannot promise.

How would you partition a 5 billion row ledger?

By time, for example monthly partitions on posted_at, so old months can be moved to cheaper storage and queries for a period touch few partitions. The index on (account_id, posted_at) exists per partition. A point-in-time query then finds the right partition quickly, and the latest-before lookup may need to look into an earlier partition when the account was quiet, which the snapshot table can shortcut.

Can the window function still be useful here?

Yes, for backfilling. When we add balance_after to an existing ledger, a one-time job computes it with SUM(amount) OVER (PARTITION BY account_id ORDER BY posted_at, id), chunk by chunk of accounts, and writes the result. The window function is the right tool for computing the values once; it is the wrong tool for computing them on every read.

7Conclusion

In this answer, we saw that summing a ledger's history with a window function on every read costs time proportional to the history, which fails at 5 billion entries. Storing balance_after at write time under a per-account lock, or a serialized writer, turns point-in-time reads into one index lookup, and daily snapshots are an alternative when the write path cannot change. Late and back-dated entries require recomputing later balances or a bitemporal model with booking and effective times, and regular reconciliation keeps the stored numbers trustworthy.

What to say in the interviewAbout 80 seconds aloud

Open with

The window query recomputes the whole history of an account on every read, so its cost grows with the history, which is fine for small accounts and hopeless for a merchant with tens of millions of entries or a month-end report over millions of accounts.

Then, if they want more

So I'd move the work to write time. Each ledger entry gets a balance_after column.

When posting, I lock the account, for example SELECT balance FROM accounts FOR UPDATE, or I route all postings for an account through one serialized writer, then insert the entry with balance_after equal to the previous balance plus the amount and update the current balance, all in one transaction.

With an index on account_id and posted_at descending plus id as a tiebreaker, the balance at any time is just the latest entry before that time, a single index lookup. If I can't change the write path, I'd keep daily snapshots and add the entries since the last snapshot.

Back-dated entries are the hard part: either I recompute every later balance_after, or better, I keep separate booking and effective times, a bitemporal model, so stored balances follow booking order and never need rewriting. Finally I'd reconcile regularly, checking that the sum of entries equals the stored balance and alerting on any drift.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Finance asks for account balances at any point in time from a ledger of 5 billion...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/1ff08599a9/