---
title: Roll up a stream
description: Keep counts, sums and other totals of a stream per hour or day, grouped by a field, for longer than the entries themselves.
related:
  - /events/keep-a-stream
  - /sdk/stream
  - /realtime/follow-a-stream-from-an-app
---

A chart of sales per hour needs every entry of each hour, and the stream's retention may already have dropped them. Reading every entry again on each request also repeats the same work.

A rollup keeps totals of a stream per time bucket, updated with every append. Its buckets stay for as long as you choose, however long the entries stay.

## Declare a rollup

The `rollups` option of [`stream`](/sdk/stream) names each rollup. `every` sets the bucket's length, and `fields` sets what each bucket keeps, with the [`agg`](/sdk/stream) helpers.

```ts luna/lunas/shop.ts
import { agg, defineLuna, stream, t } from "luna";

const sale = t.object({ product: t.string(), amount: t.int() });

export const Shop = defineLuna({
  name: "Shop",
  key: { id: t.string() },
  streams: {
    sales: stream(sale, {
      retention: { maxAge: "7d" },
      rollups: {
        hourly: {
          every: "1h",
          keep: "90d",
          fields: { revenue: agg.sum("amount"), largest: agg.max("amount") },
        },
      },
    }),
  },
  handlers: (h) => ({
    sell: h({ args: { product: t.string(), amount: t.int() } }, (ctx, a) => {
      ctx.streams.sales.append({ product: a.product, amount: a.amount });
    }),
  }),
});
```

Entries stay 7 days here, and the hourly buckets stay 90 days. Without `keep`, buckets stay forever.

Buckets start at fixed times since the epoch, in UTC. An hourly bucket starts on the hour, and a `"1d"` bucket starts at midnight UTC.

## Choose the aggregates

Each field of `fields` is one aggregate. A path such as `"amount"` or `"customer.country"` names a value inside each entry.

| Aggregate | Each bucket keeps |
| --- | --- |
| `agg.count()` | How many entries it holds |
| `agg.count(path)` | How many of its entries have a value at `path` |
| `agg.sum(path)` | The total of the numbers at `path`, or `0` when there are none |
| `agg.avg(path)` | Their mean, or `null` when there are none |
| `agg.min(path)`, `agg.max(path)` | The smallest or the largest number at `path`, or `null` |
| `agg.first(path)`, `agg.last(path)` | The value at `path` of the first or the last entry that has one |

`sum`, `avg`, `min` and `max` count only numbers. A value that is not a number is passed over.

## Read the buckets

`rollup` returns a rollup's buckets, oldest first. Each bucket has `at`, the time it starts in milliseconds since the epoch. It also has `count`, the number of its entries, and one field per aggregate.

```ts luna/lunas/shop.ts
lastDay: h({ query: true }, (ctx) => {
  return ctx.streams.sales.rollup("hourly", { from: ctx.now() - 86_400_000 });
}),
```

| Option | Does |
| --- | --- |
| `from` | Starts with the bucket that holds this time, in milliseconds since the epoch. All kept buckets by default |
| `to` | Stops before the bucket that starts at or after this time |
| `by` | Returns only this group, for a rollup with `by` |
| `limit` | Returns at most this many buckets. The default and the most are both 1,000 |

## Group by a field

With `by`, a rollup keeps a bucket per time and per value at that path. Each bucket then also has a `by` field holding the value as text.

```ts luna/lunas/shop.ts
byProduct: { every: "1d", by: "product", fields: { revenue: agg.sum("amount") } },
```

Pass `by` to `rollup` to read one product's buckets.

```ts luna/lunas/shop.ts
const tea = ctx.streams.sales.rollup("byProduct", { by: "tea" });
```

An entry with no value at the `by` path is left out of that rollup.

## Change a rollup

A rollup counts the entries appended after it is declared. Adding one to a stream that already has entries does not count those entries.

:::warning
Changing a rollup's `every`, `by` or fields deletes its buckets when each luna moves to the new version. Removing a rollup deletes its buckets too. A deploy that does either asks you to confirm first. Changing only `keep` keeps the totals. To keep the old totals through another change, declare the new rollup under another name.
:::

## Next steps

- [Keep a stream](/events/keep-a-stream) covers appending, reading and retention.
- [Subscribe to a stream](/events/subscribe-to-a-stream) runs a handler in another luna for each entry.
- [Follow a stream from an app](/realtime/follow-a-stream-from-an-app) shows entries in an app as they arrive.
