BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
SQL and Relational Database Engineering

Expert · Lesson 12 of 12

Software Architecture

Capstone — Audit a Ledger Under Load

Two couriers, four vouchers and a disputed credit. Audit the postings, weigh a faster query against slower writes, and prove a correction from an isolated restore.

An open ledger and voucher beside a brass balance holding two stacks of counters.

A courier asks why a settlement statement credits the wrong driver. Your dashboard says every movement balances. The checkout team wants to release a faster statement query this evening, and the last backup job succeeded. You have to decide whether to authorize settlement. Each of those observations might be true while the driver is still owed money. In this SQL capstone, build the evidence that would persuade you to sign the statement, or explain precisely why you would hold it.

Use a disposable PostgreSQL database with synthetic vouchers. Audit a single currency in integer fils, with one hundred fils to the dirham. Here a signed posting simply moves value between named accounts. A transfer of 30 dirhams from dispatch to a courier produces minus 3,000 on dispatch and plus 3,000 on the courier. The signs describe this exercise’s transfer convention. Opening balances are zero, and the clearing account is allowed to go negative. We are testing attribution and conservation, not a credit-limit policy.

Write down what the ledger owes before querying it

Keep the approved vouchers outside the database being audited. Voucher V41 moves 12,000 fils from clearing to dispatch. V42 moves 3,000 from dispatch to courier-7. V43 moves 2,000 from dispatch to courier-8. With all three posted correctly, dispatch holds 7,000, clearing holds minus 12,000 and the two couriers hold 3,000 and 2,000 respectively. The four balances sum to zero. More importantly, each amount is associated with a specific obligation and a specific beneficiary.

Model a movement header with a unique, non-null voucher reference. Give its posting rows a foreign key to that reference, a line number, an account, a signed amount and a posting timestamp. Require the latter fields and make the pair of reference and line number unique. For this fixture require exactly two lines, with line one the source and line two the destination. Commit the header and both lines in one transaction. If a client retries a voucher, compare the stored request with the approved input before returning an existing result. Silently accepting a reused reference with a different recipient would make the audit trail ambiguous.

Begin by committing V41. In a second session open the audit transaction below. The first query establishes its snapshot. In a writer session now post V42, pause between its two line inserts, then finish and commit. Post V43 in another transaction. While the audit remains open, its results should continue to describe V41 alone. Close it and start a fresh audit after both commits. Now you should see three headers, six lines and the four expected balances. Write down which snapshot produced each result. Two correct answers taken at different instants can appear to contradict each other.

BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT count(*) FROM movement;  -- establish the audit snapshot
-- Run the checks below in this same session, then COMMIT.

Under PostgreSQL Read Committed, consecutive statements can see different committed populations. A reader could count headers before V42 commits and sum postings afterward. A writer using one transaction still guarantees that a single snapshot sees its complete transfer or none of it. Repeatable Read provides the stable view needed for this multi-query report. It cannot make a writer who committed its header and lines separately behave atomically. To test that defect, use a separate disposable fixture and arrange the snapshot between commits. PostgreSQL describes these visibility rules in Transaction Isolation.

Make a zero total earn its place

Start the structural check from headers. A query starting from postings alone cannot report a header with no children. Count a required child attribute so the preserved header in a left join contributes zero real lines. The expected output below is an empty result set. Verify that the test has teeth by withholding one line in a deliberately broken fixture. It should identify that voucher, its observed line count and its nonzero remainder.

SELECT m.ref, count(p.line_no) AS legs,
       coalesce(sum(p.delta_fils), 0) AS net
FROM movement AS m
LEFT JOIN posting AS p ON p.ref = m.ref
GROUP BY m.ref
HAVING count(p.line_no) <> 2 OR coalesce(sum(p.delta_fils), 0) <> 0;
SELECT account, sum(delta_fils) AS balance_fils
FROM posting GROUP BY account ORDER BY account;

Next compare the independent voucher list with the audit snapshot by reference and line number. Expect two pairs for V42: dispatch with minus 3,000 and courier-7 with plus 3,000. Use a full outer join between expected and recorded lines so a missing voucher and an unexpected extra voucher are both visible. Compare amounts and accounts with null-safe comparisons. Record discrepancies at line level before aggregating by courier. If two drivers exchange equal credits in error, both their totals can still look correct; the voucher-level match will show the swap.

Now introduce the disputed change on the training source after the three good transactions have committed. Change only the destination account of V42 line two from courier-7 to courier-8. Capture the before and after identity in the exercise record. This represents a faulty maintenance operation in a system that allowed history to be edited. Your structural test still returns no violations. Dispatch still has 7,000. The destinations now hold zero and 5,000. An aggregate grouped only over existing postings may omit courier-7 entirely. Join to the expected account list when the statement must display an explicit zero.

Inspect the plan for the question users actually ask

Operations needs both a full reconciliation and a single courier's hourly statement. They have different selectivity. Use the small dataset to establish correctness, then generate a separate load fixture with the same constraints, a known distribution across accounts and enough history to measure. Include a busy dispatch account as well as ordinary couriers. Keep the audit and timed tests reproducible by recording the dataset, concurrent writer count, query parameters and testing interval. A six-row table can show a logic error but tells you little about the cost of an end-of-day report.

EXPLAIN (ANALYZE, BUFFERS)
SELECT ref, line_no, delta_fils FROM posting
WHERE account = 'courier-7'
  AND posted_at >= TIMESTAMPTZ '2026-12-05 08:00:00+00'
  AND posted_at <  TIMESTAMPTZ '2026-12-05 09:00:00+00';

Suppose an illustrative baseline reads one million rows and returns forty for this account and hour. A scan that filters almost every row offers a plausible target for improvement. Try a B-tree index on account followed by posted_at in the test environment. With representative statistics, inspect whether the plan now restricts both values in the index condition. Check actual versus estimated rows and buffer reads or hits at the scan node. Costs are planner units. Actual rows in a repeatedly executed node are reported per loop, so take the loop count into account when interpreting the work. See PostgreSQL’s Using EXPLAIN.

A broad reconciliation may sensibly keep its sequential scan. An index consumes storage and adds work to each posting, including a write made while the audit is running. Define your acceptance criteria before comparing runs. For example, require the courier query’s 95th percentile below 200 milliseconds and the writer’s below 80 milliseconds at the agreed request rate. If a rehearsal moves the reader from 410 to 90 milliseconds while the writer rises from 55 to 95, reject this configuration for that load. These figures are decision inputs in a worked example. Measure your own percentiles from repeated end-to-end requests and collect representative plans separately.

Recover the missing evidence without erasing later work

Prepare the recovery branch of this drill before making the training error. Take a physical base backup early enough to reach consistency before V42, retain continuous archived WAL, and create a uniquely named restore point immediately after V43 commits and before the incorrect edit. Record the source timeline and confirm the archive contains the required sequence. After the incorrect edit, have dispatch pay courier-7 a legitimate additional 500 fils on V44. Your independent record now includes that fourth obligation. Rewinding the entire active database would discard it along with the bad edit.

Restore the base into an isolated destination that cannot send settlement messages or write to the source archive. Configure archive retrieval and the recorded timeline, select the named recovery target, request a pause at the target, and start archive recovery using recovery.signal on a self-managed instance. Confirm the log reached the intended marker. Query the paused copy and match V42 to courier-7, check all three original references, and confirm V44 is absent. Measure elapsed time through these business checks. The PostgreSQL continuous archiving guide explains the backup and replay chain on which this evidence depends.

The isolated copy and approved voucher now agree on the disputed destination. Preserve the mistaken posting and use an authorized compensating transfer of 3,000 from courier-8 to courier-7 on the current training ledger. Link it to V42 and the documented correction so the independent audit explains both the original discrepancy and its resolution. Keep V44. The resulting balances should be clearing minus 12,000, dispatch 6,500, courier-7 3,500 and courier-8 2,000. Verify both the accounting effect and the correction’s provenance. A second run of the correction with the same identifier must leave all four balances unchanged.

Deliver a release decision

Give the settlement owner two conclusions. First, decide whether the corrected business statement is defensible from independent vouchers, one consistent snapshot and a traceable adjustment. Second, decide whether the proposed performance change meets the writer and reader budgets. The two decisions can differ. Specify the snapshot or audit run, the exception that was approved, and what would cause you to reopen either decision. A manager can then challenge the evidence without having to guess what “audit passed” meant.

Exercise. Your restored copy matches V41 through V43 in twelve minutes against a fifteen-minute validation target. The live training ledger includes V44 and the authorized correction. Both balance checks pass, but the writer's 95th percentile is still 95 milliseconds. Do you replace the ledger, release the index, or issue the corrected statement?

One defensible answer. Retain the current ledger and issue the corrected statement after verifying the voucher-level exception and adjustment exactly once. The restore proved the earlier recipient and preserved a reference for investigation. Replacing the ledger would lose V44. Hold the index rollout because it exceeds the 80-millisecond writer budget. Repeat the load test after revising the design, and attach the measured latency and reconciliation results to the next decision.

اقرأ المشروع بالعربية

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Migrate a Busy Table Online

Move a live parcel table from a Boolean to a service code. Backfill in batches, find stale values, and prove when label readers can switch.