# Pre-aggregate events and OpenTelemetry spans into metrics

Start with a stream that delivers to a bucket. Add these three [aggregation rules](../aggregation.md), then query their output in DuckDB:

- revenue per minute and country, from `order.paid` events, keeping the raw orders;
- page views per minute and path, without storing the raw `page.view` events;
- request count, errors and p99 latency per minute and route, from OpenTelemetry server spans.

## Before you start

- A stream that delivers to a verified bucket destination, and its ingest key. [Quick start](../quick-start.md) sets one up. Table destinations work the same way, with the [DuckDB](../querying/duckdb.md) connection for your catalog.
- An account key (`s2b_acct_…`) for the [Management API](../management-api.md), on Pro or Team.

```bash
export S2B_API_KEY=s2b_ingest_...
export S2B_ACCOUNT_KEY=s2b_acct_...
export S2B_STREAM_ID=<stream_id>
```

## 1. Add the rules

`PATCH` replaces the stream's rules with this list:

```bash
curl -X PATCH "https://api.send2bucket.com/v1/manage/streams/$S2B_STREAM_ID" \
  -H "Authorization: Bearer $S2B_ACCOUNT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"aggregation_rules": [
    {"name": "revenue_by_country", "signal": "event", "interval": "1m",
     "match": {"event": "order.paid"}, "by": ["country"], "value": "cents",
     "outputs": ["sum", "avg"]},
    {"name": "page_views", "signal": "event", "interval": "1m",
     "match": {"event": "page.view"}, "by": ["path"], "keep_input": false},
    {"name": "http_server", "signal": "span", "interval": "1m",
     "match": {"kind": 2}, "by": ["resource.service.name", "name", "status_code"],
     "outputs": ["avg", "max", "quantiles(0.5, 0.99)"]}
  ]}'
```

- `revenue_by_country` keeps the raw orders, since `keep_input` defaults to `true`, and adds a `sum` and `avg` of `cents` per country.
- `page_views` counts views per path and sets `keep_input` to `false`. No other rule matches page views, so they are no longer delivered raw.
- `http_server` reads server spans (`kind` 2). Spans aggregate `duration_ms` without a `value`. Grouping by `status_code` splits errors (2) from the rest.

The response is the stream with its `aggregation_rules`. A rule Send2Bucket cannot use comes back as `400` with a `detail` such as `rule 3: by: unknown span field "route"`.

## 2. Send events

This script posts 20 orders across three countries and 30 page views across three paths in one request:

```bash
python3 - > /tmp/s2b-events.json <<'PY'
import json
countries = ["SG", "US", "DE"]
paths = ["/", "/pricing", "/docs"]
events = [{"event": "order.paid", "order_id": f"ord_{i}", "country": countries[i % 3], "cents": 1000 + 250 * i} for i in range(20)]
events += [{"event": "page.view", "path": paths[i % 3], "user": f"u{i % 7}"} for i in range(30)]
print(json.dumps(events))
PY
curl -s -o /dev/null -w "%{http_code}\n" https://api.send2bucket.com/v1/events \
  -H "Authorization: Bearer $S2B_API_KEY" -H "Content-Type: application/json" \
  --data-binary @/tmp/s2b-events.json
```

It prints `204`. Usage is counted after rules run: the dropped page views are not billed and take no storage in your bucket.

## 3. Send spans

Point an OpenTelemetry SDK at Send2Bucket with the standard exporter variables:

```bash
pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
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"
```

This script stands in for a web service: 100 server spans over two routes, where `GET /cart` is slower and fails one time in five:

```python
import random, time
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.trace import SpanKind, Status, StatusCode

provider = TracerProvider()  # service.name comes from OTEL_SERVICE_NAME
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
tracer = provider.get_tracer("checkout.http")
random.seed(7)
for i in range(100):
    route = "GET /cart" if i % 2 else "GET /products"
    with tracer.start_as_current_span(route, kind=SpanKind.SERVER) as span:
        time.sleep(random.uniform(0.001, 0.02 if route == "GET /cart" else 0.005))
        if route == "GET /cart" and i % 10 == 1:
            span.set_status(Status(StatusCode.ERROR))
provider.shutdown()
```

The raw spans are still delivered: `http_server` keeps its input.

## 4. Read the metrics

A minute's rows are written about a second after the minute ends and delivered on the usual schedule, so they land within two minutes on Trial, Pro and Team. Create the `records` view from [DuckDB](../querying/duckdb.md) for your bucket:

```sql
INSTALL httpfs; LOAD httpfs;
CREATE SECRET s2b_bucket (TYPE s3, PROVIDER credential_chain, REGION 'us-east-1');

CREATE VIEW records AS
SELECT * FROM read_json(
  's3://<bucket>/<prefix>/s2b/stream=*/date=*/hour=*/*.ndjson.gz',
  format = 'newline_delimited',
  hive_partitioning = true,
  columns = {v: 'INTEGER', delivery_batch_id: 'VARCHAR', batch_id: 'VARCHAR',
             received_at: 'TIMESTAMPTZ', signal: 'VARCHAR',
             resource: 'JSON', scope: 'JSON', data: 'JSON'});
```

Aggregate rows have `signal` `aggregate`, and the raw page views are gone:

```sql
SELECT signal, count(*) AS records FROM records GROUP BY ALL ORDER BY ALL;
```

```text
┌───────────┬─────────┐
│  signal   │ records │
├───────────┼─────────┤
│ aggregate │       9 │
│ event     │      20 │
│ span      │     100 │
└───────────┴─────────┘
```

Revenue per minute and country:

```sql
SELECT (data->>'$.window_start')::TIMESTAMPTZ AS minute,
       data->>'$.group.country' AS country,
       (data->>'$.count')::INTEGER AS orders,
       (data->>'$.sum')::DOUBLE / 100 AS revenue_usd,
       round((data->>'$.avg')::DOUBLE / 100, 2) AS avg_order_usd
FROM records
WHERE signal = 'aggregate' AND data->>'$.rule' = 'revenue_by_country'
ORDER BY minute, country;
```

```text
┌──────────────────────────┬─────────┬────────┬─────────────┬───────────────┐
│          minute          │ country │ orders │ revenue_usd │ avg_order_usd │
├──────────────────────────┼─────────┼────────┼─────────────┼───────────────┤
│ 2026-11-23 00:46:00+00   │ DE      │      6 │       202.5 │         33.75 │
│ 2026-11-23 00:46:00+00   │ SG      │      7 │       227.5 │          32.5 │
│ 2026-11-23 00:46:00+00   │ US      │      7 │       245.0 │          35.0 │
└──────────────────────────┴─────────┴────────┴─────────────┴───────────────┘
```

Requests, errors and p99 latency of successful requests per route. Each route has a row per `status_code`, so add the counts and pick the p99 of the rows that are not errors:

```sql
SELECT (data->>'$.window_start')::TIMESTAMPTZ AS minute,
       data->>'$.group.name' AS route,
       sum((data->>'$.count')::INTEGER) AS requests,
       coalesce(sum((data->>'$.count')::INTEGER)
         FILTER (WHERE (data->>'$.group.status_code')::INTEGER = 2), 0) AS errors,
       round(max((data->>'$.quantiles."0.99"')::DOUBLE)
         FILTER (WHERE (data->>'$.group.status_code')::INTEGER <> 2), 1) AS ok_p99_ms
FROM records
WHERE signal = 'aggregate' AND data->>'$.rule' = 'http_server'
GROUP BY ALL
ORDER BY minute, route;
```

```text
┌──────────────────────────┬───────────────┬──────────┬────────┬───────────┐
│          minute          │     route     │ requests │ errors │ ok_p99_ms │
├──────────────────────────┼───────────────┼──────────┼────────┼───────────┤
│ 2026-11-23 00:47:00+00   │ GET /cart     │       50 │     10 │      19.9 │
│ 2026-11-23 00:47:00+00   │ GET /products │       50 │      0 │       5.1 │
└──────────────────────────┴───────────────┴──────────┴────────┴───────────┘
```

## 5. Roll minutes up

Counts and sums add up across windows, so one rule serves any coarser view. Page views per hour:

```sql
SELECT date_trunc('hour', (data->>'$.window_start')::TIMESTAMPTZ) AS hour,
       data->>'$.group.path' AS path,
       sum((data->>'$.count')::INTEGER) AS views
FROM records
WHERE signal = 'aggregate' AND data->>'$.rule' = 'page_views'
GROUP BY ALL
ORDER BY hour, views DESC;
```

```text
┌──────────────────────────┬──────────┬────────┐
│           hour           │   path   │ views  │
├──────────────────────────┼──────────┼────────┤
│ 2026-11-23 00:00:00+00   │ /pricing │     10 │
│ 2026-11-23 00:00:00+00   │ /docs    │     10 │
│ 2026-11-23 00:00:00+00   │ /        │     10 │
└──────────────────────────┴──────────┴────────┘
```

Percentiles do not add up the same way: an hour's p99 is not the largest or the average minute's p99. Windows go up to 15 minutes, so for p99 per quarter hour add a rule with `"interval": "15m"`.

## Notes

- Filter on `window_start`, not on the `hour=` folder: a window ending on the hour is written to the next hour's folder.
- A client that resends a request after a timeout is counted twice, in the aggregates as in the raw records. See [Delivery semantics](../delivery-semantics.md).
- Group by bounded fields. A rule grouped by user or trace ID writes a row per user or trace every minute.
- To keep these rows in a bucket of their own, give a rule an `output_stream_id`: see [Send rows to another bucket](../aggregation.md#send-rows-to-another-bucket).
- Every rule, field and output is in [Stream aggregation](../aggregation.md).
