---
title: Subscribe to a stream
description: Run a handler in one luna for each entry of another luna's stream, in order, from where you choose, and stop when you no longer need it.
related:
  - /events/keep-a-stream
  - /sdk/stream
  - /realtime/follow-a-stream-from-an-app
---

A luna sometimes needs each entry of another luna's stream, such as every message of a room a user joined. Reading the stream on a timer wakes both lunas and leaves you to track where you stopped.

A subscription runs a handler of yours for each entry, in order. It remembers how far it got in your luna's own database.

## Subscribe to another luna's stream

[`ctx.subscribe`](/sdk/stream) takes the luna type, the key, the stream's name and the handler to run. It returns the subscription's id.

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

const entry = {
  subscription: t.string(), stream: t.string(),
  offset: t.int(), at: t.int(), data: t.json(),
};

export const User = defineLuna({
  name: "User",
  key: { id: t.string() },
  schema: { mentions: table({ offset: t.int(), text: t.string() }) },
  handlers: (h) => ({
    join: h({ args: { room: t.string() } }, (ctx, { room }) => {
      return ctx.subscribe(Room, { id: room }, "messages", { handler: "heard" });
    }),
    heard: h({ args: entry }, (ctx, e) => {
      const msg = e.data as { author: string; text: string };
      if (!msg.text.includes(`@${ctx.key.id}`)) return;
      ctx.db.mentions.insert({ offset: e.offset, text: msg.text });
    }),
  }),
});
```

`Room` is the luna type from [Keep a stream](/events/keep-a-stream). A luna may also subscribe to its own streams.

The subscription is a write. It is kept only if the handler that made it succeeds. Each call makes a new subscription, so calling `join` twice for one room runs `heard` twice for each message. Check [`ctx.subscriptions()`](/sdk/stream) first when a handler may run more than once.

## What the handler receives

The handler gets a [`StreamDelivery`](/sdk/stream) as its arguments. Declare them as the example does.

| Field | Holds |
| --- | --- |
| `subscription` | The subscription's id |
| `stream` | The stream's name |
| `offset` | The entry's offset in that stream |
| `at` | When the entry was appended, in milliseconds since the epoch |
| `data` | The entry |

In the handler, `ctx.caller` names the luna whose stream it is.

## Choose where it starts

Without `from`, the subscription starts with the next entry appended after the room records it. The subscription reaches the room as a message once your handler's writes are stored, so entries appended in between are not delivered.

Pass `from` to start at an offset. `from: 0` starts with the oldest entry the stream still keeps.

```ts luna/lunas/user.ts
ctx.subscribe(Room, { id: room }, "messages", { handler: "heard", from: 0 });
```

## Order, retries and a sleeping subscriber

Each entry reaches your luna as a message. A sleeping luna wakes for it, as it does for any message.

Entries arrive one at a time, in order. Your luna stores how far it got together with the handler's writes, so an entry whose handler succeeded never runs again, even after a restart.

If the handler throws, the entry is tried again later and the entries after it wait. Retries follow the rules of messages in [Call another luna](/lunas/call-another-luna). After the last attempt the entry is set aside and the next entry runs. [`luna logs`](/cli/logs) with `--event deadLetter` shows each entry set aside. A declared error from `ctx.fail` is not retried, and the next entry runs at once.

:::warning
An entry is skipped for good when every attempt fails, or when the stream's retention drops it before it is sent. A request to the outside world in the handler runs again on each attempt.
:::

## List and stop subscriptions

`ctx.subscriptions()` lists the streams this luna follows. Each has its `id`, `lunaType`, `key`, `stream`, `handler`, `createdMs`, and `next`, the offset it expects next.

`ctx.unsubscribe(id)` stops one and returns `false` if there was no such subscription. Entries already on their way are dropped.

```ts luna/lunas/user.ts
leave: h({ args: { room: t.string() } }, (ctx, { room }) => {
  for (const s of ctx.subscriptions()) {
    if (s.lunaType === "Room" && s.key.id === room) ctx.unsubscribe(s.id);
  }
}),
```

## Next steps

- [Keep a stream](/events/keep-a-stream) covers appending, reading and retention.
- [Follow a stream from an app](/realtime/follow-a-stream-from-an-app) reads a stream in an app instead of a luna.
- [Listen to events](/events/listen-to-events) fits when several luna types need the same facts.
