# Stream events and OpenTelemetry into DuckLake

Send JSON events over HTTP or export OTLP to a DuckLake table. Send2Bucket appends each batch in one transaction and commits at least once a minute while data flows. DuckLake stores metadata in your SQL catalog and data in Parquet files.

## How it works

```text
POST /v1/events (JSON) ─┐
                        ├─▶ api.send2bucket.com ──60 s or 16 MiB──▶ one DuckLake transaction
OTLP logs/traces/metrics┘                                        catalog: your PostgreSQL
                                                                 data: Parquet under your data path
```

The table has four columns, `signal_type`, `delivery_batch_id`, `ingested_at` and `payload`. `payload` is the record's envelope as JSON, so new event properties and new span attributes never need a schema change. [Delivery format](../delivery-format.md) describes it.

## 1. Create the catalog and the destination

1. Create a [PostgreSQL](../querying/postgres.md#ducklake-catalogs-in-postgresql) database for the catalog and a user for Send2Bucket that owns it. Any PostgreSQL reachable over TLS works, including Supabase, Neon or RDS.
2. In the [dashboard](pathname:///app/), create an ingestion stream and add a DuckLake destination: the catalog DSN, a data path such as `s3://<bucket>/lake/`, the table name, and an S3 key that can read and write under the data path.
3. Select Verify. Send2Bucket attaches the catalog and creates the table if it is missing.

[DuckLake](../destinations/ducklake.md) lists every field, including `metadata_schema` for keeping the catalog's tables in their own PostgreSQL schema.

## 2. Send events and telemetry

JSON events, one object or an array, from any HTTP client:

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

```json
{"bytes":225,"accepted":3}
```

From server code, `fetch` works the same in Node.js, Deno, Supabase Edge Functions and Cloudflare Workers. Keep the key on the server:

```js
// Server-side only: the API key must never reach a browser.
export async function track(apiKey, event, properties = {}) {
  const res = await fetch('https://api.send2bucket.com/v1/events', {
    method: 'POST',
    headers: {authorization: `Bearer ${apiKey}`, 'content-type': 'application/json'},
    body: JSON.stringify({event, ...properties, sent_at: new Date().toISOString()}),
  });
  if (!res.ok) throw new Error(`Send2Bucket ${res.status}: ${await res.text()}`);
  return res.json();
}
```

OpenTelemetry SDKs send to the same stream with the standard variables:

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

## 3. Query the lake

Attach the catalog read-only from [DuckDB](../querying/duckdb.md#ducklake), with a catalog user and storage key that can only read:

```sql
INSTALL httpfs; LOAD httpfs; INSTALL ducklake; LOAD ducklake;
CREATE SECRET s2b_storage (TYPE s3, KEY_ID '<access_key_id>', SECRET '<secret_access_key>', REGION '<region>');
ATTACH 'ducklake:postgres:host=<host> dbname=<database> user=<reader> password=<password>' AS lake
  (METADATA_SCHEMA '<metadata_schema>', READ_ONLY);

CREATE VIEW product_events AS
SELECT ingested_at,
       p->>'$.data.event' AS event,
       p->>'$.data.user_id' AS user_id,
       p->'$.data' AS properties
FROM (SELECT ingested_at, payload::JSON AS p FROM lake.main.events WHERE signal_type = 'event');
```

Omit `METADATA_SCHEMA` if you did not set one. Events, users and revenue per event name, after the `curl` above on a new table:

```sql
SELECT event, count(*) AS events, count(DISTINCT user_id) AS users,
       sum((properties->>'$.cents')::INTEGER) / 100 AS revenue_usd
FROM product_events
GROUP BY ALL
ORDER BY events DESC;
```

```text
┌────────────┬────────┬───────┬─────────────┐
│   event    │ events │ users │ revenue_usd │
├────────────┼────────┼───────┼─────────────┤
│ order.paid │      2 │     2 │        57.0 │
│ signup     │      1 │     1 │        NULL │
└────────────┴────────┴───────┴─────────────┘
```

Spans and logs are in the same table with `signal_type` `span` and `log`; the views in [OpenTelemetry to Apache Iceberg](./opentelemetry-to-iceberg.md#4-query-with-typed-views) work on `lake.main.events` with the table name changed.

## Snapshots, time travel and change feeds

Each delivery batch is one DuckLake snapshot:

```sql
SELECT snapshot_id, snapshot_time, changes
FROM ducklake_snapshots('lake')
ORDER BY snapshot_id DESC
LIMIT 5;
```

Read the table as it was at a snapshot, for example to rerun a report on yesterday's data:

```sql
SELECT count(*) AS records FROM lake.main.events AT (VERSION => <snapshot_id>);
```

Rows added between two snapshots, for loading only what is new into another system:

```sql
SELECT signal_type, delivery_batch_id, ingested_at
FROM ducklake_table_insertions('lake', 'main', 'events', <from_snapshot>, <to_snapshot>);
```

## Maintenance

Depending on the lake's data inlining setting, small batches can be stored inline in the catalog database rather than as Parquet files, and a busy stream adds about 1,440 snapshots a day. Run maintenance from a writable attach, for example daily:

```sql
CALL ducklake_flush_inlined_data('lake');
CALL ducklake_merge_adjacent_files('lake');
CALL ducklake_expire_snapshots('lake', older_than => now() - INTERVAL 7 DAY);
CALL ducklake_cleanup_old_files('lake', older_than => now() - INTERVAL 7 DAY);
```

Flushing moves inlined rows to Parquet, merging compacts small files, and expiring and cleaning up limits time travel to seven days and deletes the files no snapshot uses. Send2Bucket's appends commit alongside these calls; a conflicting append is retried, and Send2Bucket checks for the batch's `delivery_batch_id` first, so nothing is added twice.

## Limits and costs

- A request can be up to 8 MiB decompressed; a single event, log record, span or metric has no separate limit.
- Send2Bucket bills the stored JSON of each record it accepts ([Plans and billing](../plans-and-billing.md)). Your PostgreSQL host bills the catalog and your storage provider the Parquet files.
- A client retry after a lost response is stored again: deduplicate on your own event ID if that matters. See [Delivery semantics](../delivery-semantics.md).
