Handling Partial Failure in a Payment Service Method
System DesignModel answerLast updated
Analyze a Java method that charges a payment provider then writes to a database, identifying failure scenarios and proposing fixes for consistency.
You are reviewing a Java service method that processes payments. The method performs two operations in sequence: it calls an external payment provider to charge a customer, then inserts a record into the database.
import java.util.Map;
public class PaymentService {
private final PaymentProvider provider;
private final Database db;
public Map<String, String> createPayment(String userId, int amountCents) {
// calls external provider (e.g., Stripe-like)
String chargeId = provider.charge(userId, amountCents);
db.insert("payments", Map.of(
"user_id", userId,
"amount", amountCents,
"charge_id", chargeId
));
return Map.of("status", "ok", "charge_id", chargeId);
}
}
Assumptions:
provider.chargeperforms a synchronous network call that debits the customer and returns a charge identifier on success, throwing an exception if the charge failsdb.insertwrites a single row to the payments table- The caller (a mobile app or upstream service) may retry the request if it times out or receives an error
Your task: Identify what can go wrong when failures occur during or between these operations, and explain how you would redesign this method to ensure correctness and consistency. You do not need to write production code—focus on describing the problems and your approach to solving them.
Consider questions like:
- What inconsistent states can arise?
- How should the system behave when the outcome is uncertain?
- What mechanisms ensure a purchase attempt is processed exactly once?
- What information does the caller need to send, and what should it receive back?
Hints
Hint 1
Consider what happens if the process crashes after the provider charges successfully but before the database write completes.
Hint 2
Think about whether wrapping both operations in a database transaction solves the problem, and why distributed systems need different consistency mechanisms.
Hint 3
Idempotency keys allow safe retries—how would you generate them, enforce uniqueness, and pass them to the provider?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem Analysis
The core issue is that this method performs two independent operations that cannot be wrapped in a single atomic transaction: one mutates external state (the provider's ledger), and one mutates local state (our database). Several failure scenarios create inconsistency:
Failure after the charge succeeds but before the database write:
The customer is charged, provider.charge returns a charge ID, but the process crashes or the database is unavailable. The charge exists at the provider but not in our records. The caller receives a timeout or error and retries, causing a duplicate charge.
Network timeout during the provider call: The charge request reaches the provider and succeeds, but the response is lost due to network failure. From our perspective the call timed out and we don't know if the customer was charged. A retry will charge again.
Caller retry after any error: If the caller receives an exception or timeout, it cannot distinguish between "charge failed" and "charge succeeded but recording failed." Retrying blindly may duplicate charges.
No visibility into payment state: The method returns only success or throws an exception. There is no way to communicate "unknown outcome" or "pending reconciliation," leaving the caller unable to make safe decisions.
Wrapping both calls in a database transaction does not help—the provider call commits immediately at the provider, and a database rollback cannot undo it.
Solution: Idempotency and State Tracking
1. Require a Client-Supplied Idempotency Key
The caller must generate and send a unique identifier for each purchase attempt (e.g., a UUID). This key represents the intent to make a specific payment.
public PaymentResult createPayment(String idempotencyKey, String userId, int amountCents)
2. Record the Attempt Before Calling the Provider
Write a row to the database immediately, in a PENDING state, with the idempotency key as a unique constraint. This ensures duplicate requests are detected early.
db.insert("payments", Map.of(
"idempotency_key", idempotencyKey,
"user_id", userId,
"amount", amountCents,
"status", "PENDING",
"created_at", now()
));
If the insert violates the unique constraint, the request is a retry. Look up the existing payment and return its current state.
3. Pass the Idempotency Key to the Provider
Most payment providers accept an idempotency key parameter. If the same key is used in multiple requests, the provider returns the original charge result instead of creating a new charge.
String chargeId = provider.charge(userId, amountCents, idempotencyKey);
4. Update the Payment Record with the Outcome
If the provider call succeeds, update the row to COMPLETED and store the provider's charge ID. If the provider rejects the charge (e.g., insufficient funds), update to DECLINED.
db.update("payments",
Map.of("status", "COMPLETED", "charge_id", chargeId),
Map.of("idempotency_key", idempotencyKey)
);
If an exception occurs during the provider call and we cannot determine the outcome, leave the status as PENDING. A background reconciliation job periodically queries the provider for all pending payments and updates their final state.
5. Return Explicit Status to the Caller
The response should distinguish between success, decline, and unknown outcome:
return new PaymentResult(
status, // COMPLETED | DECLINED | PENDING
chargeId, // null if pending
idempotencyKey
);
If the status is PENDING, the caller should poll or wait for a webhook rather than retry immediately.
Additional Improvements
Timeouts and retries within the service:
Configure a reasonable timeout for the provider call. If it times out, mark the payment PENDING and rely on reconciliation rather than throwing an exception that prompts the caller to retry.
Reconciliation job:
A scheduled task queries all payments in PENDING state for longer than a threshold (e.g., 5 minutes) and calls the provider's lookup API using the idempotency key or charge reference to determine the final outcome.
Logging and observability: Log every state transition with the idempotency key, user ID, and charge ID to enable troubleshooting and auditing.
Distinguish transient vs permanent provider errors:
A 400 Bad Request (invalid card) should result in DECLINED. A 503 Service Unavailable should leave the payment PENDING and be retried internally or reconciled later.
Common Mistakes
- Believing a database transaction can make the provider call atomic—it cannot coordinate with external systems.
- Generating the idempotency key server-side on each request, which defeats the purpose since retries generate new keys.
- Not recording the attempt before calling the provider, leaving no trace of the intent if the call times out.
- Treating all errors the same way—some indicate the charge definitely failed, others indicate uncertainty.
- Not surfacing "unknown outcome" to the caller, forcing them to guess whether retrying is safe.
This design ensures that each purchase attempt is processed exactly once, even in the presence of network failures, crashes, and retries, and provides honest feedback when the outcome is uncertain.