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.
Explain the difference between tokenization and encryption when protecting cardholder data. Describe how tokens are generated and mapped to PANs, where the mapping and encryption keys ideally live, and how tokenization can reduce PCI footprint while supporting use cases like recurring payments.
Sample Answer
Direct answer
Encryption transforms the card number with a key; anyone with the key can mathematically reverse it, so the encrypted value is still card data and the systems holding it (and the keys) stay in audit scope. Tokenization replaces the card number with a random substitute that has no mathematical relationship to it; the only way back is a lookup in a separately secured token vault. Systems that hold only tokens, and cannot ask the vault to reverse them, can be taken out of scope for most of the card-security standard. That is why merchants store tokens for recurring billing instead of card numbers.
Key terms
- PAN (primary account number): the card number, typically 13 to 19 digits in practice (the ISO/IEC 7812 standard allows 8 to 19); most Visa, Mastercard and Discover cards use 16, American Express uses 15, and some older Visa cards use 13.
- PCI DSS (Payment Card Industry Data Security Standard): the security standard every business that stores, processes or transmits card data must meet.
- CDE (cardholder data environment): the systems that touch PANs plus anything connected to them. "Reducing PCI footprint" means shrinking the CDE.
- Detokenization: exchanging a token back for the PAN. Only a few tightly controlled systems should be able to do it.
- HSM (hardware security module): tamper-resistant hardware that stores keys and performs cryptography so the key never leaves it. A cloud KMS (key management service) offers similar key custody as a managed service.
Tokenization vs encryption
| Encryption | Tokenization | |
|---|---|---|
| Relationship to PAN | Mathematical: ciphertext plus key gives the PAN | None: a random value, reversible only through the vault |
| What an attacker needs | The ciphertext and the key | Access to the vault itself |
| Scope effect | For whoever holds or can use the key, the ciphertext is still cardholder data | Systems holding only tokens, with no detokenize access, can be out of scope |
| Typical use | Protecting PANs inside the vault, on disk, and in transit | Letting the rest of the business reference a card safely |
| Format | Ciphertext is usually longer binary data unless format-preserving encryption (encrypting into an output that still looks like a normal card number: same length, same character set) is used | Can be designed to look like a card number (same length, keep last four digits) |
They are complementary: the vault itself encrypts the PANs it stores. Tokenization moves the problem into one small place; encryption protects that place.
How tokens are generated and mapped
- Generate a token from a cryptographically secure random number generator, not from the PAN. A format-preserving token might keep the length and last four digits (useful for receipts and "card ending 4242" screens) and randomise the rest, taking care the result cannot be mistaken for a real, valid card number, for example by deliberately failing the Luhn check (the checksum built into every genuine PAN's last digit, which software uses to catch typos) that a real card number would pass.
- Store the mapping in the vault as
token -> encrypted PAN. The PAN is encrypted with a data key; the data key is itself encrypted by a master key in the HSM or KMS (this is called envelope encryption). - Support lookup by PAN (so the same card gets the same token for a customer, if you want that) with a keyed hash of the PAN, such as an HMAC (a hash combined with a secret key, so only someone holding that key can compute or check it) with a key held in the HSM. A plain unsalted (no random, per-value salt mixed in before hashing, so the same PAN always produces the same output) hash of a PAN is not safe: a 16-digit PAN's first six digits are a public BIN (bank identification number) and its last digit is a Luhn check digit computed from the rest, not random, leaving only about 9 unknown digits, at most 10^9 (one billion) possibilities. Someone who obtains the hashes can precompute all one billion candidates for a known BIN, which is well within reach of ordinary hardware in under a day, and read off which hashes match, so they can be brute-forced.
- Detokenize only for a short list of callers (the service that sends the authorization to the processor), each authenticated, authorised and logged.
Where things should live. The vault, its database and the keys belong in separate security domains: keys in an HSM or KMS whose administrators are not the vault's database administrators, and the vault in its own network segment or cloud account. Stealing the database alone yields ciphertext; stealing a key alone yields nothing to decrypt. Many merchants never run a vault at all: the payment service provider (PSP, the company that processes card payments for the merchant) runs it, and the merchant only ever sees the PSP's tokens.
How this reduces PCI footprint and supports recurring payments
- The customer types their card into a payment form hosted by the PSP (a hosted page or an embedded iframe), so the PAN goes browser to PSP and never reaches the merchant's servers.
- The PSP returns a token such as
pm_1a2b3c. The merchant's database, billing jobs, logs and analytics hold only that token. - For each monthly charge, the merchant's billing job calls the PSP API with the token. The PSP detokenizes inside its own environment and sends the authorization to the card network.
- Because the merchant never stores, processes or transmits the PAN and cannot detokenize, its CDE shrinks dramatically, and its compliance validation becomes far lighter.
Network tokens go one step further: the card networks themselves (for example Visa Token Service and Mastercard's tokenization service) issue a token tied to a merchant, and the network updates it when the physical card is reissued or expires. Recurring billing then keeps working after the customer gets a new card, which reduces involuntary churn.
Worked example
A streaming service bills 2 million subscribers monthly. With encryption only, it would store 2 million encrypted PANs and manage the keys: its database servers, billing workers, backup system and every administrator with key access would be inside the CDE. With PSP tokenization, its database stores pm_... tokens and "Visa ending 4242, expires 08/28" for display. A breach of that database leaks tokens that are useless outside that merchant's PSP account, and cannot be turned into card numbers. The billing job on the 1st of the month submits 2 million charges by token; the PSP holds the only mapping.
Trade-offs and pitfalls
- Tokens are PSP-specific. A token from one PSP does not work at another, which creates lock-in and complicates failover to a backup processor. Network tokens or a PSP-independent vault reduce this, at extra cost or scope.
- "Out of scope" requires that no system can detokenize. If a merchant service has an API credential that can reverse tokens, that service is back in scope.
- Never store sensitive authentication data (the CVV security code, full magnetic-stripe or chip data, PINs) after authorization, whether encrypted or tokenized. PCI DSS forbids it regardless of protection.
- Encryption is not a scope escape for the key holder. Encrypting PANs in your own database is required protection, but if you also hold the keys, those systems are still in scope.
- Card numbers leak sideways. Logs, error messages, support tickets and analytics pipelines are where PANs turn up unexpectedly; scan for them.
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.
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.
Architect a fraud rule engine for a merchant platform that supports rule authoring, staging, and fast evaluation in the live payment path. Describe how rules are stored, compiled/deployed, evaluated under high throughput, how to rollback problematic rules, and how to avoid performance impacts on the authorization latency budget.
Sample Answer
Direct answer
Treat rules as versioned data compiled into an immutable ruleset artifact, not as code in the payment service and not as rows the evaluator queries at request time. Analysts author rules in a restricted expression language through a UI; every change creates a new ruleset version that is validated, backtested against historical payments, run in shadow (evaluated and logged but not enforced) and then promoted. Evaluator instances load the compiled ruleset into memory and swap to a new version atomically, so evaluation is pure in-memory work over features that were precomputed before the request arrived. Rollback is repointing to the previous version, which every instance already holds, and individual rules have a kill switch.
Requirements
- Analysts (not engineers) add or change a rule and have it live within minutes, safely.
- Evaluation fits inside a small slice of the authorization latency budget: say 5 ms of a roughly 100 ms fraud decision, at thousands of TPS (transactions per second).
- Every decision is explainable: which rules fired, in which ruleset version.
- A bad rule can be undone in seconds without a deploy.
Architecture
flowchart LR
UI[Rule authoring UI] --> VAL[Validate and lint]
VAL --> STORE[(Rule store, versioned)]
STORE --> BT[Backtest on history]
BT --> COMP[Compile ruleset vN]
COMP --> REG[(Artifact registry)]
REG --> EV[Evaluators in the payment path]
FEAT[(Precomputed features)] --> EV
EV --> LOG[(Decision log with version)]
LOG --> DASH[Rule hit rates and shadow diffs]
Storage
- A rule has an ID, owner, description, a condition in the rule language, an action (
allow,review,block,step_upto 3-D Secure authentication), a priority, a scope (all merchants, one merchant, one category), and a lifecycle state:draft,shadow,active,disabled. - A ruleset version is an immutable snapshot: the exact list of rules and states at publish time, with who approved it. Rules are never edited in place; a change produces a new version. The audit trail comes for free.
- The store is a normal relational database. It is on the authoring path, not the evaluation path.
The rule language
Give analysts a restricted expression language, not a general programming language: field references from a fixed catalogue, comparison and set operators, boolean logic, and a small set of functions. Google's CEL (Common Expression Language) is an off-the-shelf example designed for exactly this: safe, side-effect-free, fast to evaluate. The restriction is the point: a rule cannot call the network, loop, or read arbitrary data, so its cost is bounded and it cannot break the evaluator.
Compile and deploy
- Validate: every field exists in the feature catalogue, operators suit the field types, thresholds are in range. Reject anything that needs a feature not available within the latency budget.
- Lint (an automated check for likely mistakes, without actually running anything): flag rules that would block a large share of traffic, duplicate another rule, or can never fire.
- Backtest: replay the last N days of logged decisions and features through the new version; report how many decisions change, on which segments, and how many known-fraud and known-good payments each changed rule catches.
- Compile: turn the ruleset into an in-memory structure: parsed expressions or generated predicates (small functions that test one condition and return true or false), rules indexed by scope so a payment only evaluates rules relevant to its merchant and category.
- Publish: write the artifact to a registry; evaluators poll or are notified, load it in the background, and swap an atomic pointer (flip a single reference to the new version in one indivisible step, so no request ever sees a half-loaded ruleset). Requests in flight finish on the old version; new ones use the new one.
Evaluation under high throughput
- Features are precomputed. Velocity counts ("attempts on this card in 10 minutes"), customer age and device reputation are maintained by a streaming job and read by key in one batched lookup before rules run. A rule can only reference catalogue features, so no rule can add a database query to the request.
- Cost is bounded by construction: evaluation is O(rules in scope × predicates per rule) (its cost scales with just two numbers: how many rules apply, times how many conditions each one checks), with no I/O. Indexing by scope keeps the "rules in scope" term small even when the total rule count grows into the thousands.
- Horizontal scale: evaluators are stateless apart from the loaded ruleset, so throughput scales by adding instances.
- A per-evaluation deadline still exists: if something unexpected (a pathological rule, a slow feature read) exceeds the budget, the evaluator returns a decision from the rules evaluated so far plus a conservative default, and records that it did so.
Staging and rollback
- Shadow first: a new or changed rule runs in shadow for a period, and a dashboard shows how many live decisions it would have changed.
- Promote with an approval step (a second person for rules that block).
- Rollback of a whole version: repoint to the previous version, a config change measured in seconds.
- Kill switch per rule: disable one rule without republishing everything, for the common case where a single new rule is misbehaving.
- Automatic guardrails: alert or auto-disable when a rule's hit rate jumps far above its shadow-period baseline, which catches a mistyped threshold (500 instead of 50,000) within minutes.
Runnable sketch
A minimal version of the compile, evaluate and shadow steps: rules stored as data, validated against an allowed field and operator list at compile time (no eval, Python's built-in for running an arbitrary string as code, which would let a "rule" read secrets, call the network or do anything else the process can do), each rule compiled into a closure (a small function that remembers the specific field, operator and value it was built from, so it can later be called with just a transaction) rather than re-parsed every time, and a candidate version compared against the live one on the same traffic.
import operator
# Rules as authored and stored (data, not code). Version 42 of the ruleset.
# Amounts are in cents, the ledger's minor unit, so 50000 below means 500.00 in the merchant's currency.
RULESET_V42 = [
{"id": "R1", "when": [["amount", ">", 50000], ["country_mismatch", "==", True]], "action": "review"},
{"id": "R2", "when": [["card_attempts_10m", ">=", 5]], "action": "block"},
{"id": "R3", "when": [["email_domain", "in", ["mailinator.com", "tempmail.io"]]], "action": "review"},
]
# Candidate v43 changes R2's threshold from 5 to 3; it runs in shadow first.
RULESET_V43 = [dict(r) for r in RULESET_V42]
RULESET_V43[1] = {"id": "R2", "when": [["card_attempts_10m", ">=", 3]], "action": "block"}
OPS = {">": operator.gt, ">=": operator.ge, "==": operator.eq, "in": lambda a, b: a in b}
ALLOWED_FIELDS = {"amount", "country_mismatch", "card_attempts_10m", "email_domain"}
SEVERITY = {"allow": 0, "review": 1, "block": 2}
def compile_ruleset(rules):
"""Validate once at deploy time, then return one closure per rule. No eval()."""
compiled = []
for r in rules:
preds = []
for field, op, value in r["when"]:
if field not in ALLOWED_FIELDS or op not in OPS:
raise ValueError(f"{r['id']}: unknown field or operator")
f = OPS[op]
# field=field, f=f, value=value bind each closure to THIS loop iteration's
# values; without the defaults, every closure would share the same loop
# variables and all of them would end up testing the LAST rule parsed.
preds.append(lambda tx, field=field, f=f, value=value: f(tx[field], value))
compiled.append((r["id"], r["action"], preds))
# Most severe rules first (a production engine could stop at the first block).
compiled.sort(key=lambda c: -SEVERITY[c[1]])
return compiled
def evaluate(compiled, tx):
hits = [rid for rid, action, preds in compiled if all(p(tx) for p in preds)]
action = max((a for rid, a, _ in compiled if rid in hits), key=SEVERITY.get, default="allow")
return action, hits
live, shadow = compile_ruleset(RULESET_V42), compile_ruleset(RULESET_V43)
traffic = [
{"amount": 1200, "country_mismatch": False, "card_attempts_10m": 1, "email_domain": "gmail.com"},
{"amount": 60000, "country_mismatch": True, "card_attempts_10m": 1, "email_domain": "gmail.com"},
{"amount": 900, "country_mismatch": False, "card_attempts_10m": 4, "email_domain": "gmail.com"},
{"amount": 700, "country_mismatch": False, "card_attempts_10m": 3, "email_domain": "tempmail.io"},
{"amount": 300, "country_mismatch": False, "card_attempts_10m": 6, "email_domain": "gmail.com"},
]
diffs = 0
for i, tx in enumerate(traffic):
a_live, h_live = evaluate(live, tx)
a_shadow, _ = evaluate(shadow, tx) # logged, never enforced
diffs += a_live != a_shadow
print(f"tx{i}: live={a_live:<6} hits={h_live} shadow={a_shadow}")
print(f"shadow would change {diffs} of {len(traffic)} decisions")
try:
compile_ruleset([{"id": "BAD", "when": [["__import__", "==", 1]], "action": "block"}])
except ValueError as e:
print("rejected at deploy:", e)
Output:
tx0: live=allow hits=[] shadow=allow
tx1: live=review hits=['R1'] shadow=review
tx2: live=allow hits=[] shadow=block
tx3: live=review hits=['R3'] shadow=block
tx4: live=block hits=['R2'] shadow=block
shadow would change 2 of 5 decisions
rejected at deploy: BAD: unknown field or operator
The shadow comparison shows exactly what the backtest and shadow stages are for: lowering R2's threshold from 5 to 3 attempts would turn one allow and one review into blocks. Whether that is good depends on whether those payments turn out to be fraud, which is what the decision log and later chargeback data answer. The last line shows the validator refusing a rule that references a field outside the catalogue before it can reach production.
Trade-offs and pitfalls
- Rules that query the database at evaluation time are the usual reason a rule engine blows the latency budget; the feature catalogue is the enforcement point.
- Editing active rules in place loses the audit trail and makes rollback impossible; always version.
- Rule sprawl: hundreds of overlapping rules nobody owns. Track hit rates, give every rule an owner and a review date, retire rules that never fire.
- Rules versus models: rules are transparent and fast to change, models generalise better. Most platforms run both, with rules for known patterns, hard policy and fast response to a new attack.
Design a public payments API for a client that must handle 1 billion requests per day across multiple regions, comply with PCI-DSS, provide sub-100ms median latency for non-card operations, and support partner integrations. Cover the architecture components, security controls, data-residency strategy, and how you'd version and evolve the API without breaking partner integrations.
Sample Answer
Direct answer
Build it as a set of regional cells behind a global edge (a worldwide network of entry points close to each partner, which forwards each request into the right region), with each partner account pinned to a home region inside its data-residency jurisdiction, and with card data confined to a small, separately secured card vault so that almost every request (reads, refunds, payouts, webhooks) never touches raw card numbers. The sub-100ms median target is met by answering non-card calls entirely inside the home region from caches and a local primary database. The API evolves through date-based versions pinned per partner, with the server translating between versions, so partners upgrade on their own schedule and nothing they depend on changes underneath them.
Requirements and load
First, a few terms. PCI DSS (Payment Card Industry Data Security Standard) is the card industry's security standard; its current version is v4.0.1. The CDE (cardholder data environment) is every system that stores, processes or transmits card numbers, and every system connected to those; all of it is audited against PCI DSS. A PAN (primary account number) is the long card number. Data residency means a customer's personal and payment data must be stored and processed inside a named jurisdiction (for example, EU data stays in the EU).
Turn "1 billion requests per day" into a rate:
86,400 s109 requests11,574×3 (assumed peak-to-average ratio)≈11,574 RPS average≈34,722 RPS at peak(RPS is requests per second.) The 3x peak factor is an assumption to state out loud and replace with measured traffic shape. Assume 5% of requests carry card data (creating a payment method or a card payment). That is 50 million card operations per day, about 579 RPS on average. This split is the whole architecture: 95% of the traffic can be served by systems outside the CDE, and the CDE can stay small.
Assume three jurisdictions (US, EU, and a third such as India), each with two regions so a regional failure can fail over without data leaving the jurisdiction. If peak traffic splits evenly across jurisdictions, each carries about 11,574 RPS at peak, and each region in a pair must be sized to absorb its partner's full load: about 11,574 RPS per region, not half of it. Residency is what forces that doubling. You cannot fail EU traffic over to a US region.
Architecture components
flowchart LR
P[Partner client] --> E[Global edge: TLS, WAF, geo routing]
E --> G[Regional API gateway]
G --> A[Auth and rate limiter]
G --> I[Idempotency store]
G --> S[Payments services]
S --> D[(Regional primary DB)]
S --> V[Card vault in CDE]
V --> H[HSM or KMS]
S --> Q[Event bus]
Q --> W[Webhook dispatcher]
Q --> R[Reporting store]
| Component | Responsibility | Why it is there |
|---|---|---|
| Global edge | TLS termination (the point where the partner's encrypted connection is decrypted before the request continues inside the network) near the partner, WAF (web application firewall, which blocks malicious request patterns), absorption of DDoS (distributed denial-of-service) floods, routing to the account's home region | Cuts round-trip time and keeps attack traffic off the regional cells |
| Regional API gateway | API-key or OAuth token validation (OAuth is the standard for delegated access tokens), per-partner rate limits, request schema validation, version translation | One place to enforce the contract before business logic runs |
| Idempotency store | Records each write's idempotency key (a client-chosen unique ID for one intended operation) and its stored response | Partners retry on timeouts; without this, retries create duplicate charges |
| Payments services | Payment state machine, refunds, payouts, partner configuration | Business logic, outside the CDE |
| Card vault | Accepts PANs, returns tokens, talks to card networks and processors | The only place PANs exist, so the audited footprint is small |
| HSM / KMS | A hardware security module or a key management service holds encryption keys; software never sees raw key material | Keys that protect card data never sit next to the data |
| Event bus and webhook dispatcher | Publishes state changes; delivers signed webhooks to partners with retries | Partners integrate asynchronously instead of polling |
| Reporting store | Read-optimised copy for dashboards and exports | Keeps heavy analytical reads off the transactional database |
Routing to the home region. Every account ID and object ID embeds its home-region code (for example acct_eu1_...). The edge reads the partner's credential, looks up the home region from a small replicated routing table (non-personal data only), and forwards there. Object IDs carrying the region mean any request for an existing payment routes correctly without a global lookup.
Cells. A cell is a complete, independent copy of the service stack. A region is the geographic and legal boundary (where the data is allowed to live); a cell is a smaller blast-radius boundary inside it, and a region normally runs several of them. Partners are spread across a region's independent cells (each serving a subset of partners). A bad deployment or a runaway partner then affects one cell, not the region.
Meeting sub-100ms median for non-card operations
A median (p50, the 50th percentile) under 100ms is a budget you allocate, then verify with load tests. An allocation that fits:
| Step | Budget |
|---|---|
| Partner to edge, TLS reuse on a warm connection | 20 ms |
| Edge to home region | 25 ms |
| Gateway: auth (cached key lookup), rate limit, validation | 5 ms |
| Idempotency check and record (writes only) | 5 ms |
| Service logic plus one or two primary-database queries by primary key | 20 ms |
| Headroom | 25 ms |
These are allocations, not measurements. What makes them achievable: no cross-region calls on the request path, API-key verification cached in the gateway, every read by indexed key, and no call to external processors for non-card operations. Card operations are explicitly exempt from the 100ms target because they wait on card networks and issuers you do not control; publish a separate objective for them.
Security controls
- Scope reduction first. Partners collect cards through hosted fields (payment form fields served by an iframe from the vault's own origin, so the card number is typed directly into the vault, never the partner's page) or client SDKs that send the PAN straight to the vault, which returns a token. The partner's servers and your main services only ever see tokens, so they are outside the CDE.
- Card vault hardening. A separate network segment and separate cloud account, no human interactive access by default, envelope encryption (each record encrypted with a data key, and data keys encrypted by a master key held in the HSM or KMS), and key rotation.
- Partner authentication. Secret API keys scoped per environment (test vs live) and per permission set; OAuth for partner platforms acting on behalf of merchants; optional mTLS (mutual TLS, where the client also presents a certificate) for high-value partners.
- Service-to-service. mTLS between internal services and authorization checks on every call, so a compromised service cannot freely call the vault.
- Abuse controls. Per-partner and per-endpoint rate limits, anomaly detection on card-testing patterns (many small authorizations with different cards), and fraud scoring on payments.
- Webhooks. Signed with an HMAC (a keyed hash) over the timestamp and body so partners can verify origin and reject replays.
- Audit. Append-only audit logs of administrative actions and key usage, shipped to storage the platform's own operators cannot edit.
Data-residency strategy
- The partner chooses a home jurisdiction at onboarding; all personal and payment data for that account lives in that jurisdiction's two regions.
- The global control plane (the one piece of the platform allowed to be non-regional; it maps account IDs to home regions and holds nothing else) stores only non-personal routing metadata (account ID to region), never names, emails or card data.
- Replication and backups stay within the jurisdiction's region pair.
- Cross-border needs (a global partner selling in both EU and US) are handled as separate accounts per jurisdiction linked by a parent organisation, not by moving data.
- Analytics that must be global use aggregated or anonymised extracts produced inside each jurisdiction.
Versioning and evolution
- Additive changes ship to everyone. New optional request fields, new response fields, new endpoints and new enum values are non-breaking. Partners are told up front to ignore unknown fields and handle unknown enum values; that expectation is part of the contract.
- Breaking changes get a new dated version (for example
2026-09-01). Each partner account is pinned to the version it first integrated against. A request can override with a version header, which lets a partner test the next version one call at a time. - Translation layer. Internally there is one current model. The gateway runs a chain of small transforms that downgrade responses (and upgrade requests) between adjacent versions. Old versions cost one transform each rather than a forked codebase.
- Webhooks follow the account's pinned version, so an event payload does not change shape under a partner.
- Safety net. Consumer contract tests (automated checks that a real partner request shape still gets back the response that partner's code expects) for the most common partner request shapes run in CI; per-version traffic metrics show who still uses what; deprecation is announced with a long notice period and only retired when traffic reaches zero or the partner has been contacted.
Worked example
A partner in Germany integrated in 2025, pinned to version 2025-03-01. In 2026 the platform renames amount to a nested amount: {value, currency} object. That is breaking, so it ships as 2026-09-01. The German partner's GET /v1/payments/pay_eu1_8f2... routes by the eu1 prefix to Frankfurt, reads one row from the regional primary, and the gateway's downgrade transform flattens the nested object back into the old shape. No card data is read, no processor is called, and the partner sees exactly the response it saw last year. If Frankfurt fails, the request is served from the EU partner region, never from the US.
Trade-offs and pitfalls
- Residency doubles capacity cost. Each jurisdiction needs two full regions; that is the price of failing over without moving data. A single global active-active database (one dataset that every region can write to directly, with every write visible everywhere) would be cheaper and simpler, and illegal for many customers.
- Version transforms accumulate. Each old version adds a transform to maintain and test. Put a lifetime on versions and invest in migration tooling, or the chain becomes the slowest part of the gateway.
- Common wrong turn: putting the whole platform in PCI scope because one service touches PANs. That makes every deploy an audit event and slows everything.
- Common wrong turn: one global idempotency store. Keys must be checked in the home region with strong consistency (every read sees the latest write immediately, never a stale replica's answer), or two regions can both accept the same retried payment.
- Latency pitfalls: synchronous calls to the fraud engine or to a global service on the non-card path quietly break the median; move them off the request path or make them regional.
Unlock Full Question Bank
Get access to all 35 Payment and Transaction Processing Systems interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.