Payment and Transaction Processing Systems Questions
Designing systems that move money correctly: idempotent payment flows, exactly-once semantics, reconciliation, ledgers, double-entry accounting, and fraud-detection architecture. Covers handling retries and partial failures without double-charging, and the consistency guarantees payments demand. Also covers protecting cardholder data through tokenization and PCI scope reduction, reconciling processor webhooks, and merchant and partner payouts. A high-stakes specialization of distributed transactions.
You must consume webhooks from a third-party payment provider reliably. Design a robust integration strategy that handles duplicate deliveries, out-of-order webhooks, signing and authentication, and replay protection, with sensible retry behavior. Explain how you would test this integration and how you would operate it in production.
Sample Answer
Direct answer
Split the integration into a thin, fast receiver and a separate processor. The receiver verifies the provider's signature on the raw body, rejects stale timestamps (replay protection), stores the event once keyed by the provider's event ID, and returns 2xx within milliseconds. The processor applies events idempotently (applying the same event twice has the same effect as applying it once) and treats each one as a hint: it moves our records only forward, and for anything that matters it re-reads the object from the provider's API, so duplicates and out-of-order deliveries cannot corrupt state. Retries are the provider's job for delivery and ours for processing (backoff, then a dead-letter queue), and a reconciliation job closes whatever webhooks miss.
What the provider actually guarantees (and what it does not)
A webhook is an HTTP POST the provider sends to our endpoint when something happens (a payment succeeds, a dispute opens). Taking Stripe as the concrete example (other providers are similar, check each one's documentation):
- Delivery is at-least-once: the same event can arrive more than once, and occasionally two different event objects describe the same change.
- Order is not guaranteed:
invoice.paidcan arrive beforeinvoice.created, and event timestamps have one-second resolution, so they cannot be used to order events. - Undelivered events are retried for up to three days with exponential backoff in live mode. A non-2xx response or a timeout counts as a failure.
- Each delivery carries a
Stripe-Signatureheader:t=<unix timestamp>,v1=<hex HMAC-SHA256>computed over the stringtimestamp + "." + raw bodywith the endpoint's signing secret. HMAC is a keyed hash: only someone holding the secret can produce a matching value. The official libraries reject timestamps more than 5 minutes old by default.
So the design has to supply deduplication, ordering tolerance and replay protection itself.
Architecture
flowchart LR
PR[Provider] -->|POST event| LB[TLS load balancer]
LB --> RX[Receiver: verify, store, 2xx]
RX --> INBOX[(Inbox table: unique event_id)]
INBOX --> Q[Queue]
Q --> W[Processor workers]
W -->|re-read object| API[Provider API]
W --> DB[(Payments + ledger)]
W -->|after N failures| DLQ[Dead-letter queue]
RECON[Reconciler: list events and objects] --> DB
1. Receiver: authenticate, persist, acknowledge
- Read the raw bytes of the body before any JSON parsing (re-serialised JSON changes whitespace and breaks the signature).
- Verify the
v1signature with a constant-time comparison (so response timing does not leak how many characters matched), ignoring any other scheme, and check the timestamp is within tolerance. INSERT INTO webhook_inbox(event_id, type, object_id, payload, received_at) ON CONFLICT (event_id) DO NOTHING.- Return 200. No business logic here: slow handlers time out, timeouts trigger provider retries, and retries multiply load exactly when the system is struggling.
Signature failures return 400 and are counted; they should be near zero, and a spike means a rotated secret or an attack.
2. Deduplication
- Event-level: the unique
event_idin the inbox. - Effect-level: every side effect has its own guard. Marking an order paid is
UPDATE ... WHERE status <> 'paid'; posting a ledger entry has a unique key(payment_id, entry_type); sending a receipt goes through an outbox keyed by(payment_id, 'receipt'). This catches the case of two distinct event IDs for the same change, which event-ID dedupe alone misses.
3. Out-of-order events
Pick one of two strategies per resource type, not a global one:
| Strategy | How | Use when |
|---|---|---|
| Forward-only state machine | Rank states (requires_capture < succeeded < refunded); ignore an event whose state ranks at or below the current one | Linear lifecycles such as a payment |
| Re-fetch on every event | Ignore the payload's snapshot; call the provider's API for the object's current state and apply that | Objects that can move backward or have many fields (subscriptions, disputes); the default for money-moving decisions |
Re-fetching costs one API call per event (about 93 extra reads/second at the load below), which is cheap insurance. Serialise processing per object ID (partition the queue by object_id) so two workers never apply two events for the same payment concurrently.
4. Replay protection
- The signed timestamp bounds how long a captured request stays usable: an attacker who records a valid delivery cannot resend it an hour later. Keep server clocks on NTP (Network Time Protocol) so a skewed clock does not reject real events.
- Within the tolerance window, a replay is just a duplicate and the inbox's unique key absorbs it.
- Optionally allow-list the provider's published source IP ranges at the load balancer as a second layer; never as the only one.
5. Retry behaviour on our side
- Delivery retries belong to the provider; we just must return 2xx once the event is safely stored, even if processing later fails.
- Processing retries: exponential backoff with jitter (random spread so failures do not retry in lockstep), for example 1 s, 2 s, 4 s ... capped at 5 minutes, up to 8 attempts, then move the event to a DLQ (dead-letter queue: a holding area for messages that repeatedly failed, for a human or a fixed version of the code to replay).
- Poison events (a type we do not understand, a payload that fails validation) go to the DLQ immediately rather than burning retries.
A runnable check of the core rules
The program below signs events the same way, delivers three state changes for one payment shuffled with one duplicate, then tries a tampered body and a one-hour-old replay. Standard library only; the shuffle seed is pinned.
import hashlib, hmac, json, random
SECRET = b"whsec_test_secret"
TOLERANCE_S = 300
def sign(body: bytes, ts: int) -> str:
mac = hmac.new(SECRET, f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
return f"t={ts},v1={mac}"
def verify(body: bytes, header: str, now: int) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
ts = int(parts["t"])
expected = hmac.new(SECRET, f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, parts.get("v1", "")):
return False
return abs(now - ts) <= TOLERANCE_S # replay window
# Payment state machine: a status may only move forward.
RANK = {"requires_capture": 1, "succeeded": 2, "refunded": 3}
seen_event_ids = set() # in production: a unique-keyed table, written in the same transaction
payments = {} # payment_id -> status
def handle(body: bytes, header: str, now: int) -> str:
if not verify(body, header, now):
return "rejected"
ev = json.loads(body)
if ev["id"] in seen_event_ids:
return "duplicate"
seen_event_ids.add(ev["id"])
pid, new = ev["payment_id"], ev["status"]
old = payments.get(pid)
if old is not None and RANK[new] <= RANK[old]:
return f"stale ({new} after {old})"
payments[pid] = new
return f"applied -> {new}"
events = [{"id": f"evt_{i}", "payment_id": "pay_1", "status": s}
for i, s in enumerate(["requires_capture", "succeeded", "refunded"], 1)]
rng = random.Random(3)
deliveries = events + [events[1]] # one duplicate delivery
rng.shuffle(deliveries) # out of order
now = 1_700_000_000
for ev in deliveries:
body = json.dumps(ev).encode()
print(ev["id"], ev["status"], "=>", handle(body, sign(body, now - 10), now))
body = json.dumps(events[0]).encode()
print("tampered =>", handle(body.replace(b"pay_1", b"pay_9"), sign(body, now), now))
print("replayed 1h later =>", handle(body, sign(body, now - 3600), now))
print("final state:", payments)
Output:
evt_2 succeeded => applied -> succeeded
evt_1 requires_capture => stale (requires_capture after succeeded)
evt_3 refunded => applied -> refunded
evt_2 succeeded => duplicate
tampered => rejected
replayed 1h later => rejected
final state: {'pay_1': 'refunded'}
The late requires_capture event cannot drag the payment backward, the duplicate is dropped, and both the tampered and the stale deliveries fail verification.
Load and sizing (assumed numbers)
2,000,000 payments/day x 4 events each = 8,000,000 events/day, which is 8,000,000 / 86,400 = about 93 events/second on average. Subscription renewals at the start of a month can spike 20x, to about 1,850/second. The receiver does one signature check and one indexed insert per event, so a few stateless instances behind the load balancer absorb that; the queue lets processors drain the spike at their own pace instead of the spike hitting the database.
How to test it
- Unit tests: signature verification against known vectors (valid, wrong secret, modified body, timestamp just inside and just outside tolerance, header with several
v1values during a secret rotation, extra unknown schemes); state-transition rules for every pair of states. - Property-style tests: generate a random sequence of valid lifecycle events, deliver them in every permutation with random duplicates, and assert the final state equals the state after in-order delivery. The small program above is one instance of that property.
- Integration tests with the provider's tooling: Stripe's CLI can forward test-mode events to a local endpoint (
stripe listen --forward-to) and trigger specific event types (stripe trigger payment_intent.succeeded); use them to exercise real payloads and real signatures. - Failure injection in staging: make the processor fail for 10 minutes and confirm events pile up in the queue and drain afterwards; return 500 from the receiver and confirm the provider's retries are absorbed as duplicates; kill a worker mid-transaction and confirm nothing is half-applied.
- Contract drift: pin the provider API version your endpoint receives, and test a version upgrade against recorded payloads before switching.
How to operate it in production
- SLOs (service-level objectives): for example 99.9% of deliveries acknowledged within 500 ms, and 99% of events processed within 60 s of receipt.
- Dashboards and alerts: receive rate by type (a drop to zero is itself an incident: a firewall change or a disabled endpoint), signature-failure rate, inbox-to-processed lag, age of the oldest unprocessed event, DLQ depth, and the provider's own delivery-failure view.
- Reconciliation as the safety net: every hour, list recent events from the provider's events API and compare against the inbox; daily, compare payment objects and settlement reports with the ledger. Webhooks are the fast path, not the only path.
- Secret rotation: Stripe lets the old signing secret stay valid for up to 24 hours after rolling, sending one signature per active secret; deploy the new secret to the verifier during that overlap.
- Runbooks: replaying from the DLQ after a fix, backfilling a window of missed events, and disabling a single event type's processing without dropping the rest.
Trade-offs and pitfalls
- Processing inline in the HTTP handler is the most common failure: it couples provider retries to your database latency.
- Deduping only on event ID misses duplicate changes carried by different events; guard effects too.
- Trusting payload snapshots for money decisions lets a stale event win; re-read the object.
- Using a tolerance of zero in some libraries disables the timestamp check entirely rather than making it strict.
- What would change the design: at very low volume, a single table plus a cron worker is enough (no queue); if the provider offers direct delivery into a cloud event bus, you can drop the public receiver and inherit the bus's retry and dead-letter features, while keeping the same idempotent processor.
Your primary payment processor experiences an extended outage. Design a disaster recovery plan that ensures merchants can continue accepting payments (or degrade gracefully), eventual settlement and reconciliation occur correctly, fees and mapping are handled for backup processors, and customers and regulators are informed as required.
Sample Answer
Direct answer
Plan for three things in order: keep taking payments by routing new authorizations to a pre-integrated backup processor (and degrading payment methods that cannot move), never lose or double-count money by freezing every in-flight transaction with the primary as "unknown" until the primary can be asked what happened, and settle and reconcile per processor afterwards, because each processor pays out, charges fees and reports in its own way. Communication runs on a pre-agreed clock: merchants and customers through status pages and API signals within minutes, regulators and card-scheme partners according to their incident-reporting obligations.
Key terms
- Processor / PSP (payment service provider): the company that sends card authorizations to the card networks and later pays out the money.
- Authorization: the issuing bank approves and places a hold on funds. Capture: the merchant claims the held funds. Settlement: the processor actually transfers the money, usually a day or more later, minus fees.
- Reconciliation: matching what your own records say should have happened against what processors and banks report did happen.
- Circuit breaker: logic that stops sending traffic to a failing dependency once errors cross a threshold, then probes it periodically.
- MID (merchant ID): the identifier a processor or acquirer assigns to a merchant account; the backup needs its own.
What must exist before the outage
A DR (disaster recovery) plan for payments is mostly work done in advance:
- A second processor, integrated and warm (fully set up and already carrying a slice of live traffic, not sitting idle). Signed contract, underwriting completed (the processor's own review and approval of your business before it will process for you), MIDs issued for every merchant you intend to fail over, and a small share of live traffic (for example 2 to 5%) routed there permanently, so you know it works today, not in theory.
- Portable card credentials. Tokens issued by the primary processor do not work at the backup. Stored cards (subscriptions, one-click checkout) can only fail over if you hold network tokens (issued by the card networks, usable across processors) or run your own vault that can send card data to either processor. Without that, only customers typing a card fresh can pay through the backup.
- A mapping layer. A table per processor translating your internal payment methods, currencies, merchant category codes (MCCs, the standard 4-digit codes that classify what kind of business a merchant is), statement descriptors (the text that shows up on the cardholder's statement), decline codes and 3-D Secure (the card-holder authentication step) settings into that processor's vocabulary. Divergence here (for example a merchant category code the backup does not recognise, or a decline code mapped to the wrong retry behavior) is what turns a failover into a flood of declines.
- A routing service with per-processor health, a circuit breaker, and a manual override switch.
During the outage
flowchart TD
A[New payment] --> B{Primary healthy?}
B -- yes --> C[Primary processor]
B -- no --> D{Card usable at backup?}
D -- yes --> E[Backup processor]
D -- no --> F[Offer other method or retry later]
G[In-flight at primary when it failed] --> H[State: unknown, no retry elsewhere]
H --> I[Resolve via primary status query or settlement report]
- Route new authorizations to the backup once the breaker opens. Keep the idempotency key (the client's unique ID for this payment attempt) as your internal reference so each processor call is traceable to one payment.
- Do not replay in-flight payments at the backup. A request that timed out at the primary may have been approved there. Retrying it at the backup risks charging the customer twice. Mark it
unknown, tell the merchant the outcome is pending, and resolve it once the primary answers status queries or its settlement file arrives. - Captures, refunds and voids follow the original processor. An authorization made at the primary can only be captured or refunded through the primary. Queue these operations durably and drain them when the primary returns; if an authorization would expire first (online card authorizations are typically valid for about 7 days), decide per merchant whether to re-authorize at the backup.
- Degrade gracefully. Recurring charges on non-portable tokens are deferred and retried later rather than failed; merchants see a clear "processing delayed" status rather than hard declines. For card-present terminals, offline "store and forward" approvals (the terminal approves the sale itself on the spot, with no live authorization call, then submits it for real authorization once connectivity returns) under a low per-transaction limit are possible but the merchant carries the risk of later declines; enable it only where merchants opted in.
- Protect the backup. Ramp traffic gradually and watch approval rates; a sudden jump in volume can trigger the backup's own fraud controls.
After the outage: settlement and reconciliation
- Reconcile per processor. Each processor's settlement report is matched against your ledger (your internal, append-only record of money movements) for the transactions it handled. The routing decision is recorded on every payment, so each payment belongs to exactly one processor's reconciliation.
- Resolve every
unknown. For each, the primary either reports it approved (keep it, capture as normal) or never received or declined it (mark failed, and if the customer retried and succeeded at the backup, there is no double charge to unwind). Any real duplicate found is refunded proactively. - Different payout timing. The backup may pay out a day later, to a different bank account, with different fee deductions. Merchants' payout projections and your treasury forecast (the internal projection of cash moving in and out of the business) must show this explicitly.
- Chargebacks and disputes (a customer disputing a charge through their bank) for backup-processed payments arrive from the backup for months afterwards; the dispute system must know to look there.
Fees and who pays them
Fees differ between processors, so decide in advance whether the platform absorbs the difference or passes it on. Illustrative numbers (assumed contract rates, not any real vendor's price list):
- A merchant processes 2,000,000 USD per day, spread evenly, at an average ticket of 50 USD. A 6-hour outage moves 6/24 of that, 500,000 USD, or 10,000 payments, to the backup.
- Primary rate 2.2% + 0.10 USD: 11,000 + 1,000 = 12,000 USD.
- Backup rate 2.9% + 0.30 USD: 14,500 + 3,000 = 17,500 USD.
- Extra cost of the outage: 5,500 USD for this merchant.
Most platforms absorb this for short outages (it is small against lost sales and merchant trust) and write the rule into their merchant terms so it is not negotiated during an incident.
Communication
| Audience | When | What |
|---|---|---|
| Merchants | Within minutes of routing change | Status page, API status field on affected payments, dashboard banner: what works, what is delayed, whether payouts shift |
| Customers | Via merchants | Clear "payment pending" messages, never "failed" for an unknown outcome |
| Backup processor | Before ramping | Warn them of volume so their risk controls do not block it |
| Card schemes (another name for the card networks, such as Visa or Mastercard) and acquiring partners (the banks or institutions that hold your merchant accounts with those networks) | Per contract | Incident notices where agreements require them |
| Regulators | Per jurisdiction | Where the platform is a regulated payment institution (licensed by a financial regulator to move customers' money, not just a software vendor), major operational incidents are reportable within fixed deadlines measured in hours to days (for example, under the EU's DORA, the Digital Operational Resilience Act, for financial entities). Legal and compliance own the filing; engineering supplies the timeline and impact numbers |
Trade-offs and pitfalls
- Cost of warmth. Keeping a second processor live costs contract minimums and engineering on two integrations, but a cold backup is almost always broken when needed.
- Automatic vs manual failover. Automatic failover reacts in seconds but can flap (switch back and forth rapidly as health checks briefly pass, then fail, then pass again) on a partial outage and send traffic to the backup that the primary would have approved. A common compromise: automatic for hard failures (connection refused, sustained 5xx), human decision for soft degradation (elevated latency, falling approval rate).
- The dangerous mistake is converting timeouts into failures and retrying them elsewhere. That produces the double charges that customers remember long after the outage.
- Approval rates will drop on the backup (new MIDs, no transaction history, different issuer relationships). Plan and tell merchants; do not treat it as a new incident.
Design the monitoring and alerting surface for a payment processing system: what would you instrument to catch degraded authorization health, fraud-signal drift, stuck or mismatched settlements, and capacity problems before customers or finance notice? Explain how you'd decide what pages on-call immediately versus what's a dashboard-only signal.
Sample Answer
Direct answer
Instrument the outcomes customers and finance experience, not just server health: authorization success split by processor (the company that actually routes the authorization call to the card networks and returns approved, declined or timed out, for example Stripe or Adyen), card brand (the network the card runs on, such as Visa or Mastercard) and issuer country (the country of the issuer, the shopper's own bank and the party that actually decides approve or decline); how fraud scores and decisions are distributed; how long money sits in each state between capture (telling the processor to actually collect funds that were only held at authorization) and settlement (the multi-day process by which that captured money actually lands in the merchant's bank account); and how close each dependency is to its limits. Page on-call only when a signal is customer-impacting now, urgent, and actionable by a human, measured against an SLO (service-level objective, a target such as "99.9% of authorization requests succeed technically over 30 days") and using burn-rate alerts; everything that is slow-moving, needs business judgment, or can wait until morning goes to a ticket or a dashboard.
What to instrument, by failure family
1. Degraded authorization health
- Technical success rate (the call got an answer from the processor) versus approval rate (the issuer said yes). They fail differently: a processor outage kills the first; a misconfigured merchant category code (the four-digit code that tells the issuer what kind of business this is, which some fraud rules key on) or an issuer's new fraud rule drops the second while every call "succeeds".
- Approval rate segmented by processor, card brand, issuer country, payment method and merchant. A 30-point drop for one issuer is invisible in the global average.
- Decline-code mix: a jump in "do not honor" (the issuer's generic refusal, usually a fraud or risk rule) versus "insufficient funds" (the shopper's own account, not fraud) tells you whether it is fraud rules or customer behaviour.
- Latency percentiles (p50, p95, p99: the latency that half, 95% and 99% of calls beat) per processor, and timeouts, especially timeouts with unknown outcome, which risk double charges: a naive retry cannot tell whether the first attempt actually succeeded, so if it did, retrying charges the card a second time.
- Business canary: payments completed per minute compared with the same minute last week. It catches problems no technical metric sees (a broken checkout button).
2. Fraud-signal drift
- Distribution of fraud scores over time, compared to a baseline with a drift statistic such as PSI (population stability index, which compares the share of traffic in each score bucket now versus a reference period; values above about 0.25 are conventionally treated as a large shift).
- Decision rates: approve / review / decline / step-up (sending the shopper through 3-D Secure authentication, an extra verification step such as a one-time code, that shifts liability for fraud onto the issuer) per hour.
- Fallback rate: share of decisions made without the primary fraud model or vendor.
- Lagging truth: chargeback (the issuer forcibly reversing a captured payment after the cardholder disputes it) and confirmed-fraud rates by cohort week (they arrive weeks later, so they are for trend, not paging).
3. Stuck or mismatched settlements
- Age of money in each state: oldest captured-but-not-settled payment, oldest
unknownoutcome, oldest payoutin_transit. An "age of oldest item" metric catches a stuck pipeline that a throughput metric misses. - Settlement file arrival: did today's file from each processor arrive, and does its record count look normal?
- Reconciliation mismatch (comparing two independent records of the same money and flagging where they disagree): count and total amount of payments present in the ledger (our own append-only record of every money movement) but not in the processor's settlement file, and vice versa, plus the fee variance against the contract.
- Ledger integrity: debits equal credits per shard; a non-zero sum is always a severe bug.
4. Capacity problems
- Saturation: database connection pool use, queue consumer lag (how far behind a consumer is from the newest message on the queue), partition skew (one partition of a queue or database getting far more traffic than the others, so adding more consumers does not help), thread pools per processor adapter.
- Headroom against external limits: requests per second versus each processor's contracted rate limit, and 429 (rate-limited) responses.
- Error budget: remaining budget for the month per SLO.
Paging versus dashboard: the decision rule
A signal pages only if all four are true:
- Customers or money are affected now (not "might be next week").
- It is urgent: waiting until business hours makes the damage materially worse.
- A human can act: fail over a processor, roll back, pause a merchant.
- It is reliable: it would not have fired falsely more than rarely in the last quarter.
| Signal | Page? | Why |
|---|---|---|
| Technical success rate burning the SLO budget fast | Page | Every minute loses sales; failover is actionable |
| Approval rate down 15 points for one processor over 10 minutes, with enough volume | Page | Revenue loss now; reroute traffic |
| Unknown-outcome timeouts rising | Page | Double-charge risk; stop retries |
| Ledger debit/credit imbalance | Page | Correctness bug; stop postings |
| Settlement file missing at expected time plus 2 hours | Ticket (page if it blocks today's payouts) | Money is late, not lost; usually a vendor email fixes it |
| Reconciliation mismatch within tolerance | Dashboard | Normal timing differences |
| Fraud score PSI above threshold | Ticket to risk team | Needs judgment, not a 3 a.m. action |
| Chargeback rate trend | Dashboard / weekly review | Arrives weeks late |
| Queue lag growing but under the payout deadline | Ticket | Fixable in hours |
Burn-rate alerting (worked example)
With an SLO of 99.9% technical success over 30 days, the error budget is 0.1% of requests. Burn rate is how many times faster than "exactly on budget" you are failing. A 30-day window is 720 hours. Both thresholds start from the same paging rule, chosen backwards: page if a sustained burn would consume 2% of the month's budget within 1 hour, or 5% within 6 hours, because burning that fast for that long breaks the SLO well before the month ends. Solving each for the burn rate gives the numbers below:
- Burn rate 14.4 sustained for 1 hour consumes 14.4 × 1 ÷ 720 = 2% of the month's budget: page.
- Burn rate 6 sustained for 6 hours consumes 6 × 6 ÷ 720 = 5%: page.
- Slower burns become tickets.
Pair each long window with a short one (for example 5 minutes) that must also be firing, so the alert stops soon after recovery.
Minimum volume guard: a merchant with 20 payments an hour will show a "40% drop" on two declines. Segment alerts require a minimum count (say 200 attempts in the window) before they can fire.
Worked example: an approval-rate drop
Normal approval rate for UK debit via processor A is 94% on about 3,000 attempts per 10 minutes. It falls to 78%. The alert fires because the segment has volume and the drop exceeds the threshold, while the global approval rate only falls from 91% to 88% (UK debit via A is one segment among many). That is consistent with a total volume of about 16,000 attempts per 10 minutes across all processors and segments: this segment's approvals drop by 3,000 × (94% − 78%) = 480, and 480 as a share of 16,000 attempts is 3 points, matching the global 91% → 88% move. The decline-code panel shows "do not honor" spiking; latency is normal, so the processor is up but issuers are declining. On-call shifts that segment to processor B via the router, sees B's approval at 93%, and files a ticket with A. Without segmentation this would have looked like noise.
Trade-offs and pitfalls
- Alerting on causes (CPU at 80%) instead of symptoms pages people for things customers never notice.
- Dashboards without owners rot. Each ticket-level signal needs a named team and a review cadence.
- Per-merchant alerts at scale create thousands of noisy alerts; alert per segment and let merchant-level anomalies feed a daily report.
- Instrument the unknown outcomes: the most damaging payment incidents (double charges) show up there first.
You investigate an incident where several customers were charged twice after a rolling deployment. Logs show idempotency key collisions were possible due to a library change. Outline the steps you would take for root-cause analysis, immediate remediation, notifying affected customers, compensating transactions, and long-term architectural and process fixes to prevent recurrence.
Sample Answer
Direct answer
First stop the bleeding: halt or roll back the deployment and confirm with data that duplicates have stopped. Then scope exactly who was charged twice by comparing the processor's charges against our orders, refund every duplicate (or void it if still uncaptured), record each correction as a reversing ledger entry, and tell affected customers before they notice on their statements. The root-cause work has to explain a subtle point: a key collision on its own usually makes a payment get skipped (a different customer's request is answered with someone else's stored result), not charged twice. A double charge means one purchase ended up with two keys. So the investigation is about how the library change and the rolling deploy together turned one intent into two keys, and the long-term fix is keys that are random, generated once per intent, persisted before the first attempt, and verified by a duplicate-charge detector that can stop a deploy automatically.
Terms
- Idempotency key: a unique ID per payment intent, sent with every retry so the server can return the first result instead of charging again.
- Rolling deployment: replacing instances a few at a time, so for a while old and new versions serve traffic side by side.
- Compensating transaction: a new transaction that undoes the effect of an earlier one (a refund for a duplicate charge), because the original cannot be deleted.
- Entropy (of a key): how many effectively random, unpredictable bits it actually carries. A key built from fewer random bits, or from input data that repeats across requests, has low entropy and collides with another key far more often than its printed length would suggest.
1. Immediate containment (first hour)
- Declare an incident, assign an incident commander, open a timeline document.
- Stop the change: pause the rollout and roll back to the last known-good version, so the fleet is no longer mixed.
- Stop amplifiers: temporarily disable automatic payment retries in clients and background jobs that could keep creating new keys.
- Measure that it stopped: a query that counts orders with more than one successful charge in the last N minutes, grouped by service version. The incident is contained when that count stops growing, not when the rollback finishes.
2. Scoping the impact
Pull the processor's successful charges for the window (from its API or settlement report, not only our database, because our records may be exactly what is wrong) and group by order:
SELECT order_id, customer_id, count(*) AS charges, sum(amount_minor) AS total_minor,
array_agg(psp_charge_id ORDER BY created_at) AS charge_ids
FROM psp_charges
WHERE created_at BETWEEN :deploy_start AND :rollback_done + interval '1 hour'
AND status = 'succeeded'
GROUP BY order_id, customer_id
HAVING count(*) > 1;
Also check the opposite failure: orders with no charge but marked paid. If keys collided across different customers, some customers received someone else's cached success response and were never charged at all. That is a revenue and fulfilment problem, and it is the tell-tale sign of a true collision.
3. Root-cause analysis
Reconstruct, for a handful of affected orders, every request with its key, instance, service version and outcome. Then test hypotheses against that evidence:
| Hypothesis | How a double charge happens | Evidence that confirms it |
|---|---|---|
| Key derivation changed between versions | The library now computes the key differently (new serialisation, new hash input). A retry from an old instance and one from a new instance produce different keys for the same order. | Duplicate pairs straddle the two versions; both keys are well-formed and different |
| Key collision plus conflict fallback | The new library produces low-entropy keys, so two different purchases can share a key. The second is rejected as "same key, different parameters"; the client's error handler treats that as retryable and generates a fresh key, and the same handler also fires on timeouts, so a request that actually succeeded is re-sent under a new key | Conflict errors spike after the deploy; duplicate pairs are preceded by a conflict or a timeout |
| Key regenerated per attempt | The library change moved key generation inside the retry loop | Every retry of an order has a different key |
Put numbers on the collision hypothesis. With n keys in the retention window and b random bits per key, the expected number of colliding pairs is approximately
2⋅2bn(n−1)which is just (number of distinct pairs of keys) times (the chance any one given pair matches): n(n−1)/2 is how many pairs you can form from n keys, and 1/2b is the chance two independent b-bit random keys happen to be equal, so their product is the expected count of colliding pairs.
If the library truncated keys to a 32-bit hash and the service handles 1,000,000 payments in a 24-hour window, that is about 116 expected colliding pairs per day (1,000,000 × 999,999 / 2 ÷ 2³² ≈ 116); at 100,000 payments, about 1.2. A version 4 UUID (universally unique identifier) has 122 random bits, giving about 9.4 × 10⁻²⁶ expected pairs at 1,000,000 keys, effectively zero. So "collisions were possible" is plausible only if entropy dropped by orders of magnitude, which the diff will show.
Finish with the causal chain in plain language, and the contributing factors that let it ship: no test pinned key derivation across versions, no canary metric (a small, closely watched signal, checked automatically during a rollout, that halts it the moment the signal turns bad, named after canaries once carried into mines to give early warning of gas) for duplicate charges, key generation delegated to a general-purpose library whose change was treated as a routine upgrade.
4. Remediation for customers
- Refund each duplicate (the later charge, keeping the one the order references), using a deterministic idempotency key per refund such as
refund:<duplicate_charge_id>so the remediation script can be re-run safely. If a duplicate is still only authorized and not captured, void it instead: the hold disappears faster and no money moves. - Customers never charged because of collisions: do not silently charge them later. Contact them, and decide per business policy whether to request payment or absorb the loss.
- Check for disputes already filed on duplicates before refunding, so a customer is not refunded twice (refund plus chargeback).
5. Compensating entries in the ledger
Never delete the duplicate charge from the ledger. Post a reversing entry linked to the incident. Two accounts do the work: processor_receivable is an asset account, money the processor owes us for charges it has taken but not yet paid out, and a debit increases an asset. sales_clearing is the account that holds a sale's proceeds until they clear, and a credit increases it. So the first row below records the duplicate exactly as if it were a real sale (receivable goes up, clearing goes up); the second row reverses both sides precisely (receivable back down, clearing back down), which is what a debit to sales_clearing and a credit to processor_receivable do:
| Entry | Debit | Credit |
|---|---|---|
| Duplicate charge (as it happened) | processor_receivable 49.99 | sales_clearing 49.99 |
| Refund of duplicate | sales_clearing 49.99 | processor_receivable 49.99 |
The net effect is zero, the history shows what happened and why, and reconciliation will match the processor's refund line to the refund entry.
6. Notifying customers
Communicate proactively, within a day of confirming scope: what happened (charged twice for order X), what we did (refunded Y on date Z), when it will appear (refunds typically take several business days to show on a statement), and a support contact. Give support staff a script and a lookup tool. For large incidents, merchants and partners who need to know under their contracts get a summary too.
7. Long-term fixes
Architecture
- Keys are random (a version 4 UUID, universally unique identifier, or equivalent from a cryptographically secure generator), generated once per payment intent, stored with the order before the first request, and reused on every retry. Never derived from request contents, never regenerated in a retry loop.
- A second line of defence independent of keys: a unique constraint on
(order_id, attempt_number)for successful charges, so one order cannot hold two successful charges without an explicit new attempt. - Server-side fingerprint check: same key, different body is rejected, never retried with a new key automatically.
Process
- Contract tests (automated tests that pin the exact shape of an interface, here the key format and derivation logic, so either side changing it without the other breaks the build instead of production) that pin key format and derivation, run against both the old and new version in CI (continuous integration), so a mixed fleet cannot disagree.
- A canary metric, orders with more than one successful charge, that automatically halts a rollout when it rises above zero.
- Dependency upgrades in the money path are reviewed like code changes, with changelogs read, not auto-merged.
- Daily reconciliation that flags multiple charges per order, so any recurrence is caught within a day even if every other guard fails.
- A blameless post-mortem (a written review of the incident that focuses on what in the system and process allowed it to happen, not on blaming whoever wrote the code) with owners and dates for each action.
Trade-offs and pitfalls
- Refunding from our own records only misses charges our system does not know about; scope from the processor's data.
- Refunding without idempotency in the remediation script creates a second incident.
- Stopping at "the library did it" leaves the real gap (no cross-version test, no duplicate metric) open for the next library.
- Waiting for customers to complain multiplies support load and disputes; proactive refunds are cheaper than chargebacks.
Design a global active-active payment processing architecture to support 10,000 TPS with P95 API latency under 200ms across 3 regions. Requirements: idempotent transactions, correct merchant balances, failover for processor outages, and handling per-region data residency constraints. Describe service decomposition, data replication approach, conflict resolution, routing, and reconciliation.
Sample Answer
Direct answer
Make every merchant single-home: each merchant's balance and idempotency records are owned by exactly one region (its home region, chosen by data-residency rules), so there is only ever one writer for the facts that must be exactly right. This is active-active in the sense the client sees, not in the sense of every region independently accepting writes for the same data: all three regions are active (each is home to a third of merchants and accepts traffic for all of them, so there is no single "primary site" a client must reach), but a write for a merchant homed elsewhere is forwarded to the home region instead of being accepted locally and merged later, which is what keeps balances correct. Balances are derived from an append-only ledger (the authoritative, append-only record of every money movement) of immutable entries, so cross-region replication copies facts rather than resolving conflicting numbers. Processor outages are handled by multiple processors per region behind a router; region outages by an in-jurisdiction standby (an already-running, up-to-date replica in the same legal jurisdiction, ready to take over); and a continuous reconciliation job compares our ledger with processor settlement files.
Requirements and the numbers they imply
- 10,000 TPS (transactions per second) peak globally, split across 3 residency domains (see Data residency below), each running its own home region plus an in-jurisdiction standby: about 3,333 TPS per domain at peak. Because a domain's failover target is always its own standby, never one of the other two domains' regions (residency forbids that), no region ever has to absorb another domain's load. Size every region, home and standby alike, for its own domain's full peak of about 3,333 TPS plus headroom, not for a fraction of the global total.
- P95 under 200 ms (95% of API calls finish within 200 ms). A cross-region round trip between continents is on the order of 70 to 150 ms (estimate; depends on the region pair), so no synchronous cross-continent step can sit on the common path. I read the 200 ms as our platform's own latency; the processor's authorization round trip to the card network is outside our control, so the API either includes it with a separate budget or returns
pendingand completes by webhook. That split is stated to the product owner, not assumed. - Write amplification: a payment writes roughly 6 rows (idempotency record, payment, 2 to 3 ledger entries, outbox event), so 10,000 × 6 = 60,000 row writes per second at peak, about 20,000 per region: shard the ledger.
- Storage: if average load is 30% of peak (assumption), that is 10,000 × 0.3 × 86,400 = 259.2 million payments per day; at about 2 KiB of rows each (2,048 bytes), 259.2 M × 2,048 bytes ≈ 531 GB per day before indexes and replicas.
- Replication bandwidth at peak: 10,000 × 2,048 bytes ≈ 20.5 MB/s globally, which is modest.
Service decomposition
flowchart LR
C[Client] --> E[Regional edge gateway]
E --> PA[Payment API]
PA --> TV[(Regional token vault)]
PA --> IDM[(Idempotency store)]
PA --> RR[Home-region router]
RR --> LD[(Ledger shards)]
PA --> PR[Processor router]
PR --> P1[Processor 1]
PR --> P2[Processor 2]
PA --> OB[(Outbox)] --> Q[Event stream]
Q --> ST[Settlement and payouts]
Q --> RC[Reconciliation]
| Service | Responsibility |
|---|---|
| Regional edge gateway | TLS termination (the point where the client's encrypted connection is decrypted before the request continues inside the network), auth, rate limits; routes the client to the nearest region by latency-based DNS (a DNS system that answers each client with whichever region measures fastest for them, instead of one fixed answer). Each region fronts its own set of regional payment gateway connections, so in-region acceptance meets a tighter internal target of 150 ms, measured from when the edge receives the request to when it responds; that leaves roughly 50 ms of the 200 ms client-measured P95 as headroom for the client's own network path to the edge, which the platform does not control |
| Token vault (per region) | Tokenization: swaps the card number for a random token at the edge, so only the vault holds card data; this keeps PCI DSS (the card industry's data security standard) scope to one small service per region, and the vault never replicates raw card data across regions |
| Payment API | Validates, checks idempotency, orchestrates the payment state machine |
| Home-region router | Knows each merchant's home region; forwards writes for non-local merchants |
| Ledger | Append-only, double-entry (every entry paired with an equal, opposite entry elsewhere, so nothing is created or destroyed unnoticed) entries, sharded by merchant ID; balances computed per merchant shard |
| Processor router | Chooses among processors, circuit breakers, failover |
| Outbox and event stream | Everything not needed for the synchronous response (settlement, payouts, notifications, analytics, fraud re-scoring) is queued, not done inline |
| Settlement and operational controls | Ingests processor settlement files, schedules payouts, applies holds and reserves, provides the operator tools to pause a merchant or a processor |
| Reconciliation | Matches ledger with processor files and cross-region replicas |
Data flow for one payment (merchant homed in this region)
- Edge tokenizes the card; the API receives the token.
- Idempotency: insert
(merchant_id, idempotency_key)with a unique constraint in the merchant's home shard. If it exists, return the stored result. Because the key lives only in the home region, a client retrying against another region still hits the same record (after forwarding), so there is no cross-region double charge. - Call a processor (with its own idempotency key) through the processor router.
- In one local transaction on the merchant's shard: update payment state, post ledger entries, write outbox event. Replicated synchronously across availability zones (separate data centres within the region) with a quorum (a majority of replicas acknowledging the write before it counts), so a zone loss loses nothing; this costs a few milliseconds, not a cross-continent round trip.
- Respond. The outbox relay publishes the event for async consumers.
For a merchant homed elsewhere, step 2 onwards runs in the home region after one forward; that adds one inter-region round trip, which is why merchants are homed near their customers and why the forward path is measured separately.
Data replication and conflict resolution
- Within a region: synchronous quorum replication across three zones (for example a Raft-based distributed SQL database, or Postgres with synchronous standbys (replicas that must confirm a write before it counts as committed)). Raft is a consensus protocol in which a majority of replicas must acknowledge a write before it counts.
- Across regions: asynchronous, one-way from home to a standby. The standby lags by seconds.
- Conflict resolution by design: with a single writer per merchant there are no write-write conflicts (two writers changing the same record at the same time, one silently overwriting the other) on balances or idempotency keys. Ledger entries are immutable facts with globally unique IDs, so merging replicas is a set union. The rejected alternative, multi-writer balances merged later (last-writer-wins or CRDT counters, conflict-free replicated data types that merge automatically), cannot enforce "balance never goes below zero" or "charge exactly once", because two regions can each approve a spend the other has not seen. (The rejected alternative's "last-writer-wins" means: when two conflicting writes arrive, keep whichever has the later timestamp and silently discard the other, which is exactly how a second spend can vanish from the losing region's view.)
Data residency
The home region is chosen by residency: an EU merchant's personal and cardholder data is homed in the EU region and its standby must also be in the EU (a second EU region, or at minimum separate zones), never the US region. Cross-region, only what is allowed leaves: aggregated or pseudonymized (personal identifiers replaced with a substitute so the record can't be traced straight back to a person) events for global reporting and fraud models. The token vault is per region. This means "three regions" is really three residency domains, each with its own failover pair.
Failover
- Processor outage: each region has at least two processors. The breaker opens on error or timeout rate; new payments go to the backup. A timed-out call is not resent elsewhere until the first processor's status is queried, to avoid double authorization.
- Zone outage: absorbed by quorum replication, no action.
- Region outage: merchants homed there are promoted to their standby (in-jurisdiction) after the lag has drained or with a documented loss window. Promotion is a deliberate, fenced operation: the old home is marked read-only by incrementing a fencing epoch (a number the ledger checks on every write, so a partitioned (cut off from the rest of the cluster by a network split, but still running and unaware it has been replaced) old primary's writes are rejected). Until promotion, payments for those merchants are refused or queued as
pending, rather than accepted by a second writer.
Reconciliation
Three loops: (1) intra-system, ledger debits equal credits per shard every few minutes; (2) standby versus home, entry counts and hashes per merchant per hour; (3) external, processor settlement files matched to payments by processor reference daily, with every unmatched item opened as a case. Merchant balances reported to finance come from the reconciled ledger.
Trade-offs and pitfalls
- Home-region forwarding costs latency for travelling merchants' customers; the alternative (multi-writer) costs correctness. For money, pay the latency.
- Asynchronous standby means a region disaster can lose the last seconds of committed payments. Mitigation: the processors hold the truth for authorized payments, and reconciliation replays them. If zero loss is required, the standby must be synchronous and nearby, which costs latency on every write.
- Idempotency keys stored in a global cache that replicates asynchronously is the classic double-charge bug.
- Hot merchants: one merchant producing 2,000 TPS overloads a single shard; split its ledger by sub-account and aggregate balances.
Unlock Full Question Bank
Get access to all 8 Payment and Transaction Processing Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.