# Stream aggregation

An aggregation rule groups matching records from a stream by time window and the fields you choose. Send2Bucket writes one summary row per group per window to a bucket or table. Rules can process JSON events, logs, spans and metric points.

Use a rule for a recurring calculation, such as revenue per minute or p99 latency per route, or when you want a metric from high-volume records without storing every record. [Pre-aggregate events and spans into metrics](./guides/stream-aggregation.md) walks through it end to end.

## How it works

```text
request ──▶ rules ──▶ window state ──▶ aggregate rows ──▶ bucket or table
   │                  (with the batch)  (window ended)
   └──▶ raw records, unless every rule they match drops them
```

- A request's contribution to each window is committed in the same durable write as its batch, before Send2Bucket answers `2xx`. An acknowledged record is counted once, also across restarts.
- Windows are aligned to the interval in UTC and follow acceptance time (`received_at`), not timestamps inside the records.
- About a second after a window ends, its rows become a batch with `signal` `aggregate`. That batch is delivered like any other: within 10 seconds on Free and 60 seconds on Trial, Pro and Team.

## Rules

A stream has up to 20 rules, set on its dashboard page or through the [Management API](#set-rules). This rule sums `order.paid` revenue per country per minute:

```json
{
  "name": "revenue_by_country",
  "signal": "event",
  "interval": "1m",
  "match": {"event": "order.paid"},
  "by": ["country"],
  "value": "cents",
  "outputs": ["sum", "avg", "quantiles(0.5, 0.99)"],
  "keep_input": true
}
```

| Field | Required | Meaning |
|---|---|---|
| `name` | yes | Lowercase letters, digits and underscores, starting with a letter, up to 64 characters, unique in the stream. Each row carries it as `rule`. |
| `signal` | yes | `event`, `log`, `span` or `metric`. A rule reads records of one signal. |
| `interval` | yes | The window length: `10s`, `30s`, `1m`, `5m` or `15m`. Windows are at most 15 minutes and never span two hourly folders. |
| `match` | no | [Fields](#fields) and the values they must equal; a list matches any of its values. Up to 8 fields and 32 values each. Without `match`, every record of the signal matches. |
| `by` | no | Up to 8 fields whose values group the rows. Without `by`, a window has one row. |
| `value` | no | The numeric field that `sum`, `min`, `max`, `avg`, `last` and quantiles read. Spans default to `duration_ms` and metrics to `value`; events and logs need one for those outputs. |
| `outputs` | no | Any of the [outputs](#outputs) below. Defaults to `["count"]`. |
| `keep_input` | no | `true` by default: matching records are still delivered raw. See [Keeping or dropping raw records](#keeping-or-dropping-raw-records). |
| `output_stream_id` | no | Another stream of the workspace whose destination receives this rule's rows. Without it, rows go to this stream's destination. See [Send rows to another bucket](#send-rows-to-another-bucket). |

Send2Bucket checks rules when you save them and rejects an invalid one with the reason, such as `rule 2: interval must be one of 10s, 30s, 1m, 5m, 15m`.

## Fields

| Signal | Fields |
|---|---|
| `event` | Any key of the event. `user.plan` reads the `plan` key of the `user` object; a key that itself contains dots is read first. |
| `log` | `severity_text`, `severity_number`, `body` (string bodies), plus the common fields. |
| `span` | `name`, `kind`, `status_code`, `duration_ms` (end minus start, in milliseconds), plus the common fields. |
| `metric` | `name`, `unit`, `value` (the data point's number), plus the common fields. `attributes.<key>` reads the data point's attributes. |

The common fields of OpenTelemetry records are `resource.<attribute>`, such as `resource.service.name`, `attributes.<attribute>`, such as `attributes.http.route`, `scope.name` and `scope.version`.

- Enums are the numbers in the delivered JSON: span `kind` 2 is a server span, `status_code` 2 is an error, and `severity_number` 17 is `ERROR`.
- Gauge and sum metrics give one sample per number data point. Histograms, exponential histograms and summaries never match a rule, so they are always delivered raw.
- Numbers match numbers whatever their notation, so `1` matches `1.0`. Strings match exactly. A missing field matches nothing and groups as `null`.
- Records sent to the log drain endpoints, such as `/v1/events/vercel` or `/v1/events/json`, are not matched by rules and are always delivered raw. `POST /v1/events` itself is matched.

## Outputs

| Output | Row field | Value |
|---|---|---|
| `count` | `count` | Records that matched. Always included. |
| `sum` | `sum` | Sum of `value`. |
| `min`, `max` | `min`, `max` | Smallest and largest `value`. |
| `avg` | `avg` | `sum` divided by the number of records with a numeric `value`. |
| `last` | `last` | The `value` of the last record accepted in the window. |
| `quantiles(0.5, 0.99)` | `quantiles` | One estimate per quantile from 0 to 1, within 1% of the exact value. |

A record whose `value` is missing or not a number counts in `count` only. Value outputs are 64-bit floats, and `null` when no record in the window had a number.

## Aggregate rows

Each row is an envelope line like any record ([Delivery format](./delivery-format.md)), with `signal` `aggregate` and the window in `data`:

```json
{"v":1,"delivery_batch_id":"dlv_00361rdoo3jq0b8ujac5tr9fpom8k","stream_id":"4f1c2b9e-8d3a-4e7b-9c51-0a6f2d8e3b17","batch_id":"bat_00361rdoib95t792m6io69nlngrd2","received_at":"2026-11-23T08:53:00.409438Z","signal":"aggregate","data":{"rule":"http_server","source_stream_id":"4f1c2b9e-8d3a-4e7b-9c51-0a6f2d8e3b17","window_start":"2026-11-23T08:52:00Z","window_end":"2026-11-23T08:53:00Z","group":{"resource.service.name":"checkout","name":"GET /cart","status_code":0},"count":40,"avg":11.048173799999997,"max":20.008991,"quantiles":{"0.5":10.913817739716837,"0.99":19.886670240866188}}}
```

| `data` field | Meaning |
|---|---|
| `rule` | The rule's `name`. |
| `source_stream_id` | The stream whose records the rule counted. The envelope's `stream_id` is the stream that received the row: the same one, or the rule's output stream. |
| `window_start`, `window_end` | The window, start included and end excluded, in UTC. |
| `group` | The `by` fields and their values. |
| `count` and the outputs | In the order the rule lists them. |

- Rows sit in the folder of the stream that receives them, in the `hour=` folder of when they were written, a moment after the window ended. Filter on `window_start` rather than `hour`: a window ending on the hour lands in the next hour's folder.
- Table destinations get one row per window and group, with `signal_type` `aggregate`.

## Keeping or dropping raw records

`keep_input` decides whether matching records are also delivered raw. A record is dropped only when every rule it matches sets `keep_input` to `false`; a record that no rule matches is always kept.

| Rules a record matches | Raw record |
|---|---|
| None | Delivered |
| Only rules with `keep_input: false` | Dropped |
| At least one rule with `keep_input: true` | Delivered |

A metric is one raw line with all its data points, so it is dropped only when every one of its points would be. Usage is counted after rules run, on the raw records left for delivery: dropping raw records lowers your Send2Bucket bill as well as your storage. Aggregate rows count their `data` JSON when their window closes. See [Plans and billing](./plans-and-billing.md).

## Send rows to another bucket

Set `output_stream_id` to send a rule's rows to another stream of the workspace, and so to that stream's bucket or table. Use it to keep metrics apart from raw records, for example with a longer retention. The rows become records of that stream, under its folder, and `source_stream_id` names the stream they came from, so several streams can send rows to one metrics stream.

```json
{"name": "revenue_by_country", "signal": "event", "interval": "1m",
 "match": {"event": "order.paid"}, "by": ["country"], "value": "cents",
 "outputs": ["sum", "avg"], "output_stream_id": "9a7d3c41-2b6e-4f08-8c15-5e2d7f1a0b93"}
```

The rows of that rule land under the output stream's folder in its bucket, and no longer in this stream's:

```text
<metrics prefix>/s2b/stream=9a7d3c41-2b6e-4f08-8c15-5e2d7f1a0b93/date=2026-11-23/hour=08/dlv_00361rdoo3jq12aeqrihmhfdaq8nq.ndjson.gz
```

- The output stream must be another stream of the same workspace with a destination. It needs no API key or records of its own.
- While a rule sends rows to it, the output stream cannot be deleted or lose its destination. The refusal names the rule, such as `stream metrics receives aggregate rows from rule revenue_by_country of stream web`.
- The output stream's destination is chosen when each request is accepted, as a raw batch's is. If that destination fails, the rows wait and are retried, and the error shows on the output stream. Raw records of the source stream are not held up.
- `keep_input` still decides what happens to this stream's raw records; it does not follow the rows.

## Timing and accuracy

- **At least once, like raw records.** A client that resends a request after a timeout is counted twice, as its records are stored twice ([Delivery semantics](./delivery-semantics.md)). Send2Bucket's own retries to your destination never write a row twice.
- **Late commits.** A request accepted just before a window closed but committed just after it counts in the next window, so no window is written twice.
- **Rule changes.** Changing anything but `keep_input` starts new windows under the new definition, and the open windows of the old one still close and are delivered. In the minute of a change, a window can have two rows for the same rule and group: add their counts and sums. Deleting a rule also delivers its open windows.
- **Combining windows.** Add `count` and `sum`, take the smallest `min` and largest `max`, and divide summed `sum` by summed `count` for an average when every record had a value. Quantiles do not combine: choose the interval you want to read percentiles at, up to 15 minutes.
- **Cardinality.** Each distinct `by` tuple is a row per window. Group by bounded fields such as a route or a country, not a user or trace ID.

## Set rules

On any plan, owners, admins and members build rules under **aggregation rules** on the stream's page in the [dashboard](pathname:///app/): start from a template or **+ new rule**, pick the signal, conditions, window, grouping, outputs, where rows go and what happens to raw records, and check the preview of the row it writes. The preview also shows the rule as JSON for the Management API. Viewers see the list only.

On Pro and Team, the [Management API](./management-api.md) replaces a stream's rules. `[]` removes them:

```bash
curl -X PATCH https://api.send2bucket.com/v1/manage/streams/<stream_id> \
  -H "Authorization: Bearer $S2B_ACCOUNT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"aggregation_rules": [{"name": "page_views", "signal": "event", "interval": "1m", "match": {"event": "page.view"}, "by": ["path"], "keep_input": false}]}'
```

An invalid rule returns `400` with `invalid_request` and a `detail` naming the rule and the problem. Rules apply to requests accepted after the change.

## Query aggregate rows

Read them like any record. With the `records` view from [DuckDB](./querying/duckdb.md), 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 │
└──────────────────────────┴─────────┴────────┴─────────────┴───────────────┘
```

## Limits

| Limit | Value |
|---|---|
| Rules per stream | 20 |
| `match` fields, values per field | 8, 32 |
| `by` fields | 8 |
| `interval` | `10s`, `30s`, `1m`, `5m` or `15m` |
