Charged Twice: Safe Retries With Idempotency Keys in Fiber v3.7
A customer taps "Pay" on a train. The app sends POST /v1/orders, the server
charges the card, writes the order and answers 201. The answer never arrives,
because the train went into a tunnel. The app waits, times out and does what
every good HTTP client does with a request that may not have reached the server:
it sends it again. The server has no idea it has seen this request before. It
charges the card a second time.
Retries are everywhere, and most of them are not in your code. Mobile SDKs retry
on timeouts, service meshes retry on connection resets, job queues deliver a
message again when a worker dies, and people press the button a second time when
nothing seems to happen. For GET that is harmless. For a POST that moves
money, sends an email or creates a ticket, it is a real bug. The usual fix is an
idempotency key: the client picks a random value per operation and sends it with
every attempt, and the server answers every repeat with the response of the
first attempt instead of doing the work again.
Fiber has shipped an idempotency middleware since
v2.42.0, and v3 carries it on. Fiber
v3.7.0 made it fit for an
endpoint like this one: keys can be scoped to the caller with KeyScope,
cookies are no longer replayed to whoever sends a key
(#4791), and headers that earlier
middleware sets on every request are no longer copied into the stored response
(#4834). This post builds the
checkout endpoint from the story on top of it and then goes through the parts
the middleware leaves to you. Everything was built and tested against Fiber
v3.7.0 with Go 1.26.11, the Redis storage driver v3.6.4, go-redis v9.23.0 and
Redis 7.0. KeyScope needs Fiber v3.7.0 or later, which needs Go 1.26.
What the Middleware Doesโ
The core of it is short. The middleware reads a key from a request header,
X-Idempotency-Key by default. A request without that header, or with a safe
method such as GET, passes through untouched. The first request with a key
takes a lock on it, runs the handler and, if the handler returns nil, stores
the status, body and headers under the key for Lifetime, which defaults to 30
minutes. Every later request with the same key gets that stored response, and
the handler does not run. A request that arrives while the first one is still
running waits for the lock and then gets the stored response too. If the handler
returns an error, nothing is stored, and the next request with that key runs the
handler again.
That last rule decides more than any option does, and it gets its own section below. Just as important is what the middleware does not do. It does not require a key, it does not compare the request that comes with a stored key to the request that created it, and its default lock and storage live in the memory of one process. Each of those is a reasonable default for a library, and each of them is a gap in a payment endpoint.
There is a standard for this, though not a finished one. The IETF HTTP API
working group has an Idempotency-Key header
draft
that names the header Idempotency-Key and suggests 400 when a required key
is missing, 422 when a key is reused for a different payload and 409 when a
retry arrives while the original request is still being processed. Stripe's
API uses the same header name,
and
MDN
documents the same status codes. I followed those conventions below, because the
clients you care about probably already speak them.
The Checkout Endpointโ
The example is one endpoint, POST /v1/orders, behind API key authentication. A
fake payment processor stands in for the real one; it sleeps for 300
milliseconds and counts every charge, which makes double charges easy to see.
Orders live in a map. The idempotency setup lives in a function of its own,
idempotent, which comes right after this file:
package main
import (
"context"
"errors"
"fmt"
"log"
"math/rand/v2"
"os"
"sync"
"sync/atomic"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/idempotency"
"github.com/gofiber/fiber/v3/middleware/keyauth"
redisstore "github.com/gofiber/storage/redis/v3"
"github.com/redis/go-redis/v9"
)
type accountKey struct{}
// accounts maps API keys to account IDs. A real app looks them up.
var accounts = map[string]string{
"key-alice": "acct_alice",
"key-bob": "acct_bob",
}
func accountID(c fiber.Ctx) string {
return fiber.Locals[string](c, accountKey{})
}
// payments stands in for a card processor: every call moves money.
type payments struct {
latency time.Duration
charges atomic.Int64
down atomic.Bool // refuses every charge, for the tests
lost atomic.Bool // charges, then loses the answer, for the tests
}
var (
// errProcessorDown means the processor refused before moving money.
errProcessorDown = errors.New("payment processor unavailable")
// errAnswerLost stands for a timeout or a reset connection: the
// charge may or may not have happened.
errAnswerLost = errors.New("payment processor did not answer")
)
// Charge takes a reference that identifies the operation. A real
// processor takes it as its idempotency key and stores it with the
// charge, so a charge with an unknown outcome can be found again.
func (p *payments) Charge(
ctx context.Context, ref, account string, cents int64,
) (string, error) {
if p.down.Load() {
return "", errProcessorDown
}
select {
case <-time.After(p.latency):
case <-ctx.Done():
return "", ctx.Err()
}
n := p.charges.Add(1)
if p.lost.Load() {
return "", errAnswerLost
}
return fmt.Sprintf("ch_%d", n), nil
}
type order struct {
ID string `json:"id"`
Account string `json:"account"`
Cents int64 `json:"amount_cents"`
ChargeID string `json:"charge_id"`
}
type orderStore struct {
mu sync.Mutex
orders map[string]order
fail atomic.Bool // makes the next Save fail, for the tests
}
var errStoreDown = errors.New("order store unavailable")
// NewID is random so that instances do not hand out the same ID. A real
// app takes the ID from its database.
func (s *orderStore) NewID() string {
return fmt.Sprintf("ord_%012d", rand.Uint64N(1e12))
}
func (s *orderStore) Save(o order) error {
if s.fail.Swap(false) {
return errStoreDown
}
s.mu.Lock()
defer s.mu.Unlock()
s.orders[o.ID] = o
return nil
}
type createOrder struct {
Cents int64 `json:"amount_cents"`
}
func createOrderHandler(pay *payments, store *orderStore) fiber.Handler {
return func(c fiber.Ctx) error {
var in createOrder
if err := c.Bind().JSON(&in); err != nil {
return fiber.NewError(fiber.StatusBadRequest, "body must be JSON")
}
if in.Cents <= 0 {
return fiber.NewError(fiber.StatusBadRequest,
"amount_cents must be positive")
}
// Fiber's Ctx is never canceled, so the call gets a deadline of
// its own, well below the lock TTL.
ctx, cancel := context.WithTimeout(c.Context(), 10*time.Second)
defer cancel()
// The same reference for every attempt of this operation.
ref := accountID(c) + ":" + c.Get(keyHeader)
chargeID, err := pay.Charge(ctx, ref, accountID(c), in.Cents)
switch {
case errors.Is(err, errProcessorDown):
// Refused before money moved: an error is not stored, and a
// retry with the same key runs the handler again.
return fiber.NewError(fiber.StatusServiceUnavailable,
"payment processor unavailable, safe to retry")
case err != nil:
// The outcome is unknown. Store the answer so that a retry
// cannot charge again, and reconcile with the processor.
log.Printf("charge %s unknown, reconcile: %v", ref, err)
return c.Status(fiber.StatusBadGateway).JSON(fiber.Map{
"error": "payment outcome unknown, do not retry",
})
}
// From here on the customer has paid. Never return an error, or
// the retry charges the card a second time.
o := order{
ID: store.NewID(),
Account: accountID(c),
Cents: in.Cents,
ChargeID: chargeID,
}
if err := store.Save(o); err != nil {
log.Printf("order %s (charge %s) not saved: %v",
o.ID, chargeID, err)
return c.Status(fiber.StatusAccepted).JSON(fiber.Map{
"charge_id": chargeID,
"status": "paid, order pending",
})
}
c.Location("/v1/orders/" + o.ID)
return c.Status(fiber.StatusCreated).JSON(o)
}
}
func errorHandler(c fiber.Ctx, err error) error {
code, msg := fiber.StatusInternalServerError, "internal error"
var fe *fiber.Error
if errors.As(err, &fe) {
code, msg = fe.Code, fe.Message
} else {
log.Printf("%s %s: %v", c.Method(), c.Path(), err)
}
return c.Status(code).JSON(fiber.Map{"error": msg})
}
func newApp(pay *payments, store *orderStore,
kv fiber.Storage, lock idempotency.Locker,
) *fiber.App {
app := fiber.New(fiber.Config{ErrorHandler: errorHandler})
auth := keyauth.New(keyauth.Config{
Validator: func(c fiber.Ctx, key string) (bool, error) {
id, ok := accounts[key]
if !ok {
return false, keyauth.ErrMissingOrMalformedAPIKey
}
c.Locals(accountKey{}, id)
return true, nil
},
})
v1 := app.Group("/v1", auth)
// Handlers run in the order given, so the order handler goes last.
chain := append(idempotent(kv, lock), createOrderHandler(pay, store))
v1.Post("/orders", chain[0], chain[1:]...)
return app
}
func main() {
pay := &payments{latency: 300 * time.Millisecond}
store := &orderStore{orders: map[string]order{}}
// Without REDIS_URL, storage and lock default to this process only.
var kv fiber.Storage
var lock idempotency.Locker
if url := os.Getenv("REDIS_URL"); url != "" {
opts, err := redis.ParseURL(url)
if err != nil {
log.Fatal(err)
}
rdb := redis.NewClient(opts)
kv = redisstore.NewFromConnection(rdb)
lock = newRedisLocker(rdb)
}
addr := os.Getenv("ADDR")
if addr == "" {
addr = ":3000"
}
app := newApp(pay, store, kv, lock)
app.Get("/stats", func(c fiber.Ctx) error {
return c.JSON(fiber.Map{"charges": pay.charges.Load()})
})
log.Fatal(app.Listen(addr))
}
Authentication runs before anything that has to do with idempotency, because the
key will be scoped to the account. REDIS_URL switches the storage and the lock
from process memory to Redis, which gets a section of its own.
Closing the Gapsโ
The second file configures the middleware and puts three small handlers around it. The next four sections go through it piece by piece:
package main
import (
"crypto/sha256"
"encoding/hex"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/idempotency"
"github.com/valyala/fasthttp"
)
const (
keyHeader = "Idempotency-Key"
replayedHeader = "Idempotent-Replayed"
fingerprintHeader = "X-Request-Fingerprint" // stored, never sent
)
// idempotent returns the handlers that make a route safe to retry:
// a key is required, a stored response is replayed only to the same
// caller, and a key reused for a different request is refused.
func idempotent(store fiber.Storage, lock idempotency.Locker) []any {
cfg := idempotency.Config{
KeyHeader: keyHeader,
KeyHeaderValidate: validateKey,
KeyScope: func(c fiber.Ctx) string {
return accountID(c) // set by the auth middleware
},
Lifetime: 24 * time.Hour,
Storage: store,
Lock: lock,
}
return []any{
requireKey,
checkFingerprint,
idempotency.New(cfg),
recordFingerprint,
}
}
// requireKey rejects a request without a key. The middleware itself
// lets such a request through unprotected.
func requireKey(c fiber.Ctx) error {
if c.Get(keyHeader) == "" {
return fiber.NewError(fiber.StatusBadRequest,
keyHeader+" header is required")
}
return c.Next()
}
// validateKey accepts a UUID in its canonical text form. Returning a
// *fiber.Error makes the error handler answer 400 instead of 500.
func validateKey(key string) error {
if !isUUID(key) {
return fiber.NewError(fiber.StatusBadRequest,
keyHeader+" must be a UUID")
}
return nil
}
func isUUID(s string) bool {
if len(s) != 36 {
return false
}
for i := 0; i < len(s); i++ {
switch ch := s[i]; {
case i == 8 || i == 13 || i == 18 || i == 23:
if ch != '-' {
return false
}
case '0' <= ch && ch <= '9',
'a' <= ch && ch <= 'f',
'A' <= ch && ch <= 'F':
default:
return false
}
}
return true
}
// fingerprint identifies what a request asks for. Retries must send
// the same method, path and body bytes to count as the same request.
func fingerprint(c fiber.Ctx) string {
h := sha256.New()
h.Write([]byte(c.Method()))
h.Write([]byte{0})
h.Write([]byte(c.Path()))
h.Write([]byte{0})
h.Write(c.Body())
return hex.EncodeToString(h.Sum(nil))
}
// recordFingerprint runs only when the idempotency middleware lets a
// request through to the handler. The header it sets is stored with
// the response, so the fingerprint and the response share one entry.
func recordFingerprint(c fiber.Ctx) error {
c.Set(fingerprintHeader, fingerprint(c))
return c.Next()
}
// checkFingerprint runs before the idempotency middleware. After a
// replay it compares the stored fingerprint with this request's and
// refuses a key that was used for something else.
func checkFingerprint(c fiber.Ctx) error {
// Headers set so far come from earlier middleware such as CORS and
// must survive a refusal; everything after this is the replay's.
var upstream fasthttp.ResponseHeader
c.Response().Header.CopyTo(&upstream)
err := c.Next()
// Removed on every path, errors included, before the client sees it.
stored := c.GetRespHeader(fingerprintHeader)
c.Response().Header.Del(fingerprintHeader)
if err != nil || !idempotency.IsFromCache(c) {
return err
}
if stored != fingerprint(c) {
c.Response().Reset()
upstream.CopyTo(&c.Response().Header)
return fiber.NewError(fiber.StatusUnprocessableEntity,
keyHeader+" was already used for a different request")
}
c.Set(replayedHeader, "true")
return nil
}
The Header Nameโ
The default header is X-Idempotency-Key. A client that follows the draft or
has been talking to Stripe sends Idempotency-Key, and the default
configuration does not look at that header at all. Nothing fails. The request
simply has no key as far as the middleware is concerned, so it runs the handler
every time. I checked this with the default configuration: two requests with the
same Idempotency-Key ran the handler twice. Nothing in the logs points at it.
Pick one name, set KeyHeader to it and document it.
Requiring a Keyโ
Because a request without a key passes through, the protection is opt-in for
every single client. For a payment endpoint I want the opposite, so requireKey
answers 400 when the header is missing. It runs first in the chain, before
anything is parsed or locked.
The validator deserves a look too. The default KeyHeaderValidate checks only
that the key is 36 characters long, and when it fails it returns a plain error,
which the default error handler turns into a 500 with the text invalid idempotency key: invalid length: 5 != 36. A client error reported as a server
error ends up on the wrong dashboard. validateKey checks the canonical UUID
format and returns a *fiber.Error, so the client gets a 400 it can act on. A
UUID check says nothing about how random the key is, by the way. The middleware
documentation is explicit that a stored key works for whoever sends it, so
clients have to draw keys from a secure random source and never build them from
counters or user IDs.
One Account's Key Is Not Another'sโ
Before v3.7.0, the key alone identified a stored response. If two accounts sent the same key, the second one got the first one's response, here including the other customer's order ID and charge ID. With random UUIDs an accidental collision is not the worry; a buggy client that hardcodes a key, or someone who learns a key from a log line, is.
KeyScope fixes that. It returns a string that identifies the caller, and the
middleware stores, replays and locks per scope and key together. The scope and
key are hashed into the storage key, so account IDs do not show up in Redis. In
the test at the end, Alice and Bob send the same key and each gets their own
order, with two charges. Two details are easy to miss. The middleware that sets
the account has to run before the idempotency middleware, or every request lands
in the empty scope. And every request for which KeyScope returns the same
string shares a scope, the empty string included, so a route without
authentication should not rely on KeyScope at all.
The Same Key for a Different Requestโ
The middleware does not look at the body. If a client reuses a key for a new
order, by mistake or because a developer copied a request in a test tool, it
gets the response of the old order with a 201 and believes the new one was
placed. The draft and Stripe both refuse such a request instead.
The fingerprint is a SHA-256 of the method, path and body. The interesting part
is where it is stored. A tempting design keeps fingerprints in a separate
storage entry, but then there are two entries that can disagree, and two
concurrent first requests can both pass the check. Instead, recordFingerprint
runs after the idempotency middleware, which means only when the handler is
about to run for real, and puts the fingerprint into a response header. The
middleware stores that header with the rest of the response. On a replay,
checkFingerprint, which wraps the idempotency middleware from the outside,
reads the replayed header, compares it with the fingerprint of the request in
front of it and answers 422 on a mismatch. The fingerprint and the response
are one entry, written once, under the lock. The header is deleted before
anything goes to the client. On a mismatch the replayed response is thrown
away, but the headers that earlier middleware had set before the chain, such
as a CORS Access-Control-Allow-Origin, are copied back first. Without them a
browser client could not even read the 422.
idempotency.IsFromCache is what makes this possible: it reports whether the
current response was replayed, and it is meant to be read from a middleware
registered before the idempotency middleware, after c.Next() returns. I also
use it to set Idempotent-Replayed: true on replays, which is the header
Stripe's error handling guide tells
clients to look for. It helps whenever someone has to read client logs.
idempotency.WasPutToCache is the counterpart for the other direction; it
reports whether the current response was stored, which makes a good metric.
The trade-off is that the fingerprint is computed from raw bytes. A client that
sends the same JSON with its keys in a different order gets a 422. Real retry
logic resends the same bytes, so I have not seen that matter, but if your
clients rebuild the request on every attempt, fingerprint the bound struct
instead of the body.
More Than One Instanceโ
The default lock is a mutex map in one process, and the default storage is an
in-memory store in that same process. Run two instances behind a load balancer
and both are wrong. I started the example twice, on two ports, without
REDIS_URL, and sent three requests with the same key at the same time, two to
the first instance and one to the second. All three got a 201. The first
instance charged once, because its own lock made its second request wait and
replay. The second instance charged again. Two charges for one order.
Pointing both instances at the same Redis storage is not enough on its own. In a
test with a shared Redis storage and the default lock, two concurrent requests
on two instances both ran the handler, because each saw an empty storage before
either had written its response. The lock has to be shared as well. Fiber's
Locker interface has two methods, Lock(key) error and Unlock(key) error,
and Lock has to block until the caller holds the key. Here is an
implementation on Redis with SET NX:
package main
import (
"context"
"crypto/rand"
"errors"
"sync"
"time"
"github.com/gofiber/fiber/v3"
"github.com/redis/go-redis/v9"
)
// errKeyInUse is what a client gets when another request with the same
// key is still running and did not finish within the wait.
var errKeyInUse = fiber.NewError(fiber.StatusConflict,
"a request with this Idempotency-Key is still in progress")
// unlockScript deletes the lock only if it still holds our token, so a
// request whose lock expired cannot release one that another process
// took over. Within one process, tokens is keyed by lock name only,
// because Unlock gets nothing else; keep the TTL above the slowest
// handler so that case never arises.
var unlockScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0`)
// redisLocker implements idempotency.Locker across processes with
// SET NX PX. TTL must be longer than the slowest handler it protects.
type redisLocker struct {
rdb redis.UniversalClient
ttl time.Duration // how long a crashed holder blocks the key
wait time.Duration // how long a second request waits for the first
poll time.Duration
tokens sync.Map // lock name -> token of the request holding it
}
func newRedisLocker(rdb redis.UniversalClient) *redisLocker {
return &redisLocker{
rdb: rdb,
ttl: 30 * time.Second,
wait: 5 * time.Second,
poll: 50 * time.Millisecond,
}
}
func (l *redisLocker) Lock(key string) error {
// Locker has no context parameter, so bound every call ourselves.
ctx, cancel := context.WithTimeout(context.Background(), l.wait)
defer cancel()
name := "idempotency-lock:" + key
token := rand.Text() // Go 1.24+, 26 random base32 characters
for {
ok, err := l.rdb.SetNX(ctx, name, token, l.ttl).Result()
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return errKeyInUse
}
return err
}
if ok {
l.tokens.Store(name, token)
return nil
}
select {
case <-ctx.Done():
return errKeyInUse
case <-time.After(l.poll):
}
}
}
func (l *redisLocker) Unlock(key string) error {
name := "idempotency-lock:" + key
token, ok := l.tokens.LoadAndDelete(name)
if !ok {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
return unlockScript.Run(ctx, l.rdb, []string{name}, token).Err()
}
With REDIS_URL set on both instances, the same three requests produced one
charge. The first request to arrive took the lock, the other two waited on it
and then got the stored response, all with the same order ID.
The design has limits. The lock expires after ttl, 30 seconds here, so a
crashed instance cannot block a key forever. The price is that a handler which
runs longer than that loses its lock without noticing, and a retry on another
instance can run the handler a second time. Set the TTL well above your slowest
payment call, and give that call a deadline below it. The handler does that with
context.WithTimeout, because Fiber's Ctx is never canceled on its own. The
tokens map is keyed by lock name because Unlock only gets the key, which
holds up only as long as no lock expires. Last, this is a lock on a single Redis
server. If that server fails over and the replica has not received the lock yet,
two requests can hold the same key. For that case the payment processor's own
idempotency support is the backstop; more on that below.
Redis itself can fail too. If the lookup or the lock fails, the middleware
returns an error and the request gets a 500 without running the handler, which
is the safe direction. If the write after the handler fails, the client gets a
500 for an order that was paid, and its retry runs the handler again. Watch
the error rate on that write, and treat a Redis outage as an incident for this
endpoint, not as a cache miss.
The wait is bounded too. The built-in lock in v3.7.0 waits for as long as the
first request takes. redisLocker gives up after five seconds and returns a
*fiber.Error with 409 Conflict, which the middleware passes on wrapped in
its own error, and which the error handler finds with errors.As. That matches
what the draft suggests for a retry that overlaps the original, and the client
can try again a little later. The test at the end checks it with a one-second
charge and a 100-millisecond wait.
Errors Are Retryable, Responses Are Finalโ
A handler that writes a response and returns nil has its response stored
whatever the status code. I wrote a probe handler that sets 500 with
c.Status(500).SendString(...) and returns nil: the retry got the same 500
from storage, and the handler ran once. Stripe works the same way, storing a
500 and replaying it, while not storing errors from before the work began,
such as validation failures.
That turns the choice between return err and return c.Status(...) into a
decision you make on purpose in every branch of the handler. The question to ask
is whether anything irreversible has happened yet.
In createOrderHandler, a body that does not parse or an amount that is not
positive returns an error. Nothing happened, the client can fix the request and
retry with the same key. If the payment processor refuses the charge before
money moves, the handler also returns an error, a 503 here, so that a retry
once the processor is back runs the handler again. The test
TestErrorsAreNotStored checks exactly that.
Not every processor error is that clear, though. A timeout or a reset
connection can arrive after the processor has charged the card, so the outcome
is unknown. Returning an error there would let the retry charge again. The
handler stores a 502 that tells the client not to retry, and the charge has to
be reconciled with the processor before anyone tries again with a new key. For
that, the handler sends a reference built from the account and the client's key
with every attempt and logs it when the outcome is unknown, so the charge can be
found again on the processor's side. A real app would also write a pending
operation with that reference to its database before calling the processor.
TestUnknownOutcomeIsStored simulates a processor that charges and then loses
its answer: the retry gets the stored 502, and the card is charged once. Treat
an error as retryable only when you know that nothing happened.
After the charge, the rule flips. If saving the order fails, returning an error
would leave nothing stored, and the client's retry would charge the card again.
So the handler logs the failure and answers 202 with the charge ID and a
status that says the order is pending, which is stored and replayed. In a real
system something has to pick that order up later, usually from the processor's
records or an outbox. What matters here is that every retry gets the same answer
and the card is charged once, which is what TestPaidButNotSavedIsStored
checks.
One gap remains that no middleware can close. The response is stored after the
handler returns. If the process dies between the charge and that write, nothing
is stored, the lock expires, and the retry charges again. That is why payment
processors accept an idempotency key of their own. Pass a key derived from the
scope and the client's key down to the processor, and the processor refuses the
second charge for the same operation, at least while it still keeps the key;
Stripe documents at least 24 hours. A repeat does not necessarily return the
charge, though. Stripe replays the saved response of the first request, and if
that was a 500, the repeat is the same 500 without a charge ID. The key
prevents the second charge, but an unknown outcome still has to be reconciled
with the processor before you treat the charge as settled.
What a Replay Containsโ
A replay sends the stored status, body and headers, and v3.7.0 changed which
headers are part of that. Set-Cookie is no longer stored unless
KeepResponseHeaders names it, so a session cookie set for the first client
does not end up with whoever sends the key next. Header lines that were already
on the response before the handler ran, with the same value, are no longer
stored either. Middleware registered before the idempotency middleware runs on
every request, so its headers are fresh on every replay. I checked this with the
request ID middleware in front and a handler that set a cookie: the first
response had a cookie and one request ID, the replay had no cookie and a
different request ID. That is the order to aim for. CORS, request IDs and
security headers go before the idempotency middleware, and anything after it is
replayed as it was.
Two more things end up in Redis that you might not expect. The full response
body is stored, so whatever your order response contains sits in Redis for the
whole Lifetime. I set it to 24 hours, the window Stripe documents, so a client
that retries after a long outage still gets its answer; the default 30 minutes
is short for mobile clients. That is also 24 hours of bodies to keep, so keep
the response small. A retry that arrives after the Lifetime runs the handler
again, so it is part of your API contract: clients should create one key per
operation, keep it with the pending operation (also across an app restart) and
stop retrying with it well before the window ends.
If several apps share one Redis, mind the keyspace. Scoped and unscoped entries
live side by side under the same prefix, so the middleware documentation
recommends a storage of its own for an instance with KeyScope, or the same
KeyScope on every instance that shares it.
Streamed responses without a known length, such as SendStreamWriter, are not
stored at all, nor are streams longer than 1 MiB. The next request with that key
runs the handler again, so keep streams out of endpoints that need this
protection.
If you upgrade from v3.6, one more detail matters on the day of the deploy.
Since v3.7.0, entries are stored under an idempotency: prefix, and the
middleware documentation states that responses stored by an earlier version are
not replayed after the upgrade. A client whose first attempt hit the old version
and whose retry hits the new one runs the handler again. That window is not the
deploy itself but the old Lifetime after it, 30 minutes with the default:
any operation first sent within one Lifetime before the switch can be retried
against the new version. Draining traffic for the length of the deploy does not
close it. The processor-level key from the previous section does, because the
processor still recognizes the operation. Without one, either keep the endpoint
closed to retries for a full Lifetime after the switch or accept the risk
knowingly.
Trying Itโ
Start the server with go run . and send the same order twice with the same
key. This is the real output with the Date and Content-Length lines removed;
order IDs are random and differ on every run:
curl -i -X POST localhost:3000/v1/orders \
-H 'Authorization: Bearer key-alice' \
-H 'Idempotency-Key: 7c1b9a52-3e4f-4d2a-9b8e-0f6a1c2d3e4f' \
-H 'Content-Type: application/json' \
-d '{"amount_cents":4200}'
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: /v1/orders/ord_868265633747
{"id":"ord_868265633747","account":"acct_alice","amount_cents":4200,"charge_id":"ch_1"}
The second request is a replay, marked as such, with the same order:
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: /v1/orders/ord_868265633747
Idempotent-Replayed: true
{"id":"ord_868265633747","account":"acct_alice","amount_cents":4200,"charge_id":"ch_1"}
The same key with a different amount is refused, and Bob's request with Alice's key creates an order of his own:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json; charset=utf-8
{"error":"Idempotency-Key was already used for a different request"}
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: /v1/orders/ord_518635343470
{"id":"ord_518635343470","account":"acct_bob","amount_cents":4200,"charge_id":"ch_2"}
A missing key and a key that is not a UUID both get a 400:
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"error":"Idempotency-Key header is required"}
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"error":"Idempotency-Key must be a UUID"}
curl localhost:3000/stats then reports {"charges":2}: one for Alice and one
for Bob.
Pin It Down in a Testโ
The tests run the app in process with app.Test, and the two that need Redis
use miniredis v2.41.0, an in-process Redis for tests, so they need no
server:
package main
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/idempotency"
redisstore "github.com/gofiber/storage/redis/v3"
"github.com/redis/go-redis/v9"
)
const (
testKey = "7c1b9a52-3e4f-4d2a-9b8e-0f6a1c2d3e4f"
orderJSON = `{"amount_cents":4200}`
)
type env struct {
app *fiber.App
pay *payments
store *orderStore
}
func newEnv(t *testing.T, kv fiber.Storage, lock idempotency.Locker) *env {
t.Helper()
pay := &payments{latency: 50 * time.Millisecond}
store := &orderStore{orders: map[string]order{}}
return &env{app: newApp(pay, store, kv, lock), pay: pay, store: store}
}
// send is safe to call from any goroutine; post is the t.Fatal version.
func (e *env) send(apiKey, idemKey, body string) (
*http.Response, string, error,
) {
req := httptest.NewRequest(fiber.MethodPost, "/v1/orders",
strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
if idemKey != "" {
req.Header.Set(keyHeader, idemKey)
}
resp, err := e.app.Test(req, fiber.TestConfig{Timeout: 10 * time.Second})
if err != nil {
return nil, "", err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
return resp, string(b), err
}
func (e *env) post(t *testing.T, apiKey, idemKey, body string) (
*http.Response, string,
) {
t.Helper()
resp, b, err := e.send(apiKey, idemKey, body)
if err != nil {
t.Fatal(err)
}
return resp, b
}
func TestRetryReplaysWithoutCharging(t *testing.T) {
e := newEnv(t, nil, nil)
first, body1 := e.post(t, "key-alice", testKey, orderJSON)
retry, body2 := e.post(t, "key-alice", testKey, orderJSON)
if first.StatusCode != fiber.StatusCreated ||
retry.StatusCode != fiber.StatusCreated {
t.Fatalf("status %d then %d", first.StatusCode, retry.StatusCode)
}
if body1 != body2 {
t.Fatalf("retry got a different order:\n%s\n%s", body1, body2)
}
if retry.Header.Get(replayedHeader) != "true" ||
first.Header.Get(replayedHeader) != "" {
t.Fatal("only the retry should be marked as replayed")
}
if first.Header.Get(fingerprintHeader) != "" ||
retry.Header.Get(fingerprintHeader) != "" {
t.Fatal("fingerprint header leaked to the client")
}
if n := e.pay.charges.Load(); n != 1 {
t.Fatalf("%d charges, want 1", n)
}
}
func TestKeyReusedForOtherRequest(t *testing.T) {
e := newEnv(t, nil, nil)
e.post(t, "key-alice", testKey, orderJSON)
resp, _ := e.post(t, "key-alice", testKey, `{"amount_cents":9900}`)
if resp.StatusCode != fiber.StatusUnprocessableEntity {
t.Fatalf("status %d, want 422", resp.StatusCode)
}
}
func TestKeysAreScopedPerAccount(t *testing.T) {
e := newEnv(t, nil, nil)
_, alice := e.post(t, "key-alice", testKey, orderJSON)
_, bob := e.post(t, "key-bob", testKey, orderJSON)
if strings.Contains(bob, "acct_alice") || alice == bob {
t.Fatalf("bob saw alice's order: %s", bob)
}
if n := e.pay.charges.Load(); n != 2 {
t.Fatalf("%d charges, want 2", n)
}
}
func TestErrorsAreNotStored(t *testing.T) {
e := newEnv(t, nil, nil)
e.pay.down.Store(true)
resp, _ := e.post(t, "key-alice", testKey, orderJSON)
if resp.StatusCode != fiber.StatusServiceUnavailable {
t.Fatalf("status %d, want 503", resp.StatusCode)
}
if resp.Header.Get(fingerprintHeader) != "" {
t.Fatal("fingerprint header leaked on an error")
}
e.pay.down.Store(false)
resp, _ = e.post(t, "key-alice", testKey, orderJSON)
if resp.StatusCode != fiber.StatusCreated {
t.Fatalf("retry after outage: status %d, want 201", resp.StatusCode)
}
}
func TestUnknownOutcomeIsStored(t *testing.T) {
e := newEnv(t, nil, nil)
e.pay.lost.Store(true)
first, _ := e.post(t, "key-alice", testKey, orderJSON)
e.pay.lost.Store(false)
retry, _ := e.post(t, "key-alice", testKey, orderJSON)
if first.StatusCode != fiber.StatusBadGateway ||
retry.StatusCode != fiber.StatusBadGateway {
t.Fatalf("status %d then %d, want 502 twice",
first.StatusCode, retry.StatusCode)
}
if n := e.pay.charges.Load(); n != 1 {
t.Fatalf("%d charges, want 1", n)
}
}
func TestMismatchKeepsUpstreamHeaders(t *testing.T) {
app := fiber.New(fiber.Config{ErrorHandler: errorHandler})
app.Use(func(c fiber.Ctx) error {
c.Set(fiber.HeaderAccessControlAllowOrigin, "https://shop.example")
return c.Next()
})
chain := append(idempotent(nil, nil), func(c fiber.Ctx) error {
return c.Status(fiber.StatusCreated).SendString("created")
})
app.Post("/orders", chain[0], chain[1:]...)
e := &env{app: app}
for _, body := range []string{orderJSON, `{"amount_cents":9900}`} {
req := httptest.NewRequest(fiber.MethodPost, "/orders",
strings.NewReader(body))
req.Header.Set(keyHeader, testKey)
resp, err := e.app.Test(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
got := resp.Header.Get(fiber.HeaderAccessControlAllowOrigin)
if got != "https://shop.example" {
t.Fatalf("status %d: CORS header %q lost", resp.StatusCode, got)
}
if body != orderJSON &&
resp.StatusCode != fiber.StatusUnprocessableEntity {
t.Fatalf("status %d, want 422", resp.StatusCode)
}
}
}
func TestPaidButNotSavedIsStored(t *testing.T) {
e := newEnv(t, nil, nil)
e.store.fail.Store(true)
first, body1 := e.post(t, "key-alice", testKey, orderJSON)
retry, body2 := e.post(t, "key-alice", testKey, orderJSON)
if first.StatusCode != fiber.StatusAccepted ||
retry.StatusCode != fiber.StatusAccepted {
t.Fatalf("status %d then %d, want 202 twice",
first.StatusCode, retry.StatusCode)
}
if body1 != body2 || e.pay.charges.Load() != 1 {
t.Fatalf("retry charged again: %d charges", e.pay.charges.Load())
}
}
func TestConcurrentDuplicates(t *testing.T) {
e := newEnv(t, nil, nil)
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
_, _, err := e.send("key-alice", testKey, orderJSON)
if err != nil {
t.Error(err)
}
})
}
wg.Wait()
if n := e.pay.charges.Load(); n != 1 {
t.Fatalf("%d charges, want 1", n)
}
}
// TestTwoInstances runs two apps against one Redis, as two pods would.
func TestTwoInstances(t *testing.T) {
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
kv := redisstore.NewFromConnection(rdb)
pay := &payments{latency: 200 * time.Millisecond}
var apps []*env
for range 2 {
store := &orderStore{orders: map[string]order{}}
app := newApp(pay, store, kv, newRedisLocker(rdb))
apps = append(apps, &env{app: app, pay: pay, store: store})
}
var wg sync.WaitGroup
for i := range 6 {
wg.Go(func() {
resp, _, err := apps[i%2].send("key-alice", testKey, orderJSON)
if err != nil {
t.Error(err)
} else if resp.StatusCode != fiber.StatusCreated {
t.Errorf("status %d", resp.StatusCode)
}
})
}
wg.Wait()
if n := pay.charges.Load(); n != 1 {
t.Fatalf("%d charges across instances, want 1", n)
}
}
func TestLockWaitIsBounded(t *testing.T) {
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
lock := newRedisLocker(rdb)
lock.wait = 100 * time.Millisecond
e := newEnv(t, redisstore.NewFromConnection(rdb), lock)
e.pay.latency = time.Second
done := make(chan struct{})
go func() {
defer close(done)
if _, _, err := e.send("key-alice", testKey, orderJSON); err != nil {
t.Error(err)
}
}()
// Wait until the first request holds the lock.
for deadline := time.Now().Add(time.Second); len(mr.Keys()) == 0; {
if time.Now().After(deadline) {
t.Fatal("first request never took the lock")
}
time.Sleep(10 * time.Millisecond)
}
resp, _ := e.post(t, "key-alice", testKey, orderJSON)
<-done
if resp.StatusCode != fiber.StatusConflict {
t.Fatalf("status %d, want 409", resp.StatusCode)
}
}
TestTwoInstances is the most important one. It builds two apps that share
nothing but Redis and fails if anybody swaps the Redis lock for the default one.
TestConcurrentDuplicates covers the single-process case, and the remaining
tests pin down the error rules, so a refactor that turns a c.Status(...) into
a return err after the charge fails in CI. All tests passed with -race. To
try the whole thing, put the four files into an empty directory:
go mod init example.com/orders
go get github.com/gofiber/fiber/[email protected] \
github.com/gofiber/storage/redis/[email protected] \
github.com/alicebob/miniredis/[email protected]
go mod tidy
go test -race ./...
REDIS_URL=redis://localhost:6379/0 go run .
When Not to Use Itโ
Not every endpoint needs keys. PUT and DELETE are idempotent by definition
when they are implemented as such, although the middleware still handles them by
default, since its default Next skips only safe methods. A
PUT /v1/orders/{id} with a client-chosen ID and a unique constraint in the database
is often the better design: the database enforces the rule in the same
transaction as the write, and there is nothing to store, lock or expire. I would
use the middleware where the server chooses the ID, where the operation calls
something outside your database, like a payment processor or an email service,
or where you cannot change the API that clients already use.
I would also not wrap every route in it by default. Each protected request costs a lock round trip and a storage write, and each stored response is data you keep around. Put it on the routes where running twice costs money or trust.
Wrapping Upโ
Since v3.7.0 the idempotency middleware is a good base for retry-safe POST
endpoints, but the defaults are written for a single process and a cooperative
client. Share the lock as well as the storage, refuse reused keys, and look at
every return err in the handler: before the irreversible step it is right,
after it, write a response instead.
Internal Referencesโ
- Idempotency Middleware: behavior,
KeyScopeand config - Keyauth Middleware
- Error Handling guide
- Redis storage driver
- App: Test
- Fiber v3.7.0 release (KeyScope, cookies, upstream headers)
- Stop idempotency cookie replay (#4791)
- Exclude unchanged upstream headers from idempotency storage (#4834)
- Redis storage v3.6.4 release
- IETF draft: The Idempotency-Key HTTP Header Field
- Stripe: Idempotent requests
