Video in progress
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.
-
State model.
NEW → SENT → SUCCEEDED / FAILED, and a separateUNKNOWN. A timeout, a dropped connection, a 5xx: all of them lead toUNKNOWN. -
Write before sending to the provider. First the
SENTstate and the idempotency key (ourpayment_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. -
Idempotency key. Most providers support an
Idempotency-Keyor their ownmerchant_transaction_id. Resending with the same key doesn't charge a second time, so afterUNKNOWNit is safe to ask again. If the provider doesn't support this, resending is forbidden and you can only query the status. -
Finding out the state.
- The provider's webhook (the signature is verified, handled idempotently).
- A background job asks the provider's status API about
UNKNOWNpayments: 30 seconds, 2 minutes, 10 minutes... - If it is still unknown after a set time, it goes to an operator queue.
-
What the customer sees. "Payment is being verified" is the honest state. The order stays reserved, and the pay-again button is blocked.
-
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.
Sign up to mark studied questions and save your progress.