A retry that charges twice
A gateway charges an order and the confirmation goes missing. What happens when the bot asks it to charge the order again? We compare two models of how the gateway handles the retry.
The customer places one order. The bot requests payment and the gateway processes the charge. When the request times out, the bot still has no way to tell whether the payment went through. If it sends the request again, the gateway may charge the customer a second time.
To reproduce the bug in a test, simulate the loss of the reply after the charge succeeds. A test that only simulates a declined payment will miss this case.
The model
Retry.tla records the number of charges in charged and the reply status in reply. The bot stops when it receives ok and retries after a timeout. The property NoDoubleCharge requires charged ≤ 1.
Show the code Retry.tla, RetryKey.tla
TLC: Invariant NoDoubleCharge is violated.
TLC: No error has been found.
How the second charge happens
TLC finds a four-state trace in Retry.tla. Initially there are no charges. After the first charge, the bot times out. It prepares to retry, then the gateway processes the new request and charged reaches 2. The diagram shows that sequence.
The fix
The diagram illustrates one way to implement the fix with an idempotency key. The payment client and the gateway must agree on which requests belong to the same charge. RetryKey.tla captures the effect of that agreement in one rule. Once the order has been charged, the count stays at 1. TLC checks NoDoubleCharge in all four reachable states of this model.
Scope of the check
- The model covers one order and one gateway. Concurrent orders and partial refunds fall outside its scope.
- The model leaves out the keys and their storage. To check the integration, verify that the client reuses the original key and that the gateway still recognises it when the retry arrives.
Run it yourself
With the TLA+ tools installed, run these commands in the directory containing the models and their configuration files.
java -cp tla2tools.jar tlc2.TLC -config Retry.cfg Retry.tla
java -cp tla2tools.jar tlc2.TLC -config RetryKey.cfg RetryKey.tlaShow the code Retry.cfg, RetryKey.cfg
Retry.cfg
RetryKey.cfg