Idempotency
Clients and AI agents retry timed-out requests. muzak.WithIdempotency deduplicates retried
mutations (POST, PUT, PATCH, DELETE) and MCP tools/call requests using an
Idempotency-Key header and a pluggable muzak.IdempotencyStore.
store := muzak.NewMemoryIdempotencyStore()
app := muzak.New(muzak.AppOptions{
Title: "Shop API",
Idempotency: muzak.IdempotencyOptions{
Store: store,
},
})
app.Post("/orders", handlers.CreateOrder)
app.Get("/healthz", handlers.Health, muzak.SkipIdempotency())
Pipeline order and safety
Idempotency runs after security schemes, CaptureBody(), and guards, and before
providers (Transaction), the route handler, session writes, and AfterResponse:
- An unauthenticated or unauthorized caller cannot poison or probe another caller's keys.
- By default, keys are scoped by
Method + Route Pattern + Authenticated Principal(and MCP tool name fortools/call). SetDisablePrincipalScope: trueonly on intentionally public routes. - A matching request replays the stored status, headers, and body without re-running
Transaction, the handler, orAfterResponse, and recordsidempotency.replayed=trueon spans and access logs. - A different request body with the same key returns
422 Unprocessable Entity. - A concurrent in-flight request with the same key returns
409 ConflictwithRetry-After: 1untilComplete,Delete, orLockTTL(default30s) expires. - Responses returning
5xx, panics, or bodies larger thanMaxBodySize(default1 MiB) callDeleteand are never cached. - Enabling idempotency on
SSEorWSroutes, or withStore == nil, is a build error.
Options reference
| Field | Default | Effect |
|---|---|---|
Store | required | IdempotencyStore (NewMemoryIdempotencyStore for single-node/tests, or custom Redis/SQL store) |
Header | "Idempotency-Key" | Request header carrying the idempotency key |
TTL | 24h | How long completed responses stay replayable |
LockTTL | 30s | In-flight acquisition lease duration before self-healing after a crash |
MaxBodySize | 1 MiB | Maximum response body size eligible for caching |
StoreTimeout | 2s | Timeout per IdempotencyStore call (negative removes the bound) |
FailOpen | false | Serve unmetered on store errors/timeouts instead of answering 503 |
RequireKey | false | Require the header on idempotent routes (400 when missing) |
DisablePrincipalScope | false | Omit the authenticated principal from the key scope |