📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Design the payment integration for an Australian e-commerce site that takes card payments through a payment service provider. Walk me through the payment flow and state machine, how you keep PCI DSS scope small, how you make charges idempotent when a request times out, how you handle webhooks, and how you reconcile with the provider's settlement reports.

A full payment gateway integration design: requirements and volumes, hosted fields and tokenisation to minimise PCI DSS scope, a payment state machine with 3-D Secure, idempotency keys and unknown-outcome handling, verified and deduplicated webhooks, daily reconciliation against settlement reports, and failure modes, in .NET on Azure.

Senior SystemDesign Advanced idempotency payments pci-dss reconciliation system-design webhooks

๐ŸŽฏ Key points

  • Card data never touches our servers: PSP hosted fields / payment page → token → smallest PCI DSS v4.0.1 scope (SAQ A eligibility)
  • PCI DSS v4.0.1 still applies to the page hosting the iframe: script inventory and authorisation (req. 6.4.3) and change/tamper detection on the payment page (req. 11.6.1), plus TLS 1.2+ for every call and webhook
  • Payment state machine: Created → RequiresAction (3DS) → Authorised → Captured → Refunded / Failed / Cancelled
  • Idempotency key per payment attempt sent to the PSP; a retry reuses it, never a new key
  • Timeout = unknown outcome: query the PSP by merchant reference before retrying or failing the order
  • Webhooks: verify HMAC signature and timestamp, dedup by event id (inbox), apply via the state machine so out-of-order events are safe
  • Daily reconciliation vs settlement report: auto-resolve timing differences next day, auto-void orphan authorisations, route true mismatches to a finance case with the PSP and order ids
  • Amounts as integer minor units (cents) with currency; outbox for 'payment captured' events

โฑ 30-second answer

I keep card data out of our systems entirely: the browser uses the PSP's hosted fields, we get a token, and our PCI DSS scope shrinks to the smallest self-assessment. Each payment is a state machine (Created โ†’ RequiresAction for 3-D Secure โ†’ Authorised โ†’ Captured โ†’ Refunded). Every call to the PSP carries an idempotency key tied to the payment attempt, so retries can't double-charge. A timeout is an unknown outcome: I query the PSP by our merchant reference before deciding. Webhooks are verified, deduplicated by event id and applied through the state machine, so out-of-order delivery is harmless. A daily reconciliation compares our records with the settlement report. The trade-off: the PSP owns the money movement and much of the flexibility; we own correctness of our records.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd clarify the scope: card payments, probably Apple Pay and Google Pay through the same provider, authorise at checkout and capture on dispatch, refunds from the back office, all in AUD for now. Volumes for a mid-sized retailer: two million orders a month is under one a second on average, but a sale can hit 50 a second. So this isn't a throughput problem; it's a correctness problem. Every bug here is either lost revenue or a double charge.

First, PCI scope. The browser renders the provider's hosted fields or redirect page, card data goes straight to the PSP, and we receive a token. Our servers never see a card number, which keeps us in the lightest PCI DSS self-assessment and keeps auditors out of our Kubernetes cluster. Then the flow: our API creates a Payment row in state Created with an idempotency key, calls the PSP to create a payment intent with that key and our order reference, and handles 3-D Secure if the issuer asks for it. When the PSP says Authorised, we move the order on.

The hard part is timeouts. If the call to the PSP times out, we don't know whether the customer was charged. Retrying with a new key could charge twice; failing the order could lose a paid order. So we retry with the same idempotency key, or query the PSP by merchant reference. For example, at [company] we [found duplicate charges during a provider slowdown because the retry generated a new key]; [moving the key onto the payment attempt row] took duplicates to [zero]. Webhooks are the source of truth for asynchronous outcomes: we verify the signature, store the event id in an inbox table to drop duplicates, and apply it through the state machine so an old event can't move a refunded payment back to captured.

The mistake I see is trusting our own database as the truth about money. The provider's settlement report is the truth, so every day we reconcile against it. Payments is idempotency, a state machine and reconciliation; the API call is the easy bit."


Requirements

Type Requirement Assumption
Functional Card, Apple Pay, Google Pay via one PSP AUD only initially
Functional Authorise at checkout, capture on dispatch Auths expire after ~7 days (scheme dependent)
Functional Full and partial refunds Back-office role, audited
Non-functional No double charges, no lost paid orders Idempotency + reconciliation
Non-functional Minimal PCI DSS scope Hosted fields / redirect
Non-functional Checkout p95 < 2 s excluding 3DS challenge PSP in-region where possible

Capacity estimate

Quantity Arithmetic Result
Orders/month given 2,000,000
Average rate 2M รท 2.6M s โ‰ˆ 0.8/s
Peak (sale) assumption โ‰ˆ 50/s
Webhooks ~3 per payment โ‰ˆ 6M/month, peak 150/s
Payment + event rows/year 24M ร— ~5 rows ร— 500 B โ‰ˆ 60 GB

High-level design

Browser โ”€โ”€ hosted fields (card data) โ”€โ”€โ–บ PSP
   โ”‚                                        โ”‚ โ–ฒ
   โ”‚ token + order                          โ”‚ โ”‚ create/confirm/capture (Idempotency-Key)
   โ–ผ                                        โ–ผ โ”‚
Checkout API (ASP.NET Core) โ”€โ”€โ–บ Payments service โ”€โ”€โ–บ Azure SQL: Payments, PaymentAttempts, Inbox, Outbox
                                   โ–ฒ                      โ”‚ outbox relay
PSP webhooks โ”€โ”€โ–บ Webhook endpoint (verify signature) โ”€โ”˜      โ–ผ
                                                   Service Bus: payment-captured โ”€โ”€โ–บ Orders, Fulfilment
Settlement report (SFTP/API, daily) โ”€โ”€โ–บ Reconciliation job โ”€โ”€โ–บ mismatches queue โ”€โ”€โ–บ finance screen

Payment states

State Entered by Allowed next
Created our API RequiresAction, Authorised, Failed
RequiresAction PSP (3DS challenge) Authorised, Failed
Authorised PSP response or webhook Captured, Cancelled
Captured capture call / webhook Refunded (partial/full)
Failed / Cancelled / Refunded terminal (Refunded may be partial) โ€”

Production example

For a retailer processing [1.5 million] payments a month, reconciliation flagged on average [12] mismatches a day, mostly webhooks delayed past the cut-off, all auto-resolved the next day. After introducing unknown-outcome handling, duplicate charges fell from [about 40 a month] during provider incidents to zero.

๐Ÿ” What the interviewer is checking

Checks that the candidate understands money correctness: scope, idempotency, unknown outcomes, asynchronous events and reconciliation.

Green flags

  • Keeps card data out of scope with tokenisation
  • Explains the unknown outcome on timeout and how idempotency keys resolve it
  • Verifies and deduplicates webhooks and uses a state machine
  • Reconciles daily against settlement reports

Red flags

  • Stores card numbers or CVVs
  • Retries payment calls blindly
  • Treats webhooks as reliable and ordered
  • Uses floating-point amounts

๐Ÿ“š Learn in depth

1. PCI DSS scope

PCI DSS (version 4.0.1 is current) applies to systems that store, process or transmit cardholder data, and to systems connected to them. With a redirect or hosted fields (an iframe served by the PSP), the card number never reaches your servers. Merchants with fully outsourced card capture usually qualify for the shortest self-assessment questionnaire (SAQ A), though v4 still expects you to protect the payment page scripts (inventory and integrity of scripts on the page that loads the iframe) and to manage the page's security headers. Check the current SAQ eligibility criteria with your acquirer.

In scope (small):  checkout page that embeds PSP iframe, its scripts, CSP
Out of scope:      APIs, database, AKS cluster (they only see tokens)

2. Idempotency and the unknown outcome

Attempt row: (PaymentId, AttemptNo, IdempotencyKey = PaymentId:AttemptNo, Status)

call PSP with Idempotency-Key โ”€โ”€โ–บ 200: record result
                               โ”€โ”€โ–บ 4xx (declined): record, terminal for this attempt
                               โ”€โ”€โ–บ timeout / 5xx: status = Unknown
                                       โ”‚
                                       โ”œโ”€ retry with SAME key (PSP returns the original result), or
                                       โ””โ”€ GET payment by merchant reference / wait for webhook

PSPs such as Stripe and Adyen store results by idempotency key for a period (often 24 hours), so a retry with the same key returns the original outcome instead of charging again. A new attempt (new key) is created only after the previous one is known to have failed, for example a decline, after which the customer tries another card.

3. Webhooks

  • Verify the signature (HMAC with the endpoint secret) over the raw body, and reject old timestamps to stop replays.
  • Return 2xx quickly; process asynchronously.
  • Store the event id with a unique index (inbox pattern) so duplicates are dropped.
  • Apply events through the state machine: a payment.captured arriving after refund.succeeded must not move the payment backwards. Compare states, or use the PSP object's version/timestamp.
  • Expect gaps: if a webhook never arrives, a sweeper queries the PSP for payments stuck in Created or Unknown for more than [15 minutes].

4. Reliable downstream events

When the payment becomes Captured, insert an outbox row in the same transaction; a relay publishes PaymentCaptured to Service Bus. Orders and fulfilment consume idempotently. Without the outbox, a crash between commit and publish leaves a paid order never shipped.

5. Reconciliation

Daily: load the PSP's settlement report (transactions, fees, refunds, chargebacks, payouts), match on PSP payment id and merchant reference, compare amount and currency, and classify: matched; missing on our side (paid but no order, the worst case); missing on PSP side; amount mismatch. Unmatched items go to a finance work queue. Also reconcile payouts against the bank statement.

6. Money representation and audit

Store amounts as long minor units plus ISO currency, never double. Payment records are append-only events plus a current state; every refund records who did it and why. Keep tokens and PSP ids, never PANs or CVVs.

7. Australian notes

Debit cards are often dual-network; least-cost routing for dual-network debit is something Australian merchants and regulators care about, so ask the PSP how it routes. If you add bank-account payments (for example PayTo agreements over the NPP), they have different states and timings to cards; check current scheme details before designing for them.

8. AWS mapping

Same PSP integration; API on ECS/Lambda, Aurora/DynamoDB for payments, SQS/EventBridge for events, S3 for settlement files.

Try it yourself

  1. Use your PSP's test mode: send the same create request twice with one idempotency key and confirm one charge.
  2. Inject a timeout after the PSP call in a test and verify the payment ends Unknown, then is resolved by query.
  3. Replay a webhook twice and out of order; assert the state machine ends in the right state.
  4. Write a reconciliation test with a settlement CSV containing one missing and one mismatched row.
  5. Scan your checkout page with your browser's dev tools to list every script that could read the iframe page.

๐Ÿ’ป Code

A payment state machine, idempotent PSP call with unknown-outcome handling, and a verified, deduplicated webhook endpoint.

namespace Payments;

public enum PaymentState { Created, RequiresAction, Authorised, Captured, Refunded, Failed, Cancelled, Unknown }

public sealed class Payment(Guid id, string orderRef, long amountMinor, string currency)
{
    public Guid Id { get; } = id;
    public string OrderRef { get; } = orderRef;
    public long AmountMinor { get; } = amountMinor;   // cents, never double
    public string Currency { get; } = currency;
    public PaymentState State { get; private set; } = PaymentState.Created;
    public int Attempt { get; private set; } = 1;
    public string IdempotencyKey => $"{Id}:{Attempt}"; // stable across retries of the same attempt

    private static readonly Dictionary<PaymentState, PaymentState[]> Allowed = new()
    {
        [PaymentState.Created] = [PaymentState.RequiresAction, PaymentState.Authorised, PaymentState.Failed, PaymentState.Unknown],
        [PaymentState.Unknown] = [PaymentState.RequiresAction, PaymentState.Authorised, PaymentState.Failed],
        [PaymentState.RequiresAction] = [PaymentState.Authorised, PaymentState.Failed],
        [PaymentState.Authorised] = [PaymentState.Captured, PaymentState.Cancelled],
        [PaymentState.Captured] = [PaymentState.Refunded],
    };

    // Returns false for stale or duplicate transitions, so out-of-order webhooks are harmless.
    public bool TryMoveTo(PaymentState next)
    {
        if (!Allowed.TryGetValue(State, out var targets) || !targets.Contains(next)) return false;
        State = next;
        return true;
    }

    public void NewAttemptAfterDecline() { if (State == PaymentState.Failed) { Attempt++; State = PaymentState.Created; } }
}

public interface IPspClient
{
    Task<PaymentState> AuthoriseAsync(Payment p, string token, string idempotencyKey, CancellationToken ct);
    Task<PaymentState?> FindByMerchantRefAsync(string orderRef, CancellationToken ct);
}

public sealed class PaymentService(IPspClient psp, ILogger<PaymentService> log)
{
    public async Task AuthoriseAsync(Payment p, string token, CancellationToken ct)
    {
        try
        {
            p.TryMoveTo(await psp.AuthoriseAsync(p, token, p.IdempotencyKey, ct));
        }
        catch (Exception ex) when (ex is TimeoutException or HttpRequestException or TaskCanceledException)
        {
            // Unknown outcome: never retry with a new key. Ask the PSP what happened.
            log.LogWarning(ex, "PSP outcome unknown for {PaymentId}", p.Id);
            p.TryMoveTo(PaymentState.Unknown);
            if (await psp.FindByMerchantRefAsync(p.OrderRef, ct) is { } actual) p.TryMoveTo(actual);
            // else: a sweeper retries the query, and the webhook will also resolve it
        }
    }
}
// Webhook endpoint: verify HMAC over the raw body, dedup by event id, process asynchronously.
using System.Security.Cryptography;
using System.Text;

app.MapPost("/webhooks/psp", async (HttpRequest req, IInbox inbox, IConfiguration config, CancellationToken ct) =>
{
    using var reader = new StreamReader(req.Body);
    var body = await reader.ReadToEndAsync(ct);
    var signature = Convert.FromHexString(req.Headers["X-Signature"].ToString());
    var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(config["Psp:WebhookSecret"]!), Encoding.UTF8.GetBytes(body));
    if (!CryptographicOperations.FixedTimeEquals(signature, expected)) return Results.Unauthorized();

    var eventId = System.Text.Json.JsonDocument.Parse(body).RootElement.GetProperty("id").GetString()!;
    await inbox.TryAddAsync(eventId, body, ct); // unique index on EventId: duplicates are ignored
    return Results.Ok();                         // a background worker applies events via TryMoveTo
});

public interface IInbox { Task<bool> TryAddAsync(string eventId, string payload, CancellationToken ct); }

โš  Common mistakes

  • Mistake: Letting card numbers reach your API "just to forward them". Why it is wrong: every system that touches the PAN, and everything connected to it, is in PCI DSS scope. Instead: hosted fields or a redirect, and only tokens on your side.
  • Mistake: Generating a new idempotency key on every retry. Why it is wrong: the PSP treats each as a new charge, so a timeout followed by a retry double-charges. Instead: key per payment attempt, persisted before the call.
  • Mistake: Treating a timeout as a failure. Why it is wrong: the customer may have been charged, and you cancel a paid order. Instead: mark Unknown and resolve by query or webhook.
  • Mistake: Processing webhooks synchronously without signature checks or dedup. Why it is wrong: forged or replayed events change payment state, and slow handlers cause PSP retries and duplicates. Instead: verify HMAC, store in an inbox with a unique event id, process asynchronously.
  • Mistake: Applying webhooks in arrival order. Why it is wrong: events arrive out of order, so a late 'captured' can overwrite 'refunded'. Instead: a state machine that rejects backward transitions.
  • Mistake: Storing money as double or decimal without currency. Why it is wrong: floating-point rounding and mixed currencies corrupt totals. Instead: long minor units plus ISO currency code.
  • Mistake: No reconciliation. Why it is wrong: missed webhooks and bugs leave paid orders unfulfilled or refunds unrecorded, found only by complaints or audits. Instead: daily automated reconciliation with a finance work queue.

๐Ÿ› Senior insight: trade-offs

Senior engineers treat the PSP as the system of record for money and their own database as a well-kept copy that must be reconciled. That's why I design the unknown state, the sweeper and reconciliation up front rather than bolting them on after the first incident. I'd also keep the PSP behind an interface, not to swap providers casually (that's rarely cheap), but so tests can simulate timeouts and out-of-order webhooks.

Option When it fits Cost When not to
Hosted payment page (redirect) Smallest scope, simplest Less control over UX Highly custom checkout
Hosted fields / drop-in components Custom UX, still minimal scope Script integrity duties on your page Native apps (use PSP SDKs)
Direct API with raw card data Large merchants with their own vault Full PCI DSS assessment Almost everyone else
Second PSP for failover Very high revenue per minute Two integrations, two reconciliations Most merchants: the PSP's own redundancy is enough

I measure authorisation rate, payment latency, Unknown payments older than 15 minutes, webhook lag, reconciliation mismatches per day, and duplicate charge count (target zero).

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions idempotency keys Why: Checks how dedup storage behaves when two copies of a request arrive concurrently
    How to answer

    An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.

  2. When: Candidate says webhooks are deduplicated Why: Checks the inbox pattern: unique key, one transaction with the business change, concurrent duplicates
    How to answer

    With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.

    The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.

    Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.

  3. When: Candidate connects payment to orders and inventory Why: Checks outbox, inbox and saga behaviour across services when steps fail
    How to answer

    Each service changes its own data and writes outgoing messages in one transaction (outbox), and dedups incoming messages (inbox). A saga orchestrator persists the order's progress: on OrderPlaced it sends ReserveStock; on StockReserved it sends CapturePayment; on PaymentCaptured it completes. If payment fails it sends the compensation ReleaseStock.

    At every step a crash either committed nothing (the message is redelivered) or committed everything (the outbox resends). Duplicates hit the inbox. Missing replies trigger scheduled timeouts, and late replies after a timeout get their own handling, such as refunding a late capture. Poison messages dead-letter with alerts.

    The trade-off: reliability without distributed transactions, paid for with eventual consistency, more states and more operational tooling.

๐Ÿ›  Real-world problems: how you handle them

Duplicate card charges during a PSP slowdown
Situation
Checkout for [an online fashion retailer], [1.5 million] payments a month on [Azure App Service + Azure SQL], integrated with [a PSP]. A [mid-season sale] coincided with PSP latency.
Signals
Customer complaints of being charged twice; the PSP dashboard showed pairs of authorisations [seconds] apart for the same order; Application Insights showed PSP dependency timeouts at [10 s] and retries from Polly.
Investigation
Traced the retry policy: each retry built a new request with a new idempotency key generated in the HTTP handler. Matched PSP payment ids to orders and found [180] duplicates in [3 hours].
Resolution
Immediate: disabled automatic retries on the authorise call and voided duplicate authorisations through the PSP. Long term: idempotency key persisted on the payment attempt row, an Unknown state with query-by-reference, a sweeper for stale Unknown payments, and webhook-driven resolution.
Prevention
Integration tests that inject timeouts and assert one charge; a daily reconciliation alert on multiple authorisations per order; a review checklist item: 'no new idempotency key on retry'.

How to tell it (STAR)

**S:** At [company], during a sale with the payment provider running slow, customers started reporting double charges. **T:** I led the fix, first stopping the bleeding and then making it impossible to repeat. **A:** I found our retry policy minted a new idempotency key per retry, so the provider saw each retry as a new payment. I switched off the retry, voided the [180] duplicates with the provider, then moved the key onto the payment attempt, added an Unknown state resolved by querying the provider, and added a reconciliation check for multiple authorisations per order. **R:** We've had zero duplicate charges in [the 18 months] since, including [two] provider incidents.

โ†ฉ Usually asked after

More in Systems to Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me