Fixing a Non-Atomic Charge-Then-Record Trip Payment Flow
System DesignModel answerLast updated
Review a Java method that charges a card through an external processor and then saves a trip row, and explain how failures cause lost or duplicate charges and how to make it safe.
A ride-hailing backend contains the Java service below. When a trip ends, it collects the fare from the rider's card using an external payment processor, then saves a record of the trip in the local database.
import java.util.Map;
public class FareCaptureService {
private final CardProcessor processor;
private final Database db;
public Map<String, String> captureFare(String riderId, int fareCents) {
String captureId = processor.capture(riderId, fareCents);
db.insert("trips", Map.of(
"rider_id", riderId,
"fare_cents", fareCents,
"capture_id", captureId
));
return Map.of("status", "ok", "capture_id", captureId);
}
}
Assumptions:
processor.captureperforms a network call that actually moves money. It returns a processor-assigned capture ID and throws if it fails.db.insertwrites one row and has no other side effects.- The caller (a dispatch service) may retry when it times out or sees an error.
Question. Suppose the process running this method crashes, or a call times out, partway through. What can go wrong? How would you change the design and the code so that riders are never charged twice and no charge goes unrecorded?
This is a discussion exercise. Your code does not need to compile, but your proposed fix should be concrete.
A strong answer should:
- Identify each failure point in and around the two calls and the resulting inconsistent state (money moved but unrecorded, money moved twice, or outcome unknown).
- Explain why simply wrapping the work in a database transaction does not solve the problem.
- Propose a mechanism that makes retries safe, and show how it is enforced both locally and at the processor.
- Say what the method should return or throw when the capture succeeded but the save failed, versus when the capture call timed out with an unknown result.
- Describe a background process that repairs any remaining inconsistencies.
Hints
Hint 1
List every moment at which a crash or lost response could happen: before the call, while the request is in flight, after the processor answers but before the row is written, and after the row is written. For each, ask whether money moved and whether the database knows.
Hint 2
A local database transaction can only roll back local writes. Think about which of the two steps it cannot undo, and what that means for retries.
Hint 3
Make a retry recognizable as the same attempt. Who should create the identifier, when, and where must it be checked (your database and the processor)?
Hint 4
Record intent before acting: store a pending row first, then update it to captured, failed, or unknown. Then think about a periodic job that resolves rows that stay pending or unknown.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The core problem
captureFare performs two independent side effects in two different systems: it moves money at the processor, and it records that fact in our database. There is no way to roll back a completed card capture from inside this process, so any failure around the two calls can leave the systems disagreeing.
Failure points
- Request sent, response lost (timeout or crash before
capturereturns). The processor may or may not have charged the card. The code has no record of the attempt. A naive retry callscaptureagain and can charge the rider twice. - Crash after
capturereturns but beforedb.insertcompletes. Money has definitely moved, but notripsrow exists. The charge is untracked, and a retry will charge again. db.insertthrows (transient DB error, constraint failure, connection drop) after a successful capture. The caller sees an exception even though the rider was charged. A retry duplicates the charge.- Crash after the insert but before the response reaches the caller. The data is consistent, but the caller believes it failed and retries, which again double-charges.
Why a transaction is not enough
Wrapping db.insert in a transaction (for example @Transactional) makes the database write atomic. It does nothing for the relationship between the two systems. The processor call is not part of that transaction and cannot be rolled back by it. Putting the capture inside the transaction scope would also hold a connection and locks open across a slow network call, which is a separate problem.
The fix: idempotency key plus explicit state
- Create one idempotency key per fare-capture attempt, owned by the caller. For instance, a UUID generated once when the trip ends, before
captureFareis first invoked. Every retry for the same fare reuses it. If the key were generated inside the method, each retry would look like a new charge. - Pass the key to the processor. Most card processors guarantee that repeating a request with the same key does not charge again and instead returns the original result. This makes retrying
capturesafe even if the first attempt went through. - Enforce the same key locally with a unique constraint on the
tripstable, and write apendingrow before calling the processor. This records intent, so a crash leaves evidence that an attempt began.
public Map<String, String> captureFare(String riderId, int fareCents, String idempotencyKey) {
Trip existing = db.findByIdempotencyKey("trips", idempotencyKey);
if (existing != null && existing.status.equals("captured")) {
return Map.of("status", "ok", "capture_id", existing.captureId);
}
db.upsertPending("trips", idempotencyKey, riderId, fareCents); // unique on idempotencyKey
String captureId;
try {
captureId = processor.capture(riderId, fareCents, idempotencyKey);
} catch (ProcessorTimeoutException e) {
db.markUnknown("trips", idempotencyKey);
throw new CaptureOutcomeUnknownException(idempotencyKey);
} catch (ProcessorException e) {
db.markFailed("trips", idempotencyKey);
throw e;
}
db.markCaptured("trips", idempotencyKey, captureId);
return Map.of("status", "ok", "capture_id", captureId);
}
How each failure now behaves
- Retry after a completed run: the local row is
captured, so the method returns the stored result without touching the processor. - Retry after a lost response or crash: the row is
pendingorunknown. The retry calls the processor with the same key, which treats it as the same attempt, so no second charge occurs. - Capture succeeded but
markCapturedfailed: the exception propagates, but the row is stillpending. A retry gets the original capture ID back from the processor and then records it. The caller should be told the outcome is "captured, not yet recorded" or simply be told to retry safely. It should never be told the charge failed. - Timeout: surface this as a distinct "outcome unknown" result rather than a plain failure. The caller should not assume the rider was not charged, and should either retry with the same key or wait for reconciliation.
- Definite processor decline: mark the row
failedand raise the error. A new attempt (for example with a different card) gets a new key.
Reconciliation
Some failures never reach a catch block, such as a process killed mid-call. Run a periodic job that:
- Selects rows stuck in
pendingorunknownbeyond a grace period (say a few minutes). - Asks the processor for the real status by idempotency key or reference, not by re-sending the charge.
- Updates the row to
capturedwith the capture ID, orfailed. - Also scans the processor's recent captures and flags any with no matching local row, which catches charges that were never recorded at all.
- Alerts on rows that remain unresolved for too long, since those need human attention or a refund.
Trade-offs and details
- Key retention: processors expire idempotency keys (often after about 24 hours). Retries and reconciliation must happen within that window, or the job must look up by reference instead.
- Same key, different payload: reject a request that reuses a key with a different rider or amount rather than silently returning the old result.
- Concurrency: the unique constraint ensures two concurrent retries cannot both create a row. The loser should read the existing row and either wait or return its state.
- Alternative: outbox or saga style. You could treat the capture as a step in a durable workflow with a persisted state machine. The pending/captured/unknown/failed column is a lightweight version of that.
Common mistakes
- Relying on
@Transactionaland assuming it covers the processor call. - Retrying without an idempotency key, which directly causes double charges.
- Generating the key inside the method, so each retry gets a fresh one.
- Treating a timeout as a clean failure and telling the caller nothing was charged.
- Using a heuristic like "does this rider have a trip in the last N seconds" instead of a key. It breaks for two legitimate back-to-back trips and is racy under concurrent retries.
- Writing the local record only after the charge, so a crash leaves no trace of the attempt.