A client sends POST /payments. Your server charges the card, but the response is lost to a timeout. The client retries, and the customer is charged twice.
Retrying is the right thing for a client to do. The bug is that the server can't tell a retry from a new request.
The standard fix is an idempotency key. The client sends the same Idempotency-Key header on every retry of one operation. The server runs the operation once and replays the stored response for every retry. Stripe popularized this, and there is an IETF draft for the header.
I couldn't find a Go library I liked, so I built one: go-idempotency.
Using it
store := memory.New()
defer store.Close()
mw := idempotency.New(store)
mux := http.NewServeMux()
mux.HandleFunc("POST /payments", createPayment)
http.ListenAndServe(":8080", mw.Handler(mux))
Now retry with the same key:
curl -i -X POST localhost:8080/payments -H 'Idempotency-Key: 8e03978e' -d '{"amount":100}'
curl -i -X POST localhost:8080/payments -H 'Idempotency-Key: 8e03978e' -d '{"amount":100}'
# second response: same body, plus "Idempotent-Replayed: true"
Your handler ran once. The second response came from the store.
What the middleware does
For each protected request with a key, it fingerprints the request (method, path, query, body) and checks the store:
| Situation | Result |
|---|---|
| First time this key is seen | Handler runs, response is stored |
| Same key, same request, finished | Stored response is replayed |
| Same key, same request, still running |
409 Conflict with Retry-After
|
| Same key, different request | 422 Unprocessable Entity |
| Handler returns 5xx or panics | Nothing is stored, the key is released |
The last row is deliberate. A server error is usually temporary, so the client should be able to retry the same key and get a fresh attempt.
The hard part: concurrency
A naive version looks like "check if the key exists, run the handler, store the result". That has a race: two retries arrive together, both see no key, and both run the handler.
The fix is to make the first step atomic. The middleware asks the store to create an "in progress" record, and only one request can win. Redis uses a Lua script for this, and PostgreSQL uses a single atomic statement.
Then there is a subtler problem. What if the winning handler is slow, and its lock expires? A retry takes over and finishes first. When the slow original finishes, it would overwrite the newer result.
To prevent that, every request gets a random lock token when it takes the lock. Only the holder of the current token can complete or release the key. The slow request's late write is rejected, and the newer result stands.
A framework pitfall I hit
Echo renders errors returned by handlers after middleware finishes. If you wrap standard middleware with echo.WrapMiddleware, the middleware sees a handler that wrote nothing, and stores an empty 200 instead of the real error.
So the Echo adapter renders handler errors inside the middleware, and the real error response is what gets stored and replayed.
Stores and structure
- Memory: for tests and single-instance services
- Redis: for multiple instances, with automatic expiry
- PostgreSQL: for multiple instances with no new infrastructure
The core module has no dependencies. Each store and framework adapter is its own Go module, so importing the Redis store never pulls in a Postgres driver or Gin.
There is also a storetest package, a shared conformance suite. Every store in the repo runs it, and you can run it against your own store.
Things to get right on your side
- Generate a fresh key per operation (a UUID v4 works) and reuse it for every retry of that operation.
- Scope keys per user in a multi-user API, so two customers can't collide:
idempotency.WithKeyScope(func(r *http.Request) string {
return auth.UserID(r.Context())
})
- This does not replace database constraints. Unique indexes are still your last line of defence.
- If a server dies mid-request, the key unlocks after the lock timeout and the retry runs the handler again. Side effects outside your database should be safe to repeat.
Try it
go get github.com/ndoubismarck/go-idempotency
- Repo: https://github.com/ndoubismarck/go-idempotency
- Docs: https://ndoubismarck.github.io/go-idempotency/
It is v0.1.0, so the API is still open to change. If you build payment or order APIs in Go, I would like to hear what is missing or awkward. Issues and comments are welcome.
Top comments (1)
One addition from the EDI side: store the response with the key, not just the fact you saw it. When a partner re-sends an order file, the correct reply is the original outcome replayed, not a fresh attempt β that distinction is what keeps a retry from becoming a second shipment. β Chris, founder of SignalEDI