KatInterview

Transaction State Management with External Payment Processors

System DesignModel answer
MediumModel answerSystem Designdistributed-systemsidempotencystate-machines

Last updated

Build a service that orchestrates payment transitions through hold, capture, and settlement while handling unreliable gateway responses and ensuring financial correctness.

You're building a service that orchestrates transactions through their full lifecycle: authorizing a hold, capturing funds, and recording settlement. Your service sits between client applications and third-party payment processors that are often slow and unreliable.

What You Need to Support

Your system must handle these state transitions:

  • CREATED → AUTHORIZING → AUTHORIZED → CAPTURING → CAPTURED → SETTLED
  • At any point, a transaction can move to FAILED

Key requirements:

  1. Idempotent operations: If a client retries a capture request due to a timeout, the customer must never be charged twice.

  2. Audit trail: Every state change must be recorded in an immutable log for compliance and reconciliation.

  3. Async gateway communication: Payment processors respond via webhooks or require polling. Gateway calls can take seconds and may return ambiguous "status unknown" responses.

  4. Strong consistency for transaction state: While reporting can be eventually consistent, the transaction's own state must be strictly consistent—no lost updates, no phantom charges.

Scale and Constraints

  • Peak traffic: 5,000 new transactions per second
  • Each transaction involves roughly 3 gateway operations
  • Payment processors have p99 latencies of 2–10 seconds and occasionally time out
  • Financial accuracy is non-negotiable; prefer blocking over inconsistency

What to Design

  1. API contract: Define the endpoints clients use to create and transition payments. How do you enforce idempotency?

  2. Data model: Show the schema for transactions and the audit ledger. How do you prevent lost updates when workers race to apply webhook results?

  3. Architecture: Sketch the components—API layer, workers, queues, database. How do you ensure that updating transaction state and writing the ledger entry happen atomically?

  4. Handling ambiguity: When a gateway returns "unknown" or times out, you don't know if the customer was charged. Walk through your recovery strategy without risking a double charge.

Hints

Hint 1

Record your intent to perform an operation before calling the gateway, so you never lose track of an in-flight request

Hint 2

Use optimistic locking (a version column) to prevent concurrent state transitions from clobbering each other

Hint 3

When a gateway call times out or returns 'unknown,' schedule retries with exponential backoff using the processor's status inquiry endpoint