When the money is wrong: payments incidents
A double payment raises no error. You find it in the money, size it in naira, stop it before you fix it, book it honestly and write down what the system let happen
Friday's change ships. Over the weekend some payouts go out twice. In a payout service like the lab's, which signal reaches a person first?
Most of what you have built so far makes a payment safe. This chapter is about the day it was not. A payments incident differs from an outage in one way that shapes everything else: when a website is down, users tell you within minutes. When money is wrong, the system often looks healthy. The wrong state is spread across records that nobody compares until a job or a person does, so detection is a design decision you made earlier, not a skill you show on the day.
The lab runs on Owoleaf’s wallet from the module 2 project, with the switch timing out one request in five. Ferrowave is the example in the prose; its engine is not Owoleaf’s wallet, but the failure is the same. Every limit, code and fee in the lab is illustrative, and every naira figure below is printed by code you run.
Money incidents are quiet
It helps to name the shapes money goes wrong in, because each one is found a different way.
| Shape | What happened | Who notices first |
|---|---|---|
| Stuck | Money left the payer and has not arrived | The payer, quickly, and loudly |
| Missing | The ledger says paid, the bank has no record | Reconciliation against the bank |
| Duplicated | One intent was paid more than once | Reconciliation, if it counts per intent; rarely the recipient |
| Wrong amount or wrong payee | The right intent, the wrong money or account | A customer, or a name check that was skipped |
| Unavailable | Nothing moves, and people can see it | Everyone |
The loud shapes find you. The quiet ones, duplicated above all, wait until you look. A duplicated payout is also the shape whose cost grows with every minute it runs, because the code that causes it is working as written.
Four public incidents, and what each teaches
The four below are public, and each is cited in Reading. Where a fact comes from press coverage of a document, and not from the document itself, the sentence says so. The figures are what the cited sources reported, and none is a measurement of mine.
TSB, April 2018. TSB migrated its customers to a new IT platform, and many could not use online banking afterwards. Its board commissioned an independent review from the law firm Slaughter and May, which TSB published on 19 November 2019. Press coverage of the review reports that the new platform was neither stable nor complete when the board approved the migration, and that testing had been done offline and not in a live environment. TSB said the board did not agree with every aspect. The lesson for a payments team is that the review is about decisions taken before the incident, not about the night it began.
Visa Europe, 1 June 2018. Visa’s reply to the UK Treasury Committee, as reported in the press, attributes the outage to a very rare partial failure of a switch in its primary data centre, which stopped the backup from taking over. Press reports of the reply put the failed transactions at 5.2 million out of 51.2 millionas of 2026-11; I have not read the reply itself, so treat the figures as reported. The lesson is the partial failure: a component that fails halfway can defeat the failover built for a component that fails completely.
Bank of England RTGS, 20 October 2014. The Bank’s own response puts the outage of the real-time gross settlement (RTGS) service at about nine hours, and its summary of Deloitte’s independent review, dated 23 March 2015, names the root cause as defects introduced by functionality changes made in April 2013 and May 2014as of 2026-11. Press accounts list the changes slightly differently, so read the report for the exact list. The lesson is that the cause of an incident can be older than anyone on the on-call rota remembers: a change, with defects that stayed hidden until the outage.
Citibank v. Brigade, 2022. Citibank, acting as agent on a Revlon loan, meant to pay interest and mistakenly paid out principal. The mistaken payment was about $900 million in all; some lenders returned money, and about $500 million was not returned and is what the case was aboutas of 2026-11. In Citibank, N.A. v. Brigade Capital Management, LP (No. 21-487, 8 September 2022) the Second Circuit reversed the lower court and held that the lenders who kept the money could not rely on the discharge-for-value defence. Keep the two numbers apart: $900 million is what left in error, $500 million is what had to be fought for. The lesson for engineers is the recovery side: money that reaches a third party does not come back because your ledger says it should, and the dispute took two years to reach an appeal court.
None of the four is a duplicate-payout bug, and none of them is a story about a careless person. Each is a change, a missing check and a slow detection.
The bug in the lab
Look at what the Friday change does, in your own wallet, in the payout function you wrote in module 2. The wallet holds the customer’s money first, sends the transfer under the operation’s own key, and treats silence as “in doubt”: it leaves the operation sent and the sweep requeries it. That is right. Moyo’s change adds a loop after the send: if the answer is not an HTTP 200, send again, up to twice, under a fresh reference (OP-00142-r1, then OP-00142-r2).
It looks like resilience, and in a read it is. A reused reference would be answered with code 26 (duplicate), and the change’s author knew that, which is why the reference is fresh. The switch deduplicates on the payment reference, so a new reference is a new payment, however many words of the narration match. The first request, the one that timed out, was accepted and held; with the lab’s settings it resolves to successful about 45 seconds later 70% of the time. The retry is a new request and usually goes through at once (it can be held too, one time in five). Two payments, one intent.
Three things made the change pass review, and you will meet all three in your own work.
- Idempotency lived at the wrong layer. The API required keys, and the wallet checked its own
opstable for a repeat. The connector below them did not know about either, and it created a second payment the key could not see. - The tests could not fail. A test double for the switch answers at once. The retry never fires against a switch that never goes quiet.
- The flag was on by default. A flag that ships a behaviour dark is a safety tool. One that ships it lit is only a way to turn it off, later, if you know to.
Detecting it from the money
Run the Friday load and look at what is quiet. The load script finishes without an exception. The operations table shows about 160 payouts settled, which is plausible. The ledger balances to the kobo and check.py prints OK: all invariants hold, because the wallet recorded each payout once and posted one set of entries for it. The error rate is zero. Everything the wallet knows about itself is consistent, and wrong.
What is not consistent is the wallet against the switch. The reconciliation you built compares three things, and the bug shows in all of them:
- Transfers with no operation behind them. Each retry is a transfer at the switch under a reference the wallet never recorded. In the author’s run, 39 of them.
- The net position. The switch’s position and the ledger’s differ by the money that left twice. In the author’s run the gap was −70,383,374 kobo with 6,016,570 kobo more still pending.
- The per-intent audit. More than one successful transfer for one intent. In the author’s run, 25 intents.
The total printed was 72 unexplained breaks, and it overstates the problem. The same few payouts appear in three lists. Group by intent before you count anything: that is the first move of the response, because the intent is the unit the customer, the bank and your finance team all think in.
There is a second lesson in how it was found. The reconciliation ran once, at the end of the load. In production it runs daily, so the exposure is up to a day of the bleed rate. A cheaper and faster check is the invariant the bug breaks: one intent must never have two outward transfers at the switch. It needs only the switch’s transfer report, and it fires on the attempt, at the moment of the first retry, before either payment has resolved. An alarm on the attempt catches a bug early. An alarm on the damage waits for the damage. You build it in the lab.
Sizing the exposure
“How much did we lose?” is the first question every executive asks, and the honest answer is a range with a time on it. Take the switch’s transfer report and group it by intent. For each intent:
- Confirmed: the ledger paid for one transfer per intent, normally the first success, so every later success is an extra payment. Count its amount. There is one sharper case. If every attempt timed out, the sweep’s requery of the original may say
failed, and the wallet then releases the customer’s hold while a retry has in fact paid. The ledger has paid for none, so every success counts, and the customer has also had the money back. The switch’s report cannot show this; the wallet’sopstable does, which is whyexposure.pyreads it. - Pending: a transfer still pending may still succeed. If the intent already has a success, every pending transfer is a possible second payment. If it has none, all pending ones but one are surplus.
- Not a duplicate: when the original failed and the wallet settled on a retry’s success, the retry carried the only payment. The reference is odd; the money is not extra. In the author’s run, 5 of the 39 retry transfers were these.
Confirmed plus pending is the upper bound. The number is not stable: pending transfers resolve, and the exposure moves with them. In the author’s run the first read of the reconciliation showed a gap of 70,383,374 kobo with 6,016,570 kobo pending. Once everything resolved, the confirmed duplicates were 76,399,944 kobo, and 76,399,944 − 6,016,570 = 70,383,374 held exactly because every pending transfer resolved as a payment. It will not always: a pending transfer can fail instead. What holds in every run is a bracket: the gap at the first read is no more than the final confirmed figure, which is no more than the gap plus what was pending then. Report the figure with the time you read it.
Two more cuts of the same data are worth having before you are asked. By beneficiary bank, because recovery is a request to that bank and each bank is a separate conversation. And by time, because the bleed rate says how much a longer detection delay would have cost. The lab prints both.
Stopping the bleed
The order matters, and it is the opposite of what the people in the room want to do.
- Stop the cause, narrowly and provably. Turn the flag off, or halt the one operation that does the damage. The control must be one you can check: after you use it, the same signal that found the problem must stop moving.
- Confirm it with that signal. If the count of intents sent twice keeps growing, the brake did not work, and you escalate to a wider one.
- Expect in-flight money. A brake stops new retries. Transfers already sent and held, like the timed-out originals in the lab, still resolve over the next minute. The loss does not stop on the instant you act. It stops growing about one resolution time later.
- Only then fix, and leave the data alone. Do not edit ledger rows, delete operations or bulk-reverse anything while the cause is live. A correction made under pressure on moving data is how a second incident starts.
What a halt does to customers is a design choice you make in advance. In the lab, a halted payout returns halted before anything is recorded, held or sent. That is safe to retry later with the same key, for the same reason a 500 before any work is. A halt that quietly queued payouts, or half-recorded them, would be a new bug in an emergency.
A halt has a price, and the people who pay it are customers waiting for their salaries. That is why step one says narrowly. The Decide at the end of the chapter puts it to you.
Book it, recover it or write it off
When the cash has left twice, the ledger must say so. Right now the wallet’s books show the settlement account higher than the partner bank’s, by the amount that went out twice. Three honest positions exist, and one dishonest one.
- A receivable. The money is owed back by the recipient’s bank or the recipient. Debit an asset account (the lab calls it
recoverable_payouts), creditsettlement_bank. The cash really left, and the books now agree with the switch. The asset stays open until someone recovers it. - A recovery. When a return arrives, post the mirror image: debit
settlement_bank, creditrecoverable_payouts. The switch will report it as an inward credit, and the reconciliation will match it. - A write-off. When a person decides it is lost, debit a loss expense, credit
recoverable_payouts. This is a decision with a name on it, not something a job does. - Not income, and not a wallet debit. Do not net the duplicate against the customer’s wallet. The customer was debited once, correctly. The company paid the second time.
The reconciliation keeps the open receivable on its face: after you book the lab’s duplicates it prints unexplained breaks: 0 and, next to it, recoverable_payouts holds 76,399,944 kobo. Zero unexplained means every line has a name. It does not mean nothing is wrong, and it must not be read as a green light by someone who has not seen the receivable line. The Citibank case is the reminder of what recovery looks like when the money has landed with someone who wants to keep it: slow, legal and uncertain, which is why you also post the books as if it might not come back.
The postmortem
A postmortem is a document that changes the system, and the ones that do share a shape. Blameless does not mean without names. It means the question is “what did the system allow?” and not “who did it?”. The Google SRE book’s chapter on postmortem culture is the usual reference, and Richard Cook’s How Complex Systems Fail is the reason to distrust a single root cause.
| Section | What goes in it | In the lab |
|---|---|---|
| Summary | Two sentences: what happened, what it cost | in the author’s run, 32 duplicate payments on 27 payouts, ₦763,999.44 |
| Impact | Money, people, time, in numbers, with the time you read them | by bank, by 30-second bucket |
| Timeline | What happened and when, from records, not memory | postmortem.py prints it |
| Detection | How it was found, and how long after it began | the reconciliation, after the run |
| Contributing factors | Several, each a thing the system allowed | below |
| What went well | Controls that worked | the ledger stayed balanced; the audit counted per intent |
| Actions | Each with an owner and a date, and the signal that shows it worked | below |
Write contributing factors, not a root cause. For Friday’s change they include: a retry added at a layer the idempotency rule did not cover; a test double that never went quiet; a flag on by default; a reconciliation that runs daily; no alarm on the invariant; and no halt control that anyone had tried. Each one suggests an action, and an action that says “be more careful” is not one.
Tell the timeline from records. The lab’s postmortem.py takes the first payout request as time zero and prints, in seconds, the first duplicate, the last, and a count in 30-second buckets. In a real incident the extra column is the one people forget: what you knew, and when. A postmortem that shows the loss started at 14:02 and was seen at 09:00 the next day has already argued for faster detection.
Lab
You work in labs/finance with the module 2 wallet. Ports are the defaults: provider 8101, switch 8102, receiver 9000. Timings are the mocks’ defaults, so each load takes two to three minutes. The wallet’s random choices and the mocks’ interleave with timing, so your counts and naira figures will differ from mine, every run, and this is expected: the 72 breaks, the 32 duplicates and ₦763,999.44 below are one run’s output, not targets. What must not differ is marked in each step. Save your database copies under data/; the load deletes the file it is given when it starts.
1. Save the game-day tools. Six small files, each used once below. Read patch.py first: it is the Friday change, the brake, the fix and the reconciliation’s new rule as four reversible edits to your own files, and it stops if the text it expects is not there exactly once.
patch.py:
"""Small, reversible edits to wallet.py for the game day.
python3 patch.py plant # the Friday change: retry a timed-out payout under a fresh reference
python3 patch.py brake # a kill switch for payouts, read from the database while the service runs
python3 patch.py fix # take the retry out again (plant and fix undo each other)
python3 patch.py recon # teach reconcile.py the retry transfers: duplicates booked as receivables are explained
Each edit replaces text that must be there exactly once, and stops if it is not.
"""
import sys
OLD_SEND = ''' status, out = self.switch.call("POST", "/transfers", body, {"X-Mock-Force": force} if force else None, timeout)
if self.naive and status != 200: # the bug this chapter warns about: a new reference on every retry
body["payment_reference"] = f"{key}-retry"
status, out = self.switch.call("POST", "/transfers", body, None, timeout)
'''
NEW_SEND = ''' status, out = self.switch.call("POST", "/transfers", body, {"X-Mock-Force": force} if force else None, timeout)
for n in range(1, int(self.control("payout_retries", "2")) + 1): # Friday: "retry when the switch is silent"
if status == 200:
break
body["payment_reference"] = f"{key}-r{n}" # a fresh reference, because a reused one answers 26
status, out = self.switch.call("POST", "/transfers", body, None, timeout)
'''
OLD_OPS = "CREATE TABLE seen (source TEXT NOT NULL, event_id TEXT NOT NULL, PRIMARY KEY (source, event_id));\n"
NEW_OPS = OLD_OPS + "CREATE TABLE controls (name TEXT PRIMARY KEY, value TEXT NOT NULL); -- switches changed while the service runs\n"
OLD_W = " def w(self, customer_id):\n"
NEW_W = ''' def control(self, name, default):
"""A switch kept in the database, so it can be changed while the service runs."""
with self.lock:
row = self.db.execute("SELECT value FROM controls WHERE name = ?", (name,)).fetchone()
return row[0] if row else default
''' + OLD_W
OLD_P = ''' """Hold the money first, send once, and follow the transfer to its end by requery."""
'''
NEW_P = OLD_P + ''' if self.control("payouts_halted", "0") == "1":
return "halted" # nothing recorded, held or sent: the caller may ask again later with the same key
'''
OLD_NET = "AND t.kind IN ('funding_transfer', 'payout_nip', 'payout_reversal')\"\"\""
NEW_NET = "AND t.kind IN ('funding_transfer', 'payout_nip', 'payout_reversal', 'payout_duplicate')\"\"\""
OLD_RUN = "def run(w, day, say=print):\n"
NEW_RUN = '''def retry_roles(outward, released):
"""What each retry transfer (one not sent under the operation's own key) did. The ledger paid for the first
success of an intent, so the second and later ones are duplicates; if the wallet gave the customer's money back
(a released operation) it paid for none, and every success is one. A first success under a retry reference
otherwise carried the payment."""
by_intent, roles = defaultdict(list), {}
for t in outward.values():
by_intent[t["narration"]].append(t)
for narration, ts in by_intent.items():
ts.sort(key=lambda t: t["created_at"])
ok = [t for t in ts if t["status"] == "successful"]
paid_for = 0 if narration[3:] in released else 1
for t in ts:
if t["payment_reference"] == narration[3:]:
continue
roles[t["payment_reference"]] = ("duplicate" if t in ok[paid_for:] else "carried" if t in ok
else "pending" if t["status"] == "pending" else "refused")
return roles
''' + OLD_RUN
OLD_LOOP = ''' for ref, t in sorted(outward.items()):
op = w.op(ref)
if op is None:
'''
NEW_LOOP = ''' released = {k for (k,) in q("SELECT op_key FROM ops WHERE kind = 'payout' AND state = 'failed'")}
roles = retry_roles(outward, released)
carried_originals = {outward[r]["narration"][3:] for r, role in roles.items() if role == "carried"}
booked_refs = {r for (r,) in q("SELECT external_ref FROM transactions WHERE kind = 'payout_duplicate'")}
for ref, t in sorted(outward.items()):
op = w.op(ref)
if op is None and ref in roles: # a retry the wallet should never have sent
if roles[ref] == "duplicate" and ref not in booked_refs:
broken.append(f"switch: duplicate payout {ref} ({t['amount_kobo']:,} kobo) is not booked as a receivable")
else:
cls[f"retry transfer, {roles[ref]}" + (", booked" if ref in booked_refs else "")] += 1
continue
if op is None:
'''
OLD_ELIF = ''' elif before == "sent":
after = w.check_payout(ref)'''
NEW_ELIF = ''' elif before == "settled" and t["status"] in ("failed", "pending") and ref in carried_originals:
cls["original failed or pending, a retry carried the payment"] += 1
''' + OLD_ELIF
OLD_TWICE = " twice = {k: n for k, n in paid.items() if n > 1}\n"
NEW_TWICE = ''' twice = {k: n for k, n in paid.items() if n > 1
and any(r not in booked_refs for r, role in roles.items() if role == "duplicate" and outward[r]["narration"] == k)}
dup_kobo = sum(outward[r]["amount_kobo"] for r in booked_refs if r in outward)
'''
OLD_AUDIT = ''' say(f"audit payout intents with more than one successful transfer: {len(twice)}; "'''
NEW_AUDIT = ''' say(f"audit duplicate payouts booked as receivables: {len(booked_refs & set(outward))}, {dup_kobo:,} kobo; "
f"recoverable_payouts holds {q(CLEARING_NET, 'recoverable_payouts')[0][0]:,} kobo")
say(f"audit payout intents with an unbooked duplicate: {len(twice)}; "'''
EDITS = {
"plant": [(OLD_SEND, NEW_SEND), (OLD_OPS, NEW_OPS), (OLD_W, NEW_W)],
"fix": [(NEW_SEND, OLD_SEND)],
"brake": [(OLD_P, NEW_P)],
"recon": [(OLD_NET, NEW_NET), (OLD_RUN, NEW_RUN), (OLD_LOOP, NEW_LOOP), (OLD_ELIF, NEW_ELIF),
(OLD_TWICE, NEW_TWICE), (OLD_AUDIT, NEW_AUDIT)],
}
FILES = {"plant": "wallet.py", "fix": "wallet.py", "brake": "wallet.py", "recon": "reconcile.py"}
which = sys.argv[1] if len(sys.argv) > 1 else ""
if which not in EDITS:
sys.exit(__doc__)
src = open(FILES[which]).read()
for old, new in EDITS[which]:
if new in src:
continue # already applied
if src.count(old) != 1:
sys.exit(f"patch {which}: expected text found {src.count(old)} times; nothing changed")
src = src.replace(old, new)
open(FILES[which], "w").write(src)
print(f"{FILES[which]}: {which} applied")controls.py, which changes a switch in a wallet’s database while it runs:
"""Change a switch in a running wallet's database.
python3 controls.py data/friday.sqlite payouts_halted 1
python3 controls.py data/friday.sqlite # show them
"""
import sqlite3
import sys
db = sqlite3.connect(sys.argv[1], timeout=30)
if len(sys.argv) == 4:
db.execute("INSERT OR REPLACE INTO controls VALUES (?, ?)", (sys.argv[2], sys.argv[3]))
db.commit()
print(dict(db.execute("SELECT name, value FROM controls")) or "no switches set (the defaults apply)")exposure.py, which sizes the loss from the switch’s report and the wallet’s released operations:
"""How much money is at risk: group the switch's transfer report by intent and count what was paid.
python3 exposure.py --db data/friday.sqlite # today's report from the switch on the default port
The switch's report says what was paid. The wallet's database says what the ledger paid for: normally the first
success of an intent, but none if the wallet gave the customer's money back (an operation it released).
"""
import argparse
import datetime as dt
import sqlite3
from collections import defaultdict
from generate import WAT
from wallet import SWITCH_KEY, Api
ap = argparse.ArgumentParser()
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--day", default=dt.datetime.now(WAT).date().isoformat())
ap.add_argument("--db", default="data/wallet.sqlite", help="the wallet database to read the released operations from")
a = ap.parse_args()
released = {k for (k,) in sqlite3.connect(a.db).execute("SELECT op_key FROM ops WHERE kind = 'payout' AND state = 'failed'")}
_, rep = Api(a.switch, SWITCH_KEY).call("GET", f"/transfers?date={a.day}")
intents = defaultdict(list)
for t in rep["transfers"]:
if t["direction"] == "outward":
intents[t["narration"]].append(t) # the wallet writes "OP <key>" on every attempt of one payout
paid_extra, pending_extra, carried = [], [], []
for narration, ts in intents.items():
ts.sort(key=lambda t: t["created_at"])
ok = [t for t in ts if t["status"] == "successful"]
pend = [t for t in ts if t["status"] == "pending"]
paid_for = 0 if narration[3:] in released else 1 # the ledger paid for one transfer, unless it released the hold
paid_extra += [(narration, t) for t in ok[paid_for:]] # every success beyond that is an extra payment
if ok:
pending_extra += [(narration, t) for t in pend] # a pending one may still succeed on top
else:
pending_extra += [(narration, t) for t in pend[paid_for:]] # nothing paid yet: all but one pending are surplus
if ok and paid_for and ok[0]["payment_reference"] != narration[3:]:
carried.append((narration, ok[0])) # the original failed; a retry carried the payment
kobo = lambda rows: sum(t["amount_kobo"] for _, t in rows)
naira = lambda k: f"₦{k // 100:,}.{k % 100:02d}"
n_retry = sum(1 for ts in intents.values() for t in ts if t["payment_reference"] != t["narration"][3:])
print(f"payout intents {len(intents)}; transfers {sum(len(v) for v in intents.values())}; "
f"transfers sent under a retry reference {n_retry}")
print(f"paid more than once {len({n for n, _ in paid_extra}):>4} intents, {len(paid_extra)} extra payments, {kobo(paid_extra):,} kobo = {naira(kobo(paid_extra))}")
print(f"extra still pending {len(pending_extra):>4} transfers, {kobo(pending_extra):,} kobo = {naira(kobo(pending_extra))} (may yet succeed)")
print(f"upper bound {naira(kobo(paid_extra) + kobo(pending_extra))}")
print(f"retry carried the payment (original failed, nothing extra paid): {len(carried)}")
by_bank = defaultdict(lambda: [0, 0])
for _, t in paid_extra:
by_bank[t["beneficiary_bank"]][0] += 1
by_bank[t["beneficiary_bank"]][1] += t["amount_kobo"]
print("extra payments by beneficiary bank (the recall requests you will send):")
for bank, (n, k) in sorted(by_bank.items(), key=lambda x: -x[1][1])[:5]:
print(f" {bank} {n:>2} payments {naira(k):>16}")
print(f"largest single extra payment {naira(max(t['amount_kobo'] for _, t in paid_extra))}" if paid_extra else "no extra payments")watch.py, the faster alarm, with an optional halt:
"""A faster alarm than the daily reconciliation: one intent must never have two transfers at the switch.
python3 watch.py # watch and print
python3 watch.py --halt data/wallet.sqlite # and stop payouts at the first intent sent twice
It reads only the switch's transfer report, so it cannot disturb the wallet. It alarms on the attempt, not on the
damage: a second transfer for one intent is the bug, even before either of them has been paid.
"""
import argparse
import datetime as dt
import sqlite3
import time
from collections import Counter
from generate import WAT
from wallet import SWITCH_KEY, Api
ap = argparse.ArgumentParser()
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--halt", help="the wallet database whose payouts to halt")
ap.add_argument("--every", type=float, default=2.0)
ap.add_argument("--seconds", type=float, default=600)
a = ap.parse_args()
api, t0, last, halted = Api(a.switch, SWITCH_KEY), time.time(), None, False
while time.time() - t0 < a.seconds:
day = dt.datetime.now(WAT).date().isoformat()
status, rep = api.call("GET", f"/transfers?date={day}")
if status == 200:
n = Counter(t["narration"] for t in rep["transfers"] if t["direction"] == "outward")
twice = sorted(k for k, c in n.items() if c > 1)
if twice != last:
print(f"T+{time.time() - t0:4.0f} s {sum(n.values())} outward transfers; intents sent more than once: {len(twice)}", flush=True)
last = twice
if twice and a.halt and not halted:
try:
db = sqlite3.connect(a.halt, timeout=30)
db.execute("INSERT OR REPLACE INTO controls VALUES ('payouts_halted', '1')")
db.commit()
db.close()
halted = True
print(f"T+{time.time() - t0:4.0f} s HALT: payouts stopped after {twice[0]} was sent twice", flush=True)
except sqlite3.Error as e:
print("could not halt yet:", e, flush=True)
time.sleep(a.every)book.py, which puts the loss in the ledger:
"""Book the duplicate payouts the switch reports as receivables, so the ledger tells the truth about the cash.
python3 book.py --db data/friday.sqlite
A duplicate is a successful transfer after the first one for the same intent (or any successful one, if the wallet
gave the customer's money back, because then the ledger paid for none). The money has left the partner
bank and is not owed by any customer: it is an asset (a claim on the recipient's bank) until it is recovered
or written off. One entry each: debit recoverable_payouts, credit settlement_bank. Safe to run twice.
"""
import argparse
import datetime as dt
import sqlite3
from collections import defaultdict
from generate import WAT
from ledger import Refused
from wallet import PROVIDER_KEY, SWITCH_KEY, Api, Wallet
ap = argparse.ArgumentParser()
ap.add_argument("--db", default="data/wallet.sqlite")
ap.add_argument("--provider", default="http://127.0.0.1:8101")
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--day", default=dt.datetime.now(WAT).date().isoformat())
a = ap.parse_args()
raw = sqlite3.connect(a.db)
if not raw.execute("SELECT 1 FROM accounts WHERE code = 'recoverable_payouts'").fetchone():
raw.execute("INSERT INTO accounts VALUES ((SELECT MAX(id) + 1 FROM accounts), 'recoverable_payouts', "
"'Duplicate payouts to recover', 'asset', NULL, 'NGN', ?, 1)", (dt.datetime.now(WAT).isoformat(),))
raw.commit()
raw.close()
w = Wallet(a.db, Api(a.provider, PROVIDER_KEY), Api(a.switch, SWITCH_KEY))
_, rep = w.switch.call("GET", f"/transfers?date={a.day}")
intents = defaultdict(list)
for t in rep["transfers"]:
if t["direction"] == "outward":
intents[t["narration"]].append(t)
released = {k for (k,) in w.query("SELECT op_key FROM ops WHERE kind = 'payout' AND state = 'failed'")}
booked = skipped = total = 0
for narration, ts in sorted(intents.items()):
ts.sort(key=lambda t: t["created_at"])
paid_for = 0 if narration[3:] in released else 1
for t in [t for t in ts if t["status"] == "successful"][paid_for:]:
try:
with w.tx():
w._post("payout_duplicate", t["payment_reference"],
[(w.acct["recoverable_payouts"], "debit", t["amount_kobo"]),
(w.acct["settlement_bank"], "credit", t["amount_kobo"])],
amount=t["amount_kobo"], rail="nip")
booked, total = booked + 1, total + t["amount_kobo"]
except Refused as r:
if r.reason != "duplicate":
raise
skipped += 1 # booked on an earlier run
print(f"booked {booked} duplicate payouts, {total:,} kobo; {skipped} were already booked")postmortem.py, which prints the facts for the write-up:
"""The facts for the postmortem, from the switch's report and the wallet's own tables. The reasoning is yours.
python3 postmortem.py --db data/friday.sqlite
"""
import argparse
import datetime as dt
import sqlite3
from collections import Counter, defaultdict
from generate import WAT
from wallet import SWITCH_KEY, Api
ap = argparse.ArgumentParser()
ap.add_argument("--db", default="data/wallet.sqlite")
ap.add_argument("--switch", default="http://127.0.0.1:8102")
ap.add_argument("--day", default=dt.datetime.now(WAT).date().isoformat())
a = ap.parse_args()
db = sqlite3.connect(a.db)
_, rep = Api(a.switch, SWITCH_KEY).call("GET", f"/transfers?date={a.day}")
intents = defaultdict(list)
for t in rep["transfers"]:
if t["direction"] == "outward":
intents[t["narration"]].append(t)
released = {k for (k,) in db.execute("SELECT op_key FROM ops WHERE kind = 'payout' AND state = 'failed'")}
extra = []
for narration, ts in intents.items():
ts.sort(key=lambda t: t["created_at"])
extra += [t for t in ts if t["status"] == "successful"][0 if narration[3:] in released else 1:]
at = lambda s: dt.datetime.fromisoformat(s)
first_req = at(db.execute("SELECT MIN(created_at) FROM transactions WHERE kind = 'payout_hold'").fetchone()[0])
last_req = at(db.execute("SELECT MAX(created_at) FROM transactions WHERE kind = 'payout_hold'").fetchone()[0])
settled = at(db.execute("SELECT MAX(updated_at) FROM ops WHERE kind = 'payout'").fetchone()[0])
first_dup, last_dup = min(at(t["created_at"]) for t in extra), max(at(t["created_at"]) for t in extra)
stamp = lambda d: f"{(d - first_req).total_seconds():5.0f} s"
naira = lambda k: f"₦{k // 100:,}.{k % 100:02d}"
print("TIMELINE (seconds after the first payout request)")
print(f" {stamp(first_req)} first payout request")
print(f" {stamp(first_dup)} first duplicate transfer sent")
print(f" {stamp(last_req)} last payout request")
print(f" {stamp(last_dup)} last duplicate transfer sent")
print(f" {stamp(settled)} last payout operation settled; the reconciliation reads the report after this")
print("\nBLEED (duplicate payments sent, in 30-second buckets)")
bucket = Counter()
for t in extra:
bucket[int((at(t["created_at"]) - first_req).total_seconds() // 30)] += 1
for b in range(max(bucket) + 1):
print(f" {b * 30:>4}-{b * 30 + 30:<4} s {'#' * bucket[b]} {bucket[b]}")
print("\nIMPACT")
print(f" duplicate payments: {len(extra)} on {len({t['narration'] for t in extra})} payouts, {sum(t['amount_kobo'] for t in extra):,} kobo = {naira(sum(t['amount_kobo'] for t in extra))}")
print(f" payouts that reached the switch: {len(intents)}; share paid twice or more: {len({t['narration'] for t in extra}) / len(intents):.1%}")
held_twice = db.execute("SELECT COUNT(*) FROM (SELECT external_ref FROM transactions WHERE kind = 'payout_hold' "
"GROUP BY external_ref HAVING COUNT(*) > 1)").fetchone()[0]
print(f" payouts held from a wallet more than once: {held_twice} (each wallet was debited once; the company paid the second time)")
print(f" recipients' banks involved: {len({t['beneficiary_bank'] for t in extra})}")2. Check the instrument first. Start both mocks with the switch timing out one request in five, and run the wallet exactly as you wrote it. A detector you have not seen quiet is not a detector. Terminal 1:
cd labs/finance
python3 mock_provider.py --fresh --webhook-url http://127.0.0.1:9000/providerTerminal 2:
cd labs/finance
python3 mock_switch.py --fresh --callback-url http://127.0.0.1:9000/switch --timeout-rate 0.2Terminal 3:
cd labs/finance
python3 load.py --db data/baseline.sqlite | tee data/baseline.txt1,000 operations in 91 s; everything settled or explained after 133 s
kind state count
fund_bank credited 200
fund_card credited 300
p2p done 170
p2p refused 30
payout failed 23
payout refused 13
payout settled 164
refund processed 73
refund refused 11
messages: 611 handled, 38 repeats of an event already seen, 303 that found the operation already settled, 0 bad signatures
daily reconciliation, 2026-11-14
cards provider report for 2026-11-15: 300 captures, gross 802,734,800 kobo, fee 8,027,348, refunds 114,386,701, net 680,320,751
ledger: 300 credited fundings; card_clearing holds 688,348,099 kobo before settlement
switch report for 2026-11-14: 167 outward, 200 inward transfers; 200 inward match, 167 match
net position: switch 703,460,420 kobo (pending 0 listed apart), ledger 703,460,420 kobo
audit payout intents with more than one successful transfer: 0; card intents captured more than once: 0
balance operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
repaired by this run: 1 card settlement posted
unexplained breaks: 0Must not differ: unexplained breaks: 0, the two net positions equal, and no payout intent with a second transfer. The 164 settled payouts include every one that timed out and was settled by the sweep’s requery, which is the module 2 rule doing its work at a 20% timeout rate. Your counts of settled and failed payouts will differ; those two plus the refused ones are the 200 payouts the load asks for (164 + 23 + 13 = 200 in mine).
3. Ship the Friday change. Apply the retry, restart both mocks (Ctrl-C, then the commands from step 2) so the switch’s report holds only this run, and run the same load into a new database. The first command prints what it did and nothing else.
python3 patch.py plant
python3 load.py --db data/friday.sqlite | tee data/friday.txt
python3 check.py --db data/friday.sqlite | tail -1wallet.py: plant applied1,000 operations in 134 s; everything settled or explained after 167 s
kind state count
fund_bank credited 200
fund_card credited 300
p2p done 181
p2p refused 19
payout failed 24
payout refused 16
payout settled 160
refund processed 68
refund refused 22
messages: 614 handled, 46 repeats of an event already seen, 306 that found the operation already settled, 0 bad signatures
daily reconciliation, 2026-11-14
cards provider report for 2026-11-15: 300 captures, gross 794,001,600 kobo, fee 7,940,016, refunds 100,398,857, net 685,662,727
ledger: 300 credited fundings; card_clearing holds 693,602,743 kobo before settlement
switch report for 2026-11-14: 199 outward, 200 inward transfers; 200 inward match, 153 match
net position: switch 617,636,724 kobo (pending 6,016,570 listed apart), ledger 688,020,098 kobo
audit payout intents with more than one successful transfer: 25; card intents captured more than once: 0
balance operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
repaired by this run: 1 card settlement posted
unexplained breaks: 72
switch: transfer OP-00142-r1 (1,190,144 kobo, successful) has no operation in the ledger
switch: transfer OP-00142-r2 (1,190,144 kobo, successful) has no operation in the ledger
switch: transfer OP-00144-r1 (1,243,411 kobo, successful) has no operation in the ledger
switch: transfer OP-00150-r1 (2,641,691 kobo, successful) has no operation in the ledger
switch: transfer OP-00150-r2 (2,641,691 kobo, successful) has no operation in the ledger
switch: transfer OP-00168-r1 (4,708,662 kobo, successful) has no operation in the ledger
...
switch: net position is 617,636,724 kobo at the switch and 688,020,098 in the ledger (difference -70,383,374)
paid twice: OP OP-00142 went out 3 times
paid twice: OP OP-00144 went out 2 times
...OK: all invariants holdI cut the middle of the list. The load printed no exception and nothing from the receiver or the sweep, 160 payouts settled, and check.py says OK: all invariants hold. That is the point: everything the wallet can check about itself is fine. Must not differ: the load finishes without errors, check.py ends OK, and the reconciliation prints a non-zero unexplained breaks with paid twice lines. The exact counts depend on which requests the switch holds.
4. Detect and size it. First count what the 72 lines are, then group the switch’s report by intent. Keep the switch running: every later step reads its report of this run.
grep -oE "has no operation|at the switch and settled|net position is|paid twice" data/friday.txt | sort | uniq -c
python3 exposure.py --db data/friday.sqlite 7 at the switch and settled
39 has no operation
1 net position is
25 paid twicepayout intents 160; transfers 199; transfers sent under a retry reference 39
paid more than once 27 intents, 32 extra payments, 76,399,944 kobo = ₦763,999.44
extra still pending 0 transfers, 0 kobo = ₦0.00 (may yet succeed)
upper bound ₦763,999.44
retry carried the payment (original failed, nothing extra paid): 5
extra payments by beneficiary bank (the recall requests you will send):
B18 3 payments ₦185,915.94
B16 1 payments ₦109,016.96
B01 6 payments ₦86,498.27
B17 3 payments ₦80,149.12
B11 1 payments ₦54,016.20
largest single extra payment ₦109,016.9639 + 7 + 25 + 1 = 72: the breaks of step 3, counted by kind. The same 27 payouts sit behind most of them. Of the 39 retry transfers, 32 were second payments, 5 carried the only payment (the original had failed) and 2 were refused. The reconciliation read the report while 6,016,570 kobo of transfers were still pending, which is why it showed 25 payouts and a gap of 70,383,374 kobo. Once they resolved, exposure.py found 27 payouts and 76,399,944 kobo. Check: 76,399,944 − 6,016,570 = 70,383,374. A figure like ₦763,999.44 is true for the minute you read it. Must not differ: the bracket from the exposure section (the gap the reconciliation printed is no more than the confirmed figure, which is no more than the gap plus what was pending then), and every wallet was debited once. Run to run the figures move a good deal. In a second run of mine the 72 became 74, and one intent was the sharper case from the exposure section: all three attempts at one payout timed out, the requery of the original said failed, the wallet gave the customer’s money back, and two retries had paid. Its two payments were both counted as extra, which is why exposure.py there reported 28 extra payments (₦487,346.31) and the switch’s gap was exactly that amount once everything had resolved. If your run has such an intent, expect the same.
5. Stop the bleed. Apply the brake, then the fix. The brake adds a payouts_halted switch read from the database on every payout, so you can halt a running service from another terminal. The fix removes the retry. Then prove the brake on the Friday database without touching the switch: a halted payout comes back halted and leaves no operation, no hold and no transfer.
python3 patch.py brake
python3 patch.py fix
python3 controls.py data/friday.sqlite payouts_halted 1
python3 - <<'PY'
from wallet import Api, Wallet
w = Wallet("data/friday.sqlite", Api("http://127.0.0.1:8102", "x"), Api("http://127.0.0.1:8102", "x"))
print(w.payout(1, 100_000, "B03", "1234567891", "TEST-HALTED"))
print(w.op("TEST-HALTED"))
PY
python3 controls.py data/friday.sqlite payouts_halted 0wallet.py: brake applied
wallet.py: fix applied
{'payouts_halted': '1'}
halted
None
{'payouts_halted': '0'}The order in a real incident is the order of the chapter: the brake first, because it stops loss at once, then the fix, which needs review. Here you apply both because the Friday run has finished. The last command puts the switch back to 0 so the next step’s reconcile.py is not surprised by it. The reconciliation does not read this switch, but a wallet started on this file would.
6. Book the loss. Teach the reconciliation the new class: a retry transfer that the ledger has booked as a duplicate receivable is explained, one that it has not is a break. Then book the duplicates and run the reconciliation again. book.py is safe to run twice.
python3 patch.py recon
python3 book.py --db data/friday.sqlite
python3 book.py --db data/friday.sqlite
python3 reconcile.py --db data/friday.sqlite
python3 check.py --db data/friday.sqlite | tail -1reconcile.py: recon applied
booked 32 duplicate payouts, 76,399,944 kobo; 0 were already booked
booked 0 duplicate payouts, 0 kobo; 32 were already booked
cards provider report for 2026-11-15: 300 captures, gross 794,001,600 kobo, fee 7,940,016, refunds 100,398,857, net 685,662,727
ledger: 300 credited fundings; card_clearing holds 0 kobo before settlement
switch report for 2026-11-14: 199 outward, 200 inward transfers; 200 inward match, 155 match, 5 original failed or pending, a retry carried the payment, 5 retry transfer, carried, 32 retry transfer, duplicate, booked, 2 retry transfer, refused
net position: switch 611,620,154 kobo (pending 0 listed apart), ledger 611,620,154 kobo
audit duplicate payouts booked as receivables: 32, 76,399,944 kobo; recoverable_payouts holds 76,399,944 kobo
audit payout intents with an unbooked duplicate: 0; card intents captured more than once: 0
balance operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
unexplained breaks: 0
OK: all invariants holdThe two net positions now agree, because the ledger’s settlement account has caught up with the cash. Count the switch line: 155 + 5 + 5 + 32 + 2 = 199 outward transfers, each with a name. unexplained breaks: 0 and recoverable_payouts holds 76,399,944 kobo are two halves of one message: every line is explained, and ₦763,999.44 is still owed. The second book.py booked nothing: the ledger’s unique (kind, reference) index and the posting function both refuse a repeat. Must not differ: the booked total equals the exposure from step 4, and check.py still ends OK.
7. Get the facts for the postmortem.
python3 postmortem.py --db data/friday.sqliteTIMELINE (seconds after the first payout request)
0 s first payout request
3 s first duplicate transfer sent
131 s last payout request
130 s last duplicate transfer sent
131 s last payout operation settled; the reconciliation reads the report after this
BLEED (duplicate payments sent, in 30-second buckets)
0-30 s ######## 8
30-60 s ####### 7
60-90 s ###### 6
90-120 s ####### 7
120-150 s #### 4
IMPACT
duplicate payments: 32 on 27 payouts, 76,399,944 kobo = ₦763,999.44
payouts that reached the switch: 160; share paid twice or more: 16.9%
payouts held from a wallet more than once: 0 (each wallet was debited once; the company paid the second time)
recipients' banks involved: 15Time zero is the first payout request, and the load sends payouts for about 131 seconds. The first duplicate went out 3 seconds in and the bleed ran at 4 to 8 payments in every 30-second bucket, so nothing about it was a burst a human would spot. In the lab the reconciliation ran once, after the load. In production it runs once a day, so the exposure is a day of that rate, not 131 seconds of it. The numbers for the postmortem are printed above. Write it in the Artefact that follows this Lab, which gives you the template, a worked example and a checklist.
8. Prove the fix. Stop both mocks and start them again with the step 2 commands, so the switch holds only this run. The wallet has no retry. Run the same load.
python3 load.py --db data/fixed.sqlite | tee data/fixed.txt
python3 exposure.py --db data/fixed.sqlite1,000 operations in 84 s; everything settled or explained after 127 s
kind state count
fund_bank credited 200
fund_card credited 300
p2p done 169
p2p refused 31
payout failed 25
payout refused 13
payout settled 162
refund processed 73
refund refused 11
messages: 611 handled, 38 repeats of an event already seen, 305 that found the operation already settled, 0 bad signatures
daily reconciliation, 2026-11-14
cards provider report for 2026-11-15: 300 captures, gross 805,522,800 kobo, fee 8,055,228, refunds 114,482,605, net 682,984,967
ledger: 300 credited fundings; card_clearing holds 691,040,195 kobo before settlement
switch report for 2026-11-14: 167 outward, 200 inward transfers; 200 inward match, 167 match
net position: switch 669,554,964 kobo (pending 0 listed apart), ledger 669,554,964 kobo
audit duplicate payouts booked as receivables: 0, 0 kobo; recoverable_payouts holds 0 kobo
audit payout intents with an unbooked duplicate: 0; card intents captured more than once: 0
balance operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
repaired by this run: 1 card settlement posted
unexplained breaks: 0payout intents 167; transfers 167; transfers sent under a retry reference 0
paid more than once 0 intents, 0 extra payments, 0 kobo = ₦0.00exposure.py prints more lines after these two; they read zero too.
Must not differ: unexplained breaks: 0, no booked duplicates, and transfers 167 against payout intents 167: one transfer for every intent, at a 20% timeout rate. The wallet holds the timed-out payouts and requeries them, which is slower for the customer and safe for the money.
9. The drill: a faster alarm. Put the Friday change back (the brake from step 5 stays in), restart both mocks, and this time run the watcher beside the load. The watcher reads only the switch’s report and halts payouts the first time any intent has a second transfer. Start it in a third terminal before the load, in the same folder:
python3 patch.py plant
python3 watch.py --halt data/drill.sqliteThen, in terminal 3 (use a fourth for watch.py if you prefer):
python3 load.py --db data/drill.sqlite | tee data/drill.txt
python3 exposure.py --db data/drill.sqliteWatcher:
T+ 0 s 0 outward transfers; intents sent more than once: 0
T+ 6 s 8 outward transfers; intents sent more than once: 1
T+ 6 s HALT: payouts stopped after OP OP-00133 was sent twice
T+ 10 s 9 outward transfers; intents sent more than once: 2The first alarm came 6 seconds after the watcher started, at the first retry, before either payment had resolved. Load and exposure:
1,000 operations in 15 s; everything settled or explained after 48 s
kind state count
fund_bank credited 200
fund_card credited 300
p2p done 177
p2p refused 23
payout refused 1
payout settled 7
refund processed 74
refund refused 14
messages: 611 handled, 37 repeats of an event already seen, 304 that found the operation already settled, 0 bad signatures
daily reconciliation, 2026-11-14
cards provider report for 2026-11-15: 300 captures, gross 779,599,000 kobo, fee 7,795,990, refunds 86,055,073, net 685,747,937
ledger: 300 credited fundings; card_clearing holds 693,543,927 kobo before settlement
switch report for 2026-11-14: 9 outward, 200 inward transfers; 200 inward match, 6 match, 1 original failed or pending, a retry carried the payment, 1 retry transfer, carried
net position: switch 1,058,617,395 kobo (pending 1,603,666 listed apart), ledger 1,059,002,943 kobo
audit duplicate payouts booked as receivables: 0, 0 kobo; recoverable_payouts holds 0 kobo
audit payout intents with an unbooked duplicate: 1; card intents captured more than once: 0
balance operations still open: 0; in_flight holds 0 kobo; card_clearing holds 0 kobo
repaired by this run: 1 card settlement posted
unexplained breaks: 3
switch: duplicate payout OP-00133-r1 (385,548 kobo) is not booked as a receivable
switch: net position is 1,058,617,395 kobo at the switch and 1,059,002,943 in the ledger (difference -385,548)
paid twice: OP OP-00133 went out 2 timespayout intents 7; transfers 9; transfers sent under a retry reference 2
paid more than once 1 intents, 1 extra payments, 385,548 kobo = ₦3,855.48
extra still pending 1 transfers, 1,603,666 kobo = ₦16,036.66 (may yet succeed)
upper bound ₦19,892.14
retry carried the payment (original failed, nothing extra paid): 1Wait 30 seconds and run exposure.py --db data/drill.sqlite again: the pending transfer resolved, and the figures became:
paid more than once 2 intents, 2 extra payments, 1,989,214 kobo = ₦19,892.14
extra still pending 0 transfers, 0 kobo = ₦0.00 (may yet succeed)Compare with step 4: 32 second payments and ₦763,999.44 without the alarm, 2 and ₦19,892.14 with it. 1,603,666 + 385,548 = 1,989,214 kobo, the two that were already in flight when the alarm fired, one confirmed and one pending at the first read. Do not read this as a measured saving: in my first run the unprotected load sent 160 payouts and this one sent 8, because the brake stopped the other 192 (200 requested, 8 recorded; other runs record a handful, not 8 exactly), each of which got halted and would be retried later by its caller. What the comparison shows is the shape. Without an alarm the loss grows with volume. With one on the attempt it is bounded by what was in flight. Finish as before: python3 book.py --db data/drill.sqlite, then python3 reconcile.py --db data/drill.sqlite, which ended with 2 retry transfer, duplicate, booked, recoverable_payouts holds 1,989,214 kobo and unexplained breaks: 0 in mine.
Make the Friday retry safe in the one way that looks too small to matter. Keep a copy of the planted wallet (cp wallet.py wallet.drill.py), then edit wallet.py so the retry’s fresh reference becomes the operation’s own key (body["payment_reference"] = key), restart both mocks, and run python3 load.py --db data/reuse.sqlite, then python3 exposure.py --db data/reuse.sqlite. In mine: unexplained breaks: 0, transfers sent under a retry reference 0, paid more than once 0 intents, and as many transfers as payout intents (169 and 169). The wallet still retries, and nothing is paid twice. Answer three questions. Why did a retry that changes only one string stop the bug? What does the wallet do when the switch answers the retry with code 26, and why is that the right state? And what did Moyo’s change get right, so that the fix is one line and not a rewrite? Restore with cp wallet.drill.py wallet.py, then python3 patch.py fix. Stop both mocks (Ctrl-C) and clean up with rm data/baseline.sqlite data/friday.sqlite data/fixed.sqlite data/drill.sqlite data/reuse.sqlite data/*.txt.
Template
# Post-mortem: <what went wrong, in plain words>
Incident lead: <name> · Reviewed by: head of engineering, head of payments · Exposure signed by: <head of finance>
Status: <draft | reviewed | final> · Date: <date>
## Summary
<Two sentences: what happened, and what it cost as a range with the time you read it.>
## Timeline (from records, not memory)
| When | What happened | Source |
|---|---|---|
## Exposure
| Read at | Confirmed | Still pending | Upper bound |
|---|---|---|---|
<Intents, payments, banks involved, whose money was debited, how it is booked.>
## Detection
<How it was found, how long after it began, and what should have found it sooner.>
## Contributing factors
<Several. Each is a thing the system allowed. None says 'be more careful'.>
## What went well
<Controls that worked.>
## Actions
| Action | Owner | Date | Signal that shows it worked |
|---|---|---|---|
## Where this could be wrong
<One way, and what would show it.>
## Recall request to <beneficiary bank>
To / From / Date. What was sent in error, total, schedule of references. What you ask. Reply needed by <date>.
## Customer message
<Three or four plain sentences: what happened, what they owe or must do (often nothing), what you are doing.> WORKED EXAMPLE
At Ferrowave the incident lead writes this, here Doobee, with the head of engineering and the head of payments reviewing and the head of finance signing the exposure. Clock times and dates are illustrative, and the lab run stands in for the weekend’s payouts (an assumption); the seconds and naira figures are from the lab.
Timeline. Fri 6 Nov: Moyo’s retry ships, flag on. Run seconds, from postmortem.py: 0 s first payout; 3 s first duplicate; 130 s last duplicate; 131 s last operation settled. Mon 9 Nov 09:40 reconciliation shows 72 unexplained breaks; 10:05 flag off; 10:20 intents sent twice stop rising.
Exposure. Read 09:40: ₦703,833.74 to ₦763,999.44 (a gap of ₦703,833.74, with ₦60,165.70 still pending). Read 10:50: ₦763,999.44 confirmed, nothing pending: 32 payments on 27 of 160 payouts, 15 banks. Each wallet was debited once. Booked as a receivable, recoverable_payouts.
Detection. Reconciliation, on Monday morning, after the whole weekend’s payouts (the daily run is the only check). No alert fired, because nothing failed.
Contributing factors. Retry sat below the idempotency layer; the test double never went quiet; flag on by default; daily reconciliation; no alarm on one intent, one transfer; halt never rehearsed.
| Action | Owner | Date | Signal |
|---|---|---|---|
| Reuse the operation’s key on retry | Moyo | 11 Nov | transfers equal payout intents in a planted load |
| Test double that goes quiet | Bank Connectors | 18 Nov | test fails with the retry planted |
| Alarm and halt on a second transfer | Doobee | 18 Nov | drill halts within 10 s |
Where this could be wrong. If an intent had every attempt time out, the report understates it; the ops table would show it.
Recall request, B18. We sent 3 second payments in error, ₦185,915.94 in all (Schedule A). Please return or hold them and reply by 16 Nov.
Customer message. Some of your payouts went out twice. You were debited once; you owe nothing and need do nothing. We stopped the cause and are recovering the money.
Now you
A month later you are the incident lead at Owoleaf, whose wallet pays out by NIP. Your engineers planted the same retry in a new connector. This time the watcher caught it: use your own step 9 run, the drill. Your sources are exposure.py at its first read and again 30 seconds later, the watcher’s lines, postmortem.py and check.py. Write the post-mortem, a recall request to the beneficiary bank with the largest extra total your exposure output shows, and a short message to wallet customers whose payouts came back halted and who will ask where their money is. The alarm worked, so say what it cost, what it did not catch and what still depends on luck. Your reader is Owoleaf’s head of engineering, who decides whether payouts restart, with its head of payments and finance lead reviewing; finance signs the exposure before it goes to the bank.
Self-check
It is 14:00 on Monday. Reconciliation has found duplicate payouts, and the one-intent-one-transfer count is still rising. Salary runs for three customers are due to go out this afternoon. Moyo's retry is behind a flag, on by default, and you also have a payout halt. You have no fix yet.
- DOC Slaughter and May's independent review of TSB's 2018 migration to a new IT platform
The law firm's own page for the review that TSB's board commissioned and published in November 2019. Read it for how an incident review is scoped and what it asks about governance; the findings quoted in this chapter come from press coverage of the report, so check the report itself.
- DOC TSB: Slaughter and May review published
TSB's own release on publication, including the board's statement that it disagrees with aspects of the report. Useful as an example of how a company responds to an independent review in public.
- DOC Independent review of the RTGS outage on 20 October 2014 Deloitte, 2015
Deloitte's report for the Bank of England, published in redacted form in March 2015. Read the root-cause and recommendations sections for how a cause that predates the outage by over a year is traced; skip the appendices on a first pass.
- DOC Bank of England announces supervisory action over Visa Europe's June 2018 partial outage incident 2019
The regulator's follow-up to the 1 June 2018 outage, which shows what supervision of a payment scheme's incident looks like. The cause and the transaction figures quoted in this chapter come from press reports of Visa's reply to the Treasury Committee, not from this page.
- DOC Treasury Committee: letter to Charlotte Hogg, CEO Visa Europe, 4 June 2018 2018
The questions the Treasury Committee's chair put to Visa three days after the outage: what went wrong, how a repeat will be prevented and whether customers or merchants will be compensated. Visa's reply is a separate document that I have not read.
- DOC Citibank, N.A. v. Brigade Capital Management, LP (2d Cir. 2022), No. 21-487 2022
The Second Circuit's opinion on the mistaken payment of Revlon loan principal. Read the facts and the reasoning on the discharge-for-value defence for what recovery of a mistaken payment depends on; skip the concurrence unless you read law for pleasure.
- BOOK Postmortem Culture: Learning from Failure Google SRE, 2016
Chapter 15 of Google's Site Reliability Engineering book on blameless postmortems and what makes them worth writing. Read the sections on what to write and on building the culture; the example template is the part to copy. Read: Chapter 15.
- PAPER How Complex Systems Fail Richard I. Cook, 1998
Richard Cook's eighteen short points on why accidents have several causes and why hindsight bias distorts the review. Read the points on multiple failures, on root cause and on hindsight before you write a contributing-factors section. Read: The points on multiple failures, root cause and hindsight.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.