Stripe retry and idempotency behaviour is from Stripe's docs, checked on 14 November 2026. Volumes on this page are labelled assumptions for the arithmetic, not benchmarks.
A payment system takes a request to move money, gets a payment service provider (PSP) to move it, and keeps an exact record of what happened, even when the network, the PSP or your own servers fail halfway through. The design isn't hard because of volume. It's hard because an API call that times out may still have charged the card.
1. Requirements
Functional: create a payment, confirm it (including 3D Secure when the issuer asks), capture, refund in full or in part, receive PSP webhooks, record every money movement, reconcile against PSP and bank reports.
Non-functional, in priority order:
- Never charge twice. Idempotency at every boundary.
- Never lose a payment. Every state change is durable, and every event about it is eventually delivered.
- Auditable. Every cent traceable from charge to bank deposit.
- Available, but correctness wins: when the outcome is unknown, the system says "unknown" and finds out, rather than guessing.
Say these out loud in an interview before drawing anything. Most candidates jump to throughput, and payments is the domain where consistency beats it.
2. Components
| Component | Job | Why it's separate |
|---|---|---|
| Payments API | Accepts requests from your checkout or backend, requires an Idempotency-Key header | One front door with one idempotency rule |
| Payment service | Owns the payments table and the state machine | The only writer of payment state |
| PSP adapter | Translates to Stripe, Adyen, PayPal; classifies errors | Provider quirks stay in one place; orchestration plugs in here |
| Ledger | Double-entry record of every money movement | Balances are derived and checkable (payments ledger) |
| Outbox and relay | Publishes payment events in the same transaction as the state change | No lost events between the commit and the queue (outbox pattern) |
| Webhook ingestion | Verifies signatures, dedupes, enqueues, returns 2xx fast | PSPs retry and duplicate; the handler has to absorb both |
| Reconciliation | Compares your records with PSP and bank reports | Catches what the other components missed |
3. The flow
- Client calls
POST /paymentswith an idempotency key. The API stores the key with the request; a retry with the same key gets the stored response back. - Payment service inserts the payment as
created, and calls the PSP adapter. - The adapter calls the PSP with its own idempotency key derived from the payment ID, so every attempt for this payment carries the same key.
- The PSP answers
succeeded,requires_action(3DS: hand the client what it needs and wait),processing, or a decline. Or it doesn't answer. - The payment service applies the result, and in the same transaction writes the outbox event and, for money that moved, the ledger entries.
- The PSP's webhook arrives later (and maybe twice). Ingestion verifies it, dedupes on the event ID, and the payment service applies it through the same state machine.
- Nightly, reconciliation matches payments, PSP balance transactions and bank deposits, and raises what doesn't match.
4. The state machine
Model the payment as a state machine with an explicit list of legal transitions, and reject everything else: created, requires_action, processing, succeeded, failed, then partially_refunded, refunded and disputed after success (payment lifecycle states). Add one state most designs forget: unknown, for when you asked the PSP and didn't get an answer. The chapter 5 excerpt below has a full transition table.
5. Idempotency at three boundaries
| Boundary | Duplicate comes from | Guard |
|---|---|---|
| Client to you | Double-clicks, mobile retries, your load balancer | Idempotency-Key on POST /payments, stored with the response |
| You to the PSP | Your own retries after a timeout | The PSP's idempotency key, derived from the payment ID, same on every attempt (idempotency keys) |
| PSP to you | Webhook retries and duplicate deliveries | Dedupe on the event ID in the same transaction as the effect (duplicate webhooks) |
6. Failure modes
A timeout with an unknown outcome. The defining failure. Stripe's docs say a network error means you might not know whether the request was received or executed; retry with the same idempotency key and parameters within 24 hours, and after that stop and reconcile, rather than retry with any key. A 500 is the same: "treat the outcome ... as indeterminate" (Stripe). Two corollaries: never retry with a fresh key, and never fail over to a second PSP on a timeout, because the first one may have charged the card. Chapter 18's execution engine, below, stops on exactly this case.
import stripe
def charge(payment):
"""One payment, one idempotency key, for every attempt, for its whole life."""
try:
intent = stripe.PaymentIntent.create(
amount=payment.amount_minor,
currency=payment.currency,
customer=payment.customer_id,
payment_method=payment.payment_method_id,
confirm=True,
off_session=True,
metadata={"payment_id": str(payment.id)}, # find it again later
idempotency_key=f"pay-{payment.id}-confirm", # derived, not random
)
except stripe.CardError as exc:
return payment.mark_failed(exc.code) # a real answer: declined
except (stripe.APIConnectionError, stripe.APIError):
# Timeout, dropped connection or 5xx: the charge MAY have happened.
# Don't fail over to another provider and don't mint a new key.
return payment.mark_unknown() # a worker retries with the same key,
# then reconciles if it stays unknown
return payment.apply_provider_status(intent.status)
Duplicate and out-of-order webhooks. Stripe retries for up to three days in live mode, doesn't guarantee order, and may deliver the same event more than once (Stripe). Dedupe on the event ID; for order, treat the webhook as a hint and fetch the object's current state, or refuse transitions the state machine doesn't allow.
A crash between the database write and the publish. Solved by the outbox: the event is written in the same transaction.
A webhook that never arrives. Your endpoint was down for longer than the retry window, or the event was filtered out. A sweeper that queries the PSP for payments stuck in processing or unknown past a threshold, plus nightly reconciliation, catches it.
The PSP is down. A circuit breaker stops you hammering it. Failing over to another PSP is safe only for errors that prove the request was never accepted (connection refused, an explicit "not processed"), never for a timeout.
A refund after the payout. The PSP balance can go short. That's a ledger entry and a cash-flow question, not a bug, provided the ledger records it.
7. Scaling, with the assumptions shown
Size from your own volume, not a headline. Two assumptions for illustration:
- Assume 1,000,000 payments a day. Average: 1,000,000 / 86,400 seconds = about 11.6 payments per second.
- Assume your busiest minute runs at 10x that average (measure yours; it's the number that matters). Peak: 11.6 x 10 = about 116 payments per second.
Each payment touches several rows. With the worked example's charge (one payment row, one outbox row, three ledger entries), that's 5 row writes, so at the assumed peak about 116 x 5 = 580 row writes per second before webhooks, refunds and reconciliation. Whether that's comfortable depends on your database and hardware, which is why chapter 21 tells you to load test at a multiple of your own measured peak. What usually breaks first isn't the payment write path; it's something slow and synchronous on it, like an email send, a CRM call, or a PSP with no timeout.
The scaling moves that keep correctness: partition the payments table by time, keep slow work behind the queue, put a timeout and a circuit breaker on every PSP call, and shard by merchant or customer only when one primary truly can't keep up, so a payment's state, outbox rows and ledger entries stay in one transaction.
The failover loop that separates a decline, a provider that never accepted the request, and a timeout with an unknown outcome. From chapter 18.
Payment Execution Engine (Where the Magic Happens)
The execution engine is where all your careful routing decisions meet reality. This is the part that actually tries to charge the customer's card, handles failures gracefully, and automatically tries the next provider if needed.
We call this "cascading resilience" - if provider A fails, immediately try provider B, then C if needed. The customer never knows about the drama happening behind the scenes.
Implementation: src/examples/18-orchestration/payment_orchestrator.py
Cascading Execution Pattern (Conceptual):
# Automatic failover pattern (conceptual)
async def process_payment(payment_id, context):
# Get routing chain from orchestrator
routing_chain = orchestrator.route_payment(context)
# [(STRIPE, PRIMARY), (ADYEN, FALLBACK), (BRAINTREE, FALLBACK)]
# Try each provider in order
for provider, reason in routing_chain:
try:
result = attempt_payment(provider, payment_id, context)
if result.status in [SUCCEEDED, REQUIRES_ACTION]:
log_success(provider, reason, result)
return result # Success!
log_failure(provider, reason, result)
if result.is_hard_decline:
# The issuer said no to this card. Another provider reaches
# the same issuer, and retrying looks like card testing.
return result
except TimeoutError as e:
# Unknown outcome: the charge may have gone through. Failing over
# now risks a double charge, so stop and reconcile this provider.
log_error(provider, reason, e)
return PaymentResult(PENDING_RECONCILIATION, "Outcome unknown")
except ProviderUnavailableError as e:
# Rejected before processing (connection refused, or a connect
# timeout before the request was sent): safe to try the next one.
log_error(provider, reason, e)
continue
# All providers failed
return PaymentResult(FAILED, "All providers exhausted")
The complete implementation includes provider-specific API translation (Stripe, Adyen, Braintree), error handling, metrics collection, and circuit breakers. See src/examples/18-orchestration/README.md for full code.
A transition table that rejects impossible moves, and a retry budget so a broken payment can't loop forever. From chapter 5.
2. Handle State Transitions Properly
Not all state transitions are valid. Build validation into your system:
MAX_RETRIES = 3
# Authoritative internal state machine. Keys are current states; values are
# the set of states they may legally transition to. Provider-specific status
# strings (Stripe, PayPal, etc.) must be translated into this vocabulary
# before validation - see the webhook handler below.
VALID_TRANSITIONS = {
'intent_created': ['payment_method_attached', 'failed', 'expired'],
'payment_method_attached': ['processing', 'failed', 'expired'],
'processing': ['requires_action', 'succeeded', 'failed'],
'requires_action': ['processing', 'succeeded', 'failed', 'expired'],
'succeeded': ['refunded', 'partially_refunded', 'chargeback_pending'],
'partially_refunded': ['refunded', 'chargeback_pending'],
'refunded': [], # Terminal
'chargeback_pending': ['chargeback_won', 'chargeback_lost'],
'chargeback_won': [], # Terminal (merchant kept funds)
'chargeback_lost': [], # Terminal (funds clawed back)
'failed': ['pending_retry'], # Only via retry_with_budget()
'pending_retry': ['processing', 'failed'],
'expired': [], # Terminal
}
def transition_payment_state(payment_id, new_state):
payment = get_payment(payment_id)
if new_state not in VALID_TRANSITIONS[payment.status]:
raise InvalidStateTransition(
f"Cannot transition from {payment.status} to {new_state}"
)
payment.status = new_state
payment.updated_at = datetime.now()
payment.save()
def retry_with_budget(payment):
"""
The ONLY supported path out of `failed`. Enforces a retry budget so a
permanently broken payment cannot loop forever. Call this instead of
transitioning `failed -> processing` directly.
"""
if payment.status != 'failed':
raise InvalidStateTransition(
f"retry_with_budget only valid from 'failed', got {payment.status}"
)
if payment.retry_count >= MAX_RETRIES:
# Out of budget - leave the payment in `failed` and surface to ops.
raise RetryBudgetExhausted(
f"Payment {payment.id} exhausted {MAX_RETRIES} retries"
)
payment.retry_count += 1
transition_payment_state(payment.id, 'pending_retry')
# The retry worker will pick this up and move pending_retry -> processing.
Use a state machine pattern to enforce valid transitions. This prevents impossible states like going from "succeeded" to "processing" and makes your code much easier to reason about. Libraries like python-statemachine or statesman (Ruby) can help formalize this.
Turning daily volume into transactions per second, and why you plan around your peak minute, not the average. From chapter 21.
Throughput Targets
Size throughput from your own numbers, not someone else's headline. Average TPS is daily transactions divided by 86,400: 10,000 payments a day is about 0.12 TPS, and 1 million a day is about 12. Traffic isn't flat, so measure your busiest minute over the last year and express it as a multiple of that average. That multiple, not the average, is the number to plan around.
| Scale | TPS | Use Case |
|---|---|---|
| Normal | Your measured peak minute | Day-to-day operation |
| Target | 10x that peak | Black Friday ready |
| Spike | Whatever your last flash sale did, then double it | Flash sale survival |
Black Friday traffic can run many times your normal peak, and last year's ratio is the best predictor you have. Test at 10x your peak expected traffic to find breaking points before they find you.
What interviewers probe
If this is for a system design interview, expect follow-ups on the same few seams. How do you avoid charging twice when the client retries? (Idempotency key, stored response.) What if the PSP call times out? (Unknown state, same-key retry, then reconcile; no failover.) How does fulfilment learn the payment succeeded? (Outbox, at-least-once, idempotent consumer.) How do you know the books are right? (Double-entry ledger, three-way reconciliation.) Where does it break at ten times the volume? (Whatever synchronous call you left on the request path.) A design that answers those five is a better answer than one with more boxes.
Questions
How do you design a payment system?
Start from the requirements: never charge twice, never lose a payment, keep it auditable. Then the components: a payments API with idempotency keys, a payment service that owns the state machine, a PSP adapter, a double-entry ledger, an outbox for events, webhook ingestion that verifies and dedupes, and reconciliation against PSP and bank reports.
What happens when a payment API call times out?
The outcome is unknown: the charge may have gone through. Mark the payment unknown, retry with the same idempotency key and parameters (Stripe says within 24 hours), and if it's still unresolved, reconcile by looking the payment up rather than retrying. Never retry with a new key or fail over to another provider on a timeout.
How do you prevent double charges in a payment system?
Idempotency at three boundaries: an idempotency key from the client on your own API, a key derived from the payment ID on every call to the PSP, and deduplication on the event ID for incoming webhooks.
What components does a payment system need?
A payments API, a payment service with the state machine, a PSP adapter, a double-entry ledger, an outbox and relay for events, webhook ingestion, and reconciliation. Each one exists to handle a specific failure: retries, provider quirks, lost events, duplicates and missed records.
How do you size a payment system?
From your own volume. Divide daily payments by 86,400 for the average per second, then plan around your measured peak minute, which is a multiple of that. As an assumption, 1,000,000 payments a day averages about 11.6 per second, and a peak at 10 times average would be about 116 per second.