# 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

```text
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](../delivery-semantics.md).
- [`ctx.waitUntil()`](https://developers.cloudflare.com/workers/runtime-apis/context/#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](pathname:///app/), add a destination, and create an API key on the stream's page. The [Quick start](../quick-start.md) walks through it. For the destination:

| You want the events in | Destination |
|---|---|
| Cloudflare R2 | [S3-compatible storage](../destinations/s3-compatible.md): endpoint `https://<account_id>.r2.cloudflarestorage.com`, region `auto`, and an R2 API token with Object Read & Write on the bucket |
| Amazon S3 | [Amazon S3](../destinations/aws-s3.md), with an IAM role |
| Google Cloud Storage | [Google Cloud Storage](../destinations/gcs.md), 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](https://developers.cloudflare.com/workers/configuration/secrets/) are encrypted and reach the Worker as `env.S2B_API_KEY`:

```bash
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:

```bash
S2B_API_KEY="s2b_ingest_..."
```

The endpoint is not secret, so it goes in `vars` in `wrangler.jsonc`, the [config format](https://developers.cloudflare.com/workers/wrangler/configuration/) Cloudflare recommends for new projects:

```jsonc
{
  "$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()`:

```js
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](https://developers.cloudflare.com/workers/platform/limits/) (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](../api-reference.md#post-events).
- **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`](https://developers.cloudflare.com/workers/development-testing/) runs the Worker on your machine in workerd, reads `.dev.vars`, and sends the events to the real endpoint:

```bash
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:

```text
✘ [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](https://developers.cloudflare.com/workers/observability/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:

```json
{"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](../delivery-format.md) describes the envelope and the object keys.

[DuckDB](../querying/duckdb.md) reads the objects in place. With the secret from its [S3-compatible storage](../querying/duckdb.md#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`:

```sql
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](../querying/index.md).

## 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](https://developers.cloudflare.com/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:

```js
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`:

```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](https://developers.cloudflare.com/queues/platform/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](https://developers.cloudflare.com/queues/platform/pricing/).

## Limits and costs

- **Send2Bucket.** It bills each event's JSON as stored, so batching saves requests, not bytes. See [Plans and billing](../plans-and-billing.md).
- **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

| Option | What it does | Choose it when |
|---|---|---|
| [Workers Analytics Engine](https://developers.cloudflare.com/analytics/analytics-engine/) | `writeDataPoint()` 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 Logpush](https://developers.cloudflare.com/workers/observability/logs/logpush/) | Sends request metadata, `console.log()` messages and exceptions to a Logpush destination, which can be Send2Bucket's [`/v1/events/json`](../api-reference.md#log-drains). Workers Paid; logs and exceptions together are truncated past 16,384 characters. | You want the Worker's logs, not structured events. See [Log drains](./log-drains.md). |
| [Workers OpenTelemetry export](https://developers.cloudflare.com/workers/observability/exporting-opentelemetry-data/) | Sends 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](../api-reference.md#otlp-http). |
| [Basin Pipelines](https://developers.cloudflare.com/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](../compare/send2bucket-vs-cloudflare-pipelines.md). |
| An [R2 binding](https://developers.cloudflare.com/r2/api/workers/workers-api-reference/) | The 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.
