# Events and OpenTelemetry to R2 Data Catalog (Iceberg)

Cloudflare’s [Basin Catalog](https://developers.cloudflare.com/basin-catalog/), formerly R2 Data Catalog, manages Iceberg tables in an R2 bucket. To ingest JSON events or OTLP, send them to Send2Bucket. Each delivery batch creates one snapshot in the catalog.

## Pipelines or Send2Bucket?

Cloudflare's own way to fill these tables over HTTP is [Basin Pipelines](https://developers.cloudflare.com/basin-pipelines/), formerly Cloudflare Pipelines: you create a stream, which gets an endpoint at `https://<stream-id>.ingest.cloudflare.com` ([Writing to streams](https://developers.cloudflare.com/basin-pipelines/streams/writing-to-streams/)), and a [Basin Catalog sink](https://developers.cloudflare.com/basin-pipelines/sinks/available-sinks/r2-data-catalog/) writes it to a table.

| You want | Use |
|---|---|
| Producers on Workers, a SQL transform before storage, the lowest price per GB | Basin Pipelines |
| OTLP from SDKs or a Collector without an adapter | Send2Bucket |
| The same events in R2 Data Catalog and in S3, Google Cloud Storage or another catalog | Send2Bucket |

[Send2Bucket vs Cloudflare Pipelines](../compare/send2bucket-vs-cloudflare-pipelines.md) compares price, limits and transforms.

## How it works

```text
curl, SDK or Collector ──HTTPS──▶ api.send2bucket.com ──Iceberg REST──▶ <catalog_uri>
                                                       └─Parquet──────▶ your R2 bucket
```

Send2Bucket commits through DuckDB's Iceberg extension, the client in [Cloudflare's DuckDB example](https://developers.cloudflare.com/basin-catalog/config-examples/duckdb/), which needs DuckDB 1.4.0 or later to write. A `204` for JSON, or a `200` for OTLP, means the batch is stored and will be committed at least once ([Delivery semantics](../delivery-semantics.md)). Batches are committed at least every 10 seconds on Free and every 60 seconds on Trial, Pro and Team.

The table has five columns: `signal_type`, `delivery_batch_id`, `stream_id`, `ingested_at` and `payload`, the record's envelope as JSON text ([Table columns](../delivery-format.md#table-columns)).

## 1. Enable the catalog and create a token

Enable the catalog on a bucket with Wrangler, as [Manage catalogs](https://developers.cloudflare.com/basin-catalog/manage-catalogs/#enable-basin-catalog-on-a-bucket) shows, or select **Create catalog** on the dashboard's **Basin Catalog** page:

```bash
npx wrangler r2 bucket create <bucket>
npx wrangler basin catalog enable <bucket>
```

Note the **Catalog URI** and **Warehouse** it prints. The catalog does not support buckets in a non-default jurisdiction.

Then create an R2 API token, following [Authenticate your Iceberg engine](https://developers.cloudflare.com/basin-catalog/manage-catalogs/#authenticate-your-iceberg-engine):

1. On the **R2 object storage** page, select **Manage API tokens**, then **Create API token**.
2. Under **Permissions**, choose **Admin Read & Write**. Creating tables and committing appends needs write access to both the catalog and R2 storage; **Object Read & Write** does not reach the catalog.
3. Create the token and copy the **Token value**, the **Access Key ID** and the **Secret Access Key**. Cloudflare shows the secret once ([R2 authentication](https://developers.cloudflare.com/r2/api/tokens/)).

In the dashboard, only the Object permissions can be scoped to buckets. To limit a catalog token to one bucket, create it through the API with the `Workers R2 Data Catalog Write` and `Workers R2 Storage Bucket Item Write` permission groups on that bucket, as Cloudflare's example access policy shows.

## 2. Create the namespace

Send2Bucket creates the table but not its namespace. Create one with [DuckDB](../querying/duckdb.md), the same way Cloudflare's example does:

```sql
INSTALL httpfs; LOAD httpfs; INSTALL iceberg; LOAD iceberg;
CREATE SECRET r2_catalog (TYPE iceberg, TOKEN '<token>');
ATTACH '<warehouse>' AS r2 (TYPE iceberg, ENDPOINT '<catalog_uri>', SECRET r2_catalog);
CREATE SCHEMA r2.s2b;
```

[PyIceberg's](https://developers.cloudflare.com/basin-catalog/get-started/) `catalog.create_namespace_if_not_exists("s2b")` does the same.

## 3. Add the destination

Create an ingestion stream in the [dashboard](pathname:///app/) and add an [Apache Iceberg (REST) destination](../destinations/iceberg-rest.md):

| Field | Value for R2 Data Catalog |
|---|---|
| `catalog_uri` | The **Catalog URI** from step 1 |
| `warehouse` | The **Warehouse** from step 1 |
| `namespace` | `s2b` |
| `table` | `events`, or any name; Send2Bucket creates it |
| `token` | The token value |
| `access_key_id`, `secret_access_key` | The same token's Access Key ID and Secret Access Key |
| `region` | `auto` ([R2's S3 API](https://developers.cloudflare.com/r2/api/s3/api/)) |
| `endpoint` | `https://<account_id>.r2.cloudflarestorage.com` |

The catalog hands engines [SigV4 credentials for the data files](https://developers.cloudflare.com/basin-catalog/manage-catalogs/#authenticate-your-iceberg-engine), with the token's R2 permissions, which is why Cloudflare's DuckDB example writes with the token alone. Send2Bucket's form asks for an S3 key as well, so give it the same token's keys and R2 endpoint.

Select Verify. Send2Bucket creates the table, or reuses a compatible one, and the destination becomes `active`. To partition by day, add the spec now, before the first delivery: [OpenTelemetry to Apache Iceberg](./opentelemetry-to-iceberg.md#2-partition-by-day-before-the-first-delivery) shows how with PyIceberg. Copy the stream's API key:

```bash
export S2B_API_KEY=s2b_ingest_...
```

## 4. Send events and OpenTelemetry

`POST /v1/events` takes one JSON object or an array. Each object becomes one row, stored unchanged under `data` in `payload`:

```bash
curl -sS -w '%{http_code}\n' https://api.send2bucket.com/v1/events \
  -H "Authorization: Bearer $S2B_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '[{"event":"order.paid","order_id":"ord_20931","cents":4200},
       {"event":"signup","user_id":"usr_0042","plan":"free"}]'
```

```text
204
```

The request is accepted or rejected as a whole ([API reference](../api-reference.md#post-events)). OpenTelemetry SDKs read the standard variables, so a service that exports OTLP needs no code change:

```bash
export OTEL_SERVICE_NAME=checkout
export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.send2bucket.com
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20$S2B_API_KEY"
```

`http/protobuf` and `http/json` both work. gRPC works at the endpoint in the [API reference](../api-reference.md#otlp-grpc), and a Collector forwards with an `otlphttp` exporter, configured in [OpenTelemetry to Amazon S3](./opentelemetry-to-s3.md#or-keep-the-collector-you-run). Logs, spans and metrics land in the same table as the events, with `signal_type` `log`, `span` or `metric`.

## 5. Query the table

Give readers an **Admin Read only** token: the vended credentials inherit the token's R2 permissions, so a token with R2 write access can write files even through a read-only catalog grant. In DuckDB:

```sql
INSTALL httpfs; LOAD httpfs; INSTALL iceberg; LOAD iceberg;
CREATE SECRET r2_catalog (TYPE iceberg, TOKEN '<read_only_token>');
ATTACH '<warehouse>' AS r2 (TYPE iceberg, ENDPOINT '<catalog_uri>', SECRET r2_catalog);

CREATE VIEW records AS
SELECT signal_type AS signal, ingested_at, delivery_batch_id,
       payload::JSON->'$.resource' AS resource, payload::JSON->'$.data' AS data
FROM r2.s2b.events;
```

Events by name, with revenue from `cents`. Add `ingested_at >= now() - INTERVAL 1 DAY` to read one day; with a day partition, the other days' files are skipped:

```sql
SELECT data->>'$.event' AS event,
       count(*) AS events,
       sum((data->>'$.cents')::INTEGER) / 100 AS revenue_usd
FROM records
WHERE signal = 'event'
GROUP BY ALL
ORDER BY events DESC;
```

```text
┌────────────┬────────┬─────────────┐
│   event    │ events │ revenue_usd │
├────────────┼────────┼─────────────┤
│ page.view  │    177 │        NULL │
│ order.paid │     53 │      4161.0 │
│ email.sent │     47 │        NULL │
│ signup     │     23 │        NULL │
└────────────┴────────┴─────────────┘
```

Log records by service and severity. `service.name` is one entry in the resource's attribute list:

```sql
SELECT (SELECT a->>'$.value.stringValue'
        FROM unnest(json_extract(resource, '$.attributes[*]')) AS t(a)
        WHERE a->>'$.key' = 'service.name') AS service,
       data->>'$.severityText' AS severity,
       count(*) AS logs
FROM records
WHERE signal = 'log'
GROUP BY ALL;
```

```text
┌──────────┬──────────┬───────┐
│ service  │ severity │ logs  │
├──────────┼──────────┼───────┤
│ checkout │ Info     │    20 │
└──────────┴──────────┴───────┘
```

Each delivery batch is one snapshot, so the snapshot list doubles as a delivery log:

```sql
SELECT snapshot_id, timestamp_ms
FROM iceberg_snapshots(r2.s2b.events)
ORDER BY timestamp_ms DESC
LIMIT 5;
```

[Basin SQL](https://developers.cloudflare.com/basin-sql/query-data/), Cloudflare's serverless engine for these tables, runs a query from Wrangler with a token in `WRANGLER_BASIN_SQL_AUTH_TOKEN` that also has Basin SQL permission:

```bash
npx wrangler basin sql query <warehouse> "SELECT signal_type, count(*) FROM s2b.events GROUP BY signal_type"
```

Cloudflare documents catalog settings for PyIceberg, [Apache Spark](../querying/spark.md), [Snowflake](../querying/snowflake.md), [StarRocks](../querying/starrocks.md) and [Trino](../querying/trino.md) under [Connect to Iceberg engines](https://developers.cloudflare.com/basin-catalog/config-examples/). Our engine guides have the SQL for this table's columns, and [Python](../querying/python.md) covers PyIceberg.

## Table maintenance

One snapshot per batch means about 1,440 snapshots and as many small data files a day on a stream that delivers every minute. Basin Catalog can [compact files and expire snapshots](https://developers.cloudflare.com/basin-catalog/table-maintenance/) for you. Turn both on for the catalog, with a token as the service credential:

```bash
npx wrangler basin catalog compaction enable <bucket> --target-size 128 --token <token>
npx wrangler basin catalog snapshot-expiration enable <bucket> --token <token> --older-than-days 7 --retain-last 10
```

If a compaction commit and a Send2Bucket append conflict, the append fails and is retried. Before each retry Send2Bucket looks for the batch's `delivery_batch_id`, so a batch is committed once ([Delivery and retries](../destinations/iceberg-rest.md#delivery-and-retries)).

## Limits and costs

- **Send2Bucket.** A request can be up to 8 MiB decompressed. Send2Bucket bills the stored JSON of each record it accepts ([Plans and billing](../plans-and-billing.md)).
- **Basin Catalog.** From [Basin Catalog pricing](https://developers.cloudflare.com/basin-catalog/platform/pricing/): 1 million catalog operations a month included, then $9.00 per million. Compaction is billed only when on: 10 GB and 1 million objects a month included, then $0.005 per GB processed and $2.00 per million objects. Snapshot expiration is free. The catalog needs an active R2 subscription.
- **R2.** From [R2 pricing](https://developers.cloudflare.com/r2/pricing/) for Standard storage: $0.015 per GB-month, $4.50 per million Class A operations, with 10 GB-month and 1 million Class A operations free each month, and no egress charge.
- **Per delivery.** In our test against a generic REST catalog, each delivery made four catalog requests and wrote three objects (a Parquet data file, a manifest and a manifest list). A stream that delivers every minute makes about 43,200 deliveries a month: roughly 173,000 catalog requests and 130,000 object writes, inside both free allowances if Cloudflare counts them one for one.

## Related

- [Apache Iceberg destination](../destinations/iceberg-rest.md): every field and the access each credential needs.
- [OpenTelemetry to Apache Iceberg](./opentelemetry-to-iceberg.md): typed views over spans and logs, and partitioning.
- [Send2Bucket vs Cloudflare Pipelines](../compare/send2bucket-vs-cloudflare-pipelines.md).
