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 for tools/call). Set DisablePrincipalScope: true only on intentionally public routes.
  • A matching request replays the stored status, headers, and body without re-running Transaction, the handler, or AfterResponse, and records idempotency.replayed=true on 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 Conflict with Retry-After: 1 until Complete, Delete, or LockTTL (default 30s) expires.
  • Responses returning 5xx, panics, or bodies larger than MaxBodySize (default 1 MiB) call Delete and are never cached.
  • Enabling idempotency on SSE or WS routes, or with Store == nil, is a build error.

Options reference

FieldDefaultEffect
StorerequiredIdempotencyStore (NewMemoryIdempotencyStore for single-node/tests, or custom Redis/SQL store)
Header"Idempotency-Key"Request header carrying the idempotency key
TTL24hHow long completed responses stay replayable
LockTTL30sIn-flight acquisition lease duration before self-healing after a crash
MaxBodySize1 MiBMaximum response body size eligible for caching
StoreTimeout2sTimeout per IdempotencyStore call (negative removes the bound)
FailOpenfalseServe unmetered on store errors/timeouts instead of answering 503
RequireKeyfalseRequire the header on idempotent routes (400 when missing)
DisablePrincipalScopefalseOmit the authenticated principal from the key scope
Open source under MIT / Apache-2.0.Built on net/http, and nothing else.