---
title: stream
description: Declare an append-only log in a luna, read and roll it up with ctx.streams, and follow another luna's stream with ctx.subscribe.
related:
  - /events/keep-a-stream
  - /events/roll-up-a-stream
  - /events/subscribe-to-a-stream
---

`stream` declares an append-only log of typed entries that a luna keeps in its own database, under the luna type's `streams` option.

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

export const Room = defineLuna({
  name: "Room",
  key: { id: t.string() },
  streams: {
    messages: stream(t.object({ from: t.string(), text: t.string() }), { retention: { maxCount: 1000 } }),
  },
  handlers: (h) => ({
    say: h({ args: { from: t.string(), text: t.string() } }, (ctx, m) => ctx.streams.messages.append(m)),
    history: h({ args: { from: t.int() }, query: true }, (ctx, { from }) => ctx.streams.messages.read({ from, limit: 50 })),
  }),
});
```

## Reference

### stream(type, options)

| Prop | Type | Default | Description |
| - | - | - | - |
| `type` | `Ty<T>` | - | Each entry's type, built with `t`. |
| `options.retention?` | `Retention` | `{}` | Which entries are kept, and with no limit set, every entry is kept for good. |
| `options.rollups?` | `Record<string, Rollup>` | - | Time-series aggregates kept up to date with every append. |
| `options.live?` | `boolean` | `false` | Each append is kept and readable at once, on its own, rather than when the handler commits. |

### Retention

An entry is dropped once it passes any limit you set.

| Prop | Type | Default | Description |
| - | - | - | - |
| `maxAge?` | `string \| number` | - | Drops entries older than this, as a duration such as `"7d"` or milliseconds. |
| `maxCount?` | `number` | - | Keeps at most this many entries, the newest. |
| `maxBytes?` | `number` | - | Keeps at most this many bytes of entries as JSON, oldest dropped first, and the newest always stays. |

### Rollup

| Prop | Type | Default | Description |
| - | - | - | - |
| `every` | `string \| number` | - | The length of each bucket, from 1 second to 1 year. |
| `keep?` | `string \| number` | - | How long buckets are kept, at least one bucket long, and with none set, for good. |
| `by?` | `string` | - | A dotted path into each entry: buckets are kept per value found there. |
| `fields` | `Record<string, Aggregate>` | - | The aggregates of each bucket, made with `agg`, at most 32. |

A stream has at most 16 rollups. An aggregate's name is letters, digits and `_`, at most 64 characters, and is never `at`, `by` or `count`.

### agg

Each takes a dotted path into an entry's data, such as `"ms"` or `"req.route"`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `count(path?)?` | `Aggregate` | - | Entries in the bucket, or with a path, those where it holds a value. |
| `sum(path)?` | `Aggregate` | - | The sum of the values. |
| `min(path)?` | `Aggregate` | - | The smallest value. |
| `max(path)?` | `Aggregate` | - | The largest value. |
| `avg(path)?` | `Aggregate` | - | The mean of the values. |
| `first(path)?` | `Aggregate` | - | The value of the bucket's first entry. |
| `last(path)?` | `Aggregate` | - | The value of the bucket's last entry. |

### Stream

A handler reaches each stream as `ctx.streams.<name>`.

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The stream's name. |
| `append(data)` | `number` | - | Appends an entry and returns its offset. |
| `appendMany(data[])` | `number` | - | Appends entries in order and returns the first one's offset. |
| `read(opts?)` | `StreamPage<T>` | - | Up to `limit` entries from offset `from` on, with `from` 0 and `limit` 100 by default, and 1,000 at most. |
| `rollup(name, opts?)` | `RollupRow[]` | - | A rollup's buckets, oldest first, from `from` up to before `to`, only group `by` if given, at most `limit` and 1,000. |

`from` and `to` of `rollup` are milliseconds since the epoch.

### StreamEntry and StreamPage

| Prop | Type | Default | Description |
| - | - | - | - |
| `offset` | `number` | - | The entry's place in the stream, from 0, kept for good. |
| `at` | `number` | - | When it was appended, in milliseconds since the epoch. |
| `data` | `T` | - | The entry. |

A `StreamPage<T>` holds a page of entries.

| Prop | Type | Default | Description |
| - | - | - | - |
| `entries` | `StreamEntry<T>[]` | - | The entries read. |
| `first` | `number` | - | The oldest offset still kept. |
| `next` | `number` | - | Where to read on from. |
| `end` | `number` | - | The offset the next append gets. |

### RollupRow

| Prop | Type | Default | Description |
| - | - | - | - |
| `at` | `number` | - | When the bucket starts, in milliseconds since the epoch. |
| `by?` | `string` | - | The bucket's group, for a rollup with `by`. |
| `count` | `number` | - | How many entries the bucket holds. |
| `[field]?` | `any` | - | Each aggregate, under the name it was declared with. |

### ctx.subscribe, ctx.unsubscribe and ctx.subscriptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `subscribe(luna, key, stream, opts)` | `string` | - | Follows a luna's stream: each entry runs the handler `opts.handler` here, and it returns the subscription's id. |
| `unsubscribe(id)` | `boolean` | - | Stops following, and returns `false` if there was no such subscription. |
| `subscriptions()` | `SubscriptionInfo[]` | - | The streams this luna follows. |

`opts.from` is the offset to start at. By default a subscription starts at the next append.

### StreamDelivery

What the subscribed handler receives for each entry. Declare these args on it.

| Prop | Type | Default | Description |
| - | - | - | - |
| `subscription` | `string` | - | The subscription's id. |
| `stream` | `string` | - | The stream's name. |
| `offset` | `number` | - | The entry's offset. |
| `at` | `number` | - | When it was appended, in milliseconds since the epoch. |
| `data` | `T` | - | The entry. |

### SubscriptionInfo

| Prop | Type | Default | Description |
| - | - | - | - |
| `id` | `string` | - | The subscription's id. |
| `lunaType` | `string` | - | The followed luna's type. |
| `key` | `Record<string, unknown>` | - | The followed luna's key. |
| `stream` | `string` | - | The followed stream. |
| `handler` | `string` | - | The handler each entry runs. |
| `next` | `number` | - | The next offset it expects, and everything before it is handled. |
| `createdMs` | `number` | - | When it was made, in milliseconds since the epoch. |

## Good to know

- An append is kept once the handler commits, and a handler that fails leaves nothing behind. On a `live` stream, each append is kept at once and stays if the handler fails.
- A stream is live or not for good, so its offsets stay in order.
- Luna checks each entry against the stream's type. An entry of another type fails the call.
- Retention drops the oldest entries. Offsets never move, so `first` grows as entries go.
- Rollups are kept apart from the entries. A bucket outlives the entries it counted.
- A subscription delivers entries durably, in order and at least once.
- A retention limit must be above zero.

## Examples

### Roll up messages per hour

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

export const Room = defineLuna({
  name: "Room",
  key: { id: t.string() },
  streams: {
    messages: stream(t.object({ from: t.string(), text: t.string() }), {
      retention: { maxCount: 1000 },
      rollups: { hourly: { every: "1h", keep: "30d", by: "from", fields: { sent: agg.count() } } },
    }),
  },
  handlers: (h) => ({
    busiest: h({ query: true }, (ctx) => ctx.streams.messages.rollup("hourly", { from: ctx.now() - 86_400_000 })),
  }),
});
```

### Follow another luna's stream

```ts luna/lunas/follower.ts
import { defineLuna, type StreamDelivery, t, table } from "luna";
import { Room } from "./room.ts";

export const Follower = defineLuna({
  name: "Follower",
  key: { id: t.string() },
  schema: { seen: table({ offset: t.int(), text: t.string() }, { primaryKey: ["offset"] }) },
  handlers: (h) => ({
    follow: h({ args: { room: t.string() } }, (ctx, { room }) =>
      ctx.subscribe(Room, { id: room }, "messages", { handler: "onMessage" }),
    ),
    onMessage: h(
      { args: { subscription: t.string(), stream: t.string(), offset: t.int(), at: t.int(), data: t.json() } },
      (ctx, delivery) => {
        const d = delivery as StreamDelivery<{ from: string; text: string }>;
        ctx.db.seen.upsert({ offset: d.offset, text: d.data.text });
      },
    ),
    leave: h({}, (ctx) => {
      for (const s of ctx.subscriptions()) ctx.unsubscribe(s.id);
    }),
  }),
});
```

### Report progress while a handler runs

```ts luna/lunas/room.ts
streams: {
  progress: stream(t.int(), { live: true, retention: { maxAge: "1d" } }),
},
```

```ts luna/lunas/room.ts
work: h({}, async (ctx) => {
  for (let step = 1; step <= 10; step++) {
    await new Promise((r) => setTimeout(r, 100));
    ctx.streams.progress.append(step * 10);
  }
}),
```

Apps follow a live stream as it grows. See [LunaHandle](/sdk/luna-handle).
