Back to Cloudflare

Retries and Replay Without Duplicate Business Actions

November 5, 2026 Updated November 6, 2026 Wasil Zafar 30 min read

Separate transport delivery from business-level effects

Table of Contents

  1. Messages Can Arrive More Than Once
  2. A Durable Idempotency Record Has Its Own Failure Modes
  3. Queue Redelivery and Stream Replay Differ
  4. External Side Effects Need Reconciliation
  5. Walk Through a Crash Between Commit and Acknowledgment
  6. Demonstrate Recovery With a Recorded Event History

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:shipment is 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.

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.

Messages Can Arrive More Than Once
%%{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.

Five boundaries between a business intent and its effect A producer assigns an idempotency key. The transport may deliver the message more than once. The handler may therefore run more than once. A durable deduplication record decides whether the effect may run. The external system applies the effect and may have its own idempotency window. The effect count is decided at the durable boundary, not by the broker Producer Owns the intent Assigns the key once order:1042:shipment Never regenerates it on a retry Boundary 1 Who names the intent? Transport May deliver 1..n times Queues: at least once K2: at least once per subscription No deduplication Boundary 2 What is promised? Handler May run 1..n times Can crash at any line Can keep running after its lease expires Holds no truth Boundary 3 Is retry safe here? Durable record One row or object per idempotency key Atomic claim Stores the outcome and the external id Boundary 4 Who decides twice? External system Applies the effect Its own key window May accept, reject, or time out Owns its own truth Boundary 5 Can you ask it later? claim result reconcile unknown state A duplicate is only a bug when it crosses boundary 4 or 5 without being recognised. Delivery at boundary 2 is allowed to repeat. Effect at boundary 5 is not, unless it can be keyed or queried.

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 pointWhat the record saysWhat the world showsA naive retryWhat the design must do
Before the claimNothingNo effectProceedsNothing; this is the safe case
After the claim, before the effectin_progressNo effectSuppresses the retryExpire the lease, then prove the effect is absent
After the effect, before the outcome is recordedin_progressThe effect existsRuns the effect againReconcile by key before doing anything
After both, before the acknowledgementsucceededThe effect existsReads the stored outcomeAcknowledge 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.

CREATE TABLE processed (
  key TEXT PRIMARY KEY,
  status TEXT NOT NULL,           -- in_progress | succeeded | failed_permanent | unknown
  lease_expires_at INTEGER,
  external_ref TEXT,              -- the provider's id, for reconciliation
  result TEXT,                    -- the stored outcome to replay
  attempt INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL
);
// The claim decides; the handler never trusts its own memory.
const claim = await env.DB.prepare(
  `INSERT INTO processed (key, status, lease_expires_at, updated_at)
   VALUES (?, 'in_progress', ?, ?)
   ON CONFLICT(key) DO NOTHING`
).bind(key, Date.now() + LEASE_MS, Date.now()).run();

if (claim.meta.changes === 0) {
  const row = await env.DB.prepare(
    "SELECT status, lease_expires_at, result FROM processed WHERE key = ?"
  ).bind(key).first();

  if (row?.status === "succeeded") return row.result;   // replay the stored outcome
  if (row?.status === "in_progress" && row.lease_expires_at > Date.now()) {
    throw new Error("lease live");                       // retry later, do not run twice
  }
  return reconcile(env, key);                            // stale: unknown, not failed
}

await runEffect(env, key);
# Local D1 state persists across restarts, so the same order id is a real duplicate.
npx wrangler dev
curl -sS -X POST http://localhost:8787/orders \
  -H 'content-type: application/json' -d '{"orderId":"1042"}'

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.

MechanismAtomic claimSurvives a handler crashWindow you controlDuplicate it preventsResidual failure
Workers KV flagNo. Eventually consistent, no atomic read-modify-write, negative lookups cached (How KV works)Yes, but reads can be stale for 60 seconds or moreTTL, not immediateAlmost noneTwo isolates both read "absent" and proceed
D1 row with UNIQUE(key)Yes, on the primary databaseYesUntil you delete the row; archive deliberatelyConcurrent duplicates and retry duplicatesCrash after claim leaves work unfinished until reconciliation
Durable Object per keyYes. Single-threaded instance, transactional SQLite storage, input and output gates (Rules of Durable Objects)YesUntil storage is deletedConcurrent duplicates, interleaving, and claim racesSame unfinished-work window; per-object throughput ceiling
Provider idempotency keyProvider-side, outside your controlYes, provider-ownedProvider's published window; verify per providerRetried external calls inside that windowWindow shorter than your retry or replay horizon; timeout still ambiguous
Queue or stream deduplicationNot offeredn/aMessage or record retention onlyNothingEvery redelivery re-runs the handler

Figure 3 shows the record as a state machine, including the loop most designs omit.

A Durable Idempotency Record Has Its Own Failure Modes
%%{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.

QuestionQueuesK2
What is a message?A unit of work, deleted on acknowledgementA record in a retained history
Who reads it?One consumer configuration per queue, many concurrent invocationsEvery subscription reads every record, up to 128 workers holding leases
What does acknowledgement do?Deletes the message; no offset to rewindAdvances a cursor; records stay until retention ends
When does delivery repeat?Failure-driven: a failed batch retries, then the DLQConsumer-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 togetherAt-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.

Queue redelivery compared with stream replay On the left, a queue holds messages for one consumer configuration; acknowledgement deletes a message, and failed delivery retries or moves to a dead-letter queue. On the right, a stream retains records for a retention period and three independent subscriptions read the same records at different positions, so a new subscription can replay history. Same word, different lifetime Queue: work sharing M1 order M2 order M3 order One consumer configuration many concurrent invocations a batch retries together deliver retry ack deletes message No rewind after acknowledgement. Failure path: retry, then dead-letter queue. Stream: retained history R1 R2 R3 R4 R5 R6 retained for 1 hour to 30 days, default 7 days Subscription A position: R6 Subscription B position: R4 Subscription C new: start earliest Ack advances a cursor; records remain. Every subscription sees every record. Replay = new subscription over retained records. Neither mechanism deduplicates. Both deliver at least once. Queue redelivery repeats a failed unit of work. Stream replay re-runs history on purpose. The second is more dangerous because it is deliberate, larger, and often run against production handlers.

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.

-- D1 batch(): the business change and the outbox row commit, or neither does.
UPDATE orders SET status = 'paid' WHERE id = 1042 AND status = 'pending';
INSERT INTO outbox (key, payload, status, attempt)
VALUES ('order:1042:capture', ?, 'pending', 0);
// The relay may run many times; the key never changes.
try {
  const res = await fetch(env.PROVIDER_URL, {
    method: "POST",
    headers: { "content-type": "application/json", "idempotency-key": row.key },
    body: row.payload,
  });
  if (res.ok) await settle(env, row.key, await res.json());
  else await classify(env, row.key, res.status); // 5xx retries, 4xx is permanent
} catch {
  // No answer. The provider may already have applied the effect.
  await markUnknown(env, row.key);
}
npx wrangler dev
# The relay is safe to re-run: every attempt carries the same key.
curl -sS -X POST http://localhost:8787/outbox/relay

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.

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.

Blind retry compared with keyed reconciliation The upper path writes business state, calls an external provider, crashes before recording the result, and retries the call, producing two effects. The lower path writes business state and an outbox row with an idempotency key in one transaction, calls the provider, records an unknown outcome on timeout, then queries the provider by key before deciding whether to resend. Two ways to cross the same gap Blind retry 1. Write order status = paid 2. Call provider no idempotency key 3. Provider applies then the caller crashes 4. Retry the call no record of attempt 1 5. Second charge two effects, one intent Keyed outbox and reconciliation 1. One transaction order + outbox row key = order:1042 2. Relay calls with the same key on every attempt 3. Timeout outcome unknown not "failed" 4. Query by key or provider reference read the truth 5. Settle mark succeeded, or resend if absent one effect survives The upper path is not fixed by a longer deduplication window. The window only helps if the effect was recorded, and the crash happened before the record existed. Reconciliation is the only mechanism that can resolve an effect whose outcome you never observed. Budget for it as a permanent component, not as an incident response.

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.

-- The second business effect surfaces as a primary-key violation.
CREATE TABLE effects (
  effect_id TEXT PRIMARY KEY,   -- the idempotency key itself
  key TEXT NOT NULL,
  created_at INTEGER NOT NULL
);
// The crash switch stops the same handler at a chosen point.
const crashAt = env.CRASH_AFTER; // "after_claim" | "after_effect" | undefined
# Persistent local state, so attempts outlive a restart.
npx wrangler dev --persist-to .wrangler/state
curl -sS -X POST http://localhost:8787/orders \
  -H 'content-type: application/json' -d '{"orderId":"1043"}'
Guided exercise

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.

  1. Send 1042 once. One processed row marked succeeded, one effects row, acknowledged.
  2. Re-send the identical message. Zero rows changed on the claim, the stored status succeeded is replayed, still one effect row, acknowledged without work.
  3. Crash after the claim, then send 1043. One in_progress row, zero effects, and a redelivery. The retry defers on a live lease or reconciles on a stale one.
  4. Crash after the effect, then send 1044. One in_progress row, one effect, and a redelivery. The retry must find the effect and complete the record rather than insert again.
  5. 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.
  6. 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.
  7. 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 succeeded record with no effect.
  • An in_progress record 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