Messages Can Arrive More Than Once
Kestrel Supply sells replacement parts. A customer pays for order 1042. A webhook reaches a Worker, the Worker writes to a queue, and a consumer creates the shipment and emails a receipt. Both succeed. Then the isolate is evicted before its acknowledgement reaches the queue, so the queue delivers the message again. A second shipment is created, and the customer gets two receipts and two parcels.
Nothing is broken. The queue delivered, the handler ran, the provider sent. The bug is that the system equated delivering a message with performing a business action.
A courier's signature proves the envelope arrived, not that the invoice inside was paid. Transport acknowledgement is a fact about the envelope; a business effect is a fact about the world.
Five terms keep delivery and effect apart.
- Transport delivery is one broker attempt to hand a message to a consumer. It may happen zero or more times.
- A business effect is a state change outside the handler: a row inserted, a payment captured, an email accepted.
- Idempotent means applying the same intent twice leaves the same state as applying it once:
f(f(x)) = f(x), for business state. - An idempotency key is a stable identifier for one intent, assigned by the producer before the first send and copied unchanged through every retry.
order:1042:shipmentis a key; a UUID minted inside the consumer is not. - A deduplication window is how long the key is remembered; a durable deduplication boundary is the store that survives the handler's crash and is consulted atomically before the effect.
The model is short: delivery count is not under your control; effect count is. Queues delivers at least once, keeps one consumer configuration per queue, and does not preserve publish order (How Queues Works). K2 delivers every record to every subscription at least once, redelivers after a negative acknowledgement or expired lease, and deduplicates on neither produce nor consume (K2 delivery guarantees). Neither offers exactly-once delivery.
Exactly-once is an effect property
Exactly-once is not a delivery mode you can buy. It is built from at-least-once delivery, a durable key, and an effect that tolerates repetition. A key gives exactly-once effects for one call inside its window; a unique constraint gives them for a row.
Figure 1 traces the duplicate: the producer assigns the key once, attempt 1 performs and records the effect, the acknowledgement is lost, and attempt 2 suppresses the repeat.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
P["Producer: order 1042
key = order:1042:shipment"] --> Q[("Broker stores
one message")]
Q --> A1["Attempt 1:
consumer runs"]
A1 --> C1["Claim key in durable store
status = in_progress"]
C1 --> E1["Create shipment
send receipt"]
E1 --> K1["Mark key succeeded
store external reference"]
K1 --> ACK{"Acknowledgement
reaches the broker?"}
ACK -->|"yes"| DONE["Message retired"]
ACK -->|"no: lease expires,
nack, or crash"| A2["Attempt 2:
same key arrives"]
A2 --> C2{"Existing record
for this key?"}
C2 -->|"succeeded"| SUP["Return stored outcome
skip the effect"]
C2 -->|"in_progress, lease live"| WAIT["Retry later,
do not run twice"]
C2 -->|"in_progress, lease stale"| REC["Reconcile with the
external system first"]
C2 -->|"absent"| C1
SUP --> ACK2["Acknowledge again"]
WAIT --> ACK2
REC --> ACK2
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class ACK,ACK2 primary;
class P,A1,C1,E1,K1,DONE,A2,C2,SUP,WAIT,REC secondary;
Figure 2 redraws the flow as five boundaries. Each answers a different question, and the mistake is almost always assigning an answer to the wrong one.
The key belongs to the producer: only the producer knows the intent before any attempt exists. A consumer that mints a key on start is labelling each duplicate as a fresh intent. Idempotency is also not uniqueness (a unique row does not prove the work finished) or ordering (two idempotent events can land backwards); each needs its own mechanism.
A Durable Idempotency Record Has Its Own Failure Modes
The record is a write, so it fails too. No transaction spans a D1 row and a payment provider call; there is always a gap, and the crash can land inside it.
The crash can land in four places, and each fails differently.
| Crash point | What the record says | What the world shows | A naive retry | What the design must do |
|---|---|---|---|---|
| Before the claim | Nothing | No effect | Proceeds | Nothing; this is the safe case |
| After the claim, before the effect | in_progress | No effect | Suppresses the retry | Expire the lease, then prove the effect is absent |
| After the effect, before the outcome is recorded | in_progress | The effect exists | Runs the effect again | Reconcile by key before doing anything |
| After both, before the acknowledgement | succeeded | The effect exists | Reads the stored outcome | Acknowledge again |
Claim-first and effect-first trade one window for another. Claim-first optimises for the third row and creates the second; effect-first does the reverse. Neither ordering is universally right. The design has two phases, and the state between them must be observed, expired, and repaired.
The record has to store the outcome, not just the fact that work started.
The dangerous state is not the duplicate
A duplicate is visible; an in_progress row that never resolves is silent. A stale claim is an unknown outcome, not a failure, and must be reconciled before the effect runs again.
The mechanisms are not interchangeable.
| Mechanism | Atomic claim | Survives a handler crash | Window you control | Duplicate it prevents | Residual failure |
|---|---|---|---|---|---|
| Workers KV flag | No. Eventually consistent, no atomic read-modify-write, negative lookups cached (How KV works) | Yes, but reads can be stale for 60 seconds or more | TTL, not immediate | Almost none | Two isolates both read "absent" and proceed |
D1 row with UNIQUE(key) | Yes, on the primary database | Yes | Until you delete the row; archive deliberately | Concurrent duplicates and retry duplicates | Crash after claim leaves work unfinished until reconciliation |
| Durable Object per key | Yes. Single-threaded instance, transactional SQLite storage, input and output gates (Rules of Durable Objects) | Yes | Until storage is deleted | Concurrent duplicates, interleaving, and claim races | Same unfinished-work window; per-object throughput ceiling |
| Provider idempotency key | Provider-side, outside your control | Yes, provider-owned | Provider's published window; verify per provider | Retried external calls inside that window | Window shorter than your retry or replay horizon; timeout still ambiguous |
| Queue or stream deduplication | Not offered | n/a | Message or record retention only | Nothing | Every redelivery re-runs the handler |
Figure 3 shows the record as a state machine, including the loop most designs omit.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
stateDiagram-v2
[*] --> Absent
Absent --> InProgress: unique claim wins
Absent --> Duplicate: claim conflicts
Duplicate --> Succeeded: read stored outcome
InProgress --> Succeeded: effect confirmed
InProgress --> Unknown: effect sent, no response
InProgress --> InProgress: crash before effect, lease expires
Unknown --> Succeeded: reconcile finds the effect
Unknown --> InProgress: reconcile proves it absent
InProgress --> FailedPermanent: non-retryable rejection
Succeeded --> [*]
FailedPermanent --> [*]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class InProgress primary
class Absent secondary
class Duplicate,Unknown warn
class Succeeded ok
class FailedPermanent danger
D1 is the cheapest record to reason about. One unique constraint plus the changed-row count tells you whether you won the claim, and the primary writer enforces it. A batch runs statements sequentially and non-concurrently, so the claim and the business row can commit together (D1 Database API). When the claim and the business state must be one atomic unit across many writes, a Durable Object is stronger: one instance per key, one SQLite database, and writes without an intervening await coalesce into a transaction.
The plan boundary is part of the design.
- Queues is on Free and Paid, but retention differs: 24 hours and non-configurable on Free, four days by default and up to 14 on Paid (Queues pricing).
- K2 is Workers Paid only, in public beta at writing, with 10 GB per account and 20 streams (K2 limits). Do not design a free-plan architecture around it.
- Durable Objects are on both plans, but Free offers only SQLite (Durable Objects limits).
- Workflows gives durable steps with retries (five by default, exponential, 10-minute timeout) and rollback handlers, but the documented model is still at-least-once execution of the step body (Sleeping and retrying).
Queue Redelivery and Stream Replay Differ
Replay is not a reset button
Replay is not a reset button and it is not free. A K2 subscription cannot be rewound in place; you create a new subscription, and it reads whatever retention has not yet deleted. Any handler attached to it must already be idempotent, because replay deliberately re-delivers records that were previously processed successfully.
A queue is work sharing; a stream is retained history. The words sound interchangeable in planning meetings and are not.
| Question | Queues | K2 |
|---|---|---|
| What is a message? | A unit of work, deleted on acknowledgement | A record in a retained history |
| Who reads it? | One consumer configuration per queue, many concurrent invocations | Every subscription reads every record, up to 128 workers holding leases |
| What does acknowledgement do? | Deletes the message; no offset to rewind | Advances a cursor; records stay until retention ends |
| When does delivery repeat? | Failure-driven: a failed batch retries, then the DLQ | Consumer-driven: a nack, an expired lease, or a new subscription at an earlier position |
| What bounds it? | Retry limit (three by default), dead-letter queue, retention (24 hours Free, up to 14 days Paid) | Retention only (one hour to 30 days, seven days by default) |
| What must the handler assume? | At-least-once, and a batch retries together | At-least-once, over history that can be replayed |
In Queues, a message exists to be processed once and removed. A batch retries as a batch unless messages were explicitly acknowledged, and a consumer past its wall-clock budget cannot acknowledge, so its batch becomes eligible again. Once deleted there is no offset to rewind.
In K2, consuming deletes nothing. A new subscription created at the earliest position can read history that predates it, and each batch is leased for five minutes, then acknowledged or released as a batch.
These are documented defaults; confirm the current values before sizing a design. Queue retry behaviour is specified under batching, retries and delays; K2 retention and subscription configuration under K2 configuration.
Figure 4 puts them side by side. The queue's acknowledgement removes the message; the stream's advances a cursor, and three readers can sit at three positions over the same records.
Consider a composite scenario. A team ships an order-events stream. The first subscription feeds fulfilment. Six months later a second feeds a search index, its handler copied from the queue consumer that emails shipping notices. A quarter later the index drifts, so an engineer creates a third subscription with start_at: earliest. The rebuild works, and re-sends every retained shipping notice. The stream did nothing wrong; the handler had a non-idempotent branch nobody tested under replay, because normally it ran once.
The rule follows: replay tests your idempotency harder than production ever will, deliberately. Before creating a replay subscription, ask what every branch does when the record is old, already reflected downstream, or addressed to a customer who has since cancelled.
Gaps are silent
K2 deletes records when retention ends whether or not a subscription read them, and inserts no marker where they used to be (K2 delivery guarantees). A consumer behind by more than the retention period gets the next record and continues without error. Monitor position against the oldest retained record, alert before the gap, and keep retention longer than the longest outage you will tolerate.
Ordering is the third assumption. Queues does not promise publish order. K2 does not promise order across workers sharing a subscription, and redelivery can put older records behind newer ones. If two events for one entity must apply in order, route that key to one consumer or Durable Object, or reject backwards transitions using a version. Deduplication removes repeats, not inversions.
Choose Queues for units of work that disappear after success; choose K2 for history that several readers must be able to replay.
External Side Effects Need Reconciliation
Inside one database, a transaction can make "record the decision" and "record the intent to act" atomic. Across a database and a payment provider, no transaction exists. Retries, queues, and workflow engines do not solve this dual-write problem. One write must be the source of truth, the other a repeatable projection of it.
The transactional outbox is the standard shape. In the same atomic unit as the business change, write an outbox row holding the key and the payload. A relay then reads unsent rows and calls the provider with that key.
A crash retries the relay; a timeout records an unknown outcome. A later job asks the provider what happened, using the stored key or reference.
Unknown is a real state
A timeout after the request was sent is ambiguous: the provider may have applied the effect and failed to answer. Retrying is safe only if the provider honours the key; otherwise, query before resending.
Figure 5 contrasts the two failure paths. The upper lane commits, calls, crashes, and retries blind. The lower lane commits an outbox row and a key, calls, gets no answer, and reconciles.
Reconciliation has costs that are usually underestimated:
- It needs a queryable identifier. Store the provider reference when you receive it, and derive the key deterministically.
Date.now()cannot be recomputed. - It needs a horizon longer than your worst retry. If the provider forgets the key and your DLQ drains a week later, the replay duplicates.
- It needs a stop rule. A job that retries forever is a slow denial of service. Route permanent failures to a queue with an owner.
- It needs privacy discipline. Full provider responses copy personal data elsewhere. Keep the minimum, and expire it.
There is a simpler variant for local state. When the effect is a state transition in your own database, you may not need a key table: UPDATE orders SET status = 'shipped' WHERE id = ? AND status = 'paid' changes zero rows on the second run, so the affected-row count is the decision. This works when the event carries the target state. It does not work when the effect leaves your database.
Walk Through a Crash Between Commit and Acknowledgment
The exercise starts at window 4 from the second section: the effect is committed, the acknowledgement never arrives, and the message is delivered again. It uses Wrangler's local Queues and D1 emulation, so no Cloudflare account, domain, or paid plan is required. A hosted variant is optional and not part of the pass criteria.
Walk Through a Crash Between Commit and Acknowledgment
Execution status: design-only. Not executed. Documentation was re-checked on 2026-11-05. No local or hosted run occurred, no Wrangler version was tested, and no retry timing or duplicate rate is measured. Expected observations are acceptance criteria, not results.
Prerequisites and plan requirements. Node.js 22 LTS, npm, and a terminal. Install Wrangler at run time and record the version; local Queues requires 3.1.0 or later (Queues local development). No Cloudflare account is needed locally. The hosted variant needs a plan that can create a queue and a D1 database, and must use an invented order id and a test provider.
Minimal setup. One Worker with a D1 binding, a queue producer, and a consumer configured for one message per batch and three retries, with a dead-letter queue. The widget above shows the effect table, the crash switch, and the local run.
The claim is one statement, and one changed row means you own it. The effect is a local stand-in: an insert keyed by the idempotency key, so a second business effect appears as a primary-key violation rather than a silent duplicate. In production, that insert is the provider call.
- Send 1042 once. One processed row marked
succeeded, one effects row, acknowledged. - Re-send the identical message. Zero rows changed on the claim, the stored status
succeededis replayed, still one effect row, acknowledged without work. - Crash after the claim, then send 1043. One
in_progressrow, zero effects, and a redelivery. The retry defers on a live lease or reconciles on a stale one. - Crash after the effect, then send 1044. One
in_progressrow, one effect, and a redelivery. The retry must find the effect and complete the record rather than insert again. - Remove the conflict clause from the effect insert, then repeat step 4. A primary-key failure, proving the table enforces uniqueness, not the handler's memory.
- Push the lease expiry into the past by direct SQL, then re-send. The reconciliation branch reads the effects table, finds the effect, and marks the record
succeeded. - Throw a non-retryable error and inspect the dead-letter queue. The message leaves the main queue after its retry budget, and the processed row is still
in_progress.
Expected observations. At least one duplicate delivery and zero duplicate effects; effect rows must equal distinct order ids.
Failure checks.
- Two effects for one key means deduplication ran after the effect.
- Zero effects with a succeeded status means completion was recorded without the work.
- A row stuck in progress means reconciliation is missing; endless retries of a permanent rejection means the stop rule is.
- A run where the queue never redelivered means the crash switch did not fire.
Cost dimensions. The local run is free apart from 45 to 90 minutes. The hosted variant incurs Queues operations (one write, one read, one delete per message, plus a read per retry), D1 rows read and written, and Worker requests. At a handful of messages the cost is negligible; operation counts scale with retries.
Cleanup. Stop the dev server, delete the local state directory and test tables. On the hosted variant, delete the queue, DLQ, D1 database, and Worker, then confirm the queue rejects sends. Discard the invented order ids.
Demonstrate Recovery With a Recorded Event History
Planned exercise: execution not yet performed. Documentation was verified on 2026-11-05. No local or hosted run occurred, no Wrangler, Workers, D1, Queues, or K2 version was tested, and no recovery time, duplicate rate, or cost is measured. Planning baseline: 2026-11-02.
The drill adds an append-only attempts(event_id, attempt, worker, started_at, ended_at, outcome, reason) table, one row per invocation including suppressed ones, then runs three phases.
Phase 1, duplicate injection. Deliver 50 invented events twice with the same key. Pass: 50 effect rows and 100 attempt rows, each suppression labelled already_succeeded, lease_live, or a reconciliation hit.
Phase 2, crash injection. For 10 events, crash after the claim and before the effect. Pass: every event reaches a terminal state through reconciliation, at most one effect row, and none is succeeded with zero effects. This phase catches silent loss.
Phase 3, replay. Produce 200 events into a short-retention K2 stream, consume through one subscription, then create a second with start_at: earliest and run the same handler over history. Pass: the projection hash is identical and the effect count unchanged. A replay that creates 200 new effects has failed.
Pass evidence. Keep the attempt log, both tables, the subscription id and start position, and the projection hash. A candidate passes when effect count equals distinct intent count; every duplicate has a suppression reason; every succeeded record has an effect or reference; every crashed claim reaches a terminal state; and replay changes the projection only by intended recomputation.
Any one of these fails the run
- Two effects for one intent.
- A
succeededrecord with no effect. - An
in_progressrecord older than the reconciliation interval. - A replay that re-sends notifications, re-charges cards, or increments counters.
- A consumer position behind the oldest retained record.
Self-check, with explanations.
If delivery is at-least-once, can a consumer be exactly-once? Not in delivery. It can be exactly-once in effect: the handler runs many times, but a durable claim and stored outcome change the world once. That guarantee is only as strong as the effect's own idempotency, so a provider call still needs its own key or a reconciliation query.
Why is a KV flag the wrong deduplication record? KV is eventually consistent, may serve a stale value for 60 seconds or more elsewhere, caches negative lookups, and documents no atomic read-modify-write (How KV works). Two isolates can both read "no key" and proceed. It is a cache for a key claimed elsewhere, not the boundary that decides.
Why does a longer deduplication window not fix a crash between commit and acknowledgement? The window helps only when the record exists. Window 2 is a crash before the effect with the record written; a longer window makes that state persist longer. Only expiry plus reconciliation distinguishes "never happened" from "happened but unrecorded".
Unresolved limitations. Every threshold above is a test criterion, not a measurement. Local Queues emulation mirrors production but not every timing or failure characteristic, and consumer concurrency is unsupported locally.
Plan and platform caveats are dated. K2 is public beta on Workers Paid only, with 10 GB per account and 20 streams at writing; billing is not enabled during beta, which will change. K2 subscriptions are immutable, so "rewind" means "create a new subscription at an earlier position"; verify no rewind API has been added.
Some behaviour was not tested. Provider idempotency windows vary. D1 read replication changes which replica serves a read, and the Sessions API is the documented route to sequential consistency. Retention, limits, and entitlements are dated to 2026-11-05 and must be re-checked before publication.
References (verified 2026-11-05):
- Cloudflare Queues: https://developers.cloudflare.com/queues/
- How Queues Works: https://developers.cloudflare.com/queues/reference/how-queues-works/
- Queues limits and pricing: https://developers.cloudflare.com/queues/platform/limits/
- Cloudflare K2: https://developers.cloudflare.com/k2/
- K2 delivery guarantees: https://developers.cloudflare.com/k2/reference/delivery-guarantees/
- K2 configuration: https://developers.cloudflare.com/k2/configuration/
- K2 limits: https://developers.cloudflare.com/k2/platform/limits/
- Choosing a data or storage product: https://developers.cloudflare.com/workers/platform/storage-options/
- D1 Database API: https://developers.cloudflare.com/d1/worker-api/d1-database/
- Durable Objects rules: https://developers.cloudflare.com/durable-objects/best-practices/rules-of-durable-objects/
- Workers KV consistency: https://developers.cloudflare.com/kv/concepts/how-kv-works/
- RFC 9110, HTTP semantics: https://www.rfc-editor.org/rfc/rfc9110.html