Round 7, continued Fast, healthy and possibly wrong
The next morning an analyst reports two payments that appear associated with the same settlement. Processing is fast, the queue healthy, the infrastructure green. Evidence: same amount, similar references, a concurrent attempt may have evaluated the same settlement, and it is not yet known whether a wrong final match was committed.
- Can a settlement be associated with several payments when the rules prohibit it? Is there a uniqueness constraint?
- Can concurrent workers pick the same candidate? Is matching inside a safe transaction?
- Are match creation and the state change atomic? Can retries duplicate effects? Is the audit history complete?
Expected controls, depending on the approved relationship: uniqueness constraints, explicit transaction boundaries, row locking or another concurrency strategy, idempotent processing, deterministic rules, conflict detection, re-evaluation and a controlled correction workflow. A single-threaded application is not the only way to be correct; design around the invariant.
The data model has to say which relationship finance approved. One-to-one matching and an approved aggregated settlement need different tables, and you must not stretch one to cover the other:
sqlallocation.sql: two relationships, each enforced by the database
-- Two approved relationships, each enforced by PostgreSQL itself (fictional Apex Financial Services).
-- One-to-one: a settlement and a payment are each MATCHED at most once.
-- Aggregated: one bank line pays for several payments, only where finance approved it, and the
-- allocations must add up to the settlement amount exactly.
CREATE TABLE approval (
id BIGINT PRIMARY KEY,
requested_by TEXT NOT NULL,
approved_by TEXT NOT NULL,
CHECK (approved_by <> requested_by) -- a second person, always
);
CREATE TABLE payment (
id BIGINT PRIMARY KEY,
amount_minor_units BIGINT NOT NULL CHECK (amount_minor_units > 0)
);
CREATE TABLE settlement_record (
id BIGINT PRIMARY KEY,
amount_minor_units BIGINT NOT NULL CHECK (amount_minor_units > 0),
relationship TEXT NOT NULL CHECK (relationship IN ('ONE_TO_ONE', 'AGGREGATED')),
UNIQUE (id, relationship) -- lets each table pin the relationship
);
-- A payment is reconciled once, by either model: both models insert here in the same transaction.
CREATE TABLE reconciled_payment (
payment_id BIGINT PRIMARY KEY REFERENCES payment(id),
via TEXT NOT NULL CHECK (via IN ('MATCH', 'ALLOCATION'))
);
CREATE TABLE reconciliation_match (
id BIGSERIAL PRIMARY KEY,
payment_id BIGINT NOT NULL REFERENCES payment(id),
settlement_id BIGINT NOT NULL,
relationship TEXT NOT NULL DEFAULT 'ONE_TO_ONE' CHECK (relationship = 'ONE_TO_ONE'),
status TEXT NOT NULL CHECK (status IN ('MATCHED', 'REVERSED')),
rule_version TEXT NOT NULL,
FOREIGN KEY (settlement_id, relationship) REFERENCES settlement_record (id, relationship)
);
CREATE UNIQUE INDEX one_match_per_settlement ON reconciliation_match (settlement_id) WHERE status = 'MATCHED';
CREATE UNIQUE INDEX one_match_per_payment ON reconciliation_match (payment_id) WHERE status = 'MATCHED';
CREATE TABLE settlement_allocation (
settlement_id BIGINT NOT NULL,
relationship TEXT NOT NULL DEFAULT 'AGGREGATED' CHECK (relationship = 'AGGREGATED'),
payment_id BIGINT NOT NULL UNIQUE REFERENCES payment(id), -- one settlement per payment
amount_minor_units BIGINT NOT NULL CHECK (amount_minor_units > 0),
approval_id BIGINT NOT NULL REFERENCES approval(id),
PRIMARY KEY (settlement_id, payment_id),
FOREIGN KEY (settlement_id, relationship) REFERENCES settlement_record (id, relationship)
);
-- Conservation, checked at COMMIT: the allocations of a settlement add up to its amount exactly,
-- and each allocation covers its whole payment (partial allocation is not approved in v1).
CREATE FUNCTION check_allocation() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE
s_id BIGINT := COALESCE(NEW.settlement_id, OLD.settlement_id);
total BIGINT;
expected BIGINT;
BEGIN
IF TG_OP <> 'DELETE' AND NEW.amount_minor_units <>
(SELECT amount_minor_units FROM payment WHERE id = NEW.payment_id) THEN
RAISE EXCEPTION 'allocation for payment % does not cover the whole payment', NEW.payment_id;
END IF;
SELECT amount_minor_units INTO expected FROM settlement_record WHERE id = s_id;
SELECT COALESCE(SUM(amount_minor_units), 0) INTO total FROM settlement_allocation WHERE settlement_id = s_id;
IF total <> expected THEN
RAISE EXCEPTION 'allocations for settlement % add up to % cents, not %', s_id, total, expected;
END IF;
RETURN NULL;
END $$;
CREATE CONSTRAINT TRIGGER allocation_adds_up
AFTER INSERT OR UPDATE OR DELETE ON settlement_allocation
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_allocation();Trying to break each rule, one transaction at a time
PostgreSQL 18.7 (PGlite)
1. ST 101 = payments 1 + 2 + 3, approved committed
2. ST 102 = payment 4 only (25,000 of 90,000) refused: allocations for settlement 102 add up to 25000 cents, not 90000
3. Payment 1 allocated again, to ST 102 refused: duplicate key value violates unique constraint "settlement_allocation_payment_id_key"
4. Allocate payment 5 to one-to-one ST 103 refused: insert or update on table "settlement_allocation" violates foreign key constraint "settlement_allocation_settlement_id_relationship_fkey"
5. Match payment 2 one-to-one as well refused: duplicate key value violates unique constraint "reconciled_payment_pkey"
6. An approval granted by its own requester refused: new row for relation "approval" violates check constraint "approval_check"
7. Payment 5 matched one-to-one to ST 103 committed
Reconciled payments: ALLOCATION 3, MATCH 1Real output from PostgreSQL 18.7 (PGlite) running tools/fde/m10/allocation.sql with tools/fde/m10/run_allocation.mjs, fictional data, November 22, 2026.
| Rule | What enforces it | Attempt above |
|---|---|---|
| One-to-one: a settlement and a payment are each MATCHED at most once | The two partial unique indexes on reconciliation_match | Tested in the race test below |
| A settlement uses one relationship, chosen when finance approves it | relationship on settlement_record, pinned by a composite foreign key in each table | 4 refused |
| A payment is reconciled once, by either model | reconciled_payment: one row per payment, inserted in the same transaction as the match or allocation | 5 refused |
| A payment is allocated to at most one settlement | UNIQUE (payment_id) on settlement_allocation | 3 refused |
| Allocations add up to the settlement amount exactly, and cover whole payments | A constraint trigger deferred to COMMIT, so the rows of one allocation can be inserted in any order | 2 refused, 1 committed |
| Every allocation is approved by a second person | approval_id NOT NULL, and a check that the approver is not the requester | 6 refused |
- Transaction boundary: creating the match and changing both records' reconciliation status happen in one transaction, or not at all.
- Concurrency: the unique index is the final guard. A worker may also lock the settlement row (SELECT ... FOR UPDATE) before deciding, which avoids wasted work, but the index decides.
- Conflict handling: when an insert hits the index, the worker rolls back, re-reads the current state and marks its payment AMBIGUOUS or UNMATCHED for an analyst. It never retries the same match blindly.
- Already-committed wrong matches: before the fix, look for settlements with more than one MATCHED row, and for matches created by two workers within the same second. Correct each one through the exception workflow, with maker-checker and an audit record; never by editing rows.
- Reversals keep history: a reversal marks the match REVERSED and deletes the payment's reconciled_payment row in the same transaction, so the payment can be reconciled again while the old match stays on record. An aggregated settlement is reversed as a whole, through the exception workflow, never one allocation row at a time.
Fifty parallel runs are a start, not a strategy. Timing in a test rarely reproduces production. Combine: a deterministic interleaving test, where a latch makes both workers read before either writes, so the race happens every time; a database test that inserts a second MATCHED row directly and expects the index to refuse it; a retry-path test for the conflict handling above; a stress test with many settlements and random delays; and a daily detector query in production that alerts if any settlement ever has two MATCHED rows.
Practical exercise
Assignment 9: financial correctness report
Write the investigation report.
- The business invariant and the data evidence.
- The concurrency scenario and the root cause or remaining unknowns.
- The containment decision and corrective design.
- Regression tests and customer verification.
Show a sample regression test
- twoWorkersCannotMatchOneSettlement: a latch holds both workers after their reads, then releases them together, on real PostgreSQL. Every run ends with one MATCHED row and one AMBIGUOUS payment, and the second worker's conflict is logged. Repeated 50 times as a stress check, alongside the direct index test and the daily detector query.
What you can do now
- State a business invariant.
- Investigate concurrency evidence.
- Design and test the correction.