Skip to main content

Send events from Cloudflare Workers to your own bucket

Send a JSON event from a Cloudflare Worker with fetch(). Queue the request after returning the response so visitors don’t wait for event delivery. Send2Bucket writes the events as gzip NDJSON to Cloudflare R2, Amazon S3 or Google Cloud Storage.

How it works​

Worker ──response──▶ client
└── ctx.waitUntil(fetch) ──POST /v1/events──▶ api.send2bucket.com ──▶ s3://<bucket>/<prefix>/s2b/…
  • The Worker collects the events of one request in an array and sends them in one POST /v1/events call. A 204 means they are stored durably and will be delivered at least once. See Delivery semantics.
  • ctx.waitUntil() keeps the Worker running after it returns the response, so the client never waits for the send.
  • Send2Bucket writes one object per delivery batch, at least every 10 seconds on Free and every 60 seconds on Trial, Pro and Team, under date=YYYY-MM-DD/hour=HH/ folders.

1. Connect a bucket​

Create an ingestion stream in the dashboard, add a destination, and create an API key on the stream's page. The Quick start walks through it. For the destination:

You want the events inDestination
Cloudflare R2S3-compatible storage: endpoint https://<account_id>.r2.cloudflarestorage.com, region auto, and an R2 API token with Object Read & Write on the bucket
Amazon S3Amazon S3, with an IAM role
Google Cloud StorageGoogle Cloud Storage, with a service account

A key made on the stream's page writes only to that stream, so the Worker needs no S2b-Stream header.

2. Store the key as a secret​

Keep the key out of the Worker's code and config. Secrets are encrypted and reach the Worker as env.S2B_API_KEY:

npx wrangler secret put S2B_API_KEY

This command creates a new version of the Worker and deploys it. For wrangler dev, put the key in a .dev.vars file next to the Wrangler config, and keep that file out of git:

S2B_API_KEY="s2b_ingest_..."

The endpoint is not secret, so it goes in vars in wrangler.jsonc, the config format Cloudflare recommends for new projects:

{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "edge-events",
"main": "src/index.js",
"compatibility_date": "2026-11-20",
"vars": {
"S2B_URL": "https://api.send2bucket.com"
}
}

3. Write the Worker​

src/index.js records a page.view for every request and a plan.selected when the URL carries ?plan=, then hands the send to ctx.waitUntil():

const ATTEMPTS = 3;

async function sendEvents(env, events) {
const body = JSON.stringify(events); // one request for every event in the array
for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {
try {
const res = await fetch(`${env.S2B_URL}/v1/events`, {
method: "POST",
headers: {
Authorization: `Bearer ${env.S2B_API_KEY}`,
"Content-Type": "application/json",
},
body,
signal: AbortSignal.timeout(5000),
});
if (res.status === 204) return; // stored durably, will be delivered
const error = await res.text();
if (res.status < 500) {
// 400, 401, 409, 413, 429: the same body fails again, so do not retry
console.error(`send2bucket: ${res.status} ${error}, dropped ${events.length} events`);
return;
}
console.warn(`send2bucket: ${res.status} ${error}, attempt ${attempt}`);
} catch (err) {
// Timeout or network error. The request may have been stored, so a
// retry can duplicate it; event_id lets you deduplicate later.
console.warn(`send2bucket: ${err}, attempt ${attempt}`);
}
if (attempt < ATTEMPTS) await new Promise((r) => setTimeout(r, 1000 * attempt));
}
console.error(`send2bucket: gave up, dropped ${events.length} events`);
}

export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const events = [];
const track = (event, fields) =>
events.push({ event, event_id: crypto.randomUUID(), ts: new Date().toISOString(), ...fields });

track("page.view", { path: url.pathname, country: request.cf?.country ?? null });
if (url.searchParams.has("plan")) track("plan.selected", { plan: url.searchParams.get("plan") });

ctx.waitUntil(sendEvents(env, events)); // runs after the response is sent
return new Response("ok\n");
},
};

In your Worker, the return is your own response or fetch(request) to your origin; the tracking lines stay the same. Points worth keeping when you adapt it:

  • One request per invocation. /v1/events takes a JSON array, so every event of an invocation goes in one call. Each fetch() counts against the Workers subrequest limit (50 per invocation on Workers Free).
  • Size. Each event can be up to 8 KiB and a request up to 16 MiB decompressed. The request is accepted or rejected as a whole: one oversized event fails the whole array with 400 item_too_large. See the API reference.
  • Retry only what can succeed. Timeouts, network errors and 5xx are worth a short retry. A 4xx fails the same way again; 429 quota_exceeded lasts until the plan allowance resets.
  • Stay inside the waitUntil() window. Cloudflare gives waitUntil() up to 30 seconds after the response, shared by all its promises, then cancels them. Three attempts with a 5-second timeout and 1- and 2-second pauses take at most 18 seconds. A 503 from Send2Bucket asks for Retry-After: 30, longer than the window, so the Worker gives up and logs it; use the queue below if those events must not be lost.
  • Deduplicate with event_id. Send2Bucket does not deduplicate requests, so a retry after a lost response stores the events twice. The event_id makes duplicates easy to drop when you query.

4. Run it locally​

wrangler dev runs the Worker on your machine in workerd, reads .dev.vars, and sends the events to the real endpoint:

npx wrangler dev

It prints the local URL it serves on, port 8787 by default. Request /pricing?plan=pro on it: the answer ok comes back at once, and the send runs afterwards. Errors from the send show up in the wrangler dev output, for example with a revoked key:

✘ [ERROR] send2bucket: 401 {"error":"unauthorized"}, dropped 1 events

Then deploy with npx wrangler deploy. In production, the same messages appear in the Worker's logs.

5. Check the events​

One ?plan=pro request lands as two lines with the same batch_id, because the Worker sent them in one call. The second line:

{"v":1,"delivery_batch_id":"dlv_00361pntdf9fu0d8ro14nl2nfjgiu","stream_id":"<stream_id>","batch_id":"bat_00361pnt6e75ko46couk45sr5iopq","received_at":"2026-11-23T00:51:07.022938Z","signal":"event","data":{"event":"plan.selected","event_id":"86b3b283-c4f0-4a8b-9ca5-ea94ea91b343","ts":"2026-11-23T00:51:07.021Z","plan":"pro"}}

data is the object the Worker sent, unchanged. Delivery format describes the envelope and the object keys.

DuckDB reads the objects in place. With the secret from its S3-compatible storage section (or the S3 or Cloud Storage one, with gs:// for Cloud Storage), count today's events by name, once per event_id:

SELECT data->>'event' AS event, count(DISTINCT data->>'event_id') AS events
FROM read_json('s3://<bucket>/<prefix>/s2b/stream=*/date=*/hour=*/*.ndjson.gz',
hive_partitioning = true,
columns = {received_at: 'TIMESTAMPTZ', signal: 'VARCHAR', data: 'JSON'})
WHERE signal = 'event' AND date = current_date
GROUP BY ALL
ORDER BY events DESC;

date is the UTC day Send2Bucket received the events. Use the Worker's own ts when you need the time the event happened. Other engines are listed under Querying.

Don't lose events: send through a queue​

waitUntil() is best effort: if Send2Bucket is unreachable for longer than the retries, those events are gone. For work that does not fit in that window, Cloudflare's docs point to Queues, which store messages and retry failed batches. The Worker writes each event to a queue, and a consumer sends up to 100 queued events, from many invocations, in one request:

export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
const event = { event: "page.view", event_id: crypto.randomUUID(), ts: new Date().toISOString(), path: url.pathname };
ctx.waitUntil(env.EVENTS.send(event)); // resolves once the queue has stored it
return new Response("ok\n");
},

// Called with up to max_batch_size messages; sends them as one request.
async queue(batch, env) {
const res = await fetch(`${env.S2B_URL}/v1/events`, {
method: "POST",
headers: {
Authorization: `Bearer ${env.S2B_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify(batch.messages.map((m) => m.body)),
});
// Throwing retries the whole batch, up to max_retries, then the dead letter queue.
if (res.status !== 204) throw new Error(`send2bucket: ${res.status} ${await res.text()}`);
},
};

Create the queue with npx wrangler queues create s2b-events, and bind it as producer and consumer in wrangler.jsonc:

"queues": {
"producers": [{ "binding": "EVENTS", "queue": "s2b-events" }],
"consumers": [{
"queue": "s2b-events",
"max_batch_size": 100,
"max_batch_timeout": 10,
"max_retries": 10,
"dead_letter_queue": "s2b-events-dlq"
}]
}

Locally, five requests arrived in Send2Bucket as one batch of five, and a consumer that got a 503 was retried and delivered on the next attempt. Queue limits: 100 messages per batch, 128 KB per message. On Workers Free, Queues includes 10,000 operations a day and keeps messages for 24 hours; see Queues pricing.

Limits and costs​

  • Send2Bucket. It bills each event's JSON as stored, so batching saves requests, not bytes. See Plans and billing.
  • Workers. Each send is one subrequest. The queue adds Queues operations on top.
  • Storage. Your provider bills storage and requests on the bucket. A busy stream writes about one object a minute, plus one per 16 MiB.
  • Retention. Objects stay until you delete them. Set a lifecycle rule on <prefix>/s2b/ to expire them.

Other ways to get events out of a Worker​

OptionWhat it doesChoose it when
Workers Analytics EnginewriteDataPoint() with up to 20 strings and 20 numbers per point, queried with a SQL API. Data is kept three months and can be sampled.You want counters and dashboards inside Cloudflare, not raw events you keep.
Workers LogpushSends request metadata, console.log() messages and exceptions to a Logpush destination, which can be Send2Bucket's /v1/events/json. Workers Paid; logs and exceptions together are truncated past 16,384 characters.You want the Worker's logs, not structured events. See Log drains.
Workers OpenTelemetry exportSends the Worker's traces and logs to an OTLP endpoint, in the OTLP JSON encoding, with custom headers. Set the destinations to https://api.send2bucket.com/v1/traces and /v1/logs with an Authorization: Bearer <key> header.You want the Worker's traces and logs as OpenTelemetry records. See OTLP/HTTP.
Basin Pipelines (formerly Cloudflare Pipelines)HTTP endpoint or Worker binding, optional SQL transforms, writes JSON, Parquet or Iceberg to R2. Workers Paid.The data stays in R2. See Send2Bucket vs Cloudflare Pipelines.
An R2 bindingThe Worker writes objects to R2 itself.You batch and name objects yourself, since one object per request means many small files.

Send2Bucket fits when the events should land as raw JSON in a bucket you choose, including S3 or Cloud Storage outside Cloudflare, with the same API your other services and OpenTelemetry exporters use.