Skip to main content

Scenario: Stripe Payment Idempotency

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"A client times out while calling your payment API. How do you prevent duplicate charges, and what guarantees can you actually offer?"

2. Real-World Context​

DimensionDetail
Company / systemStripe — payment APIs used by millions of merchants
ScaleBillions of API requests; network timeouts are routine, not edge cases
Why architects careMoney requires safety over liveness; ambiguous outcomes are the default after timeouts
Public referencesStripe Idempotent Requests docs; Kleppmann DDIA Ch. 11 on stream processing and exactly-once

Stripe requires an Idempotency-Key header on mutating requests. The server stores the key with the response for 24 hours. Retries with the same key return the original response without re-executing side effects.

AWS deployment context​

Typical merchant production stack on AWS — idempotency state lives in Aurora PostgreSQL (or DynamoDB at high QPS); payment orchestration runs on ECS Fargate or Lambda behind ALB; webhooks buffer through SQS; reconciliation runs on EventBridge + Lambda.

Step-by-step flow:

StepActionExplanation
1Client requestWeb/mobile user initiates checkout with Idempotency-Key header.
2Edge routingCloudFront serves static UI; API traffic passes WAF and Route 53 to ALB.
3Load balanceALB routes to healthy ECS Fargate checkout-api task.
4Claim idempotency keyECS inserts processing row in Aurora (idempotency_keys).
5Load Stripe secretECS fetches sk_live_* from Secrets Manager.
6Call StripePOST payment_intents with same Idempotency-Key (25s timeout).
7Webhook ingestStripe sends event → webhook worker enqueues to SQS.
8Async processConsumer dedupes event_id, updates orders/charges in Aurora.
9Sweeper healLambda queries stuck processing rows; reconciles with Stripe.
10ReconciliationHourly Lambda compares Aurora ledger vs Stripe settlements.
11ObservabilityStructured logs and metrics emitted to CloudWatch.

Minutes 0–5: Clarify requirements​

  1. Functional: Accept charge requests; return success/failure; support client retries.
  2. Non-functional: No duplicate charges (safety); p99 latency < 500ms; audit trail for compliance.
  3. Non-goals: Exactly-once over the network (impossible); synchronous cross-bank settlement.
  4. Assumption: At-least-once delivery from client; crash-stop failures.

Say aloud: "After a timeout, we are in an ambiguous state — I cannot assume failure."

Minutes 5–15: Architecture​

  1. Client generates UUID idempotency key per logical operation (not per HTTP attempt).
  2. API gateway validates key format; routes to payment service.
  3. Payment service opens DB transaction:
    • Check idempotency_keys table for (tenant_id, key).
    • If COMPLETED: return stored response.
    • If IN_FLIGHT: return 409 or wait (short poll).
    • Else: insert IN_FLIGHT, call gateway, update ledger, mark COMPLETED with response body.
  4. Background reconciliation job compares ledger vs. gateway settlement files hourly.

AWS reference (interview whiteboard):

Step-by-step flow:

StepActionExplanation
1Client → CloudFrontTLS-terminated entry; static assets cached.
2CloudFront → ALBAPI path forwarded to Application Load Balancer.
3ALB → ECSRoute to checkout service; validate idempotency key format.
4ECS → AuroraAtomic claim or cache hit on idempotency_keys.
5ECS → StripePaymentIntent create with merchant idempotency key.
6Stripe → SQSWebhook buffered for at-least-once delivery.
7SQS → Webhook LambdaDedupe event_id; idempotent order update.
8EventBridge → ReconciliationScheduled hourly ledger vs Stripe diff.

Step-by-step flow:

StepActionExplanation
1First POSTClient sends charge with Idempotency-Key: abc.
2DB lookupAPI begins transaction; inserts processing.
3Gateway chargeStripe authorizes; success at gateway.
4504 timeoutResponse lost — client in ambiguous state.
5Retry same keyClient retries with identical key (not new UUID).
6Dedup hitDB returns completed; cached 200 — no second charge.

Minutes 15–30: Deep dive​

  1. Request hash: Reject same key with different body (409 Conflict) — prevents semantic bugs.
  2. TTL: Keys expire after 24h; document that clients must use new keys for new operations.
  3. Gateway support: If gateway supports idempotency, pass key through; else query-by-key before re-charge.
  4. State machine: PENDING → COMPLETED | FAILED; never skip states.
  5. Concurrent duplicates: Unique constraint on (tenant_id, idempotency_key); one wins, others read result.

Minutes 30–45: Failures and ops​

FailureBehavior
Idempotency store downFail closed on mutations; reads may use cache
Gateway slowTimeout < client deadline; return 504 with retry guidance
Duplicate webhookDedupe by event_id in webhook handler
Reconciliation driftAlert + manual review queue; never auto-reverse without policy

Metrics: Idempotency cache hit rate; reconciliation gap count; charge latency by gateway.

4. Whiteboard Guide​

Draw left-to-right:

  1. Client → API → Idempotency DB + Ledger → Gateway
  2. Label the timeout zone with "UNKNOWN" between gateway and API
  3. Add reconciliation cron below ledger ↔ gateway

AWS whiteboard layout​

Step-by-step flow:

StepActionExplanation
1Sync pathClient → CloudFront → ALB → ECS API.
2Persist stateWrite idempotency_keys + ledger rows in Aurora.
3Stripe callExternal authorization — UNKNOWN zone if response lost.
4Webhook asyncStripe event → SQS → worker updates ledger.
5ReconciliationEventBridge cron compares ledger ↔ Stripe (backstop).

MetricValueReasoning
Peak charge QPS5KMid-size payment platform
Idempotency key TTL24hStripe default; covers retry windows
Client timeout30sMobile networks
Internal gateway timeout25sMust be < client timeout
Reconciliation lag SLA1hDetect drift before settlement close

AWS service mapping at 5K QPS peak​

Step-by-step flow:

StepActionExplanation
1ALB ingress5K req/s TLS termination and path routing.
2ECS scale-out10–30 Fargate tasks; auto-scale on p99 latency.
3Aurora writesIdempotency + ledger strong consistency (writer).
4DynamoDB optionalHigh-QPS idempotency shard if Aurora contends.
5NAT egressOutbound HTTPS to api.stripe.com.
AWS serviceRole at this scale
ALBPath-based routing /api/checkout, /webhooks/stripe
ECS FargateStateless checkout service; 25s Stripe timeout per task
Aurora PostgreSQLidempotency_keys, orders, charges — sync multi-AZ
ElastiCache RedisOptional session / rate-limit counters (not dedup primary)
SQSWebhook durability; DLQ for poison events
EventBridgeCron rate(1 hour) reconciliation
Secrets Managersk_live_* rotation; IAM task role for ECS
CloudWatchidempotency_processing_stuck, charge_latency_p99 alarms

  • Distinguishes network failure from application failure
  • Names safety (no double charge) vs liveness (eventual settlement)
  • Mentions fail-closed when dedup store unavailable
  • Describes reconciliation as the backstop, not hope

7. Red Flags​

  • "Retry until success" without idempotency keys
  • "Kubernetes restarts fix it"
  • Claims exactly-once without idempotent consumers
  • No mention of ambiguous timeout state

8. Follow-Up Questions​

Follow-upStrong outline
Same key, different amount?409 Conflict; store request hash
Store partitioned?Per-tenant sharding; sticky routing
Cross-region active-active?Avoid for payment write path; Route 53 weighted writes to single region

AWS — sticky routing for payment writes:

Step-by-step flow:

StepActionExplanation
1Read pathRoute 53 latency routing → CloudFront catalog (geo).
2Write pathRoute 53 failover → single ALB us-east-1 only.
3CheckoutECS processes payment; Aurora primary is sole writer.

Hands-On Lab (Local)​

Run the full scenario stack on your laptop — no AWS account required ($0 cost).

LabPathWhat you build
Introlabs/lab-008-idempotent-api/FastAPI + Swagger on :8081; in-memory idempotency store
Full stacklabs/lab-017-stripe-payment-idempotency/FastAPI + PostgreSQL/SQLite + Redis + Stripe mock + webhook worker + sweeper

Quick start (SQLite — no Docker)​

cd labs/lab-017-stripe-payment-idempotency
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
pytest tests/ -v # 8 acceptance tests
python -m src.main --serve # API on :8080

In another terminal:

./scripts/demo_retry.sh # same Idempotency-Key twice → no double charge

Full stack (Docker Compose)​

docker compose -f docker/docker-compose.yml up --build -d
curl http://localhost:8080/health
./scripts/demo_retry.sh

Services: API :8080, PostgreSQL :5434, Redis :6381.

STEP mapping​

PhaseExercise in lab
ScopeRead requirements.md — FR/NFR from this scenario
TopologyCompare architecture.md local map to AWS diagrams in §2 and §11
ExploreTrace src/service.py idempotency state machine; run pytest
ProductionRun webhook worker (python -m src.main --worker) and sweeper
EvolveExtension exercises in lab README (DynamoDB, metrics, Stripe CLI)

Full lab guide: labs/lab-017-stripe-payment-idempotency/README.md.

Engineer guide: how the local stack works​

This section documents the runtime behavior of lab-017 as you would read it in a production runbook — component boundaries, request path, persistence, and how to verify correctness.

Runtime topology​

ProcessPort / entrypointResponsibility
Checkout API:8080 — python -m src.main --serveSynchronous charge path; idempotency claim + Stripe call
PostgreSQL:5434 — stripe_lab / stripe_labDurable idempotency store + order ledger
Redis:6381Webhook event queue (SQS stand-in)
Webhook workerpython -m src.main --workerConsumes Redis queue; dedupes by event_id
Sweeperpython -m src.main --sweeperHeals rows stuck in processing

Browser entrypoints: http://localhost:8080/ (HTML landing), http://localhost:8080/docs (Swagger UI), http://localhost:8080/health.

API contract — POST /v1/charges​

Required headers

HeaderRule
Idempotency-KeyNon-empty string; one key per logical checkout; reuse on retry
X-Tenant-IdTenant namespace (default demo); keys are unique per (tenant_id, idempotency_key)
Content-Typeapplication/json

Request body (validated by Pydantic — invalid body returns 422, not 500):

{
"amount_cents": 2500,
"currency": "usd"
}

Success response — 201 Created:

{
"order_id": "ord_78772d8f6715",
"payment_intent_id": "pi_09686b12cbd048c5",
"status": "succeeded",
"amount_cents": 2500,
"currency": "USD"
}
FieldSemantics
order_idInternal ledger row — one per real charge
payment_intent_idStripe mock intent — one per real charge
statusTerminal state from mock gateway

Handler algorithm (src/service.py)​

The charge handler executes in this order on every POST /v1/charges:

  1. Fail closed if idempotency store is unavailable → 503 (no Stripe call).
  2. Validate Idempotency-Key present → 400 if missing.
  3. Validate amount_cents + currency before any side effect → 400 / 422.
  4. Compute request_hash = SHA-256(JSON body) — same key + different body → 409 Conflict.
  5. Lookup (tenant_id, idempotency_key) in idempotency_keys:
    • completed → return cached response_body (no Stripe call, no new order).
    • processing → 409 request in flight.
  6. Claim key — INSERT … status='processing' with unique constraint on (tenant_id, idempotency_key); concurrent losers read winner's result.
  7. Call Stripe mock — create_payment_intent(); mock dedupes by idempotency key internally.
  8. Insert order — one row in orders table.
  9. Complete idempotency — UPDATE … status='completed', persist full response JSON for replay.
  10. Publish webhook — mock pushes payment_intent.succeeded event to Redis queue.

How to tell: new charge vs idempotent replay​

Compare response IDs, not HTTP status — both paths return 201.

ObservationInterpretation
Same Idempotency-Key, same order_id + payment_intent_idReplay — no new charge, no new DB order
New Idempotency-Key, new order_id + payment_intent_idNew charge — new ledger row
SELECT COUNT(*) FROM orders unchanged after retryConfirms no duplicate ledger entry

Swagger UI procedure

  1. Open http://localhost:8080/docs → POST /v1/charges → Try it out.
  2. Set Idempotency-Key: test-2, X-Tenant-Id: demo.
  3. Body: {"amount_cents": 2500, "currency": "usd"} — do not use the generic additionalProp1 placeholder.
  4. Execute → note order_id and payment_intent_id.
  5. Execute again without changing the key → identical IDs = idempotency working.

PostgreSQL inspection (Docker)​

# Order count — should increment only on NEW idempotency keys
docker compose -f docker/docker-compose.yml exec postgres \
psql -U stripe_lab -d stripe_lab -c "SELECT COUNT(*) FROM orders;"

# Full ledger
docker compose -f docker/docker-compose.yml exec postgres \
psql -U stripe_lab -d stripe_lab \
-c "SELECT order_id, amount_cents, stripe_payment_intent_id, created_at FROM orders ORDER BY created_at;"

# Idempotency state — shows processing → completed + cached response
docker compose -f docker/docker-compose.yml exec postgres \
psql -U stripe_lab -d stripe_lab \
-c "SELECT tenant_id, idempotency_key, status, response_status, stripe_payment_intent_id FROM idempotency_keys;"

Schema (3 tables):

TablePurpose
idempotency_keysPK (tenant_id, idempotency_key); stores request_hash, status, cached response_body
ordersBusiness ledger; stripe_payment_intent_id UNIQUE
webhook_eventsPK event_id; at-least-once webhook dedup

Async path — webhooks + sweeper​

After each successful charge, the Stripe mock enqueues a webhook event to Redis. The API does not block on webhook delivery.

# Terminal 1 — API (already running via compose)
# Terminal 2 — drain webhook queue
docker compose -f docker/docker-compose.yml exec api python -m src.main --worker

# Terminal 3 — heal stuck processing rows (crash mid-flight simulation)
docker compose -f docker/docker-compose.yml exec api python -m src.main --sweeper

Webhook handler dedupes on event_id — duplicate delivery inserts once into webhook_events, second call returns duplicate: true.

Error codes (charge path)​

HTTPConditionClient action
201New charge or idempotent replayTreat as success; same body on replay
400Missing key or invalid amount/currencyFix request
409Same key, different body OR request in flightNew key for new op; backoff if in flight
422Pydantic validation (Swagger default body)Use {"amount_cents": N, "currency": "usd"}
503Idempotency store downFail closed — retry later

Code map​

FileResponsibility
src/api.pyHTTP surface, Swagger schema (ChargeRequest), HTML landing page
src/service.pyIdempotency state machine + orchestration
src/db.pyPostgreSQL/SQLite persistence, unique-constraint races
src/stripe_mock.pyPaymentIntent mock with per-key dedup
src/queue.pyRedis list (in-memory fallback for tests)
src/webhook_worker.pyQueue consumer
src/sweeper.pyStuck processing reconciliation
tests/test_stripe_idempotency_lab.py9 acceptance tests

Mapping local behavior → production (this scenario)​

Local observationProduction equivalent
Same key → same payment_intent_idStripe Idempotent Requests (24h window)
orders count stable on retryAurora ledger — no duplicate settlement
webhook_events dedupSQS + Lambda event_id check
Sweeper heals processingEventBridge scheduled reconciliation Lambda
503 when store downFail closed — prefer outage over double charge
  • Partial Failure
  • Idempotency
  • Lab (intro): labs/lab-008-idempotent-api
  • Lab (full local stack): labs/lab-017-stripe-payment-idempotency
  • Case study: case-studies/stripe

10. Practice Drill​

45 minutes: Answer the interview question using STEP. Record yourself. Score: Did you mention ambiguous state, idempotency store, reconciliation, and fail-closed?


11. Production High-Level Design​

This section is a build guide for implementing Stripe-style payment idempotency in production — whether you are the merchant integrating Stripe or building an internal payment platform that exposes idempotent APIs to your own services.

AWS architecture diagram index​

SectionAWS diagram topic
§2End-to-end AWS deployment context
§3Interview AWS reference stack
§4AWS whiteboard layout
§5Service sizing at 5K QPS
§11.2.1Full VPC production stack
§11.4Pattern A vs B on AWS
§12.2.1Aurora vs DynamoDB data layer
§12.4Request path through ALB/ECS/Aurora
§12.6SQS webhook pipeline
§12.7EventBridge reconciliation
§13.4CloudFront + SPA client flow
§14Multi-AZ, multi-region DR, active-active
§15Security + observability
§16Rollout Gantt + AWS services
§17Staging + FIS chaos testing
§18Production readiness gates
§2018 PNG exports — AWS Architecture Icons for slides

11.1 Problem statement​

ConstraintRequirement
SafetyAt most one financial side effect per logical payment intent
LivenessClients can retry after timeout without special-case logic
AuditabilityEvery charge traceable to idempotency key + gateway reference
AmbiguityAfter timeout, neither client nor server knows outcome — design for that

Non-goals: Exactly-once over the network; synchronous global settlement; hiding failures from merchants.

11.2 System context (C4 Level 1)​

Logical view — technology-agnostic component boundaries.

Step-by-step flow:

StepActionExplanation
1IngressClients hit API Gateway / load balancer.
2OrchestratePayment Service claims idempotency key.
3PersistWrite idempotency store + ledger atomically.
4EventsOutbox publishes domain events (deduped).
5StripeExternal charge with same idempotency key.
6WebhookAsync confirmation updates ledger.
7ReconcileWorker diffs ledger vs Stripe settlements.

11.2.1 AWS production architecture (full stack)​

Physical AWS deployment — Pattern A merchant integrating Stripe.

Step-by-step flow:

StepActionExplanation
1User → edgeCloudFront + WAF + Route 53 health-checked routing.
2ALB → ECSCross-AZ load balance to checkout-api tasks.
3Claim keyINSERT idempotency_keys on Aurora writer.
4SecretsFetch Stripe API key from Secrets Manager.
5NAT → StripeEgress via NAT Gateway; POST with Idempotency-Key.
6Webhook queueStripe webhook → ALB → SQS → ECS consumer.
7SweeperLambda heals processing rows every 30s.
8ReconcileEventBridge triggers hourly Stripe vs ledger job.
9Replica syncAurora reader + cross-AZ sync for HA.
AWS componentIdempotency responsibility
ALBTLS, path routing, 503 when target unhealthy during DR
ECS FargateClaim key, call Stripe, cache response — stateless
Aurora PostgreSQLidempotency_keys unique constraint; multi-AZ sync
NAT GatewayOutbound HTTPS to api.stripe.com
SQSBuffer webhooks; survive consumer crash
Lambda sweeperHeal processing rows; EventBridge rate(30 seconds)
EventBridge + LambdaHourly reconciliation job
SSM Parameter Storepayments_fail_closed=true during DR promotion
Secrets ManagerStripe secret key; IAM role per ECS task

11.3 Component responsibilities​

ComponentResponsibilityIdempotency role
API GatewayAuthN/Z, rate limit, validate Idempotency-Key formatReject malformed keys before payment service
Payment ServiceOrchestrate charge; own state machineAtomic claim in idempotency store
Idempotency Store(tenant, key) → status, request hash, responseSource of truth for "already executed?"
LedgerImmutable financial recordsNatural key charge_id; links to idempotency key
OutboxReliable async eventsDedupe publish via event_id
Webhook IngestorProcess Stripe payment_intent.succeeded etc.Dedupe by event.id
Reconciliation WorkerCompare ledger vs Stripe balance transactionsBackstop for crash-window bugs
Client SDKGenerate key once; retry with same keyKeys tied to business intent, not HTTP attempt

11.4 Two deployment patterns​

Pattern A — Merchant integrating Stripe (most common)

You call Stripe's API with Idempotency-Key. Stripe owns the dedup store. You still need merchant-side idempotency: persist key with order before calling Stripe, and dedupe your own POST /checkout endpoint.

Pattern B — Internal payment platform (Stripe-like)

You expose POST /v1/charges to internal teams. You own idempotency store, ledger, gateway adapter, webhooks, and reconciliation.

Both patterns share the same state machine and ambiguous timeout semantics. The sections below cover Pattern B in full; Pattern A notes appear where the merchant layer differs.

Pattern A — AWS (merchant + Stripe):

Step-by-step flow:

StepActionExplanation
1Load UICloudFront + S3 serves checkout SPA.
2Checkout APIECS receives POST with idempotency key.
3Persist orderAurora stores order + key before Stripe call.
4Stripe chargeSame key passed to Stripe global dedup cache.
5WebhookStripe confirms → ECS updates order status.

Pattern B — AWS (internal payment platform):

Step-by-step flow:

StepActionExplanation
1Internal callBilling/marketplace services call Payment API.
2API gatewayALB authenticates internal service.
3Dedup claimPayment API writes idempotency store.
4LedgerImmutable charge row created.
5StripeExternal gateway with platform-owned keys.

11.5 High-level request lifecycle​

Step-by-step flow:

StepActionExplanation
1ReceivedPOST arrives with Idempotency-Key.
2ValidatedSchema, auth, request hash computed.
3ClaimedINSERT processing (unique constraint).
4Gateway pendingCall Stripe outside long DB transaction.
5aCompletedCache response; terminal success.
5bFailedCache error (e.g. 402); terminal failure.
R1Dedup hitRetry returns cached response — skip gateway.
R2ConflictSame key, different body → 422.
R3In-flightConcurrent duplicate → 409 or short poll.

11.6 Key architectural decisions​

DecisionRecommendationRationale
Write path topologySingle primary region; CP leader per merchant shardAvoid split-brain double charge
Idempotency store consistencyStrong consistency (Postgres txn, DynamoDB conditional write)Must not execute gateway twice
Gateway call inside or outside DB txnOutside long txn; use processing + recovery sweeperHolding DB lock during 25s gateway call kills throughput
Response cachingStore full HTTP status + bodyRetries must be bit-identical to original
TTL24h (Stripe default) or 7d for B2BBalance storage vs retry window
Fail closedIf idempotency store down → 503 on mutationsSafety over liveness for money

12. Production Low-Level Design​

12.1 API contract​

Endpoint: POST /v1/charges

Required headers:

HeaderRule
AuthorizationBearer <api_key> or mTLS
Idempotency-Key1–255 chars; [A-Za-z0-9_-]; unique per logical operation
Content-Typeapplication/json

Request body (example):

{
"amount": 24750,
"currency": "usd",
"customer_id": "cus_8f3a",
"payment_method_id": "pm_card_visa",
"metadata": {
"order_id": "ord_20260728_001"
}
}

Response semantics:

HTTPMeaningClient action
200 / 201Success (may be cached on retry)Store charge_id; stop retrying
402Card declined (terminal)Do not retry same payload blindly
409Same key still processingRetry with Retry-After (exponential backoff)
422Same key, different request hashBug — new key required
503Idempotency store or gateway unavailableRetry with same key
504Gateway timeout — ambiguousRetry with same key

Stripe reference: Idempotent requests — keys expire after 24 hours; same key returns cached response including errors.

12.2 Database schema​

Table: idempotency_keys

CREATE TABLE idempotency_keys (
id BIGSERIAL PRIMARY KEY,
tenant_id VARCHAR(64) NOT NULL,
idempotency_key VARCHAR(255) NOT NULL,
request_hash CHAR(64) NOT NULL, -- SHA-256 of canonical JSON body
status VARCHAR(16) NOT NULL, -- processing | completed | failed
http_status SMALLINT,
response_body JSONB,
charge_id VARCHAR(64), -- FK to ledger when known
stripe_pi_id VARCHAR(64), -- external reference
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL, -- created_at + 24h

CONSTRAINT uq_tenant_key UNIQUE (tenant_id, idempotency_key)
);

CREATE INDEX idx_idempotency_expires ON idempotency_keys (expires_at)
WHERE status IN ('completed', 'failed');

Table: charges (ledger)

CREATE TABLE charges (
charge_id VARCHAR(64) PRIMARY KEY, -- ch_xxx generated server-side
tenant_id VARCHAR(64) NOT NULL,
idempotency_key VARCHAR(255) NOT NULL,
amount BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
status VARCHAR(16) NOT NULL, -- pending | succeeded | failed
stripe_pi_id VARCHAR(64) UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),

CONSTRAINT uq_tenant_idem UNIQUE (tenant_id, idempotency_key)
);

Table: webhook_events (async dedup)

CREATE TABLE webhook_events (
event_id VARCHAR(64) PRIMARY KEY, -- Stripe evt_xxx
event_type VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
processed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

DynamoDB alternative (high QPS):

AttributeTypeNotes
PKTENANT#<id>#IDEM#<key>Partition key
statusStringprocessing / completed / failed
request_hashString
responseMapCached API response
ttlNumberUnix epoch for 24h expiry

Use ConditionExpression: attribute_not_exists(PK) for atomic claim.

12.2.1 AWS data layer architecture​

Option A — Aurora PostgreSQL (recommended for < 20K charge QPS):

Step-by-step flow:

StepActionExplanation
1ECS writeAll checkout tasks write to single Aurora writer.
2Sync replicaIn-region readers serve consistent reads if needed.
3DR replicateAsync replication to us-west-2 Global DB / replica.

Option B — DynamoDB for idempotency + Aurora for ledger (high QPS):

Step-by-step flow:

StepActionExplanation
1Conditional putDynamoDB PutItem claims idempotency key atomically.
2Ledger writeAurora stores orders/charges (relational integrity).
3Audit streamDynamoDB Streams → Lambda metrics/audit.
StoreAWS serviceIdempotency pattern
Dedup + ledger (simple)Aurora PostgreSQLINSERT ... ON CONFLICT in transaction
Dedup only (scale)DynamoDBPutItem with attribute_not_exists(PK)
Dedup cache (optional)ElastiCache RedisNot primary — Aurora/DynamoDB is source of truth
Audit trailS3 + AthenaAppend-only payment audit logs

12.3 Request hash (fingerprint)​

Canonicalize JSON before hashing to prevent false mismatches:

  1. Sort object keys recursively.
  2. Normalize amounts (integer cents only).
  3. SHA-256(method + path + canonical_body).

If (tenant, key) exists and request_hash differs → 422 Unprocessable Entity.

12.4 Payment service handler — step-by-step (low level)​

AWS request path — end to end:

Step-by-step flow:

StepActionExplanation
1HTTPS ingressClient POST /api/checkout via CloudFront.
2WAF filterRate limit and OWASP rule check.
3ALB routeForward to healthy ECS task.
4Claim keyINSERT idempotency_keys status=processing.
5Get secretSecrets Manager returns Stripe API key.
6Stripe APIPOST payment_intents with Idempotency-Key.
7Persist resultUPDATE idempotency + INSERT charge.
8Respond200 success or 504 ambiguous to client.

Step 1 — Ingress validation (synchronous, <5ms)

1. Parse Idempotency-Key header — reject 400 if missing on POST
2. Authenticate tenant_id from API key
3. Validate body schema (amount > 0, currency ISO 4217)
4. Compute request_hash

Step 2 — Idempotency claim (single DB round-trip)

INSERT INTO idempotency_keys (tenant_id, idempotency_key, request_hash, status, expires_at)
VALUES ($1, $2, $3, 'processing', now() + interval '24 hours')
ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
RETURNING id, status;
OutcomeNext action
INSERT succeededYou own the key — proceed to Step 3
INSERT failed — row completedReturn cached http_status + response_body — STOP
INSERT failed — row failedReturn cached error — STOP
INSERT failed — row processingGo to Step 2b (concurrent handling)

Step 2b — Concurrent duplicate

Option A (Stripe-style): Short poll — SELECT ... FOR UPDATE wait up to 2s for status change, then return cached response.

Option B: Immediate 409 Conflict + Retry-After: 1.

Step 3 — Create ledger row (same txn as claim, optional)

INSERT INTO charges (charge_id, tenant_id, idempotency_key, amount, currency, status)
VALUES ($charge_id, $tenant, $key, $amount, $currency, 'pending');
UPDATE idempotency_keys SET charge_id = $charge_id WHERE id = $idem_id;
COMMIT;

Step 4 — Call Stripe (outside long transaction)

POST https://api.stripe.com/v1/payment_intents
Headers:
Idempotency-Key: <same key>
Authorization: Bearer sk_live_...
Body:
amount, currency, customer, payment_method, metadata[order_id]
Timeout: 25s (internal) < 30s (client)
Stripe resultAction
200 + pi_xxx succeededUpdate ledger succeeded, idempotency completed, cache response
402 card_errorMark failed, cache 402 body (retries return same 402)
Timeout / 504Leave processing — critical — go to Step 5
500 Stripe errorRetry Stripe with same key (Stripe dedupes) or query status

Step 5 — Ambiguous timeout recovery

Do not mark failed. Leave processing. Options:

  1. Client retries with same key → your handler hits processing → poll or query Stripe by idempotency key.
  2. Sweeper job (every 30s): SELECT * FROM idempotency_keys WHERE status='processing' AND updated_at < now() - interval '30 seconds'. For each: GET /v1/payment_intents?metadata[idempotency_key]=... or list by metadata.
  3. Stripe Search API / reconciliation file for pi_xxx if you stored partial response.

Step-by-step flow:

StepActionExplanation
1First attemptINSERT processing; call Stripe.
2Timeout504 to client; row stays processing.
3RetryClient retries same key.
4Poll StripeQuery PI or retry POST — Stripe dedupes.
5CompleteUPDATE completed; return cached 200.

Step 6 — Persist terminal state

UPDATE idempotency_keys
SET status = 'completed',
http_status = 200,
response_body = $json,
stripe_pi_id = $pi,
updated_at = now()
WHERE tenant_id = $1 AND idempotency_key = $2;

UPDATE charges SET status = 'succeeded', stripe_pi_id = $pi
WHERE charge_id = $charge_id;

All in one transaction. Response to client only after commit.

12.5 Reference handler pseudocode​

def create_charge(tenant_id: str, idem_key: str, body: dict) -> Response:
req_hash = sha256_canonical(body)

# Fast path: already done
existing = db.get_idempotency(tenant_id, idem_key)
if existing:
if existing.request_hash != req_hash:
return Response(422, "Idempotency key reused with different parameters")
if existing.status == "completed":
return Response(existing.http_status, existing.response_body)
if existing.status == "failed":
return Response(existing.http_status, existing.response_body)
if existing.status == "processing":
return wait_or_409(existing, timeout=2.0)

# Claim key
claimed = db.try_insert_processing(tenant_id, idem_key, req_hash)
if not claimed:
return create_charge(tenant_id, idem_key, body) # retry from top

charge_id = generate_charge_id()
db.insert_charge_pending(charge_id, tenant_id, idem_key, body)

try:
stripe_resp = stripe.payment_intents.create(
**map_body(body),
idempotency_key=idem_key,
timeout=25,
)
except Timeout:
return Response(504, {"error": "ambiguous", "retry_with_same_key": True})
except StripeError as e:
db.mark_idempotency_failed(tenant_id, idem_key, e.http_status, e.json)
return Response(e.http_status, e.json)

response = map_stripe_to_api(stripe_resp, charge_id)
db.mark_idempotency_completed(tenant_id, idem_key, 200, response, stripe_resp.id)
return Response(200, response)

12.6 Webhook path (async completion)​

Stripe may confirm payment asynchronously (3DS, network delays). Webhooks are at-least-once.

Handler steps:

  1. Verify signature (Stripe-Signature header).
  2. INSERT INTO webhook_events (event_id, ...) ON CONFLICT DO NOTHING.
  3. If conflict (duplicate event_id) → return 200 immediately.
  4. Process payment_intent.succeeded: update charges + orders if not already succeeded.
  5. Use charge_id or stripe_pi_id as idempotent update key: UPDATE ... WHERE status != 'succeeded'.

Never create a second charge from webhook — only transition existing ledger row.

AWS webhook architecture:

Step-by-step flow:

StepActionExplanation
1Stripe POSTWebhook hits ALB /api/webhooks/stripe.
2Verify sigValidate Stripe-Signature HMAC.
3EnqueuePush raw event to SQS (fast ACK).
4ConsumeWorker pulls message; INSERT event_id dedup.
5Update orderIdempotent UPDATE orders SET paid.
6DLQPoison messages → DLQ → CloudWatch alarm.
AWS componentConfiguration
ALBFast ACK to Stripe (200 after SQS enqueue) — or sync process if low volume
SQSVisibility timeout > max handler duration; maxReceiveCount=5 → DLQ
ECS/LambdaIdempotent consumer: INSERT event_id ON CONFLICT DO NOTHING
DLQManual replay after fix; never auto-replay without dedup check

12.7 Reconciliation worker​

Schedule: Hourly + end-of-day settlement.

Algorithm:

  1. Pull Stripe Balance Transactions for window [T-2h, T].
  2. Join on stripe_pi_id / charge_id / metadata order_id.
  3. Flag:
    • Stripe charge, no ledger row → crash after Stripe, before DB — auto-insert or alert.
    • Ledger succeeded, no Stripe → phantom row — critical alert.
    • Amount mismatch → P1 incident.

Output: Reconciliation gap dashboard; never auto-refund without policy engine approval.

AWS reconciliation architecture:

Step-by-step flow:

StepActionExplanation
1ScheduleEventBridge cron rate(1 hour).
2Fetch ledgerLambda reads Aurora charges for window.
3Fetch StripeList Balance Transactions from Stripe API.
4DiffJoin on stripe_pi_id; flag gaps.
5ReportWrite CSV to S3; emit reconciliation_gap_count.
6AlertSNS → PagerDuty on any mismatch.

13.1 Merchant checkout (Pattern A)​

StepOwnerAction
1FrontendUser clicks "Pay" — disable double-submit
2BackendCreate order row status=draft
3BackendGenerate idempotency_key = f"ord_{order_id}" — persist on order row before Stripe call
4BackendPOST /v1/payment_intents with key
5BackendOn 200: update order.status=paid, store payment_intent_id
6BackendOn 504/timeout: return 202 to frontend with order_id — frontend polls GET /orders/{id}
7FrontendPoll order status; backend may retry Stripe with same key server-side

Critical bug to avoid: Generating a new UUID on each HTTP retry.

// Browser — key once per checkout session
const idemKey = sessionStorage.getItem('checkout_idem')
?? crypto.randomUUID();
sessionStorage.setItem('checkout_idem', idemKey);

await fetch('/api/checkout', {
method: 'POST',
headers: { 'Idempotency-Key': idemKey },
body: JSON.stringify({ cartId }),
});

13.2 Server-side retry policy​

ConditionRetry?Same key?
503, 504, connection resetYesYes
409 processingYesYes — after Retry-After
200, 201No—
402 card declinedNoSame key returns same 402
422 hash mismatchNoFix bug — new key

Backoff: min(2^n, 30s) + jitter; max 5 attempts over 2 minutes; then surface "payment pending" UX.

13.3 Batch billing jobs​

Use deterministic keys: sub_{subscription_id}_{billing_period_start}.

Persist key in invoices table before calling payment API. Job retries on next cron with same key.

13.4 AWS client integration topology​

Step-by-step flow:

StepActionExplanation
1Generate keyBrowser stores UUID in sessionStorage (once per checkout).
2POST checkoutSPA calls ALB with Idempotency-Key.
3ProcessECS claims key; calls Stripe.
4504 pollOn timeout, return 202; SPA polls GET /orders/{id}.

AWS-specific client patterns:

PatternAWS implementation
Key persistenceBrowser sessionStorage; mobile Keychain; server orders.idempotency_key column
Timeout UXAPI returns 202 + order_id; frontend polls ALB GET /orders/{id}
Fail closed during DRSSM payments_fail_closed → ALB returns 503 via Lambda@Edge or app middleware
Static assetsCloudFront caches checkout UI; API calls bypass cache (Cache-Control: no-store)

Payment idempotency and HA/DR are inseparable: failover moves or duplicates your dedup store while clients keep retrying with the same keys. This section is a production runbook for Stripe-style payment flows across single-region active-passive, multi-region DR, and active-active — with minute-by-minute timelines, fencing rules, and recovery procedures.

Core principle: Your idempotency store and Stripe's idempotency cache must agree on outcome after any failover. When they cannot (async replication lag), Stripe is the global authority — query or retry with the same Idempotency-Key before creating a new charge.

See also: Idempotency HA/DR, CAP HA/DR.

14.1 DR vocabulary (payment idempotency lens)​

TermPayment meaningIdempotency implication
RPOMax ledger + dedup lossDedup rows missing after promotion → retry looks like new charge
RTOMax payment API downtimeLonger RTO → more client retries → more pressure on dedup
Active-passiveOne write region for paymentsSingle dedup authority — simplest for money
Active-activeMultiple regions accept writesRequires global dedup or Stripe-only authority
Split brainTwo regions both chargeWorst case — duplicate PaymentIntent unless fenced
FailbackReturn to original primaryStale east primary must not accept writes with old keys
FencingRevoke old primary IAM/credentialsPrevents double Stripe calls after promotion
Fail closed503 on mutations when dedup uncertainSafety default during promotion window

Step-by-step flow:

StepActionExplanation
1Local DBMerchant idempotency store — may lag on async DR.
2Stripe cacheGlobal 24h idempotency — retry same key.
3ReconciliationHourly backstop heals crash-window gaps.

14.2 Reference architecture — payment write path​

Recommended production topology for Pattern A (merchant + Stripe) on AWS:

Step-by-step flow:

StepActionExplanation
1NormalRoute 53 → us-east-1 ALB → ECS → Aurora primary.
2ReplicateAurora Global DB streams to us-west-2.
3Detect failureHealth checks fail; enable payments_fail_closed.
4PromoteWest Aurora promoted to writer.
5Failover DNSRoute 53 → us-west-2 ALB.
6Retry same keyClients retry; Stripe returns cached PI.

Rules:

  1. All payment mutations route to primary region only (DNS, Global Accelerator, or feature flag).
  2. Idempotency key persisted on orders row in primary DB before Stripe call.
  3. Same key sent to Stripe on every retry and after regional failover.
  4. DR region does not accept payment writes until promotion + fencing complete.

14.3 Topology 1: Single-region active-passive (hot standby)​

Use when: Mid-size merchant; single AWS region; multi-AZ HA within region.

Step-by-step flow:

StepActionExplanation
1DNSRoute 53 resolves to regional ALB.
2Multi-AZ LBALB distributes across AZ-a/b/c.
3ECS tasksStateless workers in each AZ.
4Aurora writerSingle writer; sync replicas in other AZs.
5NAT egressStripe API calls via NAT Gateway.

Failover within region (AZ-a loss):

Step-by-step flow:

StepActionExplanation
1AZ-a failsPrimary AZ becomes unreachable.
2ALB drainUnhealthy targets removed from rotation.
3ECS rescheduleTasks spin up in AZ-b and AZ-c.
4Aurora failoverWriter promoted to sync replica (~30–120s).
5Client retrySame idempotency key → dedup hit or Stripe cache.
AWS behaviorIdempotency impact
ALB removes unhealthy AZ-a targetsTraffic → AZ-b/c; same dedup DB
Aurora auto-failover writer to replicaBrief write unavailability; sync rep = RPO ≈ 0
ECS replaces tasks in healthy AZsStateless — no dedup state on task
Stripe retry same keyBackstop if dedup row lagging on new writer

Normal operation​

ComponentBehavior
App fleetActive in AZ-a; standby in AZ-b
Dedup writesAll INSERT idempotency_keys → primary
Stripe callsFrom AZ-a; Idempotency-Key on every POST
RetriesSame key → dedup hit on primary

Failover scenario — primary AZ lost (granular timeline)​

Setup: Async replication lag = 2s average. Sync replication not enabled. RPO ≈ 2s.

TimeEventIdempotency stateRisk
T+0Client POST /checkout key ord_991processing inserted primary—
T+0.15sStripe payment_intents succeeds pi_abcStripe cached key ord_991—
T+0.18sApp crashes before UPDATE completedRow still processing on primary—
T+0.5sAZ-a fails — primary DB unreachableReplica in AZ-b lagging 1.8s—
T+1sClient timeout; retries key ord_991Request hits AZ-b app—
T+2sLB promotes replica to primaryDedup row may not exist yet on replicaHIGH
T+2.1sRetry: INSERT ord_991 succeeds (looks new)Second Stripe call with same keyStripe returns cached pi_abc ✓

Outcome with Stripe as authority: Safe — second Stripe call deduped.

Outcome without Stripe key (hypothetical internal gateway): Duplicate charge unless you query gateway by key before re-charging.

TimeEvent (no gateway dedup)Result
T+2.1sSecond charge attemptDouble charge
T+3sReplication finally applies first processing rowToo late

Mitigations (single-region)​

MitigationRPOImplementation
Sync replication≈ 0Postgres synchronous_standby_names; Aurora sync replica
Fail closed during promotionN/AGlobal 503 on POST /checkout for 60–120s
Stripe same-key retryN/AAlways pass merchant key to Stripe
Sweeper + Stripe queryN/AHeal processing rows via GET /payment_intents
ReconciliationN/AHourly Stripe vs ledger

Sync replication example (RPO ≈ 0):

TimeEvent
T+0INSERT processing — commit waits for sync replica ACK
T+0.2sStripe succeeds
T+0.25sUPDATE completed — sync replicated
T+1sAZ-a fails
T+90sPromote AZ-b replica
T+91sClient retries ord_991 → dedup hit completed → no Stripe call

PACELC framing: Sync standby = PC/EC normal (+1 AZ RTT); async = PC/EL — fast writes, dedup lag risk on failover.


14.4 Topology 2: Multi-region active-passive (DR standby)​

Use when: Regional disaster tolerance required. us-east-1 active, us-west-2 warm/cold DR.

Step-by-step flow:

StepActionExplanation
1NormalRoute 53 → us-east-1 ALB → ECS → Aurora primary.
2ReplicateAurora Global DB streams to us-west-2.
3Detect failureHealth checks fail; enable payments_fail_closed.
4PromoteWest Aurora promoted to writer.
5Failover DNSRoute 53 → us-west-2 ALB.
6Retry same keyClients retry; Stripe returns cached PI.

DR failover sequence on AWS:

Step-by-step flow:

StepActionExplanation
1DetectRegion impairment; PagerDuty alert.
2Fail closedSSM payments_fail_closed=true.
3PromoteDetach/promote Aurora Global DB secondary.
4Scale westECS tasks 0 → production count.
5DNS failoverRoute 53 → us-west-2 ALB.
6ResumeDisable fail closed; clients retry same keys.
7Stripe dedupSame Idempotency-Key returns cached PaymentIntent.

Planned regional DR failover — phase-by-phase runbook​

PhaseDurationActionsIdempotency controls
0 — Detect0–3 minRoute 53 health checks fail; PagerDutyEnable payments_fail_closed feature flag globally
1 — Isolate1–5 minRevoke east DB write IAM; fence east app ENIsPrevent east from calling Stripe if partially alive
2 — Assess lag2–10 minSELECT pg_last_wal_replay_lag() on west replicaDocument effective RPO = lag at failure time
3 — Promote5–15 minPromote west DB to primary; update secretsWest must become sole write target
4 — Redirect5–30 minRoute 53 → us-west-2; scale west app fleetResume mutations only after step 3 complete
5 — Drain retries30–120 minClients retry with same keysDedup in west must serve cached responses
6 — Reconcile1–4 hFull Stripe settlement vs ledgerClose crash-window gaps
7 — CommunicateOngoingStatus page; merchant notificationDocument max duplicate window = RPO

Granular scenario — charge during region failure​

Setup: Cross-region async replication lag = 4 minutes. RPO target = 5 min. Order key ord_8f3a_20260728_001.

TimeEventEastWestStripe
T+0Customer checkoutprocessing insertedReplicating...—
T+0.2sStripe auth succeedspi_xxx created—Key cached 24h
T+0.25sApp crash before completedprocessingLag 4 min behindpi_xxx exists
T+30sus-east-1 region failureUnreachableReplica last txn T-4min—
T+2minFail closed enabled—No writes accepted—
T+12minWest DB promoted—Primary; no row for ord_8f3a—
T+15minDNS → west—App accepts traffic—
T+16minClient retries same key—INSERT processing (new to west)—
T+16.1sStripe call same key——Returns cached pi_xxx ✓
T+16.2sWest marks completed—Healed—

Without Stripe idempotency: West would create second pi_yyy → double charge.

RPO breach scenario — unacceptable without intervention​

TimeEventProblem
T+0Charge succeeds east; dedup completedRow at T+0
T+1minRegion failsWest replica last sync T-6min
T+15minPromote westDedup row never existed on west
T+16minRetry same keyWest: new processing
T+16.1sStripe same keyCached ✓ if Stripe was called
T+0 altCharge succeeded but Stripe never called (crash before gateway)West retry calls Stripe — first Stripe call — OK if only one retry wins

Edge case — east completed locally, Stripe never called, row not replicated:

State east (lost)State westClient retryOutcome
completed + pi_xxxNo rowSame key → StripeStripe returns pi_xxx — safe
processingNo rowSame key → StripeStripe may create or return in-flight — sweeper required
No row (crash before insert)No rowSame keyNew charge — correct if first never charged
completed no StripeNo rowNew key by bugDuplicate — reconciliation catches

Multi-region DR — production requirements​

RequirementImplementation
RPO ≤ idempotency TTL24h Stripe window >> 5 min RPO — retries safe if same key
Fail closed during promotionFeature flag blocks POST /checkout globally
FencingRevoke east DB credentials; security group deny east → Stripe
Stripe as global dedupMandatory — same Idempotency-Key on every regional retry
Order row has keyorders.idempotency_key set before any Stripe call
Webhook routingWebhooks still arrive globally — west must process evt_xxx dedup
ReconciliationRun immediately post-failover; compare last 24h

Client experience during 15-minute promotion​

User locationT+0 normalT+2min region downT+15min post-failover
USEast 200 ~200ms503 fail closedWest 200 or 202 pending
EUEast ~120ms (WAN)503West ~80ms (local)
Mobile (retry)Same keySame key — queuedSame key → Stripe dedup

UX pattern during failover:

  1. Return 503 with Retry-After: 60 and error_code: region_failover.
  2. Client SDK backs off; never rotates idempotency key.
  3. After west healthy: retry → 200 or 202 with order_id for polling.

14.5 Topology 3: Multi-region active-active (payments)​

Default recommendation: Do not use active-active for payment writes. Use active-active for read path (catalog, CDN) only; funnel writes to single primary per merchant_id or account_id shard.

Step-by-step flow:

StepActionExplanation
1Recommended writesAll payment writes → single region ALB.
2CDN readsCloudFront serves catalog globally.
3Anti-patternDual-region writes without global dedup.
4RiskDynamoDB Global Tables lag → duplicate charges.

If you must use DynamoDB Global Tables for dedup:

Step-by-step flow:

StepActionExplanation
1East writeECS writes idempotency key to local region.
2West writeConcurrent write before replication completes.
3Replication lag1–30s Global Tables delay.
4Duplicate riskBoth regions may call Stripe with different keys.

Split-brain duplicate charge (minute-by-minute)​

TimeEastWestStripe
T+0POST ord_991 → processing——
T+0.1sStripe pi_aaa succeededReplication lagCached ord_991 → pi_aaa
T+0.5sResponse lost; client retries——
T+0.6s—DNS resolves west; no dedup row—
T+0.7s—INSERT processing succeeds—
T+0.8s—Stripe same key ord_991Returns pi_aaa ✓ (if same key)
T+0 alt—Client bug: new key ord_991_retryCreates pi_bbb → DOUBLE CHARGE

Active-active mitigations (ranked)​

PriorityStrategyHow it worksTradeoff
1Stripe idempotency key = order keyGlobal dedup at gatewayVendor lock-in; 24h TTL
2Sticky routinghash(merchant_id) → regionTravel / DNS breaks stickiness
3Global dedup storeSpanner / DynamoDB global table with conditional write+50–150ms cross-region
4Single writer per accountRoute account_id to home region; reject foreign writesComplex routing layer
5Fail closed on cross-regionIf home_region != local → 307 redirectExtra RTT

Step-by-step flow:

StepActionExplanation
1East chargePOST with key ord_991.
2Stripe cachesPI created; key stored globally.
3Partition/lagWest has no dedup row yet.
4Safe retrySame key to Stripe → cached PI.
5Bug retryNew key → duplicate charge.

14.6 Component-level failover behavior​

AWS component failover map:

Step-by-step flow:

StepActionExplanation
1ALBRemoves unhealthy AZ targets automatically.
2ECSReplaces crashed tasks (stateless).
3AuroraAuto-failover writer to sync replica.
4Fail closedSSM flag during promotion uncertainty.
5Stripe retrySame Idempotency-Key on all retries.
6SweeperHeals orphaned processing rows.

14.6.1 Idempotency store (Aurora / DynamoDB)​

FailureBehaviorAction
Primary unreachableCannot claim keysFail closed 503 — do not call Stripe
Replica laggingReads stale dedup stateRoute payment reads to primary only
Split brain (dual primary)Duplicate INSERT possibleFence lower epoch primary immediately
Promotion in progressUncertain authorityGlobal write freeze 60–120s

Postgres promotion checklist:

-- Before accepting writes on promoted replica
SELECT pg_last_wal_replay_lag(); -- document RPO
SELECT count(*) FROM idempotency_keys
WHERE status = 'processing'
AND updated_at < now() - interval '5 minutes'; -- stuck rows

14.6.2 Stripe API (external authority)​

EventBehaviorYour action
Stripe 503/504AmbiguousRetry same key — Stripe dedupes
Regional Stripe outageRare; Stripe is globalRetry with backoff; same key
Key expired (>24h)New key requiredReconciliation + manual review
Different key same orderNew PaymentIntentPrevent in client/SDK

Stripe during your DR: Stripe does not failover with your region — same API endpoint globally. Your DR changes where your app runs, not Stripe's dedup store.

Reference: Stripe Idempotent Requests.

14.6.3 Webhook ingestor during failover​

Webhooks are global — Stripe sends to your configured endpoint regardless of which region initiated the charge.

ScenarioRiskMitigation
East down; webhook arrivesWest must processMulti-region webhook consumer OR Route 53 failover on webhook URL
Duplicate event_idAt-least-once deliveryINSERT event_id ON CONFLICT DO NOTHING
Webhook before DB promotionWest lacks order rowQueue events in SQS; replay after promotion
Webhook + API raceDouble order.paid updateUPDATE orders SET status='paid' WHERE status != 'paid'

Webhook DR pattern on AWS:

Step-by-step flow:

StepActionExplanation
1Stripe webhookGlobal delivery to Route 53 endpoint.
2Primary regionEast ALB → SQS → Lambda → Aurora dedup.
3FailoverRoute 53 flips to west ALB + SQS.
4DedupSame event_id processed once across regions.

Only one consumer processes each event_id (dedup table). During DR, Route 53 flips webhook endpoint; Stripe retries undelivered webhooks for up to 3 days.

14.6.4 Sweeper job during failover​

StateSweeper action
processing > 30sQuery Stripe by Idempotency-Key or metadata order_id
Stripe has pi_xxxMark completed; cache response
Stripe has no PISafe to retry or mark failed per policy
East downSweeper runs in west only after promotion — elect single leader

Leader election: Run sweeper as singleton — EventBridge triggers one Lambda with DynamoDB lease table or Aurora pg_advisory_lock.

AWS sweeper architecture:

Step-by-step flow:

StepActionExplanation
1TriggerEventBridge every 30 seconds.
2Acquire leaseDynamoDB lease / advisory lock (singleton).
3Scan stuckSELECT processing older than 30s.
4Query StripeGET PaymentIntent by metadata/key.
5Heal rowMark completed or failed; emit metric.

14.7 Failover scenario matrix (payments)​

ScenarioTopologyDuplicate charge riskRequired response
AZ failure, sync repSingle-region APLowPromote; retries hit dedup
AZ failure, async repSingle-region APMediumStripe same-key retry
Region disaster, async DRMulti-region APMedium–HighFail closed → promote → Stripe authority
Region disaster, sync DRMulti-region APLowGlobal write stop during partition
DNS flip mid-retryActive-activeHighSticky routing + same Stripe key
Split brain (dual primary)Misconfigured HACriticalFence; reconciliation; pause mutations
Dedup DB downAnyCriticalFail closed; no Stripe calls
Stripe timeoutAnyLow (ambiguous)Leave processing; same-key retry
Failback to eastDRMediumBidirectional sync; fence west writes
Cold backup restoreCold DRCritical24h+ dedup loss — reconciliation only

14.8 Failback procedure (return to primary region)​

StepActionIdempotency note
1Verify east region healthy—
2Stop west writes — feature flagPrevent dual writers
3Replicate west → east (catch-up)Merge idempotency_keys — completed wins
4Reconcile Stripe vs both DBsResolve any processing stuck rows
5Promote east DB to primary—
6DNS → east—
7Resume writes east—
8Scale west to read replica onlyWest dedup writes disabled

Conflict resolution for dedup rows:

East rowWest rowResolution
completedcompletedSame stripe_pi_id — OK; different PI — P1 alert
processingcompletedWest wins — mark east completed
processingprocessingQuery Stripe; single terminal state
missingcompletedCopy west row to east

14.9 RPO / RTO targets for payment idempotency​

TierRPORTODedup replicationStripe role
Tier 1 — Consumer checkout0–5s5 minSync in-region + async cross-regionSame-key retry mandatory
Tier 2 — B2B invoicing5 min15 minAsync cross-regionSame-key + sweeper
Tier 3 — Internal tools1 h4 hBackup-basedReconciliation-heavy

Formula for max duplicate window:

duplicate_risk_window = max(merchant_dedup_rpo, stripe_key_ttl_remaining)
- stripe_idempotency_protection

If merchant_dedup_rpo > 0 and Stripe was never called → reconciliation is the only backstop.


14.10 DR drill — payment idempotency checklist​

AWS game day architecture:

Step-by-step flow:

StepActionExplanation
1Inject failureAWS FIS stops east ECS/RDS.
2Fail closedSSM payments_fail_closed=true.
3Promote DBOn-call promotes Aurora west.
4DNS flipRoute 53 → west ALB.
5Synthetic traffic100 checkouts with pre-set keys.
6VerifyExactly one pi_xxx per key in Stripe.

Before drill​

  • Document RPO/RTO for idempotency_keys table separately from orders
  • Baseline: count processing, completed in last 24h
  • Baseline: Stripe Balance Transactions export
  • Verify payments_fail_closed feature flag works
  • Verify east → west replication lag metric alerting
  • Confirm all services pass same Idempotency-Key to Stripe
  • Webhook SQS queue depth baseline

During drill (inject region failure)​

  • Enable fail closed — confirm 503 on POST /checkout
  • Inject: stop east app + DB (game day)
  • Measure detection → promotion time (target RTO)
  • Promote west; fence east credentials
  • Disable fail closed
  • Replay script: 100 synthetic checkouts with pre-generated keys — some mid-processing
  • Verify: each key → exactly one stripe_pi_id
  • Verify: webhooks processed once (event_id dedup)

After drill​

  • Reconciliation: zero gaps or documented exceptions
  • Scan processing older than 5 min — must be 0
  • Compare dedup row count east vs west (post-sync)
  • Update runbook with observed RPO (replication lag at failure)
  • Postmortem: any duplicate pi_xxx? any missing orders?

Failback drill (optional quarter 2)​

  • West → east sync without dual writes
  • Conflict resolution tested on conflicting idempotency_keys
  • DNS cutback without client key rotation

14.11 On-call runbook snippets​

Alert: idempotency_processing_stuck_count > 0

  1. Query: SELECT * FROM idempotency_keys WHERE status='processing' AND updated_at < now() - interval '5 min'
  2. For each row: GET Stripe PaymentIntent by metadata order_id or retry POST with same key
  3. If Stripe has PI → mark completed; if not → mark failed or retry per policy
  4. Page payments on-call if stripe_pi_id mismatch

Alert: region_failover_initiated

  1. Enable payments_fail_closed
  2. Follow promotion runbook §14.4
  3. Do not disable fail closed until west SELECT 1 on promoted primary succeeds
  4. Run reconciliation job manually for last 24h

Alert: reconciliation_gap_count > 0

  1. Halt auto-refunds
  2. Join ledger stripe_pi_id vs Stripe export
  3. For orphan Stripe PI: create compensating ledger row or refund per policy
  4. For orphan ledger: query Stripe; possible crash before gateway call

14.12 Architecture decision summary​

If you need...Choose...Idempotency pattern
Simplest safe paymentsSingle-region + Stripe keysMerchant dedup + Stripe authority
Regional DRActive-passive DR + fail closedSame Stripe key on west retry
RPO = 0Sync cross-region or SpannerPC/EC — expensive writes
Global low-latency writesActive-active reads onlyWrites to single home region
No vendor lock-inInternal gateway with global dedupSpanner/DynamoDB conditional writes

Principal interview answer: "For Stripe integrations, I treat Stripe's idempotency cache as the global backstop across failover. My merchant dedup store must be strongly consistent in the write region and fail closed during promotion. I never run active-active payment writes without a global dedup layer — I run active-passive DR with the same Idempotency-Key on every retry, hourly reconciliation, and a game day that kills the primary mid-checkout."


15. Security, Compliance, and Operations​

15.1 AWS security architecture​

Step-by-step flow:

StepActionExplanation
1DDoSShield Standard at edge.
2WAFRate limit, geo block, OWASP rules.
3TLSCloudFront TLS 1.3 termination.
4VPC isolateECS in private subnets; SG allows ALB only.
5IAM + secretsTask role least privilege; Secrets Manager for Stripe key.
6EncryptAurora encrypted with KMS.
7AuditCloudTrail + CloudWatch Logs → S3 archive.
TopicAWS implementation
PCINever log PAN; Stripe Elements / payment_method_id only; scope reduction via SAQ A
Key entropyUUID v4 minimum; WAF rate-limit predictable keys
Tenant isolation(tenant_id, key) in Aurora; IAM condition keys per merchant
Audit logCloudWatch → Kinesis Firehose → S3 → Athena; append-only
Rate limitWAF + API Gateway usage plans or ElastiCache token bucket
Fail closedSSM payments_fail_closed + ALB health check integration

15.2 AWS observability architecture​

Step-by-step flow:

StepActionExplanation
1Emit logsECS structured JSON per charge.
2CloudWatchLogs + custom metrics dashboards.
3ArchiveS3 long-term storage.
4AlertAlarms → SNS → PagerDuty.
5QueryAthena ad-hoc audit on S3 logs.

Metrics (required):

MetricAlert threshold
idempotency_cache_hit_rateInformational — high after incidents
idempotency_processing_stuck_count> 0 for 5 min
payment_ambiguous_timeout_rate> 1% of charges
reconciliation_gap_count> 0
charge_latency_p99> 500ms

Structured logs (every charge):

{
"tenant_id": "acct_123",
"idempotency_key": "ord_8f3a_20260728_001",
"charge_id": "ch_abc",
"stripe_pi_id": "pi_xyz",
"outcome": "completed|ambiguous|failed",
"duration_ms": 142
}

16. Implementation Roadmap (8-Week Production Rollout)​

16.1 AWS services per phase​

Step-by-step flow:

StepActionExplanation
1Week 1VPC, ALB, Aurora, ECS cluster.
2Week 2–3Idempotency schema + Stripe adapter.
3Week 4SQS webhooks + consumer.
4Week 6EventBridge reconciliation.
5Week 7FIS chaos + DR game day.
6Week 8Route 53 weighted canary → 100%.
PhaseWeekAWS deliverables
0 — Design1VPC design (3 AZ), IAM roles, ADR, Threat Model in Security Hub
1 — Core dedup2Aurora schema; ECS service; ALB target group; CloudWatch logs
2 — Stripe3Secrets Manager; NAT Gateway egress; Lambda sweeper + EventBridge
3 — Ledger4Aurora migrations; SQS queue + DLQ; ECS webhook consumer
4 — Client5CloudFront + S3 SPA; CORS on ALB; 202 polling endpoint
5 — Reconciliation6EventBridge hourly; Lambda; S3 reports; SNS → PagerDuty
6 — Hardening7AWS FIS chaos (kill ECS tasks, Aurora failover); DR game day
7 — Launch8Route 53 weighted routing 1% canary; CloudWatch dashboard

Logical deliverables (cross-cutting):

PhaseWeekDeliverables
0 — Design review1ADR: state machine, schema, fail-closed policy; threat model
1 — Core dedup2idempotency_keys table; claim + cache hit; unit tests
2 — Stripe adapter3Pass-through Idempotency-Key; timeout handling; sweeper job
3 — Ledger4charges table; link to orders; webhook dedup
4 — Client SDK5JS + server libraries; key persistence; retry policy
5 — Reconciliation6Hourly job; gap dashboard; PagerDuty runbook
6 — Hardening7Load test 5K QPS; chaos (DB kill, Stripe 504); DR drill
7 — Launch8Shadow mode → 1% canary → 100%; post-launch review

Launch gates:

  • Jepsen-style concurrent duplicate test (100 parallel same-key requests → 1 charge)
  • Timeout injection test → client retry → single stripe_pi_id
  • Reconciliation zero gaps over 7-day staging soak
  • On-call runbook for processing stuck > 5 min

17. Testing Strategy​

17.1 AWS test environment architecture​

Step-by-step flow:

StepActionExplanation
1CI testsUnit/integration in pipeline.
2Staging deployECS + Aurora in isolated VPC.
3Stripe test modeTest keys in Secrets Manager.
4Load testk6 from EC2 → ALB at 5K QPS.
5ChaosFIS kills tasks / Aurora failover.
6DR drillRoute 53 failover + same-key verification.
Test typeScenarioAWS tooling
UnitHash mismatch → 422; completed → cached responseCodeBuild / local
IntegrationStripe test mode; timeout mock → retry → dedupECS staging + Stripe test keys in Secrets Manager
Concurrency50 parallel same-key requests → 1 Stripe callk6 from EC2; CloudWatch ConcurrentExecutions
ChaosKill ECS after Stripe success, before DB updateAWS FIS — aws:ecs:task-stop
DR drillPromote Aurora west; verify same-key retryRoute 53 failover + SSM fail-closed flag
ContractGolden files for API response shape on retryS3 artifact store in pipeline
ReconciliationInject orphan Stripe PI — gap detected in < 1hLambda reconciliation in staging

18. Architecture Review Checklist​

18.1 AWS production readiness diagram​

Step-by-step flow:

StepActionExplanation
1NetworkVPC 3-AZ private subnets validated.
2DataAurora Multi-AZ sync replication.
3Scale5K QPS load test passed.
4SecretsNo keys in environment variables.
5AsyncSQS + DLQ webhooks operational.
6ReconcileEventBridge hourly job running.
7AlertsCloudWatch alarms → PagerDuty.
8DRGame day completed; RPO/RTO documented.
9E2ESame-key retry → single PaymentIntent verified.
10Fail closedSSM flag tested during promotion.

Before production:

  • Idempotency key required on all mutating payment endpoints
  • Key persisted with business entity before external gateway call
  • Request hash prevents same-key-different-body bugs
  • processing state + sweeper for ambiguous timeouts
  • Gateway (Stripe) receives same key as your API
  • Webhook dedup by event_id
  • Reconciliation as backstop, not primary dedup
  • Fail closed when dedup store unavailable
  • Metrics and alerts for stuck processing and reconciliation gaps
  • Client documentation: one key per logical operation, retry policy table

20. AWS Architecture PNG Exports (Presentations)​

High-resolution AWS Architecture Icons stencil diagrams for slides, architecture reviews, and interview whiteboards. Generated with the diagrams library (official AWS icon set).

Regenerate locally:

python3 -m venv .venv-diagrams
.venv-diagrams/bin/pip install -r scripts/requirements-diagrams.txt
make generate-stripe-aws-pngs

Download: Right-click any image → Save image as…, or copy from static/img/aws-architecture/stripe-payment-idempotency/.

#DiagramUse in presentations
01End-to-end AWS stackExecutive overview slide
02VPC production (3 AZ)Principal / security review
03Pattern A — merchantMerchant integration pitch
04Pattern B — platformInternal payment platform ADR
05Aurora data layerDBA / data architecture
06DynamoDB hybridHigh-QPS idempotency design
07Request path ALB→ECSSynchronous charge flow
08Webhook SQS pipelineAsync completion deep-dive
09EventBridge reconciliationOps / finance backstop
10CloudFront SPA clientFrontend + API integration
11Single-region multi-AZHA within one region
12Multi-region DRDR strategy slide
13Active-passive vs active-activeCritical — why not dual-write
14Webhook DR failoverWebhook resilience
15Security perimeterSecurity / PCI review
16ObservabilitySRE / on-call setup
17Sweeper LambdaAmbiguous timeout recovery
18DR game dayChaos engineering / game day

01 — End-to-End AWS Stack​

End-to-end AWS stack for Stripe payment idempotency

Step-by-step flow:

StepActionExplanation
1Client requestWeb/mobile user initiates checkout with Idempotency-Key header.
2Edge routingCloudFront serves static UI; API traffic passes WAF and Route 53 to ALB.
3Load balanceALB routes to healthy ECS Fargate checkout-api task.
4Claim idempotency keyECS inserts processing row in Aurora (idempotency_keys).
5Load Stripe secretECS fetches sk_live_* from Secrets Manager.
6Call StripePOST payment_intents with same Idempotency-Key (25s timeout).
7Webhook ingestStripe sends event → webhook worker enqueues to SQS.
8Async processConsumer dedupes event_id, updates orders/charges in Aurora.
9Sweeper healLambda queries stuck processing rows; reconciles with Stripe.
10ReconciliationHourly Lambda compares Aurora ledger vs Stripe settlements.
11ObservabilityStructured logs and metrics emitted to CloudWatch.

Figure: CloudFront, WAF, Route 53, ALB, ECS, Aurora, SQS, Lambda sweeper, Secrets Manager, Stripe.

02 — VPC Production Full Stack (3 AZ)​

VPC production stack with 3 availability zones

Step-by-step flow:

StepActionExplanation
1User → edgeCloudFront + WAF + Route 53 health-checked routing.
2ALB → ECSCross-AZ load balance to checkout-api tasks.
3Claim keyINSERT idempotency_keys on Aurora writer.
4SecretsFetch Stripe API key from Secrets Manager.
5NAT → StripeEgress via NAT Gateway; POST with Idempotency-Key.
6Webhook queueStripe webhook → ALB → SQS → ECS consumer.
7SweeperLambda heals processing rows every 30s.
8ReconcileEventBridge triggers hourly Stripe vs ledger job.
9Replica syncAurora reader + cross-AZ sync for HA.

Figure: Public/private/isolated subnets, NAT gateways, Aurora writer/reader, EventBridge reconciliation.

03 — Pattern A: Merchant + Stripe​

Pattern A merchant integrating Stripe

Step-by-step flow:

StepActionExplanation
1Load UICloudFront + S3 serves checkout SPA.
2Checkout APIECS receives POST with idempotency key.
3Persist orderAurora stores order + key before Stripe call.
4Stripe chargeSame key passed to Stripe global dedup cache.
5WebhookStripe confirms → ECS updates order status.

04 — Pattern B: Internal Payment Platform​

Pattern B internal payment platform

Step-by-step flow:

StepActionExplanation
1Internal callBilling/marketplace services call Payment API.
2API gatewayALB authenticates internal service.
3Dedup claimPayment API writes idempotency store.
4LedgerImmutable charge row created.
5StripeExternal gateway with platform-owned keys.

05 — Data Layer: Aurora Multi-AZ​

Aurora multi-AZ idempotency and ledger

Step-by-step flow:

StepActionExplanation
1ECS writeAll checkout tasks write to single Aurora writer.
2Sync replicaIn-region readers serve consistent reads if needed.
3DR replicateAsync replication to us-west-2 Global DB / replica.

06 — Data Layer: DynamoDB + Aurora Hybrid​

DynamoDB idempotency with Aurora ledger

Step-by-step flow:

StepActionExplanation
1Conditional putDynamoDB PutItem claims idempotency key atomically.
2Ledger writeAurora stores orders/charges (relational integrity).
3Audit streamDynamoDB Streams → Lambda metrics/audit.

07 — Synchronous Request Path​

Request path CloudFront WAF ALB ECS Aurora Stripe

Step-by-step flow:

StepActionExplanation
1HTTPS ingressClient POST /api/checkout via CloudFront.
2WAF filterRate limit and OWASP rule check.
3ALB routeForward to healthy ECS task.
4Claim keyINSERT idempotency_keys status=processing.
5Get secretSecrets Manager returns Stripe API key.
6Stripe APIPOST payment_intents with Idempotency-Key.
7Persist resultUPDATE idempotency + INSERT charge.
8Respond200 success or 504 ambiguous to client.

08 — Webhook SQS Pipeline​

Stripe webhooks through SQS to Aurora dedup

Step-by-step flow:

StepActionExplanation
1Stripe POSTWebhook hits ALB /api/webhooks/stripe.
2Verify sigValidate Stripe-Signature HMAC.
3EnqueuePush raw event to SQS (fast ACK).
4ConsumeWorker pulls message; INSERT event_id dedup.
5Update orderIdempotent UPDATE orders SET paid.
6DLQPoison messages → DLQ → CloudWatch alarm.

09 — Reconciliation (EventBridge)​

Hourly reconciliation Lambda EventBridge S3 SNS

Step-by-step flow:

StepActionExplanation
1ScheduleEventBridge cron rate(1 hour).
2Fetch ledgerLambda reads Aurora charges for window.
3Fetch StripeList Balance Transactions from Stripe API.
4DiffJoin on stripe_pi_id; flag gaps.
5ReportWrite CSV to S3; emit reconciliation_gap_count.
6AlertSNS → PagerDuty on any mismatch.

10 — Client Integration (CloudFront SPA)​

Browser SPA sessionStorage key polling checkout API

Step-by-step flow:

StepActionExplanation
1Generate keyBrowser stores UUID in sessionStorage (once per checkout).
2POST checkoutSPA calls ALB with Idempotency-Key.
3ProcessECS claims key; calls Stripe.
4504 pollOn timeout, return 202; SPA polls GET /orders/{id}.

11 — Single Region Multi-AZ​

Single region multi-AZ ALB ECS Aurora NAT

Step-by-step flow:

StepActionExplanation
1DNSRoute 53 resolves to regional ALB.
2Multi-AZ LBALB distributes across AZ-a/b/c.
3ECS tasksStateless workers in each AZ.
4Aurora writerSingle writer; sync replicas in other AZs.
5NAT egressStripe API calls via NAT Gateway.

12 — Multi-Region DR (Active-Passive)​

Multi-region DR Route 53 Aurora Global Database

Step-by-step flow:

StepActionExplanation
1NormalRoute 53 → us-east-1 ALB → ECS → Aurora primary.
2ReplicateAurora Global DB streams to us-west-2.
3Detect failureHealth checks fail; enable payments_fail_closed.
4PromoteWest Aurora promoted to writer.
5Failover DNSRoute 53 → us-west-2 ALB.
6Retry same keyClients retry; Stripe returns cached PI.

13 — Active-Passive vs Active-Active​

Recommended single-region writes vs anti-pattern dual writes

Step-by-step flow:

StepActionExplanation
1Recommended writesAll payment writes → single region ALB.
2CDN readsCloudFront serves catalog globally.
3Anti-patternDual-region writes without global dedup.
4RiskDynamoDB Global Tables lag → duplicate charges.

14 — Webhook DR Failover​

Webhook DR Route 53 failover SQS consumers

Step-by-step flow:

StepActionExplanation
1Stripe webhookGlobal delivery to Route 53 endpoint.
2Primary regionEast ALB → SQS → Lambda → Aurora dedup.
3FailoverRoute 53 flips to west ALB + SQS.
4DedupSame event_id processed once across regions.

15 — Security Perimeter​

WAF Shield CloudFront IAM Secrets Manager KMS CloudTrail

Step-by-step flow:

StepActionExplanation
1DDoSShield Standard at edge.
2WAFRate limit, geo block, OWASP rules.
3TLSCloudFront TLS 1.3 termination.
4VPC isolateECS in private subnets; SG allows ALB only.
5IAM + secretsTask role least privilege; Secrets Manager for Stripe key.
6EncryptAurora encrypted with KMS.
7AuditCloudTrail + CloudWatch Logs → S3 archive.

16 — Observability​

CloudWatch Logs S3 Athena SNS PagerDuty

Step-by-step flow:

StepActionExplanation
1Emit logsECS structured JSON per charge.
2CloudWatchLogs + custom metrics dashboards.
3ArchiveS3 long-term storage.
4AlertAlarms → SNS → PagerDuty.
5QueryAthena ad-hoc audit on S3 logs.

17 — Idempotency Sweeper Lambda​

EventBridge Lambda sweeper DynamoDB lease Aurora Stripe

Step-by-step flow:

StepActionExplanation
1TriggerEventBridge every 30 seconds.
2Acquire leaseDynamoDB lease / advisory lock (singleton).
3Scan stuckSELECT processing older than 30s.
4Query StripeGET PaymentIntent by metadata/key.
5Heal rowMark completed or failed; emit metric.

18 — DR Game Day​

AWS FIS SSM fail closed Aurora promote Route 53 synthetic checkouts

Step-by-step flow:

StepActionExplanation
1Inject failureAWS FIS stops east ECS/RDS.
2Fail closedSSM payments_fail_closed=true.
3Promote DBOn-call promotes Aurora west.
4DNS flipRoute 53 → west ALB.
5Synthetic traffic100 checkouts with pre-set keys.
6VerifyExactly one pi_xxx per key in Stripe.