Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

Durable Event Log: Stream Records, Subscriptions, Leases and Delivery

How Cloudflare K2 streams work: produce records, consume with subscriptions and leases, retention, limits, and at-least-once delivery.

This page summarises Cloudflare K2 documentation: a durable, append-only event log on the Workers Paid plan. Producers append records to a stream; consumers read through subscriptions, with batches leased for five minutes and acknowledged when processing finishes. The model fits high-volume fan-out and replay; for per-message work tracking and retries, Cloudflare recommends Workers Queues instead of K2.

K2 is a durable event log. Producers write records to a stream, and K2 stores them for a configurable retention period. Consumers read records in batches through subscriptions, and each subscription reads every record independently.

— Cloudflare, Choose a data or storage product

K2 streams vs queues: when to use a durable log

Section titled “K2 streams vs queues: when to use a durable log”

A K2 stream is an ordered, durable log between writers and readers. Unlike a queue, consumption does not remove events—writes and reads are decoupled.

The core primitive in K2 is what we call a stream — an ordered, durable, log of events. The stream sits between producers writing events and consumers reading them. Unlike a traditional queue, where consumption removes items, production and consumption in a log are completely decoupled. Writes append events to the log, while reads merely advance a pointer (or offset) within the log.

— Cloudflare, Concepts

Goal Prefer
Bulk events, volume-based pricing, many independent readers, replay K2
Each message is a unit of work to complete, retry, and track individually Workers Queues

Use Queues when each message is a unit of work that needs to be completed, retried, and tracked individually. Use K2 when you produce and consume records in bulk, and what matters is that every record is processed rather than the state of any one record.

— Cloudflare, Choose a data or storage product

During public beta, K2 is available on the Workers Paid plan; each account can store up to 10 GB unless a higher limit is requested—see Limits.

Stream records and retention: what gets stored

Section titled “Stream records and retention: what gets stored”

Each record has content (binary payload; base64 on HTTP APIs) and optional string headers for metadata without deserialising the body. Records can be up to ~1 MB including content and headers. See Concepts — Records and Produce records — Records and batches.

Retention is set per stream with retention_seconds (default 604800, seven days; range 3600 to 2592000). Expired records are deleted in the background and may remain readable briefly after the period ends—do not treat retention as a precise deletion time. Consuming a record does not remove it; data stays until retention expires. If a consumer falls behind longer than retention, unread records can be deleted—size retention for your longest acceptable downtime (Delivery guarantees — Subscriptions are independent, Configuration — Retention).

Streams are created and managed with the account REST API (Configuration, Get started). Permissions: K2 Config Write to create, update, or delete; K2 Config Read to list or get.

Setting Notes
name 1–128 letters, numbers, or underscores; unique per account; not case-sensitive; cannot rename after creation
retention_seconds 1 hour–30 days
http / worker_binding At least one input must be enabled

HTTP produce uses https://<STREAM_ID>.k2.cloudflarestorage.com. If http.authentication is not true, the /produce endpoint is public—anyone with the stream ID can write.

Authenticated producers send Authorization: Bearer <TOKEN> with K2 Produce permission (Configuration — Authentication).

Produce records: HTTP API and Workers binding

Section titled “Produce records: HTTP API and Workers binding”

You can produce via POST to /produce or from a Worker with send() on a k2 binding—each path must be enabled on the stream (Produce records).

Batch writes are atomic: either every record in the batch is stored, or none. A successful response means K2 stored the batch (Get started — How K2 works). HTTP batches use standard base64 content (not URL-safe base64); optional gzip with Content-Encoding: gzip. On failure, check error.retryable—only retry when retryable is true for a definite “not stored” outcome; code 10212 can mean unknown outcome, and retries can create duplicates because K2 does not deduplicate (Produce records — Handle errors, Delivery guarantees — Produce records).

From a Worker, configure [[k2]] in Wrangler with binding and stream (32-character hex ID). send() returns a result object—它 does not throw; use ArrayBuffer or Uint8Array for content, not strings (Produce records — Configure the binding).

Browser produce requires CORS origins on the stream and authentication disabled, which exposes /produce—validate data in consumers (Produce records — Produce from a browser).

Key produce limits (Limits — Produce records): ~30 MB/s per stream, 5 MB max request, ~1 MB per record, no fixed cap on record count beyond request size.

Subscriptions: independent consumers and start position

Section titled “Subscriptions: independent consumers and start position”

Subscriptions are how K2 tracks read position. Each subscription on a stream receives every record; subscriptions do not affect each other (Concepts — Subscriptions).

start_at.type is earliest (all retained history) or latest (only events after creation). Subscriptions are immutable after creation; duplicate name + same settings returns the existing ID; same name with different settings returns 422. Up to 100 subscriptions per stream (Consume records — Create a subscription).

Consumer calls use https://<STREAM_ID>.k2.cloudflarestorage.com with a token that has K2 Consume permission (Consume records — Before you begin).

Consume records: batches, leases, ack, nack, and extend

Section titled “Consume records: batches, leases, ack, nack, and extend”

Consumers follow a repeating cycle documented in Consume records and Get started:

  1. Create a subscription on the stream.

  2. POST to /subscriptions/<SUBSCRIPTION_ID>/consume with worker_id (1–256 chars, unique per concurrent consumer) and max_records (1–10,000).

  3. Process the returned batch; acknowledge before leased_until_ms, or extend the lease if processing needs more than five minutes.

  4. Repeat from step 2.

K2 delivers records at least once. Your consumer can receive the same record more than once. For details, refer to Delivery guarantees.

— Cloudflare, Consume records

Lease rules workers share on one subscription

Section titled “Lease rules workers share on one subscription”

When a batch is returned, K2 leases it to the requesting worker_id for five minutes (Concepts — Leases):

Rule Behaviour
One lease per worker_id Same worker re-requesting gets the same batch and a refreshed lease
Parallel workers Up to 128 active leases per subscription; 429 code 10216 when full
Record exclusivity Same records are not leased to two workers at once
Ordering No guaranteed processing order across workers on one subscription

After processing: ack advances the subscription and releases the lease; nack redelivers the whole batch on the next consume; extend sets expiry to five minutes after the extend call (Consume records — Acknowledge / Nack / Extend). Acknowledgement is per batch, not per record—one failure means nack the batch or handle the bad record inside the consumer (Delivery guarantees — How a batch is delivered).

If no records are available, the response has empty records and batch_id: null—back off polling (Consume records — No records available). Retry consume errors 10211, 10214, 10216, and 10217 after backoff; do not retry 10218—request a new batch (Consume records — Handle errors).

Delivery guarantees: fan-out, retention, and duplicate records

Section titled “Delivery guarantees: fan-out, retention, and duplicate records”

K2 delivers every record to every subscription on a stream at least once. A consumer can receive the same record more than once, so design consumers to handle duplicate records.

— Cloudflare, Delivery guarantees

Guarantee Behaviour
Delivery At least once per subscription
Fan-out Every subscription gets every record (up to 100 subscriptions)
Retention Consume does not delete; TTL applies whether or not a record was read
Deduplication None on produce or consume
Batches Ack/nack/redelivery apply to the entire batch

Duplicates can come from producer retries after ambiguous failures or from consumer redelivery after nack or lease expiry (Delivery guarantees — Produce records). Mitigations: idempotent consumers, unique IDs in content or headers, ack soon after success, extend lease before five minutes (Delivery guarantees — Handle duplicate records).

Pricing is by volume: data produced and data consumed (each subscription reads the full stream independently) (Pricing).

Common mistakes when building K2 consumers

Section titled “Common mistakes when building K2 consumers”
  • Treating K2 like a queue and expecting messages to disappear after ack—they remain until retention (Delivery guarantees — Summary).
  • Partial batch ack—you cannot ack successful records while nacking one; failed records require in-consumer handling or a full batch nack.
  • Slow consumers without lease extend—expired leases redeliver to another worker; late acks may have no effect.
  • Retrying produce without checking retryable—risk double writes; K2 does not deduplicate.
  • Public /produce from the browser—no API token in client code; anyone with the stream ID can write (Produce records — Produce from a browser).
  • Retention shorter than worst-case backlog—unread data can be deleted while a subscription is behind.
  1. In the Cloudflare dashboard, create an API token with K2 Config Write, K2 Produce, and K2 Consume for your account.
  2. Create a test stream with http.authentication: true, note the endpoint from the response, and confirm settings match Configuration — Stream settings.
  3. POST a small batch to /produce and confirm { "success": true }.
  4. Create a subscription with start_at: earliest, call /consume, decode a record, then /ack with the same worker_id; a second consume should return no records if the batch was the only data.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.