Why This Matters at Engineering Leadership Scale
In a distributed system, every network timeout is ambiguous. When a payment webhook or microservice POST request times out after five seconds, the caller cannot tell whether the request dropped before reaching the server, failed mid-flight, or committed cleanly to Postgres right before the response packet vanished. Because callers and webhook brokers automatically retry on timeouts and 5xx errors, every mutating API and async consumer in production must assume at-least-once delivery.
Without explicit consistency patterns, retries create two silent production bugs that destroy customer trust in fintech and compliance systems: duplicate side effects (charging a card twice, emitting duplicate audit entries, issuing duplicate refunds) and dual-write drift (saving a row in Postgres while the subsequent SQS or Kafka publish crashes, permanently losing downstream notifications). Fixing these after launch requires painful manual ledger reconciliation.
Core Mental Model & Architecture
Three deterministic patterns replace fragile retries and distributed two-phase commits (2PC) across enterprise platforms:
- Idempotency Keys: Require every mutating API call or webhook handler to provide a unique
Idempotency-Key(such as a Stripe or Jiraevent_id). Store the key, a SHA-256 hash of the request payload, and the final response inside a transactional table (or Redis for short-lived requests) with a 24 to 72-hour retention window. If the exact key arrives again with the same payload hash, return the stored response without re-running side effects; if the payload hash differs, reject with409 Conflict. - Transactional Outbox Pattern: Never write to Postgres and call
sqs.sendMessage()orkafka.produce()as two separate network steps. Instead, insert both the business record and anoutbox_eventsrow inside the same local ACID database transaction. A separate relay worker polls unpublished outbox rows usingFOR UPDATE SKIP LOCKED, publishes them to the broker, and marks them dispatched. Because consumers are also idempotent, brief duplicate publishes during relay restarts are completely harmless. - Saga Pattern (Orchestration vs. Choreography): When a business workflow spans multiple services (for example,
ReserveFunds -> IssueOrder -> RecordAudit), avoid locking two-phase commits across microservices. Model the workflow as a sequence of local transactions paired with explicit compensating actions on failure (ReleaseFunds). For workflows with four or more steps, prefer a central orchestrator over decentralized choreography so workflow state, retries, and compensations live in one inspectable place.
| Pattern | Consistency Guarantee | Failure Behavior | Complexity | Best Use Case |
|---|---|---|---|---|
| Naive Dual-Write (DB + SQS) | None (split-brain drift) | Crash between calls permanently drops events | Low | Never acceptable for money, billing, or audit events |
| Idempotency Keys | Effectively-once write execution | Safe retries return cached response; zero duplicates | Low-Medium | All mutating REST endpoints, webhooks, and billing APIs |
| Transactional Outbox | Atomic DB commit + guaranteed at-least-once publish | Outbox row survives pod crash and relays on recovery | Medium | Any DB write that triggers downstream queues or webhooks |
| Orchestrated Saga | Eventual consistency with explicit rollback | Runs compensating actions on downstream step failure | High | Multi-service workflows spanning 4+ bounded contexts |
Step-by-Step Implementation Tutorial
Follow these four steps to combine transactional idempotency keys with a Postgres Transactional Outbox in one atomic write path:
- Create
idempotency_keys&outbox_eventsTables: Enforce a unique composite constraint on(tenant_id, idempotency_key)so Postgres itself blocks concurrent duplicate races cleanly, and index unpublished outbox rows (WHERE published_at IS NULL). - Execute Business Write + Outbox Insert Inside One Transaction: Compute the request SHA-256 fingerprint, claim the idempotency row first, perform the domain insert, insert the outbox event payload, store the response snapshot, and commit atomically.
- Run a Concurrency-Safe Outbox Relay Worker: Poll batches of 50 unpublished events using
SELECT ... FOR UPDATE SKIP LOCKEDso multiple worker pods never publish the same batch simultaneously, send each event to SQS/Kafka carryingoutbox.idas the deduplication key, and setpublished_at = NOW(). - Enforce Idempotency on Downstream Consumers Too: Because the relay worker guarantees at-least-once delivery (it might crash right after SQS accepts a message but before updating
published_at), every downstream consumer must deduplicate onevent_id.
-- schema.sql - Atomic idempotency ledger & transactional outbox tables
CREATE TABLE idempotency_keys (
tenant_id TEXT NOT NULL,
idempotency_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
response_status INT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (tenant_id, idempotency_key)
);
CREATE TABLE outbox_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id TEXT NOT NULL,
aggregate_id TEXT NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
published_at TIMESTAMPTZ
);
CREATE INDEX idx_outbox_unpublished
ON outbox_events (created_at ASC)
WHERE published_at IS NULL;Wire the atomic write and relay worker in TypeScript using standard Postgres transactions:
// outbox-service.ts - Idempotent write + atomic outbox insert + SKIP LOCKED relay
import { createHash } from "node:crypto";
import type { Pool } from "pg";
export async function recordComplianceEventIdempotently(
pool: Pool,
tenantId: string,
idempotencyKey: string,
payload: Record<string, unknown>
): Promise<{ status: number; body: Record<string, unknown>; replayed: boolean }> {
const requestHash = createHash("sha256").update(JSON.stringify(payload)).digest("hex");
const client = await pool.connect();
try {
await client.query("BEGIN");
const inserted = await client.query(
`INSERT INTO idempotency_keys (tenant_id, idempotency_key, request_hash)
VALUES ($1, $2, $3)
ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
RETURNING request_hash`,
[tenantId, idempotencyKey, requestHash]
);
if (inserted.rowCount === 0) {
const existing = await client.query(
`SELECT request_hash, response_status, response_body
FROM idempotency_keys
WHERE tenant_id = $1 AND idempotency_key = $2`,
[tenantId, idempotencyKey]
);
await client.query("COMMIT");
const row = existing.rows[0];
if (row.request_hash !== requestHash) {
return { status: 409, body: { error: "Idempotency key reused with different payload" }, replayed: false };
}
return { status: row.response_status, body: row.response_body, replayed: true };
}
const eventRow = await client.query(
`INSERT INTO compliance_records (tenant_id, payload) VALUES ($1, $2) RETURNING id`,
[tenantId, payload]
);
const recordId = eventRow.rows[0].id as string;
await client.query(
`INSERT INTO outbox_events (tenant_id, aggregate_id, event_type, payload)
VALUES ($1, $2, 'ComplianceRecordCreated', $3)`,
[tenantId, recordId, { recordId, ...payload }]
);
const responseBody = { recordId, status: "accepted" };
await client.query(
`UPDATE idempotency_keys
SET response_status = 201, response_body = $3
WHERE tenant_id = $1 AND idempotency_key = $2`,
[tenantId, idempotencyKey, responseBody]
);
await client.query("COMMIT");
return { status: 201, body: responseBody, replayed: false };
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}In the background relay worker, run SELECT id, tenant_id, event_type, payload FROM outbox_events WHERE published_at IS NULL ORDER BY created_at ASC LIMIT 50 FOR UPDATE SKIP LOCKED, publish to SQS/Kafka, and update published_at = NOW() inside a short transaction (or use Debezium CDC streaming from the Postgres WAL if sub-50ms publish latency is required at high throughput).
Worked Production Scenario: Before vs. After
A multi-tenant brokerage and compliance platform ingested external webhook events from Jira, GitHub, and clearing brokers across 350 enterprise tenants, writing audit records to Postgres and fanning out notifications via SQS.
- Before: Webhook endpoints performed an
INSERT INTO compliance_recordsfollowed immediately byawait sqs.sendMessage(...)without idempotency keys. Whenever an upstream broker experienced transient network jitter and retried a timed-out webhook, the handler inserted duplicate audit records (14to25duplicates per week). During Kubernetes rolling deployments, pods terminated between the Postgres commit and the SQS call, silently dropping0.3%of downstream compliance alerts. Support engineers spent six hours every Friday running manual SQL reconciliation scripts. - After: The team rolled out mandatory
Idempotency-Keydeduplication keyed on(tenant_id, broker_event_id)with SHA-256 payload fingerprinting, replaced directsqs.sendMessage()calls with atomicoutbox_eventsinserts, and deployed two lightweightSKIP LOCKEDrelay workers with aDLQ > 0alarm. Over the next quarter, duplicate audit records fell to0, silent lost events dropped to0, Friday manual reconciliation work fell96%, and downstream consumers handled occasional relay retries cleanly viaevent_iddeduplication.
Common Failure Modes & Anti-Patterns
- Checking Idempotency With a Separate
SELECTBeforeINSERT: RunningSELECTto see if a key exists and then runningINSERTcreates a classic check-then-act race condition when two identical webhooks arrive 2 milliseconds apart. Structural Fix: Rely on a databasePRIMARY KEYorUNIQUEconstraint usingINSERT ... ON CONFLICT DO NOTHINGinside the transaction. - Wrapping a DB Commit and an HTTP/SQS Call in
try/catchto "Ensure Atomicity": If the SQS publish succeeds on the wire but times out returning200 OK, rolling back the database creates a phantom event for a non-existent record; conversely, if the pod OOM-kills after the DB commit,catchnever runs. Structural Fix: Never span a database transaction across a network call; write tooutbox_eventslocally and relay asynchronously. - Letting
outbox_eventsandidempotency_keysTables Grow Unbounded: Leaving millions of old published rows bloats table scans and indexes over months. Structural Fix: Run a daily scheduled cleanup job (or monthly partition drop) deletingidempotency_keysolder than 72 hours and publishedoutbox_eventsolder than 7 days.
How to Handle Pushback in the Room
Pushback 1 (Senior Engineer): "Adding an outbox table and a background relay worker feels like over-engineering. Why not just call sqs.sendMessage() right before COMMIT, and roll back Postgres if SQS throws an error?"
Verbatim Response: "Calling an external network API while holding an open Postgres transaction creates two serious production hazards: first, if SQS stalls for three seconds, our database connection pool locks up across all tenants; second, if SQS receives the message and times out on the response, our rollback deletes the database row while downstream consumers still process a phantom event. Writing to an outbox table inside the same local transaction takes under two milliseconds and guarantees our database state and event stream never drift."
Pushback 2 (Solutions Architect): "For our five-step onboarding and billing flow across four microservices, shouldn't we use pure event choreography so the services stay loosely coupled?"
Verbatim Response: "Choreography works well for simple two-step fan-outs like sending an email after signup. Once a workflow hits four or five steps with financial compensations on partial failure, scattering state across five independent event handlers makes debugging stuck customers almost impossible. A lightweight central Saga orchestrator keeps the services decoupled through explicit contracts while giving on-call engineers one place to inspect state, retries, and rollbacks."
Key Takeaways & This Week's Action Rep
- Assume at-least-once delivery on every mutating endpoint and webhook consumer because network timeouts are always ambiguous.
- Enforce transactional Idempotency Keys (
(tenant_id, key)unique constraint + payload hash check) to eliminate duplicate side effects cleanly under concurrent retries. - Replace all dual-write patterns (DB + SQS/Kafka) with the Transactional Outbox Pattern so domain state and event emission commit atomically inside one local ACID transaction.
- Use Orchestrated Sagas with explicit compensating actions instead of distributed two-phase commits or tangled 5-service choreography for complex multi-step mutations.
This Week's Action Rep: Audit your service's highest-impact webhook or mutation endpoint. Verify whether it enforces a unique Idempotency-Key constraint in Postgres and check for any bare DB-plus-queue dual writes that should be moved to a transactional outbox table.