Skip to content

About

`go-idempotent` is a typed, storage-backed Go library for duplicate suppression and replayable operation outcomes. It provides atomic execution ownership, lease-based stale-owner recovery, and fencing tokens so a reclaimed worker cannot overwrite a newer result.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

Repository files navigation

go-idempotent logo

go-idempotent

A typed, storage-backed idempotency layer for Go APIs, workers, webhooks, and retryable workflows.

Go Reference CI Go Report Card MIT license

Overview

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.

Highlights

  • 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/http middleware
  • Lifecycle hooks, contract testing, fuzz targets, and benchmarks

Install

Requires Go 1.23 or later.

go get github.com/magnexis/go-idempotent

Quick start

records := 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.

How it works

caller → executor → fingerprint / policy / codec → store
                                              ├─ memory
                                              └─ SQLite
  1. The store atomically creates a pending record and grants its owner token.
  2. Only that owner runs the operation; automatic heartbeats renew its lease.
  3. Completion and failure compare the owner token and fencing token.
  4. A stale record may be reclaimed after its lease expires; the old owner can no longer write.

HTTP middleware

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.

Workers and ownership loss

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 support

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.

Failure and security semantics

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.

Development

go test ./...
go test -race ./...
go vet ./...
go test -bench=. -benchmem ./...

See CONTRIBUTING.md, SECURITY.md, and the architecture notes.

Roadmap

  • Redis and PostgreSQL adapters with live integration tests
  • Expanded store-contract coverage and cancellation/failure injection
  • Prometheus and OpenTelemetry examples

License

MIT. See LICENSE.

About

`go-idempotent` is a typed, storage-backed Go library for duplicate suppression and replayable operation outcomes. It provides atomic execution ownership, lease-based stale-owner recovery, and fencing tokens so a reclaimed worker cannot overwrite a newer result.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages