Video in progress

Staff 🌱 Spring

You sent a request to a payment provider and got a timeout. Whether the money was charged is unknown. How do you design the system for such cases?

A timeout is not "failed", it is "unknown". You need to send the payment with your own idempotency key, store an UNKNOWN state, ask the provider for the status or wait for a callback, and close the differences with a daily reconciliation.

📖 Answer

The most dangerous mistake is to treat the timeout as a failure and tell the customer "the payment did not go through, try again". The result: the money is charged twice.

  1. State model. NEW → SENT → SUCCEEDED / FAILED, and a separate UNKNOWN. A timeout, a dropped connection, a 5xx: all of them lead to UNKNOWN.

  2. Write before sending to the provider. First the SENT state and the idempotency key (our payment_id) are committed to the database, and only then the HTTP call, outside the transaction. Otherwise you can end up in a state where the money was charged but we have no trace of it.

  3. Idempotency key. Most providers support an Idempotency-Key or their own merchant_transaction_id. Resending with the same key doesn't charge a second time, so after UNKNOWN it is safe to ask again. If the provider doesn't support this, resending is forbidden and you can only query the status.

  4. Finding out the state.

  • The provider's webhook (the signature is verified, handled idempotently).
  • A background job asks the provider's status API about UNKNOWN payments: 30 seconds, 2 minutes, 10 minutes...
  • If it is still unknown after a set time, it goes to an operator queue.
  1. What the customer sees. "Payment is being verified" is the honest state. The order stays reserved, and the pay-again button is blocked.

  2. Reconciliation. Every day, compare the provider's report file with our records: in ours but not theirs; in theirs but not ours; amount differences. This control is the last line of defense after any software guarantee, and financial audits require it too.

@Scheduled(fixedDelay = 30_000)
@SchedulerLock(name = "resolveUnknownPayments", lockAtMostFor = "PT5M")
void resolveUnknown() {
    repo.findUnknownOlderThan(Duration.ofSeconds(30), 100)
        .forEach(p -> resolver.resolve(p)); // status API, result goes to the state machine
}

Choose timeouts carefully too: larger than the provider's p99 response time, but smaller than what the user is willing to wait. A timeout that is too short artificially inflates the number of UNKNOWNs.

It all comes down to one idea: there is no "exactly-once", you accept that, and you fill the gap with idempotency, a state machine and reconciliation.