Skip to content

Lesson 6 of 9 · 26m

Idempotency, Retries, and Consistency: The Rules Nobody Can Skip

Make repeated delivery safe, define ownership of consistency invariants, and design recovery paths before the first outage.

Distributed systems do not fail by sending a message once and losing it. They fail by sending it zero, one, two, or seventeen times while timeout behavior differs by library. If retries exist, duplicates exist. The architecture either makes repetition safe or turns every transient blip into corrupted business state.

Idempotency is a semantic property

An idempotent operation can be repeated with the same intent without changing the outcome beyond the first successful application. Unique request IDs alone do not create idempotency; they merely give you a way to implement it.

CREATE TABLE processed_events (
    consumer_name text NOT NULL,
    event_id text NOT NULL,
    processed_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer_name, event_id)
);

The check and the business write must share a transaction where possible:

BEGIN;
INSERT INTO processed_events (consumer_name, event_id)
VALUES ('provisioning', 'evt_01JAH7ZK3J')
ON CONFLICT DO NOTHING;

-- If no row was inserted, rollback or skip the effect.
INSERT INTO provisioned_workspaces (workspace_id, organization_id, status)
VALUES ('wsp_448', 'org_388', 'pending');
COMMIT;

Do not log-and-continue when insertion reports a duplicate. You need to know whether the original effect completed or crashed halfway.

Distinguish safe retry from dangerous retry

Retry a timeout differently from a definitive rejection. A 409 Conflict often means the state already exists. A 422 means repeating the same payload is pointless. Network timeouts are ambiguous because the server may have succeeded.

for attempt in range(5):
    try:
        response = client.post(
            "/transfers",
            json=payload,
            headers={"Idempotency-Key": idempotency_key},
            timeout=3.0,
        )
    except Timeout:
        delay = min(2 ** attempt + jitter(), 30)
        sleep(delay)
        continue
    if response.status_code in (200, 201, 409):
        return response
    if response.status_code == 422:
        raise PermanentRejection(response.json())

Use the same idempotency key across retries. Do not generate a fresh one per attempt; that converts one user action into many business operations.

Consistency boundaries need owners

Some invariants must be strongly consistent: inventory cannot go negative, a payment cannot be captured twice, a seat count cannot exceed a license. Put those inside one transactional boundary or use explicit reservation state machines. Other facts can converge: search indexes, dashboards, analytics, notification preferences.

A useful architecture document marks each invariant:

Invariant                                Boundary                    Repair path
invoice total equals line sum            invoice aggregate           reject write
workspace exists after checkout          checkout -> provisioning    retry/reconcile job
ledger is append-only and balanced       ledger transaction          reject write
admin member count matches directory     eventual projection         rebuild projection

If nobody can say where an invariant is enforced, it is enforced nowhere.

Plan reconciliation, not perfection

Outages leave drift even when retries are correct. Build reconcilers that compare authoritative state and derived or external state. Keep them boring, rate-limited, and observable.

nightly billing reconciliation:
1. list successful provider charges since checkpoint
2. compare local payment records by provider reference
3. classify missing-local, missing-provider, amount-mismatch
4. auto-repair only missing-local webhooks with complete evidence
5. page a human for amount mismatch

The repair path is part of the architecture. If recovery depends on a senior engineer remembering a curl command, the system is unfinished.

Field notes

  • Idempotency keys should expire only after the business risk expires. Ten minutes may be fine for a form resubmit and absurd for a monthly billing job.
  • Retrying non-idempotent work with exponential backoff makes damage happen more slowly, not more safely.
  • Store enough request fingerprint data to detect same-key-different-payload misuse.
  • Dead-letter replay without fixing the poison input creates infinite incident loops.
  • Consistency requirements are business requirements. Do not let infrastructure teams guess them from latency targets.

Was this lesson helpful?

Sign in to rate