A typed, storage-backed idempotency layer for Go APIs, workers, webhooks, and retryable workflows.
go-idempotent suppresses duplicate execution by atomically assigning one caller ownership of an idempotency key. Later callers receive the recorded outcome, wait for it, reject it, or return a pending state—according to policy.
It is designed for safely retryable HTTP endpoints, at-least-once queue consumers, webhook handlers, scheduled jobs, and payment-oriented application workflows.
Idempotency makes repeated requests converge on one stored outcome. It is not a universal exactly-once guarantee or a distributed transaction across external systems.
- Atomic ownership acquisition with owner and fencing tokens
- Lease heartbeats and stale-owner recovery
- Typed results with generic executors and pluggable codecs
- Request fingerprints to reject conflicting key reuse
- Configurable pending, TTL, failure, and panic semantics
- In-memory and SQLite stores; standard-library
net/httpmiddleware - Lifecycle hooks, contract testing, fuzz targets, and benchmarks
Requires Go 1.23 or later.
go get github.com/magnexis/go-idempotentrecords := memory.New[Order]()
defer records.Close()
executor := idempotent.New[Order](
idempotent.WithStore[Order](records),
idempotent.WithSuccessTTL[Order](24*time.Hour),
)
result, err := executor.DoWithOptions(ctx, "checkout:order-123", createOrder,
idempotent.WithFingerprint(idempotent.FingerprintJSON(request)),
)The first caller runs createOrder. Concurrent duplicates replay the completed result. A reused key with a different fingerprint returns ErrFingerprintMismatch.
caller → executor → fingerprint / policy / codec → store
├─ memory
└─ SQLite
- The store atomically creates a pending record and grants its owner token.
- Only that owner runs the operation; automatic heartbeats renew its lease.
- Completion and failure compare the owner token and fencing token.
- A stale record may be reclaimed after its lease expires; the old owner can no longer write.
records := memory.New[middleware.Response]()
executor := idempotent.New[middleware.Response](idempotent.WithStore[middleware.Response](records))
handler := middleware.Idempotency(executor,
middleware.WithMaxRequestBody(1<<20),
middleware.WithMaxResponseBody(1<<20),
middleware.WithFingerprintHeaders("X-API-Version"),
)(checkoutHandler)For POST, PUT, and PATCH, the middleware fingerprints the method, path, normalized query, bounded body, and selected stable headers. It replays the stored status, body, and allowlisted headers. Conflicting requests receive 409 Conflict.
go run ./examples/http-api
curl -i -X POST http://localhost:8080/checkout -H "Idempotency-Key: checkout-123"Do not fingerprint credentials, cookies, request IDs, timestamps, or tracing headers. Streaming, hijacked, and WebSocket responses should bypass this middleware.
result, err := executor.Do(ctx, idempotent.Key(event.ID), func(ctx context.Context) (Receipt, error) {
_, ownership := idempotent.OwnershipFromContext(ctx)
select {
case <-ownership.Lost():
return Receipt{}, idempotent.ErrOwnershipLost
default:
return processEvent(ctx, event)
}
})When heartbeat renewal fails, the operation context is canceled and Ownership.Lost() closes. Stop critical side effects immediately—another process may reclaim the record.
| Store | Status | Intended use |
|---|---|---|
| Memory | Available | Tests and single-process services |
| SQLite | Available | Embedded and single-node applications |
| Redis | Planned | Shared distributed coordination |
| PostgreSQL | Planned | Shared relational coordination |
SQLite enables WAL mode and a busy timeout, but it is not a multi-host coordination solution. See store guidance.
Successful and failed results have separate TTLs. Failure caching is controlled by WithFailurePolicy; cached failures replay as *idempotent.StoredError, not an invented original error type.
Namespace untrusted keys and enforce key/result/request limits. Hash persistence keys when they may contain sensitive data. Authorize before idempotency middleware: replay must never become an authorization bypass.
go test ./...
go test -race ./...
go vet ./...
go test -bench=. -benchmem ./...See CONTRIBUTING.md, SECURITY.md, and the architecture notes.
- Redis and PostgreSQL adapters with live integration tests
- Expanded store-contract coverage and cancellation/failure injection
- Prometheus and OpenTelemetry examples
MIT. See LICENSE.
