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.
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.
"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."
| 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 |
| 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 |
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
| 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) | โ |
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.
Checks that the candidate understands money correctness: scope, idempotency, unknown outcomes, asynchronous events and reconciliation.
Green flags
Red flags
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)
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.
payment.captured arriving after refund.succeeded must not move the payment backwards. Compare states, or use the PSP object's version/timestamp.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.
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.
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.
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.
Same PSP integration; API on ECS/Lambda, Aurora/DynamoDB for payments, SQS/EventBridge for events, S3 for settlement files.
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); }
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.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).
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.
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:
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.
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.
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.
Last updated 23 Nov 2026.