In Part 1, a conditional UPDATE stopped a retried request from crediting a wallet twice. In Part 2, a UNIQUE constraint stopped a journal from being posted twice, and another conditional UPDATE stopped two withdrawals from spending the same money. In all three cases the database did the hard part, not the application.
This part looks at those tools directly. Chapter 6 covers idempotency, which means making a repeated operation harmless and choosing the key that tells you it's a repeat.
Chapter 7 covers concurrency: two operations touching the same data at the same moment, and how locks and compare-and-swap keep them apart. Chapter 8 is about the Redis lock, which is usually the first thing people reach for, and why I wouldn't let it be the thing protecting your money.
Chapter 6
Idempotency: the most important property of payment processing
The problem: a webhook that arrives twice
Every payment integration runs into this in its first month. PayCo sends us a webhook: payment pay_81 succeeded. Our handler credits the customer's wallet and commits. Then it tries to send back 200 OK, and the connection drops. Maybe a load balancer restarted, or PayCo's side timed out a moment too early.
From PayCo's point of view, it never heard back. It has no way to know whether we processed the event and the reply got lost, or whether we never got the event at all. So it sends the event again later, which is the only reasonable thing it can do. Stripe, for example, keeps retrying for up to three days in live mode (Stripe: webhooks).
evt_31 was written in the same transaction as the credit, so the second delivery is harmless.If our handler credits the wallet every time it sees a success event, the second delivery credits it again. If it remembers that it has already handled evt_31, the second delivery does nothing and returns 200 OK. The second behaviour is called idempotency.
What idempotency means
An operation is idempotent if doing it twice has the same effect as doing it once. Pressing a lift's call button is idempotent: pressing it five times still calls one lift. “Set the status to SUCCESS” is idempotent. “Add €40 to the balance” is not, unless something remembers that this particular €40 was already added.
Most operations that move money are naturally not idempotent, so we make them idempotent by giving each one an identity (a key) and refusing to apply the same key twice.
Why “exactly once” delivery isn't on the menu
It's tempting to look for infrastructure that delivers each message exactly once, so the problem goes away. It doesn't exist, for the reason in the diagram above: when a reply is lost, the sender can't tell whether the work happened. It has two choices:
| Delivery style | What the sender does after an unclear failure | Result | For money |
|---|---|---|---|
| At most once | Gives up and doesn't resend | No duplicates, but some messages are lost | Lost payments. Not acceptable. |
| At least once | Resends until it gets an answer | Nothing lost, but some messages arrive twice | Acceptable, if the receiver is idempotent |
| Exactly once | Would need to know whether the lost reply meant success | Not achievable across a network on its own | Built from the row above, not bought |
Payment systems choose at-least-once delivery, because a lost “payment succeeded” message is far worse than a duplicate one. Then they make every consumer idempotent. The combination behaves like exactly-once processing, even though delivery isn't.
When a product says it offers exactly-once, read the details: SQS FIFO queues, for example, deduplicate messages sent again within a 5-minute interval (AWS: SQS FIFO exactly-once processing). That helps, but it doesn't stop your consumer from crashing after its database commit and receiving the message again.
Where duplicates come from
- HTTP retries. Mobile apps retry on timeouts, and so do HTTP client libraries, provider SDKs and sometimes load balancers. Each retry is a new request carrying the same intent.
- Webhook redelivery. Providers resend anything they didn't get a
2xxfor. - Queues. SQS standard queues guarantee at-least-once delivery, and AWS says plainly that “more than one copy of a message might be delivered” (AWS: SQS standard queues). SNS retries deliveries to subscribers that fail or time out (AWS: SNS delivery retries), and a subscriber that processed a message but answered too slowly will see it again.
- Your own outbox. A publisher that sends an event and crashes before marking it sent will send it again on restart. Part IV covers this.
- People. Double taps, two browser tabs, and an engineer replaying a dead-letter queue after an incident.
None of these are bugs; each layer is doing its job. So every handler that moves or records money must be idempotent, and that includes the ones where someone says “this one only gets called once”.
Choosing an idempotency key
Most of the design work is in choosing the key. A good key is the same for every retry of one operation, and different for two genuinely separate operations. There are four common kinds, and which one to use depends on who decided the operation should happen.
| Kind | Example | Who creates it | Use it when |
|---|---|---|---|
| Client-generated key | Idempotency-Key: 5f1c…e2 | The client, once per intended operation | A customer's app or a partner's system starts the operation over HTTP |
| Provider event ID | evt_31 | The provider | Handling webhooks or provider events. Use their stable ID, not a hash of the payload |
| Business-derived key | payout:wd_88 | Computed from existing data | The operation follows from something that already has an identity: “the payout for withdrawal wd_88” |
| Internal command ID | cmd_01J8… | The internal caller, stored before sending | An admin action or an internal service call that isn't tied to a single existing record |
Client keys have to be generated once per intent, not once per HTTP request. The app creates a UUID when the customer taps “Pay”, saves it, and sends that same UUID on every retry of the payment. An app that generates a new UUID inside its retry loop has a key that does nothing.
Provider event IDs identify the event, not the payment. One payment can produce several events (“processing”, then “succeeded”), and each of them is processed once; the state machine from Part 1 decides what each one does.
For internal work I prefer business keys, because they can't be lost. Any worker, after any crash, can recompute "payout:" + withdrawal_id, and the key becomes a UNIQUE constraint like the journal source key in Part 2. Command IDs are the opposite case: they have to be created and stored before the first attempt, since a command ID generated on each retry is just a random number.
Scope, payload and lifetime
The key alone isn't enough. You also have to decide what it is unique within, and what happens when it's reused.
- Scope by client. Two different partners might both send key
abc. Make the unique constraint(client_id, key), neverkeyalone. - Scope by operation. The same key on
POST /paymentsandPOST /refundsmeans two different things. Include the operation in the scope. - Check the payload. Store a hash of the request body with the key. If the same key arrives with a different body, that's a client bug, not a retry. Reject it. The IETF draft for the
Idempotency-Keyheader suggests422for this case, and409when a request with the same key is still being processed (IETF draft: Idempotency-Key header). It's still an Internet-Draft, not a finished standard, but it matches what large providers do: Stripe also compares parameters and returns an error if they differ, and uses409for a concurrent request with the same key (Stripe: idempotent requests, Stripe: errors). - Keep keys long enough. A key must outlive every retry of its operation. Stripe keeps keys for at least 24 hours (Stripe: idempotent requests). For webhook event IDs, keep them longer than the provider's retry window. For business keys that are also
UNIQUEconstraints on financial records, there's no expiry: they live as long as the records.
Making the barrier atomic
The most common idempotency bug is a check that isn't atomic:
# Naive version: do not use. Two concurrent deliveries can both pass the check.
if not already_processed(event_id):
apply(event)
mark_processed(event_id)Two deliveries arriving at the same moment both see “not processed”, and both apply. And if the process crashes between apply and mark_processed, the next delivery applies again. The check, the effect and the record must happen together, in one database transaction, with a unique constraint deciding who wins.
The INSERT … ON CONFLICT DO NOTHING statement is the tool for this. PostgreSQL guarantees an atomic outcome even under high concurrency: either the row is inserted, or the conflict is detected and nothing happens (PostgreSQL: INSERT).
If two transactions insert the same key at once, the second waits for the first to finish. If the first commits, the second sees the conflict. If the first rolls back, the second inserts and carries on.
For events: an inbox table
For webhooks and queue messages, record each processed event in an inbox table, in the same transaction as its effect:
CREATE TABLE processed_events (
consumer text NOT NULL, -- which handler processed it, e.g. 'wallet-credit'
event_id text NOT NULL, -- the provider's or publisher's stable event ID
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, event_id)
);// HandleOnce runs apply inside a transaction, at most once per (consumer, eventID).
// The inbox row and the business effect commit together: if apply fails, both roll back
// and the event can be retried; if they commit, every later delivery is a no-op.
func HandleOnce(ctx context.Context, pool *pgxpool.Pool, consumer, eventID string, apply func(pgx.Tx) error) (duplicate bool, err error) {
err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
tag, err := tx.Exec(ctx, `
INSERT INTO processed_events (consumer, event_id) VALUES ($1, $2)
ON CONFLICT DO NOTHING`, consumer, eventID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
duplicate = true // seen before: do nothing, report success to the sender
return nil
}
return apply(tx)
})
return duplicate, err
}The consumer column is there for events that feed several handlers: the wallet-credit handler and the email handler each process evt_31 once, independently of each other.
The inbox and the guards from earlier parts work together. The inbox stops the same event being processed twice. The conditional status update (Part 1) and the journal's unique source key (Part 2) stop the same payment being applied twice, even if it arrives as two different events, say a webhook and a status poll. I want both: the inbox is cheap and catches most duplicates early; the business guards are what protect the money.
For APIs: an idempotency key table
APIs are harder than events for two reasons. The client expects the same response on a retry, not just a no-op. And the client may retry while the first request is still running.
CREATE TABLE idempotency_keys (
client_id text NOT NULL,
operation text NOT NULL, -- e.g. 'POST /payments'
idem_key text NOT NULL CHECK (length(idem_key) BETWEEN 1 AND 255),
request_hash text NOT NULL, -- SHA-256 of the normalised request body
status text NOT NULL DEFAULT 'IN_PROGRESS'
CHECK (status IN ('IN_PROGRESS', 'COMPLETED')),
response_code integer,
response_body jsonb,
locked_until timestamptz NOT NULL, -- lets a crashed request's key be taken over
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL DEFAULT now() + interval '24 hours',
PRIMARY KEY (client_id, operation, idem_key)
);The request goes through three steps:
- Claim the key in a short transaction of its own, so that a concurrent retry can see it's taken. If the key is new, we own it. If it exists, we check the payload hash, then either replay the stored response, answer
409because it's still running, or take it over if the previous attempt crashed and its lock expired. - Do the work and record the response in one transaction, so a response is stored if and only if the work committed.
- On a transient failure, release the key, so the client's retry can run again instead of replaying an error.
In the code below, insert_payment, authenticated_client and enqueue_provider_call stand for small helpers you'd write yourself, and pool is a psycopg connection pool.
import hashlib, json
from dataclasses import dataclass
from fastapi import Depends, Header, HTTPException
from fastapi.responses import JSONResponse
@dataclass
class Replay:
code: int
body: dict
def request_hash(body: dict) -> str:
canonical = json.dumps(body, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode()).hexdigest()
def claim_key(conn, client_id, operation, key, body):
"""Returns None if this request owns the key, or a Replay of the stored response."""
h = request_hash(body)
owned = conn.execute(
"""
INSERT INTO idempotency_keys (client_id, operation, idem_key, request_hash, locked_until)
VALUES (%s, %s, %s, %s, now() + interval '30 seconds')
ON CONFLICT (client_id, operation, idem_key) DO NOTHING
RETURNING 1
""",
(client_id, operation, key, h),
).fetchone()
if owned:
return None
stored_hash, status, code, stored_body, locked = conn.execute(
"""
SELECT request_hash, status, response_code, response_body, locked_until > now()
FROM idempotency_keys
WHERE client_id = %s AND operation = %s AND idem_key = %s
FOR UPDATE
""",
(client_id, operation, key),
).fetchone()
if stored_hash != h:
raise HTTPException(422, "this Idempotency-Key was used with a different request")
if status == "COMPLETED":
return Replay(code, stored_body)
if locked:
raise HTTPException(409, "a request with this Idempotency-Key is still in progress")
# The previous attempt crashed and its lock expired: take the key over.
conn.execute(
"""
UPDATE idempotency_keys SET locked_until = now() + interval '30 seconds'
WHERE client_id = %s AND operation = %s AND idem_key = %s
""",
(client_id, operation, key),
)
return None
def complete_key(conn, client_id, operation, key, code, body):
conn.execute(
"""
UPDATE idempotency_keys
SET status = 'COMPLETED', response_code = %s, response_body = %s
WHERE client_id = %s AND operation = %s AND idem_key = %s
""",
(code, json.dumps(body), client_id, operation, key),
)
def release_key(conn, client_id, operation, key):
conn.execute(
"""
DELETE FROM idempotency_keys
WHERE client_id = %s AND operation = %s AND idem_key = %s AND status = 'IN_PROGRESS'
""",
(client_id, operation, key),
)
@app.post("/payments", status_code=201)
def create_payment(
req: CreatePayment,
client_id: str = Depends(authenticated_client),
idempotency_key: str = Header(..., alias="Idempotency-Key"),
):
op, body = "POST /payments", req.model_dump(mode="json")
with pool.connection() as conn:
with conn.transaction(): # step 1: claim, commit at once
replay = claim_key(conn, client_id, op, idempotency_key, body)
if replay:
return JSONResponse(replay.body, status_code=replay.code)
try:
with conn.transaction(): # step 2: work + response, atomically
payment = insert_payment(conn, client_id, idempotency_key, req)
response = {"id": payment.id, "status": payment.status}
complete_key(conn, client_id, op, idempotency_key, 201, response)
except PaymentRejected as e: # permanent: remember the answer
with conn.transaction():
complete_key(conn, client_id, op, idempotency_key, 422, {"error": str(e)})
return JSONResponse({"error": str(e)}, status_code=422)
except Exception: # transient: let the retry run again
with conn.transaction():
release_key(conn, client_id, op, idempotency_key)
raise
enqueue_provider_call(payment.id) # PayCo is called later, keyed by payment.id
return JSONResponse(response, status_code=201)The call to PayCo is not inside the transaction. We can't put an external call inside a database transaction (the database can't roll back PayCo). Instead, the API creates the payment record and returns; a worker calls PayCo afterwards, using the payment's own ID as PayCo's idempotency key. If the worker crashes and retries, PayCo sees the same key and returns the original result.
The same pattern applies to every external side effect: record your intent durably first, then perform the side effect with a key derived from that record.
Permanent and transient errors
What should a retry with the same key get back if the first attempt failed? It depends on the kind of failure:
- Permanent errors (validation failed, card declined, insufficient funds) will fail again the same way. Store the response and replay it. Retrying won't help, and returning the same answer is what the client expects.
- Transient errors (database timeout, deadlock, a dependency down) might succeed next time. Don't store them; release the key so the retry runs again.
Providers differ here. Stripe's v1 API saves the first response for a key even if it's a 500, and replays it (Stripe: idempotent requests). That's simpler for them, but it means a client must use a new key after a server error.
For your own APIs I prefer releasing the key on transient errors, because it lets clients follow one simple rule: retry with the same key until you get a definite answer.
Idempotency doesn't fix ordering
Deduplication stops the same message being applied twice. It does nothing about messages arriving in the wrong order. A “refund succeeded” event can arrive before “payment succeeded”, and both are new, valid events. Ordering is the state machine's job (Part 1): each event is checked against the current state, and moves that aren't allowed yet are either rejected for a later retry or parked.
Idempotency across service boundaries
A payment usually passes through several services. Each hop needs its own idempotency, and the keys must connect, so that a retry at the top becomes a retry at every layer below rather than a new operation.
pay_81:1 is computed, not generated, a worker that crashes and retries sends PayCo the exact same key and gets the original result back.So derive downstream keys from upstream identities, and never generate a random key inside a retry path. The worker uses pay_81:1 (payment plus attempt number) because both parts are stored. If it used a fresh UUID on each try, PayCo would treat every retry as a new payment.
Common mistakes
- Generating the idempotency key inside the retry loop instead of once per intent.
- Check-then-act deduplication outside a transaction.
- Recording the event as processed in a different transaction from its effect.
- Keys scoped globally instead of per client and per operation.
- Ignoring the payload, so a buggy client's reused key silently returns the wrong payment.
- Caching transient errors, so a client's retry can never succeed.
- Making an external call inside a database transaction and assuming the rollback undoes it.
- Expiring event IDs before the sender has stopped retrying.
What to monitor and test
Monitor: the duplicate rate per consumer and per API operation (a baseline is normal; spikes mean an upstream retry storm); 409 and 422 rates on idempotent endpoints; keys stuck IN_PROGRESS past their lock; and the size and age of the inbox and key tables against your retention policy.
Test: deliver the same event 10 times, sequentially and concurrently, and expect one effect. Send the same API request twice in parallel and expect one 201 and one 409 (or two identical 201s if you choose to wait instead). Reuse a key with a different body and expect 422.
Then test the failure paths. Kill the process between the claim and the work and check that a retry after the lock expires succeeds. Inject a transient database error and check that the retry runs the work rather than replaying the error.
Checklist
- Every handler that moves or records money is idempotent.
- Each operation's key comes from whoever decided the operation, and is reused on every retry.
- Keys are scoped per client and per operation, and checked against a payload hash.
- Deduplication, effect and record commit in one transaction behind a unique constraint.
- External calls happen outside transactions, with keys derived from stored records.
- Permanent errors are replayed; transient errors release the key.
- Keys are kept longer than the longest retry window that can carry them.
Chapter 7
Database locks, compare-and-swap and concurrency control
Idempotency handles the same operation arriving twice. Concurrency control handles different operations touching the same data at the same moment: two admins acting on one payment, a withdrawal racing a fee charge on one wallet. Get it wrong and you get bugs that never show up in tests and appear in production once a week.
Race conditions and the lost update
A race condition is a bug where the result depends on the exact timing of two operations. The classic one in business software is the lost update: two people read the same value, each computes a new value from what they read, and the second write silently erases the first.
Nothing crashed, and both requests succeeded, which is why these bugs are so expensive: nobody knows they happened until someone reconciles. You saw the money version of this in Part 2's double-spend race.
What the database promises: isolation levels
Databases describe how much one transaction can see of another's work with isolation levels. The textbook problems they guard against are:
- Dirty read: seeing another transaction's changes before it commits (and maybe before it rolls them back).
- Non-repeatable read: reading the same row twice in one transaction and getting different values, because someone committed in between.
- Phantom read: running the same query twice and getting a different set of rows.
- Serialization anomaly: a result that couldn't have happened if the transactions had run one at a time, in any order.
| Level in PostgreSQL | Dirty reads | Non-repeatable reads | Phantoms | Serialization anomalies |
|---|---|---|---|---|
| Read Committed (default) | No | Possible | Possible | Possible |
| Repeatable Read | No | No | No (in PostgreSQL) | Possible |
| Serializable | No | No | No | No |
This table is PostgreSQL-specific; other databases differ. PostgreSQL never allows dirty reads: its Read Uncommitted mode behaves like Read Committed, which is also the default level (PostgreSQL: transaction isolation). At Repeatable Read and Serializable, PostgreSQL can abort a transaction with a serialization failure, and applications “must be prepared to retry” (same page). Those failures always use SQLSTATE 40001.
The uncomfortable part is that the default level does not prevent lost updates if your code reads a value, computes in application code, and writes it back. You have to pick a technique deliberately. There are four, and you've met three of them already.
Technique 1: let the database do the arithmetic
The simplest fix for many lost updates is to not read the value at all. Instead of computing 1000 + 500 in the application, ask the database to add:
-- Lost-update prone: the new value was computed from a read that may be stale
UPDATE account_limits SET daily_limit_minor = 150000 WHERE account_id = 'acc_42';
-- Safe: the database applies the change to whatever the current value is
UPDATE account_limits SET daily_limit_minor = daily_limit_minor + 50000 WHERE account_id = 'acc_42';Combined with a condition, this is the conditional update you've already used: SET balance = balance - 80 WHERE balance >= 80. It works whenever the whole decision fits in one statement.
Technique 2: compare-and-swap
When the decision is “change this, but only if it's still what I think it is”, put what you think it is in the WHERE clause. This is compare-and-swap (CAS): compare the current value with the expected one, and swap in the new value only if they match. Part 1's state transitions are CAS on the status column:
UPDATE payments
SET status = 'REVERSED', updated_at = now()
WHERE id = 'pay_81'
AND status = 'SUCCESS'; -- the "compare": 1 row means we won, 0 means it changedTechnique 3: optimistic concurrency with a version column
Sometimes the thing you're checking isn't one column but a whole row a user edited, maybe over several minutes in an admin screen. Add a version number that every write increments. Read the row with its version, let the user work, then write back only if the version hasn't moved:
var ErrConflict = errors.New("row changed since it was read")
// UpdateLimit sets an account's daily limit, but only if nobody changed the row
// since we read it at readVersion. On ErrConflict, re-read and let the user decide.
func UpdateLimit(ctx context.Context, pool *pgxpool.Pool, accountID string, newLimitMinor, readVersion int64) error {
tag, err := pool.Exec(ctx, `
UPDATE account_limits
SET daily_limit_minor = $2, version = version + 1, updated_at = now()
WHERE account_id = $1 AND version = $3`,
accountID, newLimitMinor, readVersion)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrConflict
}
return nil
}It's called optimistic because it assumes conflicts are rare: nothing is locked while the user thinks, and the rare loser gets a clear “someone else changed this, please review” instead of silently overwriting.
Technique 4: lock the row first
Sometimes several checks and writes must happen as one, based on a row's current state. Then you lock the row before reading it, with SELECT … FOR UPDATE. Any other transaction that tries to lock or update the same row waits until you commit or roll back. This is pessimistic locking: assume there will be a conflict, and queue everyone up.
Two variations are worth knowing (PostgreSQL: the locking clause):
NOWAIT: report an error immediately instead of waiting if the row is locked. Useful for interactive actions where “someone else is working on this, try again” is a better answer than a spinner.SKIP LOCKED: skip rows that are locked and return the rest. This is how many workers can pull jobs from the same table without stepping on each other. Part IV uses it for the outbox.
Worked example: two admins cancel the same payment
A realistic case where several steps have to be atomic: a customer complains about a payment. Two support agents open it at the same time, and both click “Cancel payment”. The payment is in SUCCESS, so cancelling means reversing it: a compensating ledger journal (Part 2) and a move to REVERSED (Part 1). We must end up with exactly one reversal.
The steps are:
- Lock the payment row.
- Check that its current state can be cancelled.
- Post the compensating ledger journal and update the balances.
- Move the payment to
REVERSED. - Commit everything together.
var ErrNotCancellable = errors.New("payment cannot be cancelled in its current state")
// CancelPayment reverses a successful payment: one compensating journal, one status
// change, one commit. Two admins calling it at once get one reversal between them.
func CancelPayment(ctx context.Context, pool *pgxpool.Pool, paymentID, adminID, reason string) error {
return pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
// Don't queue forever behind a stuck transaction.
if _, err := tx.Exec(ctx, `SET LOCAL lock_timeout = '3s'`); err != nil {
return err
}
// 1. Lock the payment row. A second caller waits here until we commit.
var status Status
var journalID string
err := tx.QueryRow(ctx, `
SELECT p.status, j.id
FROM payments p
JOIN ledger_journals j
ON j.source_type = 'transaction' AND j.source_id = p.id AND j.kind = 'PAYMENT'
WHERE p.id = $1
FOR UPDATE OF p`, paymentID).Scan(&status, &journalID)
if err != nil {
return err
}
// 2. Validate the current state. After waiting, the second caller sees REVERSED.
if status == Reversed {
return nil // already done by someone else: report success, change nothing
}
if !CanTransition(status, Reversed) {
return fmt.Errorf("%w: %s", ErrNotCancellable, status)
}
// 3. Compensating journal (Part 2) and its balance changes (Chapter 5).
reversalID := "rev_" + journalID
if err := ReverseJournal(ctx, tx, journalID, reversalID, reason, adminID); err != nil {
return err
}
if err := applyJournalToBalances(ctx, tx, reversalID); err != nil {
return err // e.g. the customer already spent the money: nothing is committed
}
// 4. The status change (Part 1), with its history row.
return Transition(ctx, tx, paymentID, status, Reversed, "admin_cancel:"+adminID)
}) // 5. BeginFunc commits if we returned nil, and rolls back otherwise.
}
// applyJournalToBalances updates the balance projection for every entry in a journal.
func applyJournalToBalances(ctx context.Context, tx pgx.Tx, journalID string) error {
rows, err := tx.Query(ctx,
`SELECT account_id, asset, amount::text FROM ledger_entries WHERE journal_id = $1`, journalID)
if err != nil {
return err
}
entries, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (Entry, error) {
var e Entry
var amount string
if err := row.Scan(&e.AccountID, &e.Asset, &amount); err != nil {
return e, err
}
var err error
e.Amount, err = decimal.NewFromString(amount)
return e, err
})
if err != nil {
return err
}
return applyToBalances(ctx, tx, entries)
}This one function leans on the transaction for three things. The row lock serialises the two admins, so the second one doesn't race the first; it runs after it. The state check (status == Reversed) makes that second call a successful no-op, and underneath it, ReverseJournal's unique source key would refuse a second reversal even if some other code path skipped the lock.
Then there's atomicity. The journal, the balance changes, the status change and the history row all commit together, so if the customer has already spent the money and the balance update fails, nothing is left half-done.
There's no call to PayCo in this transaction either. If cancelling should also refund the customer's card, that's a separate refund operation with its own idempotency key and lifecycle, started after this commit. Holding a row lock while waiting on a provider would make every other operation on this payment wait on PayCo too.
Choosing between optimistic and pessimistic
| Situation | Prefer | Why |
|---|---|---|
| The whole decision fits in one statement | Conditional / relative UPDATE | Shortest possible lock, no extra round trips |
| Several reads and writes must see one consistent row state | SELECT … FOR UPDATE | Simple to reason about; losers wait instead of failing |
| Many requests fight over the same row | Pessimistic lock (or redesign the hot row) | Optimistic retries would mostly fail and waste work |
| A person edits a record over minutes | Optimistic, with a version column | You can't hold a database lock while someone has lunch |
| Conflicts are rare and retries are cheap | Optimistic | No waiting in the common case |
| Complex rules across many rows | Serializable isolation + retry on 40001 | The database detects the conflict for you; you must retry |
Whatever you choose, keep the locked section short. A lock held during a slow query, a network call or a big computation turns into a queue that every related request waits in. Part V is about keeping transactions short.
Serializable transactions need a retry loop
If you use Serializable (or Repeatable Read), PostgreSQL may abort a transaction with SQLSTATE 40001 because it conflicted with another. That's not an error in your logic; it's the database asking you to try again. Wrap such transactions in a small, bounded retry loop:
// withSerializableRetry runs fn in a SERIALIZABLE transaction, retrying a few times
// when PostgreSQL reports a serialization failure (SQLSTATE 40001).
// fn must be safe to run more than once: no external calls inside it.
func withSerializableRetry(ctx context.Context, pool *pgxpool.Pool, fn func(pgx.Tx) error) error {
const maxAttempts = 5
for attempt := 1; ; attempt++ {
err := pgx.BeginTxFunc(ctx, pool, pgx.TxOptions{IsoLevel: pgx.Serializable}, fn)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "40001" && attempt < maxAttempts {
continue // Part VI adds backoff with jitter between attempts
}
return err
}
}Unique constraints are concurrency tools too
It's easy to think of UNIQUE as a data-quality rule. In a payment system it's also one of the best concurrency tools you have. When two transactions race to insert the same key, the database lets exactly one of them win, with no locks in your code at all.
Every idempotency mechanism in this part is a unique constraint underneath: the inbox's (consumer, event_id), the API's (client_id, operation, idem_key), the journal's (source_type, source_id, kind). If you can phrase a rule as “there can only be one of these”, make it a unique constraint and let the database settle every race.
Deadlocks
A deadlock happens when transaction 1 holds row A and waits for row B, while transaction 2 holds row B and waits for row A. Neither can continue. PostgreSQL detects this and aborts one of them, which your code then sees as an error it should retry.
The way to avoid most deadlocks is the one we used for balances in Part 2: always lock rows in the same order, for example sorted by ID. Use lock_timeout, as in the cancellation example, so a transaction stuck behind a slow one fails fast instead of piling up.
Checklist
- No value is computed in application code from a read and written back without a guard.
- Single-statement rules use conditional or relative updates.
- Multi-step decisions lock the row first, or use a version check.
- No external calls happen while holding a row lock.
- Locks are always taken in a consistent order.
lock_timeoutis set for interactive and admin paths.- Serializable or Repeatable Read transactions retry on SQLSTATE 40001, with a limit.
- “There can only be one” rules are unique constraints.
Chapter 8
Why Redis is not always the answer for distributed locking
When a team first meets a concurrency bug in a distributed system, someone usually suggests a Redis lock. It's fast and easy to add, and it works most of the time. This chapter is about the rest of the time: what goes wrong then, and whether it matters when the thing being protected is money.
How a Redis lock works
The standard single-instance pattern is one command (Redis: distributed locks):
SET lock:payout:wd_88 7f3a9c… NX PX 30000NX means “only set it if it doesn't exist”, so only one client can get it. PX 30000 makes the key expire after 30 seconds, so a client that crashes while holding the lock doesn't block everyone forever. That expiry turns the lock into a lease: you hold it for a limited time, not until you let go.
The value is a random token unique to this holder. When releasing, you must delete the key only if it still holds your token, because by then your lease may have expired and someone else may hold the lock.
A plain DEL is unsafe, since “a client may remove another client's lock” (Redis: distributed locks). The check and the delete must be atomic, which is done with a small Lua script (newer Redis versions also offer a single compare-and-delete command):
// releaseScript deletes the lock only if it still holds our token.
var releaseScript = redis.NewScript(`
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
end
return 0`)
// TryLock takes a lease on key for ttl. The returned token proves ownership on release.
func TryLock(ctx context.Context, rdb *redis.Client, key string, ttl time.Duration) (token string, ok bool, err error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", false, err
}
token = hex.EncodeToString(b)
ok, err = rdb.SetNX(ctx, key, token, ttl).Result()
return token, ok, err
}
// Unlock releases the lease if, and only if, we still own it.
func Unlock(ctx context.Context, rdb *redis.Client, key, token string) error {
return releaseScript.Run(ctx, rdb, []string{key}, token).Err()
}This uses the go-redis client (go-redis v9). So far, so good. The problems start when the holder is slower than its lease.
How a lease fails: the paused holder
A lease assumes the holder finishes its work before the lease runs out. Nothing guarantees that. The process can pause for a long garbage-collection cycle, the container can be starved of CPU, a database query can hang, or the network between the worker and its database can stall.
Martin Kleppmann's well-known analysis describes this case: a client that “is paused for an extended period of time while holding the lock” (Kleppmann: How to do distributed locking).
While worker A is paused, its lease expires. Worker B acquires the lock legitimately and starts its work. Then A wakes up, has no idea time has passed, and carries on writing. For a few seconds, two workers both believe they hold the lock. If the protected work was “send the payout for wd_88”, you just sent it twice.
Other failure modes lead to the same place:
- Failover. Redis replication is asynchronous. If the primary fails after granting a lock but before replicating it, the new primary has never heard of the lock and grants it again.
- Network partitions. A worker cut off from Redis can't renew its lease or learn it has lost it.
- Lease too short. Choose 30 seconds for work that usually takes 2, and one day a slow dependency makes it take 31.
Extending the lease from a background goroutine (a heartbeat) helps with slow work, but not with a paused process: a paused process can't send heartbeats, and it can't check whether its lease is still valid before each write.
Fencing tokens: moving the check to where the write happens
The fix Kleppmann describes is a fencing token: “a number that increases … every time a client acquires the lock” (Kleppmann). Each write carries the holder's token, and the storage refuses any write with a lower token than the highest it has already seen.
In PostgreSQL that's a compare-and-swap on a token column:
-- The batch remembers the highest token that has written to it.
UPDATE payout_batches
SET status = 'SUBMITTED', fence_token = $2, updated_at = now()
WHERE id = $1
AND fence_token < $2; -- 0 rows: a newer lock holder already got hereBut the thing preventing the duplicate here is the conditional UPDATE in the database. The lock decided who should do the work; the database decided whose work counted.
Kleppmann also points out that Redlock, Redis's multi-node algorithm, doesn't generate fencing tokens at all (Kleppmann). Redis's own documentation now tells you to implement fencing tokens alongside it (Redis: distributed locks). The Redlock design has been debated publicly; Redis's page links both Kleppmann's analysis and the author's reply, and both are worth reading.
Coordination versus correctness
The distinction I find most useful here is between coordination and correctness. Coordination is about efficiency: stopping two workers from doing the same work at the same time, so you don't waste effort or hammer a provider. When it fails now and then, some work gets done twice and it costs a little. Correctness is about invariants, such as money moving once and balances never going negative, and when it fails you lose money.
A Redis lock is a good coordination tool and a poor correctness tool, so use it for coordination and make sure correctness never depends on it. If the Redis lock fails, the database must still refuse the second money movement. A lock failure should cost you wasted work at worst, never a double payout.
A reasonable use: a nightly reconciliation job runs on several instances for availability, and a Redis lock stops them all running at once.
// RunNightlyReconciliation uses a Redis lease so only one instance does the work.
// reconcileDay is idempotent (Chapter 20), so if the lease ever fails and two
// instances run, the cost is wasted effort, not wrong data.
func RunNightlyReconciliation(ctx context.Context, rdb *redis.Client, day string) error {
key := "lock:reconcile:payco:" + day
token, ok, err := TryLock(ctx, rdb, key, 15*time.Minute)
if err != nil || !ok {
return err // nil error and !ok: another instance is on it
}
defer Unlock(context.Background(), rdb, key, token)
return reconcileDay(ctx, day)
}Also consider the operational dependency you add. If the money path needs a Redis lock to proceed, a Redis outage stops payments, even though PostgreSQL, which holds the real guarantees, is perfectly healthy. Decide in advance whether each lock fails open (proceed without it, relying on the database) or fails closed (stop). For coordination locks, failing open is usually right.
Comparing the options
| Mechanism | Protects correctness? | Survives a paused process? | Cost | Good for |
|---|---|---|---|---|
Database row lock (FOR UPDATE) | Yes, within the transaction | Yes: the lock lives with the transaction | Holds a connection while locked | Multi-step changes to one record |
| Unique constraint | Yes | Yes | An index | “Only one of these may ever exist” |
| Optimistic version / CAS | Yes | Yes: the stale write matches 0 rows | Retries on conflict | Low-contention updates, user edits |
| Redis lease lock | No, not on its own | No | An extra dependency | Avoiding duplicate work; coordination |
| Queue-based serialisation | Ordering only; still needs idempotency | Mostly: redelivery is possible | Throughput per key is limited | Processing one account's events in order |
On the last row: you can avoid many races by making sure all operations for one account are processed by one consumer at a time, for example with SQS FIFO message groups (AWS: SQS FIFO) or a Kafka partition key. That reduces contention a lot. But messages can still be redelivered, so the consumer still needs idempotency, and the database still needs its constraints. Part IV goes deeper.
When is a Redis lock the right tool?
| Situation | Redis lock? | What actually protects you |
|---|---|---|
| Stop a wallet being credited twice for one payment | No | Conditional status update + unique journal source (Parts 1–2) |
| Stop two withdrawals spending the same funds | No | Conditional update on the balance (Part 2) |
| One payout per withdrawal | Optional, to save effort | Unique business key + provider idempotency key |
| Only one instance runs a nightly job | Yes | The job is idempotent anyway |
| Avoid ten workers polling PayCo for the same status | Yes | Status updates are CAS-guarded anyway |
| Rate-limit calls to a provider per merchant | A Redis counter, not a lock | Provider quotas; Part VI covers rate limits |
Common mistakes
- Using a Redis lock as the only thing stopping a double payout.
- Releasing the lock with a plain
DEL, deleting someone else's lease. - No expiry on the lock, so a crashed worker blocks everything forever.
- Choosing a lease time from the average duration instead of the worst case.
- Assuming Redlock or replication makes the lock safe for correctness.
- Making payments depend on Redis being up, when the database holds all the real guarantees.
What to monitor and test
Monitor: lock acquisition failures and wait times; how often work runs longer than its lease (log the duration against the TTL); fencing-token rejections, each of which is a near miss worth reading about; and what happens to your payment paths when Redis is unreachable.
Test: make a lock holder sleep past its TTL, let a second worker acquire, then wake the first and check that the database refuses its write. Kill Redis during a run and confirm money still moves at most once. Run the reconciliation job on two instances with the lock disabled and confirm the results are identical.
Checklist
- Every lock has passed the “delete it in your head” test.
- Locks are released by token, atomically, never with a plain DEL.
- Every lock has an expiry chosen from the worst case, not the average.
- Writes that a lock protects also carry a fencing token, or a CAS condition, checked by the database.
- Each lock has a decided behaviour when Redis is down.
Further reading
- PostgreSQL: INSERT … ON CONFLICT: atomic insert-or-nothing.
- PostgreSQL: transaction isolation: levels, anomalies and serialization failures.
- PostgreSQL: the locking clause:
FOR UPDATE,NOWAITandSKIP LOCKED. - Stripe: idempotent requests: a large provider's idempotency rules.
- IETF draft: the Idempotency-Key HTTP header: a proposed standard for the header.
- AWS: SQS standard queues and FIFO deduplication: delivery guarantees.
- Redis: distributed locks: the single-instance pattern and Redlock.
- Martin Kleppmann: How to do distributed locking: leases, pauses and fencing tokens.
What's next
We can now make any single operation safe to repeat and safe to run concurrently. Next, we connect operations together. Part IV, Event-Driven Payment Architecture, builds the pipeline from webhook to queue to worker on SNS and SQS: what a visibility timeout really guarantees (less than you'd hope), and how the transactional outbox and inbox patterns make sure a committed payment is always announced, exactly as often as it needs to be.
If this was useful
Pass it on to someone who's building or fixing a payment system, or share it with your network. The handbook is free, and people passing it on is how it reaches the engineers it was written for.