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.

CustomerBotGatewaypay(42)charge(42)charged=1oktimeoutcharge(42)charged=2okpaid
The gateway's reply is lost, the bot retries, and the customer is charged twice. TLC finds this run in Retry.tla.

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
---- MODULE Retry ----EXTENDS NaturalsVARIABLES charged, reply Init == charged = 0 /\ reply = "none" \* Send the charge. The gateway's answer can be lost.Charge == /\ reply = "none" /\ charged' = charged + 1 /\ reply' \in {"ok", "timeout"} \* On a timeout, the bot tries again.Retry == /\ reply = "timeout" /\ reply' = "none" /\ UNCHANGED charged \* Once the gateway answers "ok", nothing else happens.Done == /\ reply = "ok" /\ UNCHANGED <<charged, reply>> Next == Charge \/ Retry \/ DoneNoDoubleCharge == charged <= 1====

TLC: Invariant NoDoubleCharge is violated.

Retry.tla: every retry sends a new charge.

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

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.tla
Show the code Retry.cfg, RetryKey.cfg

Retry.cfg

INIT InitNEXT NextINVARIANT NoDoubleCharge

RetryKey.cfg

INIT InitNEXT NextINVARIANT NoDoubleCharge