Idempotency and moving money exactly once
A timeout means unknown, not failed. Retry without a key and you pay twice; retry with one and the same request can run a hundred times and move money once
Your service sends a ₦15,000 transfer to another bank. Your HTTP client gives up after 2 seconds with no answer. You send the transfer again with a new payment reference. What is the most likely outcome in a system like the lab's switch?
Most payment bugs of this kind are not exotic. Someone writes a retry loop because networks fail, and the loop is right for reading data and wrong for moving money. This chapter is about the one rule that makes the loop safe, and about the places where the rule needs more than a header.
The lab runs on Owoleaf’s mocks: a payment provider on port 8101 and an instant-payment switch on port 8102. Their codes, timings and field names are invented and labelled so. The mechanism is not invented: every real payment API you integrate with has a version of it.
A timeout means unknown
A client sends a request and waits. Four things can have happened, and the client sees the same silence for all four.
| What happened | What the client sees | Did the money move? |
|---|---|---|
| The request never reached the server | Timeout | No |
| The server crashed before doing the work | Timeout | No |
| The server did the work, then crashed before answering | Timeout | Yes |
| The server did the work and answered, but the answer was lost | Timeout | Yes |
A client that treats a timeout as a failure is right about the first two rows and wrong about the last two. A client that treats it as success is the other way round. There is no third answer inside the client, because the information is not there. The lesson on idempotency and exactly-once puts it in one line: a timeout means unknown, not failed. Timeouts covers why the client has to stop waiting at all.
The mock provider has a test card for the third and fourth rows. A charge on a card ending 0005 succeeds and then answers with an HTTP 500. The response says the charge failed. The charge is real. This is the case card payments met in the card chapter: “the charge, not the response, is the fact.”
Who retries, and why you cannot stop them
You might hope to avoid the problem by never retrying. You cannot, because retries come from places you do not control.
- Your own client code. A timeout, a connection reset or a 5xx makes a loop send again. The lesson on retries, backoff and jitter shows why a loop with no spacing makes an outage worse as well.
- Infrastructure between you and the server. Load balancers and gateways may resend a request that failed on one backend. Some HTTP libraries retry on their own for a connection that was reset.
- Your customer’s code. Ferrowave’s customer retried because their job runner has a limit of its own. You cannot read their code, but you can make their retry safe.
- People. A customer taps Pay twice because the screen froze. The second tap is a retry with a fresh request.
- Message systems. A queue that delivers at least once will deliver again after a consumer crashes. Webhooks are the same: the provider resends until you answer 2xx, so your handler sees every event at least once.
At-least-once is the best any network can promise, because a sender that never hears back has only two choices, resend (and risk a duplicate) or give up (and risk a loss). For money, a loss is visible and a duplicate is not, so senders resend. Exactly-once delivery is not available. What you can build is exactly-once effect: the message may arrive many times, and the money moves once.
Idempotent by nature, and by key
An operation is idempotent when doing it twice leaves the same state as doing it once. Some operations are idempotent by nature.
| Operation | Idempotent? | Why |
|---|---|---|
Set the wallet’s status to frozen |
Yes | The second call finds it frozen |
| Read a balance | Yes | Nothing changes |
| Delete payout 41 | Yes | The second call finds nothing to delete |
| Credit a wallet by ₦500 | No | Each call adds another ₦500 |
| Pay ₦15,000 to account 2012345671 | No | Each call is a new payment |
Money movements are the second kind: they are verbs that add. You make them idempotent by giving the operation an identity. That is the idempotency key: a value the client creates for one logical operation and sends again on every retry. The server keeps the key with the result. A request with a key it has seen gets the stored result, and the work does not run again.
Three rules about the key matter more than the header’s name.
The client creates the key once, before the first attempt, and keeps it. The key identifies the operation (this top-up for this order), not the attempt. If your retry loop generates a new key each time round, you have changed nothing: the server sees every attempt as new. The break at the end of the lab makes you do exactly that. Store the key with the order, in the same database write that creates the order, so a crash and restart still has it.
The server compares the body, not only the key. A key arriving with a different amount or account is a client bug: the same operation cannot have two shapes. The server refuses it and does nothing. Quietly returning the first result would hide the bug, and quietly running the new body would pay twice.
The server stores the outcome, errors included, and replays it. If the first attempt failed with a rule violation, the retry should get the same refusal, not a second try. If the first attempt was in progress when the second arrived, the server answers that it is in progress (a 409 in the lab) and the client waits and asks again.
Stripe’s API documentation, a vendor’s claim about its own API, says an idempotency key can be up to 255 characters and that keys may be removed from the system once they are at least 24 hours old, after which reusing a key creates a new request. That is Stripe’s design; other providers choose differentlyas of 2026-11. Such a lifetime is a design choice you inherit: a retry after the key is pruned is a new payment, so a client’s retry window must be shorter than the server’s memory.
There is a standards effort. An IETF Internet-Draft, “The Idempotency-Key HTTP Header Field” (draft-ietf-httpapi-idempotency-key-header, revision -07, October 2025), proposes an Idempotency-Key request header so that POST and PATCH requests can be retried safely, with a 400 answer for a missing key and 409 and 422 answers for key conflicts. It is a draft, not an RFC. Its listed expiry, 18 April 2026, has passed and a search in this build could not show whether it has since been replaced or lapsed, so check its page for its current statusas of 2026-11. The lab’s mock uses 409 for a request in progress and 422 for a reused key with a different body. Do not cite a draft as a rule; cite it as where the convention is heading.
Reserve first, then one transaction
A key store is a table of key to result. How you use it decides whether it works. The most natural version has three steps:
- Look the key up. If it is there, return the stored result.
- Do the work: pay.
- Record the key with the result.
It looks right and it is not. Each step commits on its own, so there are two failures. If two copies of the request arrive together, both do step 1 and find nothing, both do step 2, and the customer is paid twice. This is a check-then-act race: the check and the act are not one step (see check-then-act). And if the process dies between steps 2 and 3, the money has moved and no key says so, so the retry pays again.
The fix has two parts, and each answers one of those failures.
Reserve the key first, as an atomic claim. Insert the key as started in a transaction that takes the write lock before it reads (SQLite’s way; PostgreSQL does it with an insert that ignores a key already present). Of two simultaneous requests, one claims the key and the other sees it taken and gets “in progress”. The lookup and the claim are one step, so no one can slip between them.
Do the work and record the result in one transaction. The payout row and the key’s done result commit together or not at all. After a crash, either both exist (the retry gets the stored result) or neither does (the retry runs the work for the first time). There is no state with a payment and no key.
// handler
function charge(req) {
const result = card.charge(req.amount); // side effect
return result; // response lost -> client retries -> charged again
}// handler with an idempotency key
function charge(req) {
const r = store.reserve(req.id); // atomic insert-if-absent
if (r === 'pending') return 409; // another worker is on it
if (r !== 'claimed') return r; // replay: stored result, no side effect
return store.txn(() => {
const result = ledger.charge(req); // side effect ...
store.commit(req.id, result); // ... and the key, in one commit
return result;
});
} Run the four scenarios in order. NAIVE RETRY shows the double charge. FIX: IDEMPOTENCY KEY stops it for the simple case. CRASH BETWEEN CHARGE AND RECORD shows the key store alone failing: the charge happened, the key was never written, and the retry charges again. FIX: RESERVE, THEN ONE TRANSACTION holds through the same crash. Watch the invariant strip: “each request id is applied at most once”. Then try the BREAK IT exercise below.
The key store is deployed and the retry is served from it. Inject a duplicate delivery of r1 (or a crash) at a point where it still charges the card twice.
GOAL: r1 is charged more than once
A reserved key needs one more rule. If the process dies after reserving and before doing the work, the key stays started and every retry would wait forever. The reservation therefore carries a time. A started key older than a lock period (30 seconds in the lab) may be taken over by a new request. This is safe only because the work and its record are one transaction: a started key means the work did not commit. It also needs one check at the end. A worker that is slow, not dead, may wake after another request has taken over its key, so the closing update only succeeds if the key is still started and still carries this request’s reservation time. Otherwise the worker rolls back its payout and gives way. The lock period must also be longer than the slowest honest run. Step 5 of the lab shows both crash points.
The step you cannot put in your transaction
Everything so far works when the money movement is a row in your own database. Ferrowave’s is not. A payout is a request to a bank through a switch, and no database transaction spans two companies. This is the hard part, and it is where most real double payments happen.
If the process crashes after the switch accepted the transfer and before your database recorded it, your started key has no result and the work really did happen. A new request that takes the key over and sends the transfer again will pay twice. Three habits close the gap.
Pass an identity downstream. The provider accepts an Idempotency-Key on charges. The switch accepts a payment_reference and answers a repeated one with code 26, duplicate, and the first session. Derive both from your own key, so the same operation always carries the same identity to the next system, on every attempt. Then even a takeover that resends the transfer is recognised downstream.
Write the intent before you act. Record the payout as sending, with its reference, before you call the switch. A restarted worker finds every sending payout and resolves it. It never invents a new one.
Requery before resending. After a timeout, ask the other side what happened, using the reference you sent. The mock’s requery (POST /tsq, transaction status query) answers with the status:
| Answer from the requery | Meaning | What you do |
|---|---|---|
09, pending |
Still in progress | Wait, and ask again. Do not resend |
00, successful |
It was paid | Mark the payout done. Do not resend |
successful then later reversed |
It was paid, then returned | Treat it as a returned payout (a later chapter on payment states covers reversals) |
| failed | It was refused | The attempt is over; a new attempt gets a new reference and is your decision |
25, not found |
The switch never saw the request | Resend with the same reference |
The switch’s answer to a resent reference is a useful second line of defence, but not the first. A 26 tells you the earlier request exists; it does not tell you whether it was paid. Only the requery does.
How long to wait is a real question, and published practice varies. One Nigerian bank’s support article on checking transaction status, a bank’s guidance and not a CBN rule, advises using a status query to confirm the outcome before retrying any uncertain money-movement request, and keeping the original request referenceas of 2026-11. Another bank’s developer documentation recommends re-querying for 15 minutes to confirm a final statusas of 2026-11. A third source, a provider’s help article, says to wait at least 30 minutes before checking NIBSSas of 2026-11. These come from search summaries, and they disagree. This build also could not find NIBSS’s own definition of the response code the mock calls 09, so the codes in the lab are illustrative. Take the wait from your own integration documentation, and expect minutes, not the lab’s seconds.
The mock holds a timed-out request for 35 seconds by default (timeout_hold_s) and resolves a pending transfer 10 seconds later. The lab starts the switch with --timeout-hold-s 5 so you do not wait 45 seconds each time; the lesson is the same.
Exactly once, honestly
Put the pieces together and the phrase “exactly once” has a precise meaning. The network delivers at least once. The key makes the handler safe to run again. The reservation and the single transaction make “ran again” and “ran once” produce the same state. The downstream identity extends that guarantee to the next system. What you have is at-least-once delivery with idempotent processing, which gives exactly-once effect. Two readings are worth your time for this view: Helland’s 2007 paper on messages between independent entities, and Airbnb’s post on keeping repeated payment calls from paying twice across services (the Reading list says what to look for).
The guarantee has an edge. It protects against the same operation arriving twice. It does not protect against two different operations that mean the same thing, such as a customer who really does submit two payouts to the same account. Detecting that is a different control (limits, velocity rules, a confirmation step), and it belongs next to idempotency, not instead of it.
Where it goes wrong
Name the failures first, because each of them looks like a working system.
A new key on every attempt. The key is created inside the retry loop, usually by a helper that builds the request. Everything looks idempotent in review. The break at the end of the lab does this, and the provider charges twice.
A key that is not the operation. A key made from a timestamp, a random number made per request, or a customer id alone. The first two differ between attempts. The third collides between different payments and the second one is refused as a changed body, or worse, replayed.
Recording the key after the work. The three-step handler. It passes every single-threaded test. The lab’s eight simultaneous requests make 8 payouts.
Not comparing the body. The server returns the first result for a key whatever the body says. A client bug that sends ₦20,000 under a key that paid ₦15,000 gets a success and believes the ₦20,000 moved.
Forgetting that keys expire. A retry that arrives after the server pruned the key is a new payment. Keep your retry window shorter than the key’s life, and make the final reconciliation the backstop: reconciliation finds the payments no key explained.
Resending on a timeout without a requery. The lab’s naive switch client. It is the commonest cause of a duplicate payout, because the retry is correct for every other kind of call.
Retrying a payment the other side has refused. A requery that says failed is an answer. Resending the same instruction in a loop fills the beneficiary’s bank’s logs and, for some refusals, never succeeds.
What Ferrowave builds
Sani and Ekaette write down four changes. The payout endpoint requires an Idempotency-Key and answers 400 without one. It stores keys for 7 days (a number the team picks, longer than the customer’s longest retry window, and illustrative here). The reservation and the payout row commit in one transaction, and the payout’s switch reference is derived from the key. A worker finds payouts left sending and requeries them. And the customer guide says, in the first paragraph, that a timeout means the request may have succeeded and that the key is how to find out.
You work in labs/finance. You create four files there: step2_provider.py, step3_switch.py, idem.py and step5_run.py. Customer, card, bank and account values are the lab’s. Order ids and charge ids are random, so yours will differ from the output below.
1. Start both mocks. In two terminals, from labs/finance:
python3 generate.py # skip if data/finance.sqlite exists
python3 mock_provider.py --freshpython3 mock_switch.py --fresh --timeout-hold-s 5Each prints nothing until a request arrives (add --quiet to silence the request log). The provider listens on 8101 and the switch on 8102. --fresh clears their saved state so the counts below start from zero. The switch’s default timeout_hold_s is 35 seconds: a request forced to time out is held for that long before the switch answers 97. The flag shortens it to 5 so that step 3 takes about 30 seconds instead of about 90.
2. Charge the card that loses its answer, with and without a key. Save as step2_provider.py and run it. Card 0005 charges the card and then answers with an HTTP 500, so the client must retry without knowing whether it was charged. A scenario for each of the three lessons: a new reference per retry, one key per order, and what the provider does with a misused key.
import json, secrets, urllib.error, urllib.request
BASE = "http://127.0.0.1:8101"
HEAD = {"Authorization": "Bearer sk_test_owoleaf_mock", "Content-Type": "application/json"}
def call(method, path, body=None, extra=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, data=data, headers={**HEAD, **(extra or {})}, method=method)
try:
with urllib.request.urlopen(req) as r:
return r.status, r.headers.get("Idempotent-Replayed"), json.load(r)
except urllib.error.HTTPError as e:
return e.code, e.headers.get("Idempotent-Replayed"), json.load(e)
def body_for(order, reference):
return {"reference": reference, "amount_kobo": 1_850_000, "customer_ref": "C0000042",
"card_number": "411111111111" + "0005", "metadata": {"order": order}}
def charges_for(order):
_, _, b = call("GET", "/charges?status=success")
return [c for c in b["charges"] if c["metadata"].get("order") == order]
print("A. no key, a new reference on every retry (the naive client)")
order = "ORD-" + secrets.token_hex(3)
for attempt in (1, 2):
status, _, b = call("POST", "/charges", body_for(order, f"{order}-try{attempt}"))
print(f" attempt {attempt}: HTTP {status}, {b['error']}: {b['message']}")
mine = charges_for(order)
print(f" charges at the provider for {order}: {len(mine)}, total {sum(c['amount_kobo'] for c in mine)} kobo")
print("B. one Idempotency-Key per order, reused on every retry")
order = "ORD-" + secrets.token_hex(3)
key = "topup-" + order
body = body_for(order, order)
for attempt in (1, 2, 3):
status, replayed, b = call("POST", "/charges", body, {"Idempotency-Key": key})
c = b.get("charge", {})
print(f" attempt {attempt}: HTTP {status}, Idempotent-Replayed: {replayed}, charge {c.get('id')}, status={c.get('status')}")
mine = charges_for(order)
print(f" charges at the provider for {order}: {len(mine)}, total {sum(c['amount_kobo'] for c in mine)} kobo")
print("C. what the provider does with a key that is misused")
changed = dict(body, amount_kobo=2_000_000)
status, replayed, b = call("POST", "/charges", changed, {"Idempotency-Key": key})
print(f" same key, other amount: HTTP {status}, {b['error']}")
status, replayed, b = call("POST", "/charges", body)
print(f" same reference, no key: HTTP {status}, {b['error']}, carries charge {b['charge']['id']}")python3 step2_provider.pyA. no key, a new reference on every retry (the naive client)
attempt 1: HTTP 500, internal_error: injected: the response was lost
attempt 2: HTTP 500, internal_error: injected: the response was lost
charges at the provider for ORD-51ff9e: 2, total 3700000 kobo
B. one Idempotency-Key per order, reused on every retry
attempt 1: HTTP 500, Idempotent-Replayed: false, charge None, status=None
attempt 2: HTTP 200, Idempotent-Replayed: true, charge ch_5c129f62001e498c, status=success
attempt 3: HTTP 200, Idempotent-Replayed: true, charge ch_5c129f62001e498c, status=success
charges at the provider for ORD-18957f: 1, total 1850000 kobo
C. what the provider does with a key that is misused
same key, other amount: HTTP 422, idempotency_key_reused
same reference, no key: HTTP 409, duplicate_reference, carries charge ch_5c129f62001e498cA: both attempts answer 500 and both charged the card, so the customer paid ₦37,000 (3,700,000 kobo) for a ₦18,500 order. B: the first attempt answers 500 (not replayed: it ran), and the second and third are replayed from the stored result with HTTP 200 and Idempotent-Replayed: true: one charge, 1,850,000 kobo, even though the first answer said failure. The provider stored the charge’s real result, not the 500. C: the same key with another amount is refused with 422, and the same reference without a key is a 409 that carries the existing charge, which shows that a stable reference is itself a weak form of identity.
3. Time out a transfer, then retry it two ways. Save as step3_switch.py. It sends a ₦15,000 transfer (1,500,000 kobo) forced to time out, and gives up after 2 seconds. A retries with a new payment reference. B keeps one reference and asks the switch what happened. The script waits for the first transfer to settle, so it takes about 30 seconds.
import json, secrets, socket, time, urllib.error, urllib.request
BASE = "http://127.0.0.1:8102"
HEAD = {"Authorization": "Bearer sw_test_owoleaf_mock", "Content-Type": "application/json"}
SENDER, BANK, ACCOUNT, AMOUNT = "9000000042", "B03", "2012345671", 1_500_000 # ₦15,000
def call(method, path, body=None, extra=None, timeout=10):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(BASE + path, data=data, headers={**HEAD, **(extra or {})}, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.load(e)
def transfer(ref, ne_ref, force=None, timeout=10):
"""Returns the answer, or None when the client gave up waiting."""
try:
return call("POST", "/transfers", {"payment_reference": ref, "name_enquiry_ref": ne_ref,
"sender_account": SENDER, "amount_kobo": AMOUNT, "narration": "SALARY"},
{"X-Mock-Force": force} if force else None, timeout)[1]
except (socket.timeout, TimeoutError, urllib.error.URLError):
return None
def requery(ref):
return call("POST", "/tsq", {"payment_reference": ref})[1]
def paid(prefix):
rows = call("GET", "/transfers?status=successful")[1]["transfers"]
return [t for t in rows if (t["payment_reference"] or "").startswith(prefix)]
_, ne = call("POST", "/name-enquiry", {"bank_code": BANK, "account_number": ACCOUNT})
print(f"name enquiry: {ne['response_code']} {ne['account_name']}")
print("A. the naive client: timeout, then a new reference")
run = "PAY-" + secrets.token_hex(3)
first = transfer(run + "-1", ne["name_enquiry_ref"], force="timeout", timeout=2)
print(f" attempt 1 after 2 s: {'no answer (client timeout)' if first is None else first}")
second = transfer(run + "-2", ne["name_enquiry_ref"])
print(f" attempt 2, new reference: {second['response_code']} {second['status']}")
q = requery(run + "-1")
print(f" requery attempt 1 straight away: {q['response_code']} {q['status']}")
for _ in range(20):
q = requery(run + "-1")
if q["status"] != "pending":
break
time.sleep(2)
print(f" requery attempt 1 later: {q['response_code']} {q['status']}")
rows = paid(run)
print(f" successful transfers of {AMOUNT} kobo to {ACCOUNT} for {run}: {len(rows)}, total {sum(t['amount_kobo'] for t in rows)} kobo")
print("B. one reference for the whole payout, and requery before anything else")
run = "PAY-" + secrets.token_hex(3)
ref = run + "-1"
first = transfer(ref, ne["name_enquiry_ref"], force="timeout", timeout=2)
print(f" attempt 1 after 2 s: {'no answer (client timeout)' if first is None else first}")
dup = transfer(ref, ne["name_enquiry_ref"])
print(f" same reference sent again: {dup['response_code']} {dup['response_message']}, status={dup['status']}")
q = requery(ref)
print(f" requery straight away: {q['response_code']} {q['status']}")
for _ in range(20):
q = requery(ref)
if q["status"] != "pending":
break
time.sleep(2)
print(f" requery later: {q['response_code']} {q['status']}")
rows = paid(run)
print(f" successful transfers for {run}: {len(rows)}, total {sum(t['amount_kobo'] for t in rows)} kobo")
q = requery("PAY-never-sent")
print(f" a reference the switch never saw: {q['response_code']} {q['response_message']}")python3 step3_switch.pyname enquiry: 00 HOLDER B03-5671
A. the naive client: timeout, then a new reference
attempt 1 after 2 s: no answer (client timeout)
attempt 2, new reference: 00 successful
requery attempt 1 straight away: 09 pending
requery attempt 1 later: 00 successful
successful transfers of 1500000 kobo to 2012345671 for PAY-3ba9fc: 2, total 3000000 kobo
B. one reference for the whole payout, and requery before anything else
attempt 1 after 2 s: no answer (client timeout)
same reference sent again: 26 Duplicate record, status=pending
requery straight away: 09 pending
requery later: 00 successful
successful transfers for PAY-5d2809: 1, total 1500000 kobo
a reference the switch never saw: 25 Unable to locate recordA: the first transfer was never failed. The requery straight after the timeout says 09 pending, and a moment later it says successful. The second transfer, with its new reference, was also successful. The beneficiary received ₦30,000 for a ₦15,000 payout. B: sending the same reference again is answered 26, duplicate, with the first transfer’s status, pending, so the switch does not pay twice. The requery says 09 until the transfer settles, then 00 successful: one payment of 1,500,000 kobo. A reference the switch has never seen answers 25, which is the only answer that makes a resend safe. The wait in B is a few polls of two seconds; its length varies from run to run.
4. Build the key store. Save as idem.py. Read handle before you run anything: the order of its lines is the design.
"""An idempotent payout endpoint over SQLite. Money is integer kobo.
handle() is the whole server side: it takes the client's Idempotency-Key and the request
body and returns (HTTP status, response, replayed). The 'payout' is a row in this database,
so the key and the payout can commit together.
"""
import hashlib, json, sqlite3, time
LOCK_SECONDS = 30 # how long a started request may run before another may take its key over
SCHEMA = """
CREATE TABLE IF NOT EXISTS idem (
key TEXT PRIMARY KEY, body_hash TEXT NOT NULL, state TEXT NOT NULL, -- 'started' or 'done'
locked_at REAL NOT NULL, status INTEGER, response TEXT);
CREATE TABLE IF NOT EXISTS payouts (
id INTEGER PRIMARY KEY, account TEXT NOT NULL, amount_kobo INTEGER NOT NULL CHECK (amount_kobo > 0));
"""
def connect(path):
db = sqlite3.connect(path, timeout=10, isolation_level=None) # we issue BEGIN ourselves
db.executescript(SCHEMA)
return db
def fingerprint(body):
return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
class Crash(Exception):
"""Stands in for a process dying at a chosen point."""
def handle(path, key, body, now=time.time, crash_at=None):
db, h = connect(path), fingerprint(body)
# 1. Reserve the key. BEGIN IMMEDIATE takes the write lock, so only one request at a time
# can look and then claim: the check and the act are one step.
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT body_hash, state, locked_at, status, response FROM idem WHERE key = ?", (key,)).fetchone()
if row and row[0] != h:
db.execute("ROLLBACK")
return 422, {"error": "idempotency_key_reused"}, False
if row and row[1] == "done":
db.execute("ROLLBACK")
return row[3], json.loads(row[4]), True
if row and now() - row[2] < LOCK_SECONDS:
db.execute("ROLLBACK")
return 409, {"error": "request_in_progress"}, False
stamp = now()
db.execute("INSERT INTO idem (key, body_hash, state, locked_at) VALUES (?, ?, 'started', ?) "
"ON CONFLICT (key) DO UPDATE SET locked_at = excluded.locked_at", (key, h, stamp))
db.execute("COMMIT")
if crash_at == "after_reserve":
raise Crash("died after reserving the key")
# 2. Do the work and record the result in ONE transaction: both happen or neither does.
db.execute("BEGIN IMMEDIATE")
cur = db.execute("INSERT INTO payouts (account, amount_kobo) VALUES (?, ?)", (body["account"], body["amount_kobo"]))
response = {"payout_id": cur.lastrowid, "amount_kobo": body["amount_kobo"]}
if crash_at == "before_commit":
db.execute("ROLLBACK")
raise Crash("died before the commit")
done = db.execute("UPDATE idem SET state = 'done', status = 200, response = ? "
"WHERE key = ? AND state = 'started' AND locked_at = ?", (json.dumps(response), key, stamp))
if done.rowcount == 0: # someone took our key over while we worked: undo the payout and give way
db.execute("ROLLBACK")
return 409, {"error": "reservation_lost"}, False
db.execute("COMMIT")
return 200, response, False
def handle_naive(path, key, body):
"""The three-step version: look, pay, record. Each step commits on its own."""
db = connect(path)
row = db.execute("SELECT response FROM idem WHERE key = ? AND state = 'done'", (key,)).fetchone() # look
if row:
return 200, json.loads(row[0]), True
time.sleep(0.05) # real work takes time
cur = db.execute("INSERT INTO payouts (account, amount_kobo) VALUES (?, ?)", (body["account"], body["amount_kobo"])) # pay
response = {"payout_id": cur.lastrowid, "amount_kobo": body["amount_kobo"]}
db.execute("INSERT OR REPLACE INTO idem VALUES (?, ?, 'done', ?, 200, ?)", # record
(key, fingerprint(body), time.time(), json.dumps(response)))
return 200, response, FalseThen save this as step5_run.py. It runs five cases: a plain retry, a changed body, two crash points, and eight requests at once against the three-step handler and against yours.
import os, threading
from idem import Crash, connect, handle, handle_naive
BODY = {"account": "2012345671", "amount_kobo": 1_500_000}
def fresh(name):
path = f"data/{name}.sqlite"
if os.path.exists(path):
os.remove(path)
connect(path).close()
return path
def payouts(path):
db = connect(path)
n, total = db.execute("SELECT COUNT(*), COALESCE(SUM(amount_kobo), 0) FROM payouts").fetchone()
db.close()
return n, total
def storm(fn, path, key, n=8):
results, gate = [], threading.Barrier(n)
def worker():
gate.wait()
status, _, replayed = fn(path, key, BODY)
results.append((status, replayed))
threads = [threading.Thread(target=worker) for _ in range(n)]
for t in threads: t.start()
for t in threads: t.join()
return results
print("1. the same key twice")
p = fresh("t1")
print(" ", handle(p, "k1", BODY))
print(" ", handle(p, "k1", BODY))
print(" payouts:", payouts(p))
print("2. the same key, a different amount")
print(" ", handle(p, "k1", dict(BODY, amount_kobo=2_000_000)))
print("3. a crash after the key is reserved, then retries")
p, clock = fresh("t3"), [1000.0]
try:
handle(p, "k3", BODY, now=lambda: clock[0], crash_at="after_reserve")
except Crash as e:
print(" crash:", e)
print(" retry at once: ", handle(p, "k3", BODY, now=lambda: clock[0]))
clock[0] += 31
print(" retry 31 s later: ", handle(p, "k3", BODY, now=lambda: clock[0]))
print(" payouts:", payouts(p))
print("4. a crash before the commit of the work")
p = fresh("t4")
try:
handle(p, "k4", BODY, now=lambda: 1000.0, crash_at="before_commit")
except Crash as e:
print(" crash:", e)
print(" payouts after the crash:", payouts(p))
print(" retry 31 s later:", handle(p, "k4", BODY, now=lambda: 1031.0))
print(" payouts:", payouts(p))
print("5. eight requests with the same key at the same moment")
p = fresh("t5a")
storm(handle_naive, p, "k5")
print(f" look, pay, record in three steps: payouts {payouts(p)}")
p = fresh("t5b")
res = storm(handle, p, "k5")
print(f" reserve, then one transaction: payouts {payouts(p)}; answers {sorted(set(res))}")5. Run it.
python3 step5_run.py1. the same key twice
(200, {'payout_id': 1, 'amount_kobo': 1500000}, False)
(200, {'payout_id': 1, 'amount_kobo': 1500000}, True)
payouts: (1, 1500000)
2. the same key, a different amount
(422, {'error': 'idempotency_key_reused'}, False)
3. a crash after the key is reserved, then retries
crash: died after reserving the key
retry at once: (409, {'error': 'request_in_progress'}, False)
retry 31 s later: (200, {'payout_id': 1, 'amount_kobo': 1500000}, False)
payouts: (1, 1500000)
4. a crash before the commit of the work
crash: died before the commit
payouts after the crash: (0, 0)
retry 31 s later: (200, {'payout_id': 1, 'amount_kobo': 1500000}, False)
payouts: (1, 1500000)
5. eight requests with the same key at the same moment
look, pay, record in three steps: payouts (8, 12000000)
reserve, then one transaction: payouts (1, 1500000); answers [(200, False), (200, True)]1: the second call returns the stored response with replayed true, and one payout exists. 2: a changed amount under the same key is refused with 422. 3: after a crash that reserved the key and did nothing else, a retry at once is told 409, in progress, because the key is held; 31 seconds later, past the 30-second lock, the retry takes the key over and the work runs once. 4: a crash before the commit left no payout and no result, because both are in one transaction; the retry then does the work once. 5: the three-step handler lets all 8 requests pay, 12,000,000 kobo (₦120,000) for one ₦15,000 request, on every run; the reserve-then-transaction version makes exactly 1 payout. One request answers False for replayed and the others True, though a run could also show a 409 for a request that arrived while another was mid-work. Either way the money moved once.
Go back to step2_provider.py and break section B. Move the key into the loop and give each attempt its own reference, so each attempt looks new: inside for attempt in (1, 2, 3): set key = "topup-" + secrets.token_hex(4) and send f"{order}-try{attempt}" as the reference. Run it. Every attempt is Idempotent-Replayed: false, and the provider reports 3 charges for one order, because a key made per attempt identifies the attempt, not the operation. Now fix it by creating the key once, outside the loop, from the order. Then ask the harder question: where does your client save that key so that a crash and a restart still reuse it?
Template
# Stuck-payout runbook: <product>
Owner: <operations lead> with <engineer> · Approved by: <head of payments> · Version <n>, <date>
Scope: <which payouts and which switch or provider; what is out of scope>
Decision needed: <what the approver is asked to agree>
## Recognise it
A payout is stuck when <state> and <how long> with no <final answer>. Look in <where>.
## Before you touch it
Find the reference we sent: <field>. Never create a new one.
## Requery
Ask <system> for the status of <reference>. Repeat every <minutes> for up to <minutes>.
## Decision table
| Answer | Meaning | Action (complete / wait / resend / close / escalate) | Who |
|---|---|---|---|
## Never
- <the actions that cause a double payment>
## Tell the customer
- While waiting: <wording>
- Once settled: <wording per outcome>
## Escalate to engineering when
- <conditions, with the information to attach>
## What this runbook cannot see
<one limit, and what would show it> WORKED EXAMPLE
Ekaette, who looks after the customer, writes this runbook with Sani; the head of payments approves it.
Scope: payouts to other banks through the switch. Decision needed: approve this table so the team stops resending by hand.
Recognise it. A payout is stuck when it sits in sending and the worker has had no final answer from the switch, for example a ₦15,000 payout (1,500,000 kobo) whose call timed out. A timeout means unknown, not failed.
Requery. Use the payout’s own reference. Ask straight away, then every 2 minutes for up to 30 minutes. These waits are the team’s assumption, to be replaced by the provider’s documented wait.
| Answer | Action |
|---|---|
09 pending |
Wait, ask again |
00 successful |
Complete: mark the payout paid |
| Failed | Close: the attempt is over; a new attempt, with a new reference, is a decision for the head of payments |
| Successful, then reversed | Treat as a returned payout and escalate |
25 Unable to locate record |
Resend with the same reference |
Still 09 after 30 minutes, or any other answer |
Escalate |
A 26 Duplicate record on a resend only says the earlier request exists. Requery to learn whether it was paid.
Never. Resend under a new reference while the answer is unknown. In the lab the naive client did this: 2 successful transfers, 3,000,000 kobo, for a ₦15,000 payout.
Tell the customer. While waiting: ‘Your payout is being confirmed. We will not send it again until we know the outcome.’
Could be wrong. The 30 minutes is an assumption; a payout still 09 at 31 minutes that later completes would show it. This runbook also cannot see payouts the worker never recorded as sending.
Now you
You work in operations at an unnamed lender that sends ₦15,000 loan disbursements to accounts at other banks through Ferrowave’s API. Twice this week a disbursement timed out and the team argued about whether to send it again. Write the lender’s stuck-payout runbook. Use the lab’s step 3 output for your answers: 26 Duplicate record on a resent reference, 09 pending straight after the timeout, 00 successful later, and 25 Unable to locate record for a reference never seen. Use 1,500,000 kobo for each disbursement. Choose your own waits and mark them as assumptions. Your head of payments reads it and approves it, and it supports one decision: whether the team may stop resending by hand and follow the table. An operations lead writes it with an engineer, and the head of payments signs it.
Self-check
Ferrowave's worker sends a ₦15,000 salary payout to another bank through a switch. The call times out after 10 seconds. The payout record says sending. Sani can change what the worker does next. Pay-day is today and 4,000 more payouts are queued behind it. What should the worker do?
- POST Designing robust and predictable APIs with idempotency Brandur Leach, 2017
Stripe's own post on idempotency keys, by the engineer who also wrote the Postgres version below. Read it for why retries are unavoidable and how a client chooses and reuses a key. It is one vendor's design, so check the details against the provider you use.
- POST Implementing Stripe-like Idempotency Keys in Postgres Brandur Leach, 2017
A worked implementation on PostgreSQL's transactions, with a dedicated key table, for the reserve-then-transact design in this chapter. Read the schema and how it uses transactions; skip the Ruby details. Search results gave only its opening in this build, so read the post itself before relying on a claim about it.
- DOC The Idempotency-Key HTTP Header Field (IETF Internet-Draft) Jena and Dalal, IETF HTTP API working group, 2025
The proposed standard header, including its 400, 409 and 422 answers. Read the sections on client and server behaviour. It is a draft whose listed expiry has passed, so check its status on the page before citing it.
- POST Avoiding Double Payments in a Distributed Payments System Jon Chew, Airbnb Engineering, 2019
How a large marketplace built an idempotency framework for its payments services, and the trade-offs of the approach. Search results gave only a summary in this build, and secondary write-ups add details the post may not contain, so read the original.
- PAPER Life beyond distributed transactions: an apostate's opinion Pat Helland, 2007
The case for idempotent messages between independent entities instead of global transactions, in the shorter ACM Queue version of the 2007 CIDR paper. Read the sections on entities, messages and idempotence; it is a position paper from 2007, so it does not speak of payment APIs. This build read only search excerpts. Read: Sections on entities, messaging and idempotence.
- DOC Idempotent requests (Stripe API reference) Stripe, 2026
A vendor's statement of key length, lifetime and what is saved. Read it to see one concrete contract, then read your own provider's. It is Stripe's own claim about its API and says nothing about Nigerian providers.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.