Every Tuesday - Deep dives, architecture lessons, and real engineering stories.
Every Saturday - The best DevOps, SRE, Cloud, AI, tools, tutorials, and projects from the week.
You want to fly somewhere, hit the "Pay ($412)" button.
It spins for about 30 seconds and tells you to try again, due to some error.
You check your account balance on your bank app, to find a pending deduction of $412.
Would you be inclined to hit the button once more?
Hitting it may well result in a charge of $824. On the other hand, perhaps the original attempt failed, the airline never received payment for the ticket you wanted, and it is happily sold to another person. Either option seems unattractive, primarily because of information you don't have: success or failure of the original attempt.
Presumably the website also doesn't know.
All that can be said about a timed-out call is that no response was received within the allotted time. The call may not have got as far as any server; it may have got there but errored; or it may have succeeded, with only the subsequent response failing to make it back.
These situations would all be indistinguishable.
So at minimum, a timeout should be interpreted as "uncertain outcome". There is a good chance that the desired action took place.
Clearly this is extremely important for any system dealing with payments. It's easy to see the devastation that could result from getting it wrong. In April 2025 UPI was down for about 2 hours, its longest period of unavailability since 2021-22. During this time many banks apparently continued to poll to check for completion of various payments, with no regard to frequency. These requests to check for payment completion apparently comprised a significant proportion of all requests being sent to UPI, resulting in failure of about 50% of payments being attempted.
So their safeguard against multiple charges was directly responsible for major disruption to the service.
This will resonate with many people responsible for running infrastructure. Numerous examples are easy to find:
a request forwarded to a different back-end by your load balancer;
a duplicated message processed twice by consumers;
deployment continued after failure and restart part-way through;
a scheduled task completing, then re-run following server restart.
Each could result in some action taking place twice. What should happen when that occurs?
This desirable property has been given the name "idempotent".
I hope after reading this you will have a good understanding of idempotent operations, why it is so desirable, its application to preventing multiple charges, and 5 steps towards implementing this in an API.
Causes of duplicate charges
Prevention of duplication in UPI, card payments via 3rd party APIs, and by Nginx
5 steps towards an idempotent payment API
Timed-out request
We will all have re-tried some action after it appeared to fail. There will be countless examples in code and documentation to encourage this. Many client libraries will re-attempt failed requests, K8s re-runs containers and most message brokers will attempt to deliver each message at least once.

Generally this will all be entirely benign, for example re-requesting a slow or failed web page.
All based on the false premise that failure means no action was carried out. As noted above, it is quite possible for all manner of processing to occur and only the final response to fail to return.
So consider the following. Hungry, you use an app to have something delivered to you. After hitting the button to confirm the purchase, there's a slight delay due to poor connection. So you press it again to be sure. You are then delighted to answer the door 10 minutes later to find 2 men with your meal!
Presumably nothing would appear amiss on the seller's system. Two separate requests to buy a meal were received, so two purchases were made and dispatched.
Of course it was entirely reasonable to fulfil each of the 2 requests it received. There was nothing available to it to determine they related to one purchase only.
Idempotent
Repeated application of an idempotent function makes no further difference after the first time.
Pressing the button to summon a lift to your floor is idempotent; pressing repeatedly will only result in one lift arriving.
Charging a card $412 is plainly not; repeat it 5 times for a total charge of $2,060!
So certain HTTP verbs are idempotent. There should be no effect from issuing the same GET, PUT or DELETE multiple times. However, it is typical to use POST for adding new entities, including paying for something.

Examples with infrastructure
As mentioned, Nginx will optionally forward requests to alternate back-ends if there are errors and others available, subject to the criteria set with proxy_next_upstream. However it will exclude POSTs that have been dispatched to another server, unless specifically included (non_idempotent). Clearly this is to avoid possible duplication of whatever action that POST instigates, such as a charge.
So if you had many 502 responses and thought it desirable to include more failed requests for forwarding to other servers, you might well cause many customers to be debited twice for one thing. Easy oversight, potentially expensive consequences.
Obviously therefore it would be good to avoid any re-attempts. Unfortunately there are too many circumstances where a valid response may be lost, and so some re-attempts are necessary. Poor mobile connection, servers going down and back up for deployments, transient slowness at a financial institution... all may leave a customer without confirmation of successful payment, to name but a few examples.
Clearly better therefore if there were means for the receiver to identify duplicates. If this were possible, it could simply respond as it had done originally.
Some mechanism to this end must be in place with all providers of payment services.
With UPI
A unique reference number is generated to represent each payment. So if there was no timely confirmation of the outcome to the originating bank, it can simply enquire about the state of that reference. Obviously only one sum of money can be associated with it, so only one payment can occur.
This serves to explain why initiating a fresh payment via the various apps would result in a separate charge. There would be no connection with any previous attempt, as it would have a new reference number.
So this is clearly a vital stage in the process. As described above, apparently some banks took full advantage of the opportunity to send these requests, at high frequency, even relating to payments made days earlier.
Post-incident guidance from NPCI included minimum delay before enquiring about the outcome (90 seconds, since reduced to 60) and maximum of 3 attempts over no more than 2 hours. So, reiterate with same ID, with delays between, up to a maximum number of times. A pretty reasonable set of criteria to apply to re-attempts generally!
3rd party payment providers
Typically you will be able to pass an additional header, for example, Idempotency-Key with Stripe. As before you would generate an arbitrary value, most conveniently a UUID, and include this with the initial request. Any number of re-attempts with the same value would elicit the original response. No further debits would occur. Presumably other details would also be compared on any subsequent requests, returning an error response if there were discrepancies.
It is apparently deemed useful enough for a generic version to be under consideration by IETF as an HTTP standard.
General principle
So I would urge everyone to apply the following considerations wherever re-attempts may occur, whether deliberately instigated or by some other mechanism. I'll suggest referring to it as being "Retry-Safe".
Can the recipient identify it relates to a previous request?
Am I allowing reasonable time for processing to complete?
Thus avoiding duplicates, and avoiding overwhelming some service with requests, respectively.
Presumably most people would be able to get AI to generate suitable code to process payments. It would probably be flawless under ideal conditions. But you want to be aware it would be all too easy to debit someone multiple times in less-than-ideal conditions.
Ensuring an API is retry-safe
Quoting someone far wiser than me "Only through breaking things, trying to fix them, will you learn". So let's break something and apply progressive fixes.
Multiple debits
Continuing the example above, presumably the relevant extract from server logs would show a request being passed on to a bank, taking some seconds, successfully debiting the card and attempting to pass back a response. As the customer's browser had timed out and closed its connection in the meantime, it may well log some variant of "broken pipe". Easy to overlook if scanning through logs.
Customer, understandably, tries again. Again all is reasonable on the server side, receiving what appears to be a new request, repeating the above steps, and debiting once more.
So no obvious failures anywhere. All components behaving reasonably given the information available. Only that due to time taken to complete, exceeding the customer's patience, they were unaware of the success.
Equivalent to calling out for a menu in a busy restaurant, and, not receiving one, reasonably doing so again, only to be presented with 2.
Idempotency key
So clearly useful if the customer could indicate this may relate to a previous request. Therefore generate an arbitrary value (UUID) to accompany the request when initially hitting Pay. For example

Store all received values, along with corresponding responses issued. Subsequent requests would first be checked against stored values. If new, process as described previously and record the issued response; otherwise return previously recorded response, taking no further action.
So, assuming the original attempt was successful and took longer than the timeout period, this would result in a further request receiving the original response, including payment ID. Customer would of course only have been charged once.
Importantly, you don't want to generate a new value for each attempt, only for each separate action, that is, when the user hits Pay. Otherwise you defeat the object, and each attempt would be considered new. Analogous to generating a new UPI payment, as above.
Concurrent requests
Unfortunately there are scenarios where this would fail. If 2 requests were issued in quick succession, for example customer double-clicks, load balancer and customer both decide to re-attempt, both may pass the check for an existing key. Each would therefore continue processing to debit the card, resulting in 2 debits associated with 1 key.
The usual problem when checking something and acting based on the result: any concurrency may result in undesirable outcomes.
Furthermore this assumes just one server to process the requests. If there were more, each would presumably have its own set of stored keys, so be blind to requests handled by others.
Database
Hence desirable to store the values somewhere central, common to all servers, such as a table (Postgres, MySQL) or Redis instance. And to take advantage of setting the column to unique, and attempt to add each new key as the first operation. Obviously this would be successful only once, overcoming the concurrent requests issue.
Depending on whether this was successful or not:
if successful, continue and debit the card, updating the row to include the response issued;
if unsuccessful, due to another request being currently processed (so no response recorded yet), issue 409, advising that it should re-attempt after a short interval;
if unsuccessful and a response was recorded, return this, without any further processing.
As previously mentioned, you would want to compare other details of any re-attempt, presumably storing some representation, for example a hash, of the original to compare against. Returning some 4xx (for example 422) if there were differences. You don't want to silently continue and return an unrelated original response if, say, the amounts differ. Presumably almost certainly erroneous behaviour from the client, so better to highlight it. (Termed a "fingerprint" by both Stripe and the IETF).

Sensible re-attempts
Final consideration is to ensure the customer doesn't over-do their re-attempts! As described, a contributing factor in bringing down UPI.
generate key initially and re-use for all attempts;
delay between, increasing the interval each time (1s, 2s, 4s, 8s...);
introduce some element of randomness to avoid many customers all attempting simultaneously after failures;
limit the number and move on to checking for completion. Clearly undesirable to continue indefinitely if something was genuinely wrong, further loading an already struggling system.
A couple of other considerations. Expect the key to be valid only for a limited time; after 24 hours at least for Stripe. So obviously all re-attempts should be well within this. And you want to be able to readily identify related requests. So log all keys issued and would presumably want some alerting if one appeared excessively frequently.
In summary:
request timing out leaves uncertainty as to success;
want any action to be idempotent, in particular POSTs;
therefore useful if repeat requests could be recognised, returning original response; achieve this with a customer-supplied key, constant for each action;
ensure only processed once by recording in a central location, and failing any others with same key but differing content;
customer should limit frequency and duration of re-attempts.
So identify some component under your control that may lead to re-attempts (many options suggested above), and consider if it is retry-safe.
I would be interested to hear others' experiences of processes being duplicated, payments, webhooks, deployments and so on. Happy to feature a few with suitable attribution.

Uptime Engineer
👋 Find me on Twitter | Linkedin | Connect 1:1
Thank you for supporting this newsletter.
Y’all are the best.

