idempotency

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

http-keystone Idempotency Middleware

A safe-retry middleware for Echo v5.

→ View Full API Documentation

idempotency makes unsafe requests (POST, PUT, PATCH, DELETE) safe to retry. The first request that carries an Idempotency-Key runs the handler and stores its response; any later request with the same key replays that response instead of running the handler again. This is the behaviour behind the IETF idempotency-key draft and payment APIs such as Stripe's.

Features

  • Safe retries: a retried request returns the original response byte-for-byte instead of running the handler twice.
  • Single execution under concurrency: a lock (owned, expiring) guarantees only one request per key runs at a time — across a single instance (MemoryStore) or a whole cluster (RedisStore).
  • Request fingerprinting: reusing a key with a different method, path, or body is rejected (ErrFingerprintMismatch), never replayed with the wrong response.
  • Flexible in-flight policy: reject duplicates immediately (409) or wait and replay.
  • Bounded storage: a response size cap and a status allow-list keep only what is safe to replay (never 5xx).
  • Echo v5 ready: designed for the latest pointer-based *echo.Context.

Installation

go get github.com/its-ernest/http-keystone@latest

Then import github.com/its-ernest/http-keystone/idempotency.


Basic Usage

package main

import (
	"net/http"

	"github.com/its-ernest/http-keystone/idempotency"
	"github.com/its-ernest/http-keystone/store"
	"github.com/labstack/echo/v5"
)

func main() {
	e := echo.New()

	e.Use(idempotency.New(idempotency.Config{
		Store: store.NewMemoryStore(),
		TTL:   24 * time.Hour,
	}))

	e.POST("/payments", func(c *echo.Context) error {
		// This handler runs once per Idempotency-Key, no matter how many
		// times the client retries.
		return c.String(http.StatusCreated, "payment created")
	})

	e.Start(":8080")
}

A client retries safely by sending the same key:

POST /payments HTTP/1.1
Idempotency-Key: 8f1c2b7e-...

{"amount": 100}

Configuration Options

Field Type Default Description
Store store.Store (required) Persists the fingerprint and the stored response; also provides the owned lock.
TTL time.Duration 24h How long a completed response is remembered.
Skipper middleware.Skipper DefaultSkipper Skip the middleware for selected routes.
Header string Idempotency-Key Request header that carries the key.
Required bool false Reject requests with no key (400) instead of passing through.
KeyFunc func(*echo.Context) string nil Derive the key (e.g. scope per route/tenant); overrides Header.
MaxBodySize int 1MB Responses larger than this are streamed and not stored.
InFlight InFlightPolicy InFlightReject InFlightReject (409) or InFlightWait (wait and replay).
WaitTimeout time.Duration 10s How long an InFlightWait duplicate waits.
RetryDelay / MaxRetries duration / int 20ms / 10 Poll cadence while waiting.
LockTTL time.Duration 30s Upper bound on the in-flight lock.
StoreStatusCodes []int 200,201,202,204,400,401,403,404,409,422,429 Statuses that are stored (never 5xx by default).
ErrorHandler func(*echo.Context, error) error renders error Render the rejection response.
FailClosed bool false Reject on store failure instead of failing open.

How it Works

  1. Method filter: safe methods (GET, HEAD, OPTIONS, …) pass straight through.
  2. Key: taken from KeyFunc or the configured header. Missing key passes through, or 400 when Required.
  3. Fingerprint: method + request URI + a hash of the body identify the request.
  4. Replay: if a stored response exists and the fingerprint matches, it is replayed (byte-for-byte, with Idempotency-Replayed: true). A fingerprint mismatch is rejected — the wrong response is never returned.
  5. Lock: the request acquires an owned, expiring lock keyed by the idempotency key, so exactly one request runs at a time.
  6. Run & store: the handler runs behind a recorder; its status, safe headers, and body are stored with the TTL, provided the status is in StoreStatusCodes and the body fits MaxBodySize.
  7. Concurrent duplicates: rejected with 409 (InFlightReject) or parked until the first finishes and then replayed (InFlightWait).

Retries never run the handler twice. A network blip after the server stored the response cannot cause a duplicate side effect — the retry replays the stored result.


Why use Idempotency?

Retries are inevitable: clients time out, connections drop, and users double-click. Without idempotency, a retried POST /payments can charge a card twice. This middleware makes any unsafe endpoint safe to retry by remembering the outcome of the first request, keyed by a client-supplied Idempotency-Key.

See the runnable example in _examples/idempotency.

Documentation

Overview

Package idempotency provides safe-retry middleware for Echo v5.

It makes unsafe requests (POST, PUT, PATCH, DELETE) safe to retry by remembering the response to a request that carries an idempotency key and replaying it when the same key is seen again. This is the behaviour behind the "Idempotency-Key" header in the IETF draft and in payment APIs such as Stripe's.

The middleware is built on store.Store and its owned locks (see the store package), so the "only one request runs at a time per key" guarantee holds across a single instance (MemoryStore) or a whole cluster (RedisStore).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrKeyRequired is passed to ErrorHandler when a request carries no
	// idempotency key but Config.Required is set.
	ErrKeyRequired = errors.New("idempotency: an Idempotency-Key header is required")

	// ErrKeyInvalid is passed to ErrorHandler when the key is empty, too
	// long, or contains control characters.
	ErrKeyInvalid = errors.New("idempotency: the Idempotency-Key is invalid")

	// ErrFingerprintMismatch is passed to ErrorHandler when a key is reused
	// with a different request (method, path, or body) than the one that was
	// stored. The stored response is never replayed in this case.
	ErrFingerprintMismatch = errors.New("idempotency: the key was already used with a different request")

	// ErrRequestInFlight is passed to ErrorHandler when a duplicate arrives
	// while the first request with the same key is still running and the
	// policy is InFlightReject.
	ErrRequestInFlight = errors.New("idempotency: a request with this key is already being processed")
)
View Source
var DefaultConfig = Config{
	Header:      "Idempotency-Key",
	TTL:         24 * time.Hour,
	MaxBodySize: 1024 * 1024,
	InFlight:    InFlightReject,
	WaitTimeout: 10 * time.Second,
	RetryDelay:  20 * time.Millisecond,
	MaxRetries:  10,
	LockTTL:     30 * time.Second,
	StoreStatusCodes: []int{
		http.StatusOK,
		http.StatusCreated,
		http.StatusAccepted,
		http.StatusNoContent,
		http.StatusBadRequest,
		http.StatusUnauthorized,
		http.StatusForbidden,
		http.StatusNotFound,
		http.StatusConflict,
		http.StatusUnprocessableEntity,
		http.StatusTooManyRequests,
	},
	ErrorHandler: func(c *echo.Context, err error) error {
		return err
	},
}

DefaultConfig provides the standard settings for idempotency middleware.

Functions

func New

func New(config Config) echo.MiddlewareFunc

New returns an Echo middleware that makes unsafe requests idempotent.

Types

type Config

type Config struct {
	// Store persists the fingerprint and the stored response. It must be a
	// store.Store because idempotency needs both Get/Save and owned locks.
	Store store.Store

	// TTL is how long a completed response is remembered so a later retry
	// with the same key replays it instead of running the handler again.
	// Default is 24h.
	TTL time.Duration

	// Skipper defines a function to skip the middleware. Defaults to
	// middleware.DefaultSkipper.
	Skipper middleware.Skipper

	// Header is the request header that carries the idempotency key.
	// Default is "Idempotency-Key".
	Header string

	// Required rejects requests that carry no key (400) instead of passing
	// them through. Default is false.
	Required bool

	// KeyFunc derives the idempotency key. When set it overrides Header; use
	// it to scope keys per route or tenant (for example by prefixing the
	// authenticated API key).
	KeyFunc func(c *echo.Context) string

	// MaxBodySize caps how many response bytes are stored. A larger response
	// is streamed to the client and not stored, so a retry re-runs the
	// handler. Default is 1MB.
	MaxBodySize int

	// InFlight selects the duplicate-request policy. Default is InFlightReject.
	InFlight InFlightPolicy

	// WaitTimeout bounds how long an InFlightWait duplicate waits for the
	// first request before giving up. Default is 10s.
	WaitTimeout time.Duration

	// RetryDelay and MaxRetries control the poll cadence an InFlightWait
	// duplicate uses while waiting for the first request to finish.
	// Defaults are 20ms and 10 retries.
	RetryDelay time.Duration
	MaxRetries int

	// LockTTL bounds how long the in-flight lock is held before another
	// request may take it over. Default is 30s. Set it longer than your
	// slowest idempotency-protected handler.
	LockTTL time.Duration

	// StoreStatusCodes is the allow-list of response statuses that are stored.
	// 5xx responses are never stored by default so a retry can succeed after a
	// transient failure. Default is []int{200, 201, 202, 204, 400, 401, 403,
	// 404, 409, 422, 429}.
	StoreStatusCodes []int

	// ErrorHandler renders the error response for rejected requests (missing
	// key when Required, a fingerprint mismatch, or a concurrent duplicate
	// under InFlightReject). Default renders 400/409/422 with a short message.
	ErrorHandler func(c *echo.Context, err error) error

	// FailClosed reports whether a store failure (not a lock conflict) should
	// reject the request instead of failing open. Default is false (fail open:
	// run the handler without idempotency).
	FailClosed bool
}

Config defines the settings for the idempotency middleware.

type InFlightPolicy

type InFlightPolicy int

InFlightPolicy controls what happens when a second request arrives with an idempotency key whose first request is still running.

const (
	// InFlightReject (default) answers the duplicate immediately with
	// 409 Conflict. It is the cheapest policy and matches the common
	// "the first request is still being processed, retry later" behaviour.
	InFlightReject InFlightPolicy = iota

	// InFlightWait parks the duplicate until the first request finishes and
	// then replays its stored response. It is friendlier to clients but
	// holds a goroutine (and connection) for the duration of the wait.
	InFlightWait
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL