Tobi backend & web

Booking work from 12 January Gbagada, Lagos UTC+1 Now: a rate limiter for a delivery API

14 min readPostgres · Go · Payments

Idempotency keys in Postgres, without the double charges

One table, one unique index and a rule about what to store. How I stopped a retrying app from charging a customer twice.

The bug that started it#

A customer of a salon I build for paid a ₦15,000 deposit on a Friday evening and was charged twice. Nothing was wrong with the card or the payment provider. The app had sent the same request two times, and our API had done exactly what it was told, twice.

The phone was on a weak signal in traffic on the Third Mainland Bridge. The first request reached us and succeeded, but the response never made it back. The app waited ten seconds, decided the request had failed, and sent it again.1 From the server’s side these were two separate, perfectly valid deposits.

Retries are correct behaviour on a bad network. The fix isn’t to stop retrying; it’s to make a retry safe. That is what an idempotency key is for.

What a key promises#

The client makes up a random key for each intent (“pay this deposit”), and sends the same key with every attempt at that intent. The server promises one thing in return:

However many times a request with this key arrives, the work happens once, and every attempt gets the same answer.

That second half matters as much as the first. If the retry gets a different response (an error saying “duplicate”, say), the app has to understand a new case, and most apps won’t. The retry should look exactly like the first attempt succeeding.

Sequence: the app sends a deposit request with key k_7f3a; the API claims the key in Postgres and charges the card, but the response is lost. The app retries with the same key; the API finds the stored response and returns it without charging again. app api postgres POST /deposits · key k_7f3a INSERT key (claimed) charge card 201 · lost in traffic × retry · same key k_7f3a key exists → stored response 201 · same body, no second charge
Fig. 1 — one intent, two attempts, one chargek_7f3a is an example key

One table does the work#

You can do this with Redis, and plenty of people do. I use Postgres for one reason: the key and the work it protects can be written in the same transaction, so there’s no moment where one exists without the other.

migrations/0042_idempotency_keys.sql
create table idempotency_keys (
  key           text        not null,
  account_id    bigint      not null,
  request_hash  bytea       not null,
  status        text        not null default 'claimed',
  response_code int,
  response_body jsonb,
  created_at    timestamptz not null default now(),
  primary key (account_id, key)
);

-- the clean-up job walks this index, oldest first
create index idempotency_keys_created_at
  on idempotency_keys (created_at);

Three choices in there are worth explaining:

  • The key is scoped to the account. Two customers who happen to generate the same key shouldn’t see each other’s responses. The primary key is (account_id, key), not key.
  • We store a hash of the request. If a retry arrives with the same key but a different amount, that’s a bug in the client, and we refuse it rather than replaying a response for a different request.2
  • We store the response, not just a flag. Without the body we could say “already done”, but not answer the way the first attempt did.

Claiming a key#

The handler’s first move is to insert the key. The unique index decides who wins: if two attempts race, exactly one insert succeeds, and the other learns the key is taken.

internal/deposits/handler.go
func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
	key := r.Header.Get("Idempotency-Key")
	if key == "" {
		writeError(w, 400, "missing Idempotency-Key header")
		return
	}
	body, hash := readAndHash(r)

	claim, err := h.keys.Claim(r.Context(), accountID(r), key, hash)
	switch {
	case errors.Is(err, idem.ErrMismatch):
		writeError(w, 422, "key reused with a different request")
		return
	case errors.Is(err, idem.ErrInFlight):
		// the first attempt is still running: ask the client to wait
		w.Header().Set("Retry-After", "2")
		writeError(w, 409, "request in progress")
		return
	case claim.Done:
		replay(w, claim.Code, claim.Body) // same answer as the first time
		return
	}

	res, err := h.deposits.Charge(r.Context(), body)
	h.keys.Finish(r.Context(), claim, res.Code, res.Body)
	replay(w, res.Code, res.Body)
}

The ErrInFlight case is the one people forget. If the retry arrives while the first attempt is still talking to the card network, there’s no response to replay yet. Answering 409 with a Retry-After is honest, and the app’s existing retry loop handles it without a single new line of code.

Replaying, not re-running#

Here is what it looks like from the outside. Same key, two calls, one deposit:

terminal
$ curl -s -X POST api.example.com/v1/deposits \
    -H 'Idempotency-Key: k_7f3a' -d amount_ngn=15000
{"id":"dep_2201","amount_ngn":15000,"status":"paid"}

$ curl -s -X POST api.example.com/v1/deposits \
    -H 'Idempotency-Key: k_7f3a' -d amount_ngn=15000
{"id":"dep_2201","amount_ngn":15000,"status":"paid"}   # replayed

Same id, same body. The only difference is a header we add, Idempotent-Replayed: true, which the app ignores and our logs don’t.3

Expiry and clean-up#

Keys can’t live for ever, and they don’t need to: a retry that arrives a day later isn’t a retry, it’s a new decision. I keep them for 24 hours and delete in small batches, so the clean-up never holds a lock long enough to be noticed.

jobs/expire_keys.sql
delete from idempotency_keys
where ctid in (
  select ctid from idempotency_keys
  where created_at < now() - interval '24 hours'
  order by created_at
  limit 1000
);

A claimed key that never finished (the process crashed mid-charge) is the awkward case. After five minutes the job marks it abandoned and a person looks at the payment provider’s record before anything is retried. That happens about once a month, and I’d rather a human spends two minutes on it than guess.4

What I’d do differently#

I’d add keys on day one, to every endpoint that moves money or sends a message, instead of after the first double charge. The table is twenty lines; the conversation with a customer who was charged twice is much longer.

I packaged the Go side as pg-idem so I stop rewriting it. It’s small on purpose: claim, finish, replay, expire. If you use it and something’s unclear, email me and I’ll fix the docs.

Notes

  1. Ten seconds is the default timeout in the HTTP client the app used. Most clients have one; few apps change it. ↩
  2. The hash covers the method, the path and the body after sorting its keys, so a re-ordered JSON object still matches. ↩
  3. Counting replays per day is a cheap way to see how bad the network is for your users. On this app it is about one request in forty. ↩
  4. The figures in this post are from one client’s app and are here as an example; yours will differ. ↩