Back to Cloudflare

Choose Queues or K2 for Asynchronous Events

November 5, 2026 Wasil Zafar 29 min read

Separate units of work from replayable event streams

Table of Contents

  1. A Job Queue and a Durable Event Log Serve Different Needs
  2. Queues Batches, Retries, and Dead-Letter Handling
  3. K2 Retention, Subscriptions, and Consumer Progress
  4. Delivery Guarantees Do Not Remove Application Idempotency
  5. Design Email Jobs and an Independently Consumed Event Feed
  6. Show Duplicate Handling and a Replay Recovery Plan

A Job Queue and a Durable Event Log Serve Different Needs

Picture a checkout. Payment succeeds and two follow-ups remain. One is to email a receipt: one recipient, one template, one outcome. Once sent, nobody needs the instruction again. The other is to announce that an order happened: support may read it, fraud may score it, analytics may funnel it, and a warehouse team may read it next quarter. Some of those readers do not exist yet.

Cloudflare sells a different product for each shape. Cloudflare Queues is a job queue: a producer enqueues a message, a consumer Worker receives a batch, and the message is deleted after acknowledgement. Cloudflare K2 is a durable log: a producer appends a record, records remain for a retention period, and each subscription reads at its own position. Cloudflare's storage guidance draws the same line, recommending Queues for background jobs and deferred tasks, and K2 for event data read by multiple independent consumers (Choose a data or storage product).

The analogy is a restaurant ticket rail versus building security footage. A ticket belongs to one cook and is thrown away when the dish is served. Footage is an append-only timeline; each viewer has a private position, can rewind, and the footage expires on a schedule whether or not anyone watched.

That difference defines the vocabulary. A queue has a producer, a message, a consumer, an acknowledgement, retries, and a dead-letter queue (DLQ), which is another queue with its own consumer. A log has a stream, records, subscriptions, leases, retention, and replay. A subscription is a cursor, not a copy. Reading does not delete.

A Job Queue and a Durable Event Log Serve Different Needs
%%{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
    A[Checkout succeeds] --> B{What does the receiver need?}
    B -->|"Finish one task"| C
    B -->|"Re-read the fact later"| D
    subgraph Q["Queue contract"]
      C[invoice-email-jobs] --> E[Consumer Worker]
      E -->|ack| F[Message deleted]
      E -->|"429 or 5xx"| G[Retry with backoff]
      G -->|"max_retries reached"| H[(Dead-letter queue)]
    end
    subgraph L["Log contract"]
      D[order-events stream] --> I[alerting subscription]
      D --> J[archive subscription]
      D --> K[analytics subscription]
      D -.->|"retention expires"| P[Records deleted by TTL]
      I --> M[Pager]
      J --> N[R2 bucket]
      K --> O[Warehouse]
    end
    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 A,B,C,E,F,G,D,I,J,K,P,M,N,O secondary;
Queue and durable log boundaries Left: a checkout Worker enqueues an email job, a consumer sends the email and acknowledges it, and the message is deleted. Right: an orders API appends to a stream retained for a time to live, and three independent subscriptions read it for alerting, archiving, and analytics. QUEUE: a unit of work Completion removes the item Checkout email-jobs 128 KB max deleted on ack Consumer Worker Send email then acknowledge ack is the delete signal LOG: retained facts Time removes the record, not the reader Orders API order-events 7-day TTL alerting to pager archive to R2 analytics to warehouse

The rule that follows: ask what must happen after the receiver finishes. If the answer is “nothing, the work is done,” use a queue. If the answer is “another team may read it later, and a new consumer may need history,” use a log. If the answer is “both,” use both: append the event to K2 and enqueue the receipt job. Two products in one flow is normal.

Queues also fits per-message retry control, a DLQ, and batching calls to a rate-limited API. K2 fits when bytes rather than message count drive cost, when several consumers need the same events, or when replay is a requirement. Neither replaces Workflows, which is for one job with many dependent steps, or Durable Objects, which serialize one key. A queue is for many jobs with one step each.

Queues Batches, Retries, and Dead-Letter Handling

The batch is a cost control and a blast radius. max_batch_size defaults to 10 and can reach 100, while the batch timeout defaults to five seconds and can reach 60; whichever limit trips first sends the batch. Larger batches cut invocations, but a thrown error re-runs every message (Batching, Retries and Delays).

Batching and retry policy live in the Wrangler configuration, not in the handler body. The commands create both queues before the first deploy.

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "name": "checkout-events",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-05",
  "queues": {
    "producers": [
      {
        "binding": "EMAIL_JOBS",
        "queue": "email-jobs"
      }
    ],
    "consumers": [
      {
        "queue": "email-jobs",
        "max_batch_size": 10,
        "max_batch_timeout": 5,
        "max_retries": 4,
        "retry_delay": 30,
        "dead_letter_queue": "email-jobs-dlq"
      }
    ]
  }
}
npx wrangler queues create email-jobs
npx wrangler queues create email-jobs-dlq
npx wrangler deploy

Retries are bounded, and the DLQ is a separate queue. Retries default to 3 and can be configured up to 100. When a message reaches the cap it goes to the configured dead-letter queue, or is deleted permanently if none exists. The DLQ needs its own consumer; otherwise its messages persist for four days and disappear, and it must use the same jurisdiction as the source (Dead Letter Queues).

A DLQ without a consumer is a four-day buffer

Cloudflare creates a missing DLQ automatically in the source jurisdiction, but it does not attach a consumer. Unconsumed DLQ messages expire after four days — long enough to look healthy on a dashboard, short enough to lose the evidence.

A batch of ten arrives and message 8 returns a 500. If the handler simply throws, all ten are redelivered, so messages 1 through 7 repeat their side effects. Acknowledging each success, retrying only the failed message, and acknowledging the rest shrinks the duplicate set to one. The catch is that the first acknowledgement decision wins: an ack followed by a retry is silently ignored, and a batch-level call does not override a per-message decision.

Consumer outcomeWhat Queues redeliversAttempt budgetOperational note
Handler returns normallyNothingNot consumedAn effect that has not committed before return can still be lost
Handler throwsThe entire batchOne retry per messageMessages already processed repeat unless the consumer is idempotent
Some messages acked, then handler throwsOnly the unacked messagesOne retry for each unacked messageSmaller duplicate set, but ack only after the effect is durable
msg.retry() on selected messages, rest ackedOnly the retried messagesOne retry for each retried messageBest control; the first ack or retry call for a message wins
Retries exhausted with a DLQNothing to the source queue; the message goes to the DLQBudget exhaustedThe DLQ needs a consumer or its messages expire after four days
Retries exhausted without a DLQNothing; the message is deletedBudget exhaustedSilent loss unless you alert on missing work

Backoff belongs in the consumer. Each message exposes attempts, so compute a delay and pass it to retry({ delaySeconds }). A per-message delay overrides the queue default. Figure 3 traces the branches, including the path where no DLQ is configured.

Cap the backoff at a ceiling

An exponential formula without a ceiling turns a transient outage into a multi-day stall. Delays can reach 24 hours, so choose a maximum shorter than your retention window.

Queues Batches, Retries, and Dead-Letter Handling
%%{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'}}}%%
flowchart TD
    B[Batch of up to 100 messages] --> H[queue handler runs]
    H --> R{Result for each message}
    R -->|success| A[msg.ack]
    R -->|"429, 5xx, network error"| T[msg.retry with backoff]
    R -->|"400, invalid payload"| F[Send to DLQ queue]
    A --> N[Next batch]
    T --> L{Retries left?}
    L -->|yes| B
    L -->|"no, DLQ configured"| D[Automatic DLQ delivery]
    L -->|"no, no DLQ"| X[Message deleted]
    F --> N
    D --> O[DLQ consumer and alert]
    O --> N
    X --> Z[Silent loss]
    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 B,H,R,A,T,F,N,L,D,X,O,Z secondary;

The code below makes the policy explicit. It claims a job in D1 with a unique key, sends the email with the same key as the provider's idempotency key, retries only transient status codes, and forwards permanent failures to a DLQ before acknowledging. The order is deliberate: if the DLQ write throws, the message stays unacknowledged and returns.

interface EmailJob {
  jobId: string;
  to: string;
  template: "receipt" | "reset";
}

interface Env {
  DB: D1Database;
  EMAIL_DLQ: Queue<EmailJob & { reason: string }>;
}

const TRANSIENT = new Set([408, 425, 429, 500, 502, 503, 504]);

export default {
  async queue(batch: MessageBatch<EmailJob>, env: Env): Promise<void> {
    for (const msg of batch.messages) {
      const job = msg.body;

      const claim = await env.DB.prepare(
        `INSERT INTO email_jobs (job_id, status) VALUES (?, 'sending')
         ON CONFLICT(job_id) DO NOTHING`
      )
        .bind(job.jobId)
        .run();

      if (claim.meta.changes === 0) {
        const row = await env.DB.prepare(
          "SELECT status FROM email_jobs WHERE job_id = ?"
        )
          .bind(job.jobId)
          .first<{ status: string }>();

        if (row?.status === "sent" || row?.status === "dead") {
          msg.ack();
          continue;
        }
      }

      let response: Response;
      try {
        response = await fetch("https://mail.example.test/v1/send", {
          method: "POST",
          headers: {
            "content-type": "application/json",
            "idempotency-key": job.jobId,
          },
          body: JSON.stringify({ to: job.to, template: job.template }),
        });
      } catch {
        msg.retry({ delaySeconds: backoff(msg.attempts) });
        continue;
      }

      if (TRANSIENT.has(response.status)) {
        msg.retry({ delaySeconds: backoff(msg.attempts) });
        continue;
      }

      if (!response.ok) {
        await env.EMAIL_DLQ.send({
          ...job,
          reason: `http_${response.status}`,
        });
        await env.DB.prepare(
          "UPDATE email_jobs SET status = 'dead' WHERE job_id = ?"
        )
          .bind(job.jobId)
          .run();
        msg.ack();
        continue;
      }

      await env.DB.prepare(
        "UPDATE email_jobs SET status = 'sent', sent_at = ? WHERE job_id = ?"
      )
        .bind(Date.now(), job.jobId)
        .run();
      msg.ack();
    }
  },
} satisfies ExportedHandler<Env>;

function backoff(attempts: number): number {
  return Math.min(30 * 2 ** (attempts - 1), 3600);
}

Two details matter. The jobId is a business identifier chosen by the producer, not a per-delivery identifier; a redelivery must present the same key or the dedupe row does nothing. And the provider must honor the idempotency key. If it does not, the local dedupe protects only the step between the email call and the D1 update.

The product boundary is worth stating precisely. Queues is available on Workers Free and Workers Paid, but the plans differ. Free retention is fixed at 24 hours with 10,000 queues; Paid defaults to 4 days, configurable up to 14 days, with a default cap of 10,000 queues and a charge above that.

Message and queue limits sit alongside the plan limits. A message is capped at 128 KB, a queue at 5,000 messages per second and a 25 GB backlog, and a consumer invocation at 15 minutes of wall time and 30 seconds of CPU by default, configurable to 5 minutes (Queues limits). Those numbers were read on 2026-11-05; do not treat them as permanent.

Retention is also a failure mode. An unconsumed message is deleted at the retention limit even if no consumer ever saw it. A long outage or a backlog above 25 GB turns a queue into a lossy buffer. That is the tradeoff for not paying for infinite storage.

K2 Retention, Subscriptions, and Consumer Progress

K2's unit of progress is the subscription. A stream is an ordered, append-only sequence of records. Each record has binary content and optional string headers, up to about 1 MB. Every subscription receives every record and tracks its own position. Consuming from one does not move another, and consuming does not delete the record (K2 concepts).

K2 is a public beta with dated limits. It runs only on the Workers Paid plan. The beta caps storage at 10 GB per account, and the current stream limit is 20 per account. Retention ranges from one hour to 30 days, defaulting to seven days. A stream supports 100 subscriptions, each with up to 128 active leases, and a consume request can ask for 10,000 records or 10 MB (K2 limits). Billing was not enabled at the time of writing; Cloudflare publishes rates for estimation and promises 30 days notice before billing begins (K2 pricing). Treat these as dated facts.

Creating a subscription with the same name and settings returns the existing ID, so the call is safe to retry; a name match with different settings returns a 422 (Consume records).

Consumption is pull-based over HTTP, not a push binding. A consumer posts a worker identifier and a record ceiling to the subscription's consume endpoint, and K2 leases the batch for five minutes. The tabs show the subscription body plus the create, consume, and acknowledge calls.

{
  "name": "archive",
  "start_at": { "type": "earliest" }
}
# Create the subscription and keep the returned id.
curl "$K2_ENDPOINT/subscriptions" \
  --request POST \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{"name":"archive","start_at":{"type":"earliest"}}'

# Lease a batch, then acknowledge it after the effect is durable.
curl "$K2_ENDPOINT/subscriptions/$SUBSCRIPTION_ID/consume" \
  --request POST \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{"worker_id":"archive-1","max_records":500}'

curl "$K2_ENDPOINT/subscriptions/$SUBSCRIPTION_ID/batches/$BATCH_ID/ack" \
  --request POST \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{"worker_id":"archive-1"}'

One worker identifier holds one lease at a time, and a subscription allows 128. Requesting another batch while holding a lease returns the same batch and refreshes it, which recovers a lost response. Acknowledgement is idempotent, but an ack after the lease expired has no effect.

There is no per-record acknowledgement. No documented delivery-attempt counter and no documented dead-letter path exist, so a record that always crashes the consumer can hold the subscription at that batch until you quarantine it manually. The same calls support extend and nack when processing outlives the lease or the batch must be released.

The ordering guarantee is mostly negative, and it is worth treating as a design constraint rather than a tuning detail.

Ordering is not a guarantee

K2 does not promise processing order across workers that share a subscription, and it has no partition key or per-key ordering mode. timestamp_ms is receipt time, not a business sequence, and a single worker is not a documented guarantee either.

Per-entity order needs a different mechanism. Route that entity to a Durable Object, or carry a monotonic version and reject stale writes.

Retention is the hard boundary on progress. Records are deleted at their TTL whether or not a subscription read them. A consumer down longer than retention loses the oldest unread records and resumes at the oldest survivor, with no error and no gap marker.

No push handler, no consumer binding. Consumption is an HTTP pull, so a Worker that consumes K2 needs a scheduler, such as a Cron Trigger or a Durable Object alarm, to poll and acknowledge. That scheduler is part of the reliability model: if it stops, lag grows silently until retention erases the backlog.

Delivery Guarantees Do Not Remove Application Idempotency

Both products deliver at least once, and neither offers exactly-once delivery end to end. The mechanism differs; the obligation does not. The receiver must tolerate seeing the same logical event more than once (K2 delivery guarantees).

PropertyCloudflare QueuesCloudflare K2
Delivery unitOne message, one active consumer per queueOne batch per subscription
AcknowledgementPer message, per batch, or on returnWhole batch only
DeduplicationNone built inNone on produce or consume
OrderingNo publish-order guaranteeNo processing-order guarantee across workers
Failure pathRetries, then a DLQ or deletionLease expiry or nack; no documented DLQ
ReplayOnly if payloads were archivedA new subscription at the earliest position

Duplicates arrive from several directions. A K2 producer that retries after error 10212 may store a batch twice, because the outcome is unknown and K2 does not deduplicate. A K2 consumer that finishes its work but loses the acknowledgement before the five-minute lease expires sees the batch again. A Queues handler that throws re-runs every message, including the ones that succeeded. A Queues producer that retries after a timeout can enqueue a second copy; that is reasoning rather than a documented guarantee, but assume it.

Make the consumer idempotent in concrete terms. Use a stable business identifier chosen by the producer and enforce it with a unique index, treating a conflict as “already done,” not an error. For state transitions, use a conditional update such as UPDATE jobs SET status = 'sent' WHERE job_id = ? AND status = 'sending' and check the changed-row count.

For external APIs, pass the identifier as the provider's idempotency key. Keep the dedupe record at least as long as retention plus the retry horizon; a key that expires before a replay lets the duplicate through.

Figure 4 shows the failure path that catches teams. The first delivery performs the effect and crashes before acknowledgement. The lease expires and the same event is delivered again. Without a key, the customer gets two emails. With a key, the second attempt finds the existing record and skips the effect.

Duplicate effect and idempotent recovery Lane A delivers event e-104, sends an email, crashes before acknowledging, and redelivers, causing a second email. Lane B delivers the same event, sends with key e-104, crashes before acknowledging, redelivers, finds the key already recorded, skips the effect, and acknowledges. A. At-least-once without an idempotency key Deliver e-104 attempt 1 Send email no key Crash before ack Redeliver e-104 attempt 2 Send again duplicate two emails B. At-least-once with a stable event id Deliver e-104 attempt 1 Send with key e-104 Crash before ack Redeliver e-104 attempt 2 Key exists skip effect then ack one email

“Exactly once” is the wrong phrase for business semantics. You can get at-least-once delivery, and you can get an effectively-once outcome by combining it with an idempotent effect. You cannot atomically commit an external email and an acknowledgement in two systems. Any claim of exactly-once end to end should be read as exactly-once within one boundary, plus a requirement that you make the other boundary idempotent.

Ordering is the second limit. Queues does not promise publish order. K2 does not promise processing order across workers sharing a subscription, and it has no per-key partition. If two events for the same customer land in different batches handled by different workers, the later one can commit first. A conditional write with a version number makes the stale event lose. Serializing that customer's events through a Durable Object is stronger, because one instance owns the key.

The tradeoff is cost and latency. A dedupe write per message adds a database round trip to every delivery, including the common case with no duplicate. A Durable Object per key adds a lookup and a potential bottleneck. Both are cheaper than reconciling a duplicate charge, but neither is free. Choose the key scope deliberately: tenant_id + event_id prevents cross-tenant collisions, and an ID generated at the source survives producer retries better than one generated inside the consumer.

Design Email Jobs and an Independently Consumed Event Feed

The exercise combines both products in one flow. A Worker accepts an order, appends a record to K2, and enqueues a receipt job. A Queues consumer sends the receipt with a DLQ for permanent failures, and two subscriptions, one for alerting and one for archiving, read the stream independently. The goal is to observe duplicate handling, dead-letter routing, and independent progress without pretending any of it was executed.

Guided exercise

Design Email Jobs and an Independently Consumed Event Feed

Status: design-only. This exercise was not executed for this article, and no timings, costs, or throughput numbers were measured.

Prerequisites and plan requirements. A Workers Paid plan is required for K2; K2 is not available on Workers Free. You need a current Node.js LTS, the current Wrangler release, a D1 database, one queue plus one DLQ, and a K2 stream. Use a controlled test recipient and a stub email endpoint you own. Before creating resources, write down the D1 schema, the consumer retry policy, the K2 retention period, and the cleanup step.

Minimal setup. One Worker exposes the order route, D1 holds the two dedupe tables, and the remaining resources are names to create before the run.

ResourceNameSettings
RoutePOST /orderSingle Worker front door
D1 tableemail_jobsjob_id TEXT primary key, status TEXT, sent_at INTEGER
D1 tableprocessed_eventsevent_id TEXT primary key, seen_at INTEGER
Queueemail-jobsBatch size 10, four retries, 30-second retry delay
Dead-letter queueemail-jobs-dlqSame jurisdiction, own consumer
Streamorder-eventsretention_seconds 86400, HTTP auth enabled
Subscriptionsalerting, archiveBoth start at earliest

Actions.

  1. Apply the D1 schema.
  2. Create email-jobs and email-jobs-dlq, then attach the consumer with max_batch_size 10, max_retries 4, dead_letter_queue, and retry_delay 30.
  3. Deploy the Worker and send three orders. Give one a recipient that the stub rejects with 400; give the others a recipient it accepts with 202.
  4. Inspect logs and D1: expect two sent rows, one dead row, and one DLQ message. The 400 should be forwarded immediately, not retried four times.
  5. Create the stream and both subscriptions at earliest.
  6. Produce five records with unique event_id headers and distinct order IDs.
  7. Consume each subscription with a different worker_id, decode the base64 content, and acknowledge. Both should report the same five IDs.
  8. Replay the failure path: accept the email, then throw before msg.ack(). Confirm redelivery does not send a second email.

Expected observations. The permanent failure reaches the DLQ on the first attempt; transient failures consume the retry budget. Both subscriptions see the same five records independently. A redelivered job produces one email and one sent row, and an unacknowledged K2 batch returns with a new batch identifier.

Failure checks. Produce the same K2 batch twice and confirm the archive subscription sees duplicates while the alerting path deduplicates on event_id. Stop a K2 consumer past a short retention window and confirm unread records are gone. Remove the DLQ and confirm an exhausted message is deleted. Set max_retries to 0 and confirm a failure goes straight to the DLQ.

Cost dimensions. Queues charges per 64 KB operation: write, read, and delete per message, plus a read per retry and a DLQ write. K2 charges for data produced, consumed, and retained; each subscription consumes the full stream, so two subscriptions double consumption. K2 billing was not enabled during the beta at the time of writing; published rates are $0.04 per GB produced, $0.04 per GB consumed, and $0.02 per GB per month retained. Confirm current pricing.

Cleanup. Delete the consumer, then the queue and DLQ. Delete both subscriptions, then the stream. Drop the D1 tables or delete the database. Remove the test route and any tokens created for the exercise.

The split matters because the failure semantics differ. The email job has a per-message retry budget and a DLQ. The event feed has neither. If the K2 consumer cannot process a record, it must decide inside the handler whether to quarantine that record and acknowledge the batch, or nack the batch and accept redelivery of everything in it.

Show Duplicate Handling and a Replay Recovery Plan

The evidence for this design is pass/fail, not a benchmark; none of these checks were run for this article.

Pass/fail evidence.

  • Duplicate suppression. Pass if a redelivered job with the same jobId leaves one sent row and one provider request. Fail if either count grows.
  • Permanent-failure routing. Pass if a 400 reaches the DLQ without exhausting retries and the source queue drains. Fail if it loops or is deleted.
  • Independent fan-out. Pass if both K2 subscriptions report the same five IDs and advancing one does not affect the other. Fail if one ack hides records from the other.
  • Replay isolation. Pass if a new earliest subscription re-reads retained records while the originals stay put. Fail if replay requires deleting a subscription.
  • Lag visibility. Pass if you can compare the newest processed timestamp_ms with now and alert before retention. Fail if the only signal is an empty consume response.
  • Bounded retries. Pass if Queues stops at max_retries and K2 has a quarantine path. Fail if a poison record can hold a subscription indefinitely.

Replay is a new reader, not a rewind. Stop the faulty consumer, define the recovery window by event ID or timestamp, and create a new subscription at earliest. Leave the production subscription alone, because subscriptions are immutable and there is no documented offset reset.

Filter the new subscription to the window using a stable event ID, write to a shadow table, compare counts, then promote, acknowledge, and delete the temporary subscription. If the records expired, the only source is an external archive such as R2; retention cannot be extended retroactively.

The same plan works for Queues only if you kept the payloads. A queue deletes a message on acknowledgement, so replay depends on an archive or on the DLQ. That is another reason the products pair well: K2 is the history you replay from, and Queues is the retry machinery for the side effect.

Self-check.

Question 1. A Queues batch of ten has no explicit acknowledgements, and message 8 throws. How many messages are redelivered, and why?

Answer. All ten. Batch retries are all-or-nothing by default, so successful messages repeat unless individually acked or idempotent.

Question 2. A K2 subscription is ten days behind on a stream with seven-day retention. What does the consumer see when it resumes?

Answer. Only records inside the retention window. The older unread records were deleted and no gap marker is delivered.

Question 3. If a consumer acknowledges quickly, can it skip idempotency?

Answer. No. The ack can be lost, the lease can expire after the effect, and a producer can store a batch twice.

Question 4. Does one K2 subscription give per-customer ordering if only one worker consumes it?

Answer. Do not assume so. K2 has no documented ordering guarantee and no partition key; use a Durable Object or a version check when order matters.

Unresolved limitations. K2 is a public beta capped at 10 GB per account and 20 streams, with retention capped at 30 days at the time of writing. It has no per-record acknowledgement, no documented dead-letter queue, no deduplication, and no per-key ordering, and consumption is HTTP pull, so a Worker consumer needs a scheduler. Queues has no ordering guarantee, caps a message at 128 KB and a queue at 5,000 messages per second and a 25 GB backlog, and deletes unconsumed messages at retention. The exercise was design-only: no hosted validation, latency, or cost was measured. Limits and pricing were checked on 2026-11-05 and should be re-checked before production use.

References.

Next in the Series

In Turn Events Into Analytics With Basin, we'll explore Follow ingestion through Iceberg tables to analytical queries.