Idempotency key vs unique constraint vs Redis lock: stopping a duplicate AI chat turn
Claim the message id in a shared store before the turn starts, refuse a repeat while the turn runs and for a window after it answers, and free the id when the turn fails. Idempotency keys, unique constraints and Redis locks each cover part of that.
Drafted by an AI agent, from a research brief, primary sources and the Pleach docs; reviewed by a maintainer before publishing.
No @pleach/* package is on npm yet. Each name holds a 0.0.1 placeholder until its first release, so the code here describes the source, not an install that works today. Package status
To stop a retried or double-submitted chat message from running an agent turn twice, claim the message id in a shared store before the turn starts, refuse a repeat while the turn runs and for a window after it answers, and free the id when the turn fails.
Chat clients send the same message twice more often than you'd expect. A double click does it, and so does a re-send after a connect failure or a reconnect that replays the POST. Each copy that reaches the model is a second, billed run.
The standard tools each cover part of the problem. HTTP idempotency keys, a database unique constraint and a Redis lock all detect the repeat, but they differ on retention, expiry and what the duplicate gets back. For what to record once a turn does run, see adding an audit ledger without rewriting your agent loop and streaming an answer a guard may correct.
| Property | Idempotency-Key header (Stripe-style) | DB unique constraint on message id | Redis SET key NX PX | Client debounce only |
|---|---|---|---|---|
| In-flight protection | Yes. Draft §2.6: a conflict error, 409 per §2.7 | Yes, once the row is inserted before work starts | Yes, until the PX expiry | One page only |
| Post-completion window | Stripe v1: at least 24 hours. Draft: the server publishes its own policy | As long as you keep the row | Until the key's TTL lapses | None |
| Multiple app instances | Yes, if the key store is shared | Yes, one database | Yes, one Redis deployment | Not applicable |
| Duplicate receives | Stripe v1: the saved status and body, including 500s | A unique-violation error, or zero rows inserted | A failed SET. You return a refusal | Nothing is sent |
These setups aren't like-for-like. The header is an API contract, the other two are storage primitives you build it on, and debouncing is a UI measure.
Why are streaming LLM turns harder to deduplicate than ordinary POSTs?
Streaming turns run long, produce output you can't cheaply replay, and should stay retryable after a failure. Each of those breaks a default that payment-style idempotency relies on.
HTTP doesn't make POST safe to repeat. RFC 9110 §9.2.2 lists PUT, DELETE and the safe methods as idempotent. It says a client "SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent". A chat send is a POST, so the server has to supply that means.
Replaying the original response is the expensive part. Stripe's API v1 "saves the status code and body of the first request" and returns it to retries. A chat answer is a token stream, not a body. The Vercel AI SDK's resumable streams guide says resumption "requires persistence for messages and active streams" and uses a Redis instance that "Stores stream data". That's a pub/sub layer on top of your dedup store.
Failed work also behaves differently. Stripe v1 replays a saved 500 to a retry with the same key. For a payment, that prevents a second charge. For a chat turn that errored, the user wants the retry to run.
The cost of a miss is concrete. A duplicate turn calls the model again, runs its tools again, and writes a second answer into the conversation.
What does the IETF Idempotency-Key draft require?
The draft standardizes the header and the error codes, but leaves retention and replay to the server. The current version is draft-ietf-httpapi-idempotency-key-header-08, last updated 22 October 2026.
- Key reuse. §2.2 says a key "MUST NOT be reused with another request with a different request payload". §2.7 recommends 422 when that happens.
- In flight. §2.6 says the resource "SHOULD respond with a resource conflict error" for a retry while the original is still processing. §2.7 names 409.
- Missing key. §2.7 recommends 400 when a required key is absent.
- Expiry. §2.3 says the resource "SHOULD define such expiration policy and publish it in the documentation". The draft sets no number.
- Replay. For a retry after completion, §2.6 asks for "a response consistent with the request being completed according to the user's intent". It doesn't require the identical stored response.
Stripe fills in the numbers for API v1. It keeps keys for at least 24 hours, and a reused key after pruning runs a new request. A 409 means another request with the same key is still executing, and the docs say to wait and retry with that key. A replayed response carries Idempotent-Replayed: true. Results are saved only after execution begins, so a validation failure or a concurrent conflict stays retryable.
How do a unique constraint and a Redis lock compare as the claim store?
Both give you one atomic "first writer wins" step. They differ mainly on expiry.
In Postgres, a unique constraint on the message id rejects the second insert. ON CONFLICT DO NOTHING "simply avoids inserting a row as its alternative action" instead of raising the unique violation. The command tag INSERT 0 0 versus INSERT 0 1 tells you which request won. Rows don't expire on their own, so a post-completion window needs a timestamp and a cleanup job.
In Redis, SET key value NX PX ms sets the key only if it doesn't exist, with a millisecond expiry. The expiry is the advantage: a process that dies mid-turn doesn't hold the key forever. The SET page itself calls the plain lock pattern "discouraged in favor of the Redlock algorithm".
The Redis distributed-locks page recommends a few practices for this pattern:
- Signed release. Set the value to a random token and remove the key only if the stored value still matches it.
- Size the TTL to the work. The "lock validity time" is both the auto-release time and the time the holder has to finish.
- Fencing tokens. The page recommends them for "processes that can take significant time".
- Capped extension. A holder can extend the TTL while it works, and the number of extensions "should be limited".
- Redlock. For a fault-tolerant setup across independent nodes, the page describes the Redlock algorithm.
How should the claim behave when the store is slow?
Put a short timeout on the claim call and decide in advance what the request does when it expires. Without a timeout, a slow store stalls every send.
The choice depends on what a duplicate costs. For payments, a duplicate charge is hard to undo. For chat, a duplicate turn costs one extra model call, while a refused message is visible to the user.
When to use each
- Public API with retrying clients: follow the Idempotency-Key draft. Publish your retention window and return 409 for in-flight repeats.
- Single database, strict once-only: a unique constraint with
ON CONFLICT DO NOTHING. Add a timestamp if the window should end. - Many instances, long turns, crash tolerance: a Redis
SET NX PXclaim with a random token, a token-checked release and a capped extension. - Chat UI polish: debounce the send button too. Never rely on it alone.
- Streamed answers you want to replay: budget for a resumable-stream layer. Otherwise refuse the duplicate and let the client read the original turn.
How Pleach does it
createPleachRoute claims the message id before the turn starts. It refuses a re-sent message with a 409 while the first turn runs and for 10 minutes after an answered one. See /docs/packages for package status.
Detecting the repeat
A request names its message by the body's messageId. Without one, the route uses the x-pleach-request-id header that useChat sends. The route claims that id under the request's resolved user and its session, before it creates or resumes the session. A repeat gets 409, no turn starts and no provider is called:
{
"error": "duplicate_message",
"code": "PLEACH_DUPLICATE_MESSAGE",
"state": "in_flight",
"turnId": "…",
"detail": "This message's turn is still running; no second turn was started."
}state is "in_flight" while the first turn runs. It's "settled" for a repeat within 10 minutes of an answered turn. The duplicate isn't attached to the first stream, and an answered turn isn't replayed. To show the original answer, read that turn by its turnId. On the client, useChat surfaces the 409 as a UseChatDuplicateMessageError.
Failed turns stay retryable
Only an answered turn keeps refusing. A turn counts as answered when it ends ok, with no abort and no error, and adds a non-empty answer of its own that isn't a canned stub. An error, a stop, a disconnect, a canned provider-terminal answer, or a request refused before its turn starts frees the id. A stopped turn whose graph run keeps executing frees its id only once that run settles.
The key always carries the resolved user, so one user's ids never collide with another's. Give every message an id and wire resolveUserId so every request is keyed.
Multiple instances
By default the claims live in each route instance's memory. Pass messageIdempotency.store to share them:
import {
createPleachRoute,
type MessageIdempotencyClaimStore,
} from "@pleach/core/quickstart";
declare const store: MessageIdempotencyClaimStore; // your adapter
export const POST = createPleachRoute({
messageIdempotency: { store, claimTimeoutMs: 2000 },
});Core ships no adapter and depends on no vendor. You write one over your own Redis, SQL database or KV, implementing claim, setTurnId, settle and release, plus an optional renew. claim must create the entry atomically, in Redis with SET key value NX PX ttl or in SQL with INSERT ... ON CONFLICT DO NOTHING. The store expires entries on its own clock. setTurnId, settle and release act only while the entry still carries the token its claim returned.
Treat this as protection against accidental double sends, not as a billing control.
| Option | Default | What it bounds |
|---|---|---|
ttlMs | 10 minutes | How long an answered id keeps refusing |
inFlightMaxAgeMs | 1 hour | How long a claim stands if its turn never reports ending |
keepAliveMaxMs | 30 minutes | How long, from the claim, a running turn's claim is kept past inFlightMaxAgeMs |
claimTimeoutMs | 2000 | How long the route waits for the store's claim or renew |
With a shared store, the route calls renew about every third of inFlightMaxAgeMs. With the defaults, a turn that never settles holds its message id for about 1.5 hours at most. The cap doesn't abort the running turn.
The full option table and the adapter contract are on the API routes page. The client-side error is on the React page.
Key takeaways
- Dedup on the server. RFC 9110 doesn't treat POST as idempotent, and debouncing misses reconnects and retries.
- Claim before the work starts. An atomic
SET NXorON CONFLICT DO NOTHINGmakes exactly one request the winner. - Free the id on failure. Payment APIs replay a stored 500; a chat turn that errored should run again on retry.
- Size the lease to the turn. Redis's docs recommend a random token on release, fencing tokens for long work and a capped extension.
- Time-box the claim. A short timeout on the store call keeps a slow store from stalling every send.
References
- The Idempotency-Key HTTP Header Field, draft-ietf-httpapi-idempotency-key-header-08. IETF HTTPAPI Working Group.
- RFC 9110: HTTP Semantics, §9.2.2 Idempotent Methods. IETF.
- Idempotent requests. Stripe API reference.
- Low-level error handling: idempotency. Stripe documentation.
- SET. Redis command reference.
- Distributed Locks with Redis. Redis documentation.
- INSERT. PostgreSQL 18 documentation.
- Chatbot Resume Streams. Vercel AI SDK documentation.
Frequently asked
What is an idempotency key?
An idempotency key is a client-generated value the server uses to recognize retries of the same request. The IETF draft "The Idempotency-Key HTTP Header Field" defines it as a request header. Stripe suggests V4 UUIDs or another random string with enough entropy, accepts keys up to 255 characters, and errors if a reused key arrives with different parameters. The draft recommends 422 for that case.
Should a retried request get the original response back?
It depends on the API. Stripe API v1 saves the status code and body of the first request once the endpoint starts executing, and returns that saved response to retries, including 500 errors. The IETF draft only asks for a response consistent with the request being completed. For a streamed AI answer, storing and replaying the stream needs extra infrastructure, so many chat backends refuse the duplicate instead.
How do you use Redis SET NX as a deduplication claim?
Run SET key value NX PX ms, which sets the key only if it doesn't exist and gives it a millisecond expiry. Store a random token as the value and release only when the stored value matches it. Redis's docs recommend fencing tokens for long-running work, a capped number of lock extensions, and the Redlock algorithm for a fault-tolerant multi-node setup.
Should a failed LLM turn block a retry with the same key?
Usually not. A payment API that replays a stored 500 protects against charging twice, but a chat user who saw an error wants the retry to run. A chat backend should keep refusing a message id only after the turn produced an answer, and free the id on an error, a stop or a disconnect. That choice trades some duplicate risk for a usable retry.
Is client-side debouncing enough to prevent duplicate submits?
No. Debouncing stops a double click inside one page. It does not stop a retry after a connection failure, a reconnect that replays the POST, a second tab, or an automatic client retry. RFC 9110 says a client should not automatically retry a non-idempotent request unless it can tell the request is idempotent, so the server needs its own check.
How does Pleach handle a re-sent chat message?
createPleachRoute claims the message id under the request's user and session before it creates or resumes the session. A repeat gets a 409 with code PLEACH_DUPLICATE_MESSAGE, with state in_flight while the first turn runs or settled within 10 minutes of an answered turn. Only an answered turn keeps refusing. A shared claim store covers multiple instances.