Idempotency
Mutating routes are vulnerable to duplicate execution under client retries: the network drops the response, the client retries, the handler runs twice, the bank books two transfers. IdempotencyLayer solves this by atomically reserving (principal, key) before the handler runs and replaying the captured response for any subsequent request with the same key.
Wiring
Pick the backend that fits your deployment. The trait is the same; the layer doesn't care which store backs it.
Postgres (cratestack-sqlx)
use cratestack_axum::idempotency::IdempotencyLayer;
use cratestack::SqlxIdempotencyStore;
use std::sync::Arc;
use std::time::Duration;
let store = Arc::new(SqlxIdempotencyStore::new(pool.clone()));
store.ensure_schema().await?;
let router = cratestack_schema::axum::router(db, procedures, JsonCodec, auth)
.layer(IdempotencyLayer::new(store, Duration::from_secs(24 * 3600)));Redis (cratestack-redis)
use cratestack_axum::idempotency::IdempotencyLayer;
use cratestack_redis::RedisIdempotencyStore;
use std::sync::Arc;
use std::time::Duration;
let store = Arc::new(RedisIdempotencyStore::open(
"redis://127.0.0.1/",
"bank:prod", // key prefix; the store appends `:idem:<sha256(...)>`
)?);
let router = cratestack_schema::axum::router(db, procedures, JsonCodec, auth)
.layer(IdempotencyLayer::new(store, Duration::from_secs(24 * 3600)));Redis is the right choice when:
- you already operate a Redis cluster for sessions / caching and don't want a second durable store
- you want eviction handled by the data store — Redis drops keys on TTL, no
garbage_collect()sweep needed - your idempotency window is short (minutes to hours) so durability vs Postgres matters less than the operational simplicity
Postgres remains the right choice when:
- you already run Postgres for the application data and want one transactional system of record
- you need the idempotency rows for forensic reconstruction beyond their TTL, or want them to participate in logical replication
- you care about transactional consistency between the idempotency row and other writes the handler does
The TTL is a hard upper bound on how long an in-flight reservation pins a key. Banks running long-tail async workflows pick 24 h; consumer-facing POST flows pick 5–60 minutes.
Request shape
Clients opt in by sending Idempotency-Key:
POST /transfers HTTP/1.1
Content-Type: application/json
Idempotency-Key: 7a3f-0b21-c9d4-8e15
{"from":1,"to":2,"amount":"100.00"}The key must be ASCII, non-empty, and at most 255 characters. Missing keys bypass the layer entirely — the layer is opt-in per request.
State machine
For each request the store atomically returns one of:
- Reserved — fresh claim. The handler runs and the response is persisted on completion.
- Replay — a prior execution under the same key + request hash has completed. The cached response is returned with
Idempotency-Replayed: true. - InFlight — another caller still holds the reservation. The layer returns
409 ConflictwithRetry-After: 1. - Conflict — the same key arrived with a different request body. The layer returns
422, per the IETF draft. The error code is the ordinaryVALIDATION_ERROR; the message isidempotency_key_conflict: key reused with a different request body, so match on the message prefix, not on the code.
(Since 0.14.1.) One response is not persisted: the 409 TRANSACTION_ABORTED (RPC aborted) of an @isolation procedure whose own retries ran out. Nothing was committed, so the layer releases the reservation instead, and the same key runs the call again. Every other response, errors included, is persisted as before. An abort that a different caller propagates is answered as 500 INTERNAL_ERROR and persisted, since that caller may have committed work of its own. MCP's idempotency admission follows the same rule. The 409 in the list above is the layer's own in-flight refusal, with code CONFLICT, not this one.
The request hash is SHA-256 over method, full path including query string, content-type, and body. POST /transfer?dry_run=true and POST /transfer?dry_run=false therefore hash differently — replays don't cross query-string-encoded operation modes.
Refusals before the body are not recorded
(Since 0.17.2, cratestack#1261.) A 401 or 403 that the generated dispatch produces before any procedure body runs is not persisted either. Nothing ran, so the layer releases the reservation, and a client that renews its credential or steps up and resends the call under the same key runs it once. That is what the generated clients' retry_after_step_up / retryAfterStepUp do when the call carries a fixed key. It covers:
- the
AuthProvider's refusal (authenticatereturned an error), for procedures and model routes; - the procedure's
@allow/@denycheck, its@authnrequirement and any@authorizemodel check.
A refusal that a procedure body returns is persisted and replayed as before, because the body may have written first: sending the same key again must not run that write twice. REST, RPC unary and MCP tools follow the same rule; /rpc/batch refuses an Idempotency-Key header outright. The response itself does not change by a byte.
0.17.1 and earlier record every refusal
On 0.17.1 and earlier, "errors included" covers an AuthProvider refusal and the step-up refusal of an @authn procedure (since 0.17.1). The layer records them like any other answer, so a client that renews its credential or steps up and then resends the call under the same key gets the recorded 401 replayed, and the call does not run.
Preserve a request before the first attempt
The prepared-call APIs below shipped in 0.18.1 (cratestack#1297).
Without preparing, a client instance pins each Idempotency-Key's first encoding in memory, so an in-process retry is sent the way its first attempt was. The table holds 1024 keys in Rust and 512 in TypeScript and Dart; when full it evicts the oldest first attempt, so a prompt retry stays pinned and new keys keep negotiating compact. Pins do not survive a restart; prepared calls do.
A keyed retry must preserve the request hash inputs even if compact negotiation changes or the process restarts. Preparation encodes one unary mutation without sending it. Commit its snapshot to durable storage before the first send, then execute it; after restart, restore and execute that same snapshot with the matching service, client codec, operation contract and key tables. It retains the original inner bytes and media type, route, query, key and If-Match. It does not queue work or install a server idempotency store.
let call = runtime.prepare_call(
"POST", route, path, &input, &[], &[("Idempotency-Key", key)],
)?;
let bytes = call.to_bytes()?;
// Durably commit bytes here before executing the first attempt.
let restored = cratestack_client_rust::PreparedCall::from_bytes(&bytes)?;
let response = runtime.execute_prepared(&restored).await?;For ordinary Rust calls with compact keys and a body, provide Idempotency-Key in per-call headers (they take precedence over the authorizer's). If only the authorizer supplies it, the runtime rejects the call before sending; bodiless calls pin nothing and are not checked; later changes by custom HTTP defaults or middleware are outside runtime control and must not alter identity headers or their absence. Compact-enabled Rust calls also reject duplicate Idempotency-Key or If-Match headers before encoding. These identity checks apply to ordinary compact streams too; prepared streaming is not supported.
Rust requires compact key tables for the operation, including when the frozen body is named. Only unary mutations with a non-empty key are supported; batch and streams are outside this API. Descriptors with invalid version, route, key, codec or table bindings, oversized data, or malformed JSON or CBOR framing are refused before network I/O. The caller owns the journal, its integrity and access controls, and the business decision that the operation remains authorized. A saved descriptor contains sensitive business data; protect it accordingly. This mechanism alone is not a financial guarantee.
CBOR snapshots are checked before sending as one well-formed item: text must be valid UTF-8, containers must be complete, and nesting is limited to 256. Non-preferred encodings remain byte-for-byte unchanged. This does not validate tag semantics or reject duplicate map keys; duplicate handling belongs to the receiving codec. Protect the journal against tampering.
Authentication headers and reusable COSE envelopes are not stored, and URL userinfo is rejected. Query strings and bodies are persisted and can contain secrets; protect the journal accordingly. The Rust client reauthorizes and, when configured, reseals each attempt with fresh claims. Dart sealing belongs to the transport: create a fresh seal and matching PendingResponse on each attempt. TypeScript RPC prepared calls reject custom unary links, so a sealing link cannot currently be used there. See the TypeScript and Dart guides.
Error bodies are typed
Every response this layer emits itself carries the framework's own codec-negotiated error envelope, encoded through the same Accept negotiation the generated handlers use — the REST CratestackErrorResponse{code, message, details} on ordinary paths, RpcErrorBody on /rpc/* ones. That covers the in-flight 409, the 422 key conflict, the principal-fingerprint refusal (412), and the buffer-limit errors. Before 0.11.0 these were bare text/plain strings that a generated client could not branch on (#846); consumers asserting on them as text will see the change.
An unsatisfiable or malformed Accept falls back to the default codec and keeps the original status rather than becoming a 406 or 400 — Accept is caller-controlled, and a caller must not be able to rewrite the status of a refusal aimed at it.
INFO
This layer gets no fail-open policy. Unlike rate limiting, a failed idempotency store must keep failing the request — that is the entire point of having one. What did change is promptness: RedisIdempotencyStore now configures explicit 2-second connection and response timeouts on its ConnectionManager, so it fails fast instead of awaiting an unbounded reconnect. It also gets no retry-once, because a double-apply is exactly what it exists to prevent.
Replay fidelity
Replays reproduce the original response's:
- status code
- body bytes
- every end-to-end response header the handler set (
Location,ETag,Cache-Control,Set-Cookie,Content-Type, …)
Hop-by-hop headers (Connection, Transfer-Encoding) and framework-computed headers (Content-Length, Date) are filtered at capture time and not restored. A replay carries an additional Idempotency-Replayed: true header so downstream observers can distinguish it from a live execution.
Reservation tokens
Every reservation carries a UUID reservation_id. complete and release require a matching token, so a handler that runs past the TTL and has its row reclaimed by a retry cannot poison the newer reservation. The classical TTL-overrun scenario degrades to a silent no-op rather than a wrong-response write. This guarantee holds in both the Postgres and Redis stores.
The Redis store additionally guards release on status == 'in_flight' (matching the Postgres store's AND response_body IS NULL clause), so a spurious release arriving after complete is also a no-op rather than wiping the captured response.
Principal scoping
The layer derives a principal fingerprint from the request. Two callers sharing a key under different principals do not collide. The default fingerprint takes the first of these the request carries:
| Request carries | Fingerprint |
|---|---|
a VerifiedPrincipal extension (since 0.14.0, cratestack#1006) | princ:<sha256 hex of the principal> |
an Authorization header | the SHA-256 hex of the header |
a ConnectInfo<SocketAddr> peer | the peer's IP address |
| none of these | refused, 412 (cratestack#416) |
VerifiedPrincipal is inserted by a layer in front of this one that verified the caller, such as the signed transport envelope layer (cose:<hex thumbprint> for a signed request); the rate limiter's default key reads it the same way. ConnectInfo is only present when the server is served through into_make_service_with_connect_info::<SocketAddr>(). Services keying on something else (mTLS, session cookies, a tenant) override the default:
IdempotencyLayer::new(store, ttl)
.with_principal_fingerprint(|req| {
req.extensions().get::<TenantId>().map(|t| t.to_string()).unwrap_or_else(|| "anonymous".to_owned())
})A custom fingerprint takes responsibility for its namespace, including a shared fallback like the "anonymous" above.
Upgrading to the VerifiedPrincipal default
(since 0.14.0, cratestack#1006) The VerifiedPrincipal row is new. An application that already inserts VerifiedPrincipal in front of the idempotency layer (its own middleware, or the envelope layer) moves to the princ: namespace on upgrade: an Idempotency-Key whose first attempt landed before the deploy and whose retry lands after it runs again. Keep the old namespace for the deploy, and drop the call once the idempotency TTL has passed:
let idempotency = IdempotencyLayer::new(store, ttl).with_legacy_principal_fingerprint();
// or compose it in your own fingerprint (it returns `Result<String, CratestackError>`):
// cratestack::idempotency::legacy_principal_fingerprint(&request)Custom fingerprints are unaffected.
Retries under the envelope layer
(since 0.14.0, cratestack#1006) Behind the envelope layer, this layer sees the opened request: the request hash covers the plain CBOR payload, not the COSE bytes. A client that re-seals its retry (a fresh cti, so it passes replay protection) under the same Idempotency-Key therefore gets the stored response, sealed afresh for the new request. The envelope binds Idempotency-Key exactly as sent, so a proxy that strips it from the retry (which would then run twice) breaks the signature; the client must include the key in what it signs.
Persistence
Postgres layout
SqlxIdempotencyStore ships an ensure_schema() helper that idempotently creates the table and index. The DDL is:
CREATE TABLE cratestack_idempotency (
principal_fingerprint TEXT NOT NULL,
key TEXT NOT NULL,
request_hash BYTEA NOT NULL,
reservation_id UUID NOT NULL,
response_status INT,
response_headers BYTEA,
response_body BYTEA,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (principal_fingerprint, key)
);
CREATE INDEX IF NOT EXISTS cratestack_idempotency_expires_idx
ON cratestack_idempotency (expires_at);SqlxIdempotencyStore::garbage_collect() deletes rows whose expires_at has passed. Banks call it from a scheduled task; the request path takes over a single expired row on demand but doesn't sweep.
Redis layout
RedisIdempotencyStore writes one Redis hash per (principal, key) at:
<prefix>:idem:<sha256(principal || 0x00 || key)>Hashing both sides keeps the Redis key bounded regardless of how long the principal fingerprint or idempotency key grows, and avoids any escaping concerns around : in user-supplied values. Hash fields hold the request hash, status, reservation token, captured response bytes, and timestamps — all as raw bytes (Redis hash values are binary-safe; no base64 wrapping is needed).
Atomicity comes from three small Lua scripts: reserve_or_fetch, complete, and release. They run via EVALSHA with a NOSCRIPT fallback, so the script body is loaded into the Redis server once per instance and reused across requests.
Eviction is driven by PEXPIREAT — there is no separate GC. When the TTL passes, Redis drops the hash; the next reservation observes a missing key and claims a fresh slot. A late complete or release from the previous reservation finds a rotated token and becomes a silent no-op.
Custom stores
The IdempotencyStore trait is async + dyn-compatible. Banks running multi-region deployments can plug in their own backing store — typically a Postgres replica with logical replication, a globally-consistent key-value store, or a Redis Enterprise CRDT cluster — so the reservation guarantee holds across regions.
Caveats
The shipped Postgres and Redis stores enforce the reservation guarantee within one database instance (or Redis primary). Banks running active-active multi-region clusters must either:
- accept that retries hitting a different region within the TTL race the reservation, or
- plug a globally-coordinated store into
IdempotencyStoreand bring that consensus layer's latency budget into the request path.
Both shipped stores assume a single logical service per principal_fingerprint. Services that share a backing store between unrelated applications should namespace the key in the fingerprint function — and, for Redis, choose a per-application key_prefix so deployments can't trample each other's keys.