Making External Payment Integration Resilient to Retries and Network Drops
System DesignModel answerLast updated
Analyze a buggy payment handler, explain why database transactions fail to solve distributed state issues, and design a resilient flow using idempotency and background reconciliation.
Consider the following ticket checkout handler used by an e-commerce platform. A client application calls this endpoint when a user attempts to complete a purchase. If the request times out (after 10 seconds) or returns a 5xx server error, the client automatically retries the operation once.
def process_checkout(user_id: str, event_id: str, quantity: int, price_per_ticket: int) -> dict:
total_amount = quantity * price_per_ticket
receipt = payment_gateway.charge(user_id, total_amount) # Remote API call over HTTPS
db.orders.insert({ # Single write to PostgreSQL
"user_id": user_id,
"event_id": event_id,
"quantity": quantity,
"total_amount": total_amount,
"receipt_id": receipt,
})
return {"status": "success", "receipt_id": receipt}
Assume payment_gateway.charge interacts with an external payment provider to execute a financial charge and returns a transaction identifier upon success. If a known error occurs, it raises an exception. db.orders.insert persists a single record in the local database.
Answer the following three parts:
Part 1: Failure Point Analysis
Analyze the step-by-step execution path. Identify every point where a process crash, network interruption, or database error could occur. For each failure scenario, describe:
- The state of the customer's payment balance/card.
- The state of the local
orderstable. - What happens when the client application issues an automatic retry.
Part 2: Evaluation of Database Transactions
A software engineer suggests wrapping both the payment gateway call and the database insert inside a standard database transaction block (e.g., BEGIN ... COMMIT). Explain why this solution is inadequate and what new problems it introduces.
Part 3: Architecture Redesign
Redesign the checkout flow—including API contracts, database schema, and supporting infrastructure—to guarantee that:
- A user is never double-billed for a single intent to purchase, regardless of network failures, duplicate requests, or system crashes.
- Every successful payment is eventually matched with an order record in the database.
- The client app receives a clear, accurate response even when the payment status is temporarily uncertain.
State any technical capabilities you require from the external payment gateway.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Failure Point Analysis
When executing operations across network boundaries without distributed transaction protocols, partial failures create inconsistent states.
| Failure Point | Card / Gateway State | Database (orders) State | Result of Client Retry |
|---|---|---|---|
| 1. Prior to sending request to Gateway | Not charged | No record | Safe: Charge succeeds, single order record created. |
| 2. Gateway request drops in transit | Not charged | No record | Safe: Retry reaches gateway, charge succeeds, single order record created. |
| 3. Gateway charges card, but response drops (or client times out) | Charged | No record | Double Charge: App retry issues a brand-new charge call. User is billed twice; one charge has no database record. |
| 4. Process crashes or DB fails after charge succeeds | Charged | No record | Double Charge / Orphan Charge: Money is taken, but application raises an exception. Client retry attempts another charge. |
| 5. DB insert succeeds, but response to client drops | Charged | Order record exists | Duplicate Record / Re-charge: Application executes the function again. Depending on database primary key constraints, it either charges again or fails on duplicate insert after charging. |
| 6. Gateway raises a clear decline exception | Not charged | No record | Safe: Exception bubbles up; client does not re-attempt a invalid charge. |
Key Anomalies Identified:
- Orphaned Payments: Money is deducted from the user, but no order record exists in our system.
- Double Billing: Retrying a non-idempotent operation leads to multiple credit card charges for a single purchase action.
- Inaccurate Client Feedback: Returning an error code to the client on timeout when the charge actually went through.
Part 2: Evaluation of Database Transactions
Wrapping the gateway call and database insert in a local database transaction (e.g., BEGIN ... COMMIT) does not resolve the issue for two main reasons:
- Non-Transactional External Side Effects: Standard ACID database transactions only manage internal storage state. A database rollback (
ROLLBACK) cannot undo an external HTTP request or refund a credit card charge that has already been captured by a payment processor. If the database insert fails afterpayment_gateway.charge()returns, the database rolls back, but the user's money remains taken. - Connection Starvation & Latency: External network calls can take seconds or time out entirely. Holding open an active database transaction while waiting on a third-party HTTP call consumes database connection pool slots, holds row locks unnecessarily, and makes the system vulnerable to cascading failures under load.
Conclusion: Distributed state across independent systems cannot be solved with local database transactions; it requires Idempotency combined with Asynchronous Reconciliation.
Part 3: Architecture Redesign
1. System Assumptions & Requirements
- Gateway Idempotency Support: The payment processor must support client-defined idempotency keys (e.g., Stripe's
Idempotency-Keyheader) and preserve charge outcomes for at least 24 hours. - Client Attempt Identification: The client application generates a unique UUID (
purchase_id) when the user taps "Buy". This ID persists across all network retries for that specific checkout attempt.
2. Database Schema
We track payment state transitions explicitly before calling external services.
CREATE TYPE purchase_status AS ENUM ('PENDING', 'PAID', 'FAILED', 'UNKNOWN');
CREATE TABLE orders (
purchase_id UUID PRIMARY KEY,
user_id VARCHAR(64) NOT NULL,
event_id VARCHAR(64) NOT NULL,
quantity INT NOT NULL,
total_amount INT NOT NULL,
status purchase_status NOT NULL DEFAULT 'PENDING',
receipt_id VARCHAR(128),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
3. Execution Flow
[ Client ] [ App Server ] [ DB ] [ Payment Gateway ]
| | | |
|-- POST /checkout ------->| | |
| (purchase_id=UUID) |-- INSERT (PENDING) --->| |
| |<-- OK / CONFLICT ------| |
| | |
| |-- charge(key=purchase_id) ------------------------>|
| |<-- receipt_id / timeout / decline -----------------|
| | |
| |-- UPDATE status='PAID' / 'FAILED' / 'UNKNOWN' ---->|
| | |
|<-- HTTP 200/202/400 -----| |
Handler Implementation Logic:
-
Record Intent First: Perform an idempotent insertion into
orders:INSERT INTO orders (purchase_id, user_id, event_id, quantity, total_amount, status) VALUES ($1, $2, $3, $4, $5, 'PENDING') ON CONFLICT (purchase_id) DO NOTHING;If the record already exists, fetch its current status:
- If
status == 'PAID', immediately return success withreceipt_id. - If
status == 'FAILED', return the stored error. - If
status == 'PENDING'or'UNKNOWN', proceed to re-query the gateway or inform the client that processing is in progress.
- If
-
Execute Payment with Idempotency Key: Call
payment_gateway.charge(..., idempotency_key=purchase_id).- If the gateway receives duplicate calls with the same key, it returns the existing transaction result without charging the card again.
-
Update State Based on Outcome:
- Success: Update
ordersstatus to'PAID'withreceipt_id. Return HTTP200 OK. - Definite Decline (e.g., insufficient funds): Update status to
'FAILED'. Return HTTP400 Bad Request. - Timeout / Network Error / 5xx: Update status to
'UNKNOWN'(or leave as'PENDING'). Do not return a failure error to the client. Return HTTP202 Acceptedwith a status polling endpoint:/orders/{purchase_id}/status.
- Success: Update
4. Background Reconciliation Worker
To handle instances where the application crashes after charging the gateway but before updating the database to 'PAID':
- Stale Order Poller: A worker runs periodically (e.g., every 60 seconds) querying for orders with
status IN ('PENDING', 'UNKNOWN') AND updated_at < NOW() - INTERVAL '2 minutes'. - Gateway Status Check: The worker queries the payment gateway using the
purchase_idas the lookup reference. - State Resolution:
- If the gateway confirms payment was processed, the worker updates the order record to
'PAID'and stores thereceipt_id. - If the gateway confirms no charge was processed (or the idempotency key expired unused), the worker marks the order as
'FAILED'.
- If the gateway confirms payment was processed, the worker updates the order record to
5. Complexity & Edge Case Considerations
- Payload Validation on Retry: If a client sends an existing
purchase_idwith a differenttotal_amountorevent_id, the server rejects the request with HTTP409 Conflictto prevent request tampering. - Inventory Hold Window: Seat reservations should be managed independently via temporary reservation locks with explicit expiration (TTL), ensuring tied-up seats are released if the payment ultimately transitions to
'FAILED'.