The Core Hazard: Retries Meet Non-Atomic Side Effects
Payment systems fail in subtle, expensive ways when mobile clients lose connectivity mid-checkout or a payment service provider (PSP) times out right after capturing funds. When the user taps 'Pay' twice—or an HTTP proxy automatically retries a 504 timeout—naïve endpoints execute two external charges or two local balance deductions.
Equally dangerous is the dual-write trap: committing a row to PostgreSQL (`status = 'CAPTURED'`) and then calling `kafkaProducer.send('payment.settled')` immediately afterward. If the pod restarts, hits a GC pause, or loses broker connectivity between those two calls, the database says the customer paid while fulfillment, invoicing, and analytics never receive the event.
Solving both problems cleanly without brittle distributed two-phase commits (2PC) rests on three pillars: scoped idempotency keys, immutable double-entry accounting, and a transactional outbox.
1. Scoped Idempotency Keys With Request Hashing
An idempotency key (`Idempotency-Key: <uuid>`) generated by the client per checkout attempt ensures that retries of the same logical intent return the exact cached outcome instead of executing a second charge.
A common bug is storing idempotency keys only in volatile Redis RAM with a short TTL. If Redis evicts under memory pressure, duplicate protection disappears. Instead, anchor idempotency keys inside the primary ACID transaction in PostgreSQL with a composite `UNIQUE (merchant_or_user_id, idempotency_key)` constraint and store a SHA-256 digest of the normalized request payload.
If a second request arrives with the same key but a different amount or currency (`request_hash` mismatch), reject immediately with `409 Conflict` / `422`. While the first attempt is in flight (`state = 'IN_PROGRESS'`), return `409` or wait briefly rather than racing two concurrent PSP calls.
Holding a PostgreSQL row lock open across a 3-second external HTTP call exhausts your connection pool under load. Instead, insert the IN_PROGRESS intent in TX1, call the PSP outside the transaction, and finalize status + outbox rows in TX2.
2. Double-Entry Ledger + Transactional Outbox in PostgreSQL
Instead of mutating a single `users.balance` integer column in place, production payment engines append immutable ledger postings where every money movement debits one account and credits another by an identical amount in minor currency units (integer paise/cents—never floating point).
In the exact same ACID transaction that appends the balanced ledger postings and updates the payment state machine (`AUTHORIZED` -> `CAPTURED`), write the domain event payload into `outbox_events`. Because both writes share one PostgreSQL commit log, it is mathematically impossible for a payment to capture without also scheduling its downstream notification event.
CREATE TABLE payment_idempotency (
scope_id UUID NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
request_hash CHAR(64) NOT NULL,
status VARCHAR(24) NOT NULL CHECK (status IN ('IN_PROGRESS','COMPLETED','FAILED')),
response_code SMALLINT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (scope_id, idempotency_key)
);
CREATE TABLE ledger_postings (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
transaction_id UUID NOT NULL,
account_id UUID NOT NULL,
direction SMALLINT NOT NULL CHECK (direction IN (-1, 1)), -- -1 DEBIT, +1 CREDIT
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency CHAR(3) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE outbox_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
aggregate_type VARCHAR(64) NOT NULL,
aggregate_id UUID NOT NULL,
event_type VARCHAR(96) NOT NULL,
payload JSONB NOT NULL,
published_at TIMESTAMPTZ,
retry_count INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Fast partial index so outbox relay workers only scan unpublished rows
CREATE INDEX idx_outbox_unpublished
ON outbox_events (id)
WHERE published_at IS NULL;3. Outbox Relay Delivery: Polling vs. CDC (Debezium)
Once events live reliably in `outbox_events`, an independent relay moves them to Kafka, RabbitMQ, or webhook workers. Choosing between indexed polling and log-based Change Data Capture (CDC) depends on throughput and operational maturity.
| Strategy | How It Works | Latency | Operational Overhead |
|---|---|---|---|
| FOR UPDATE SKIP LOCKED Polling | Worker batch-reads idx_outbox_unpublished every 100–500ms and marks published_at | 100–500 ms | Low — zero extra infrastructure beyond app workers |
| WAL Log Tail CDC (Debezium) | Reads PostgreSQL logical replication WAL stream directly into Kafka | 10–50 ms | Moderate/High — requires Kafka Connect + replication slot monitoring |
4. PSP Failover, Circuit Breakers & Consumer Idempotency
Even with a bulletproof outbox, outbox delivery is at-least-once: if the relay crashes right after pushing to Kafka but before setting `published_at`, the event will be published again on restart. Every downstream consumer (invoicing, email receipts, entitlement upgrades) MUST therefore track processed `event_id` keys via a `processed_events` unique table so duplicate deliveries remain harmless no-ops.
Finally, wrap outbound PSP HTTP clients in bounded timeouts (3–5 seconds), jittered exponential backoff only on safe/idempotent endpoints, and an explicit Circuit Breaker that trips open cleanly when gateway 5xx rates spike—protecting checkout threads from global exhaustion and routing traffic to backup rails or graceful queuing.
Turn architecture guides into living diagrams
Start free with 5 boards and 20 AI credits/month—spanning interactive HLD Canvas, LLD UML modeling, Database Schema Studio, and Repository Architecture mapping.