DEV Community

Raymond Conklin
Raymond Conklin

Posted on

Spot the Bug: A timeout doesn't mean the charge failed

An AI assistant gave us this payment method. It compiles and it retries on timeout, which looks careful:

public async Task Charge(Order o)
{
    var r = await _pay.CreateAsync(o.Total, o.CardToken);
    if (r.Status == "timeout")
        r = await _pay.CreateAsync(o.Total, o.CardToken);
    o.PaymentId = r.Id;
    await _db.SaveAsync(o);
}
Enter fullscreen mode Exit fullscreen mode

The bug. A timeout tells you the answer didn't arrive, not that the charge failed. The first request may have succeeded. The retry then creates a second charge.

The fix. Send an idempotency key that is stable for the logical operation, so the provider returns the first result instead of acting twice:

public async Task Charge(Order o)
{
    var key = $"order-{o.Id}-charge";
    var r = await _pay.CreateAsync(o.Total, o.CardToken, idempotencyKey: key);
    if (r.Status == "timeout")
        r = await _pay.CreateAsync(o.Total, o.CardToken, idempotencyKey: key);
    o.PaymentId = r.Id;
    await _db.SaveAsync(o);
}
Enter fullscreen mode Exit fullscreen mode

Rule. A retry is only safe when repeating the call is safe. Make it safe first, then retry.


The code in this post was written by an AI assistant for the demo; the review is ours. This is Spot the Bug, a weekly series from The Conklin Group. Watch the 40-second version: https://www.theconklingroup.com/videos/social/spot-the-bug-01-double-charge-retry.mp4

Top comments (1)

Collapse
 
osamamalik profile image
Osama Malik •

The key being stable is the part people get wrong, so it helps to persist it before the first call rather than deriving it only in memory. If the process dies between the request and the database write, a restart can then reuse the same key instead of generating a new one. Also remember that providers expire idempotency keys after some window, so a retry hours later may not be protected. For a real timeout it is often safer to look the charge up by your key or order reference first, and only then decide whether to send it again.