Why “Just Retry the Request” Isn’t Always Safe
This is pretty simple, but I thought it was interesting enough to share.
Recently I was reading about idempotency and retries, and it made me realize how something as innocent as “just retry the request” can actually cause some serious problems.
The problem
Retrying a failed request seems like the safe thing.
Network problem?
Time out?
Just try again, right?
Except sometimes the request did go through.
The server did receive the payment, but before the response was sent to the client, the connection was cut.
So the client thinks:
“The request failed. Let me try again.”
The server thinks:
“Cool, another payment.”
And now someone gets charged twice.
The fix: Idempotency Keys
The idea is pretty simple.
The client generates a unique key once for an action and sends the same key with every retry.
POST /charge Idempotency-Key: 8f14e45f-ceea-467e-88b4-5c8b7b1f3d3a
If the request times out, the client retries with the same key.
The server checks:
Have I seen this key before?
If yes → return the previous result.
If no → process the request and store the result.
Something like:
Obviously, you wouldn't use an in-memory dictionary in production.
You'd typically use something like Redis or a database table, with an expiry/TTL so old keys don't live forever.
One small edge case
What if the server stored the key, but the payment actually failed?
This is where you can't simply say “key exists = return the same thing.”
The server should distinguish between states like:
PROCESSING
→ SUCCESS
→ FAILED
A permanent failure like insufficient funds shouldn't necessarily be retried blindly, while a temporary failure might be retryable.
The important part is knowing whether the operation actually happened or whether its outcome is still unknown.
The important part
The key needs to be generated by the client before the first attempt.
This is wrong:
Because the server sees three different requests.
Instead:
Now all three attempts represent the same logical operation.
This becomes especially useful for anything with a real side effect:
Payments
Creating orders
Sending emails
Deducting inventory
Money transfers
Basically any API operation where doing the same thing twice is a problem
Retries are useful, but retries without thinking about idempotency can turn a temporary network issue into a very real production bug.
That's the part I found interesting while reading about this, so thought I'd share. Find me on LinkedIn 😄..
About the author
- I'm a backend engineer who spends most days deep in distributed systems, services talking to each other, breaking in interesting ways, and occasionally behaving. I write here about what I actually learn while building and debugging things, not the polished version.
Comments
Join the discussionNo comments yet. Be the first to comment.