Guiding on System Architecture
The user is asking for insights on architecture, retry patterns, idempotency keys, reconciliation jobs, and metrics. I should be concise but thorough, covering aspects like synchronous vs. asynchronous processing.
I'll mention patterns like the outbox pattern and state machines, focus on handling webhooks while avoiding double charges. Including examples like those from Stripe will be helpful, and I should cover practices like exponential backoff and error categorization.
I'll organize response sections in markdown for clarity, ensuring I mention regulatory aspects like PCI compliance and use checklists for best practices.
Below is a practical blueprint for a resilient payment processor integration that handles retries, idempotency, reconciliation, and alerts—and remains correct under timeouts, duplicate webhooks, partial failures, and processor outages.
1) Core principles (what you’re designing for)
You can’t get “exactly once” over the network
Assume at-least-once delivery of:
- your requests to the processor (because you retry),
- the processor’s webhooks to you (because they retry),
- your internal message processing (because workers restart).
Correctness comes from:
- idempotency (dedupe) + durable state (DB) + reconciliation (verify).
Separate “initiation” from “finalization”
Treat payment flow as a state machine:
CREATED (internal intent/order created)
SUBMITTED (request sent)
PENDING (processor accepted, awaiting final status)
SUCCEEDED / FAILED / CANCELED
UNKNOWN (timeout or ambiguous response; requires follow-up)
Never ship goods / grant entitlement until you reach a terminal “paid” state.
2) Idempotency (your #1 tool to prevent double charges)
2.1 Use a stable internal idempotency key
For “charge customer for order X”, the idempotency key should be stable and unique to the business operation, e.g.:
idem_key = "order:" + order_id + ":payment_attempt:" + attempt_number
- If user clicks “Pay” twice for the same order attempt, you reuse the same key.
- If user intentionally retries with a new attempt (new card, after failure), increment attempt number.
2.2 Store every attempt durably before calling the processor
Create a table like:
payment_attempts
id (UUID)
order_id
attempt_no
idempotency_key (unique)
amount, currency
processor (e.g., Adyen/Stripe/etc.)
processor_payment_id (nullable, unique when present)
status (CREATED/SUBMITTED/PENDING/SUCCEEDED/FAILED/UNKNOWN)
last_error_code, last_error_message
created_at, updated_at
Enforce uniqueness:
UNIQUE(idempotency_key)
UNIQUE(processor_payment_id) (when available)
2.3 Pass idempotency to the processor too
Most processors support an idempotency key / reference field. Use the same stable key (or a derived one) so the processor dedupes as well.
Also include your own reference IDs in processor “metadata” fields:
order_id
payment_attempt_id
idempotency_key
These become essential for reconciliation.
3) Retry strategy (when, how, and what not to retry)
3.1 Categorize failures
Treat errors as:
A) Safe to retry (transient):
- network timeouts
- connection resets
- 5xx from processor
- rate limits (429)
- “temporarily unavailable”
B) Not safe to retry automatically (likely permanent):
- invalid card / insufficient funds
- invalid parameters (bug)
- authentication/signature failures (config)
- “do not honor” (depends—often terminal)
C) Ambiguous (must reconcile):
- timeout after sending request
- unknown response / parse failure
- client got 502 but processor may have processed
For category C, don’t blindly “charge again”; instead:
- query processor by idempotency key / reference, or
- mark attempt
UNKNOWN and let reconciliation resolve.
3.2 Backoff with jitter
Use exponential backoff with jitter, bounded:
- initial: 250–500ms
- multiplier: 2x
- max: 30–60s
- max attempts: 5–8 (or time-based cap like 10 minutes)
3.3 Timeouts and circuit breaker
- Set tight client timeouts (connect + read).
- Use a circuit breaker to avoid dogpiling during processor outage.
- If breaker is open, fail fast and move to
PENDING/UNKNOWN for async resolution.
3.4 Make retries idempotent internally too
If your worker crashes after sending the request but before saving the processor ID, the next run must not double-charge. This is why you:
- save attempt row first,
- reuse the same idempotency key,
- and/or query processor for prior result.
4) Durable execution: Outbox / queue pattern
A common robust flow:
- API receives
POST /orders/{id}/pay
- DB transaction:
- create
payment_attempt (status CREATED)
- write an outbox event
PaymentAttemptCreated(attempt_id)
- Background worker reads outbox and calls processor
- Worker updates
payment_attempt status and stores processor IDs
- Webhooks also update status (idempotently)
This avoids “request succeeded but we crashed before enqueueing” and similar gaps.
5) Webhooks: idempotent, ordered, and verify-first
5.1 Verify authenticity
- Validate signature / HMAC
- Validate timestamp / replay protection where supported
Rejecting forged webhooks is non-negotiable.
5.2 Idempotent webhook handling
Store webhook deliveries:
webhook_events
id (processor event id; unique)
type
received_at
payload_hash
processed_at
processing_status
On receipt:
INSERT ... ON CONFLICT DO NOTHING
- If already exists, return 200.
5.3 Handle out-of-order events
Webhooks can arrive out of order (e.g., “captured” before “authorized”).
Implement a state machine with allowed transitions and/or “latest wins” rules keyed by processor event time/sequence.
5.4 Don’t trust only webhooks
Webhooks can be delayed for hours. You still need:
- polling/reconciliation for “stuck pending”
- periodic verification of account balances/transactions
6) Reconciliation (how you guarantee correctness over time)
6.1 Two levels of reconciliation
A) Near-real-time “stuck” resolver (minutes):
- Find attempts in
PENDING/UNKNOWN older than, say, 5–15 minutes
- Query processor by:
- processor_payment_id (if known), else
- idempotency key / merchant reference
- Update status accordingly
- If still unknown after threshold, raise alert
B) Daily financial reconciliation (hours/days):
- Pull processor settlement/transaction reports for a time range
- Compare to your internal ledger:
- count and sum by currency
- per-transaction matching by reference
- Detect:
- processor succeeded but you’re not marking succeeded (lost webhook / bug)
- you marked succeeded but processor shows failed/refunded/chargeback
- duplicates
- amount mismatches, currency mismatches, partial captures
6.2 Use a ledger (recommended)
Maintain an internal double-entry ledger or at least immutable journal entries:
authorization, capture, refund, chargeback, fee
So “what happened” is append-only and auditable.
6.3 Tolerances and batching
- Some processors batch settlement; settlement date may differ from auth/capture date.
- Expect delays; reconcile within known windows.
7) Alerts & observability (what to page on vs dashboard)
7.1 Metrics to collect
Reliability
- payment request success rate
- timeout rate
- retry count distribution
- webhook receive rate vs expected
- webhook processing lag (received_at → processed_at)
- percent of attempts in
PENDING/UNKNOWN > X minutes
Financial integrity
- reconciliation mismatch count/amount
- duplicates prevented (idempotency hits)
- processor-to-internal unmatched transactions
Performance
- p95/p99 latency for create/confirm
- processor API latency and error rates
7.2 Alert thresholds (examples)
Page (urgent):
- reconciliation mismatch amount > $X (or > N transactions) within last day
- spike in
UNKNOWN > baseline (e.g., >1% for 10 min)
- webhook signature failures > 0 (possible attack/config issue)
- processor 5xx/timeout rate > Y% for 5 min
- outbox backlog age > Z minutes
Non-page (ticket/dashboard):
- increased declines by reason
- increased retries but still successful
- settlement delays
7.3 Logging: what to log safely
Log:
- internal IDs (order_id, attempt_id)
- processor IDs
- error codes, request IDs/correlation IDs
- idempotency key
- state transitions
Do not log PAN/card data; keep PCI scope tight.
8) Recommended end-to-end flow (reference implementation outline)
8.1 Initiation endpoint (synchronous)
- Create payment attempt (DB transaction)
- Return
attempt_id + client action instructions (redirect/SDK token)
- Client completes authentication if required (3DS etc.)
- Final result comes via webhook/polling
8.2 Worker (async) calling processor (pseudo)
process_attempt(attempt_id):
attempt = load(attempt_id)
if attempt.status in TERMINAL: return
mark SUBMITTED if status == CREATED
try:
resp = processor.create_or_confirm_payment(
amount, currency,
idempotency_key=attempt.idempotency_key,
reference={order_id, attempt_id}
)
save processor_payment_id if present
if resp.final == true:
transition to SUCCEEDED/FAILED
else:
transition to PENDING
catch transient_error:
retry with backoff
catch ambiguous_timeout:
transition to UNKNOWN
catch permanent_error:
transition to FAILED
8.3 Webhook handler (pseudo)
handle_webhook(event):
verify_signature(event)
inserted = insert_webhook_event_if_new(event.id)
if !inserted: return 200
attempt = find_attempt_by_processor_id_or_reference(event)
if attempt missing:
alert "unmatched webhook" (but still store event)
return 200
apply_state_transition(attempt, event)
return 200
9) Common pitfalls to avoid
- Retrying “create charge” without idempotency on timeouts ⇒ double charges.
- Relying solely on webhooks for final state ⇒ stuck orders during webhook delays.
- Not persisting processor reference IDs ⇒ impossible reconciliation.
- Mixing “payment status” with “order fulfillment” without a clear gate ⇒ shipping unpaid orders.
- Not handling duplicate/out-of-order webhooks ⇒ flip-flopping states.
If you share:
- which processor (or whether it’s abstracted),
- whether you do auth/capture separately,
- whether you support refunds/chargebacks,
- your current architecture (sync API only vs queue/outbox),
I can propose a concrete state machine and table/event schema tailored to it.