KatInterview

Handling Partial Failure in a Payment Service Method

System DesignModel answer
MediumModel answerSystem Designdistributed-systemsidempotencyerror-handling

Last 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.charge performs a synchronous network call that debits the customer and returns a charge identifier on success, throwing an exception if the charge fails
  • db.insert writes 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?