Back
Jun 13, 2026
10 min read

Idempotency: how to design systems that survive retries

A timeout, a dropped connection, an impatient user: any of these can make the same request arrive twice. Idempotency is what makes that not matter. Patterns, real cases and Go examples.

Contents

What is idempotency?

Idempotency is defined as the property of performing an action several times and still getting the same result you would get if you did it only once. There is an everyday example that explains this perfectly:

When you are waiting for the elevator and press the button, what happens if you press it again? Nothing. The elevator has already been called. The second time you press the button, the system ignores it because the effect has already happened. No matter how many times you press it, the result is always the same.

That is idempotency. An operation is idempotent when repeating it changes nothing. The state of the system after the second call is identical to the state after the first one.

Why are retries unavoidable?

Imagine you are buying tickets for a concert. You press “Confirm purchase”, the screen keeps spinning, and after 10 seconds you get a generic error. Was the payment processed or not? You have no idea. The only thing you can do is try again and hope it works this time.

This happens in the real world all the time: the connection drops before the response arrives, the server takes too long and the client times out, the app closes at the wrong moment, or the user simply gets impatient and presses the button twice.

In all these cases, the client does not know whether the server processed the request or not. Its only reasonable option is to retry. And if your system is not ready for that, the result is duplicate orders, double charges or users registered twice.

Retries are not a client bug. They are a logical response to the uncertainty of distributed networks. The server has to be designed to handle them.

Operations that are already idempotent

First of all, it is worth understanding which HTTP operations are naturally idempotent:

  • GET: Always idempotent. You ask for data and you get it. Asking again changes nothing (assuming the data you are requesting did not change between requests).
  • PUT: Idempotent by design. PUT /users/1 with the same body always leaves the user in the same state.
  • DELETE: Deleting something that was already deleted should simply do nothing (or return 404).

Most critical operations in a system (creating a payment, registering a user, issuing an invoice, etc.) are POST, and none of them is naturally idempotent. You have to make them idempotent explicitly.

How do you implement it in practice?

REST APIs

As mentioned before, POST is not idempotent by nature, but we can make it idempotent with a small contract between client and server. The idea is to ask the client to include a header (usually called Idempotency-Key) with a unique value per operation, typically a UUID generated on the client side before sending the request.

On the server side, the logic is simple: when the request arrives, we look for that key in the database. If it already exists, we return exactly the same response we returned the first time. If it does not exist, we process the operation normally, save the result and store the key for future checks.

The client can retry as many times as it wants. The data is always processed only once.

alt text

Code example

Let’s see what this would look like in a Go handler. The flow is simple: if the key already exists, we return the saved result; if not, we process and save. Two paths, a single line of business logic.

func HandlePayment(w http.ResponseWriter, r *http.Request) {
    // Every request must include an Idempotency-Key header.
    // This key can be a UUID generated by the client that identifies the operation.
    key := r.Header.Get("Idempotency-Key")
    if key == "" {
        http.Error(w, "Idempotency-Key required", http.StatusBadRequest)
        return
    }

    // We look for the key in the store. In Go, functions return the error
    // as a return value: err == nil means the operation succeeded
    // (the key exists). If so, we already processed this request and return
    // the saved result directly without processing anything again.
    cached, err := store.Get(ctx, key)
    if err == nil {
        writeJSON(w, http.StatusOK, cached)
        return
    }

    // The key does not exist: this is the first time we see this request.
    // We process the operation normally.
    result := processPayment(r)

    // We save the result linked to the key before responding.
    // This way, if the client retries with the same key, we return
    // this result without running processPayment() again.
    store.Set(ctx, key, result, 24*time.Hour)

    writeJSON(w, http.StatusCreated, result)
}

Message queues

The same principle applies when you consume events from a queue like SQS or RabbitMQ. With at-least-once delivery, a message can arrive more than once if the broker did not receive confirmation in time. To handle it, when we receive an event we take its transaction ID and look for it in the database.

If it already exists, we ACK the message but ignore the event (it was already processed). If it does not exist, we process the event, save the ID and only then send the ACK. The result for the queue is always the same (an ACK), but internally we make sure the effect happens only once.

alt text

Code example

In RabbitMQ, each message has a MessageId we can use as the idempotency key. The flow is the same as in the REST API: if the ID already exists in the store, the event was processed before and we ignore it. If not, we process it and save the ID. The difference is that here the “response” is not JSON but an ACK to the queue.

func HandleEvent(msg amqp.Delivery) {
    // Each message has a unique ID that identifies the transaction.
    // We use it as the key to detect duplicates.
    eventID := msg.MessageId
    if eventID == "" {
        msg.Nack(false, false)
        return
    }

    // We look for the ID in the store. The _ discards the returned value because
    // we only care whether the key exists, not its content.
    // If err == nil (the key exists), the event was already processed: ACK and done.
    _, err := store.Get(ctx, eventID)
    if err == nil {
        msg.Ack(false)
        return
    }

    // The ID does not exist: this is the first time we see this event.
    // We process the message normally.
    processEvent(msg.Body)

    // We save the ID before sending the ACK to avoid processing it again
    // if the broker resends the message because it did not get confirmation in time.
    store.Set(ctx, eventID, "processed", 24*time.Hour)

    msg.Ack(false)
}

Common uses in tech

Idempotency shows up constantly in real systems. These are some of the contexts where it is used the most:

  • Payments: Any payment API must guarantee that a payment is processed exactly once. A retry after a timeout cannot end up charging the user twice.
  • Emails and push notifications: If a worker fails after sending but before confirming the processing, the system can resend the event. Without idempotency, the user gets two confirmation emails or two notifications.
  • Webhooks: When an external service sends a webhook, it expects a 200 as confirmation. If it does not get it in time, it will retry. Endpoints must be ready to receive the same event more than once.

Benefits of implementing it

Designing systems with idempotency has concrete consequences that go beyond “avoiding duplicates”:

  • Retries become safe: The client can retry a request without fear of side effects. This greatly simplifies error handling on the client side: instead of trying to guess whether the server processed the operation, it can simply try again.
  • The system is resilient to network failures: A timeout is no longer a critical problem. If the response never arrived, the client retries and the server returns the same result without processing anything again.
  • Better user experience: The user never sees a duplicate charge, a repeated order or an extra email. The system absorbs the network uncertainty without passing it on to the user.
  • Built-in traceability: Each operation is recorded with its unique key. This works as an implicit audit trail. You can know exactly how many times a request arrived and when it was first processed.

Details that matter in production

The basic implementation is simple, but there are some edge cases worth considering before taking this to a real system.

  • What happens if the same key arrives with a different body? There is no single right answer: you can ignore the second request and return the original result, return an error, or log the inconsistency to investigate it. The most common convention is to return a 409 Conflict, which tells the client something is wrong on its side and the request will not be processed.
  • How long do you keep the key? It depends on the domain: it can be minutes, hours or days. The question to ask is: from what point does a retry stop being a retry and become a new operation?
  • What happens if two requests with the same key arrive at exactly the same time? The solution is an atomic write: instead of checking whether the key exists and then saving it (two separate operations where race conditions can happen), you try to write it directly using an operation that the database or store guarantees to be indivisible. If it succeeds, this request processes the operation. If it fails because the key already exists, it means another request arrived first, and you return the result that first request already saved. No locks, no waiting.

Conclusion

Idempotency is not an implementation detail; it is a design decision. And like most good design decisions, it is invisible when it is done right: the user presses “Confirm” twice and it simply works.

Next time you design a POST endpoint, the question worth asking before writing the first line is: what happens if the same request arrives twice? Asking that question at design time costs much less than answering it in production.

Thanks for reading, see you in the next one 👋