# Live data

> Keep what a page shows current as the data changes - refreshOn, events, polling.

A page rendered on the server shows the data as it was. When it changes
while someone is looking - a teammate edits it, a webhook lands, a job
finishes - there are three ways to show the change, and which to use depends
on where the change comes from.

| | The change comes from | What travels | Use it for |
| --- | --- | --- | --- |
| [`refreshOn`](#refresh-a-section-when-its-data-changes) | your backend: a webhook, a job, another visitor's action | a one-line signal; the section re-renders through its own queries and guards | almost everything - dashboards, inboxes, build status, anything a backend can say changed |
| [`events()` + `useEvents`](/guides/api-routes#a-route-that-streams) | a stream of values: prices, progress, logs | each value, as it is produced | data that *is* a stream, rendered on the client |
| [`usePolling`](/guides/queries#live-data) | nowhere you can hook: a third-party API | the whole answer, every interval | values with no change signal at all |

Inside the tab that made a change, none of these is needed: an action says
what it changed, and its answer carries those sections back -
[revalidate](/guides/sections#refreshing-it).

## Refresh a section when its data changes

An action can say what it changed because it is the thing changing it. A
webhook, a job finishing in a worker, another visitor's action - none of
those is in the tab that is showing the data. For those a section says what
it depends on, by name:

```tsx title="src/app/t/[team]/repos.section.tsx"
export default section('repos', Repos, {
  refreshOn: ({ params }) => [`team:${params.team}:repos`],
})
```

and whatever changes the data says so, from wherever it is:

```ts title="src/app/api/github/webhook/route.ts"
import { changed } from '@rsc-kit/core/changed'

export async function POST(request: Request) {
  const { team, repos } = await request.json()
  await saveRepos(team, repos)
  await changed(`team:${team}:repos`)
  return new Response(null, { status: 204 })
}
```

Every open tab showing the section refreshes it - the same refresh as above,
with nothing polling and no client code. `refreshOn` is a list of names, or a
function of the section's props - the page's `params` and `searchParams` -
that makes them. A page can declare its own with `export const refreshOn`,
and a change refreshes the page as `refresh('page')` does.

The function is given the page's `params` and `searchParams` already awaited,
and runs per request, so it can read the request too - a name for the person
signed in is the usual one on a dashboard:

```tsx title="src/app/dashboard/page.tsx"
import { cookies } from '@rsc-kit/core/request'

export const refreshOn = async () => [`inbox:${(await cookies()).get('agent')?.value}`]
```

A page with url schemas types its `refreshOn` from them, so `params` arrives
parsed and typed rather than typed by hand:

```tsx title="src/app/teams/[team]/page.tsx"
import type { PageRefreshOn } from '@rsc-kit/core/section'

export const params = z.object({ team: z.string() })
export const refreshOn: PageRefreshOn<typeof params> = ({ params }) => [`team:${params.team}`]
```

A page without a schema names its route's pattern instead, and each param is
a string. The pattern is checked against the routes the build found, so a
misspelt param - `params.ap` - or a pattern that is not a page fails the
typecheck:

```tsx title="src/app/[team]/[app]/[env]/page.tsx"
export const refreshOn: PageRefreshOn<'/[team]/[app]/[env]'> = ({ params }) => [`app:${params.app}:${params.env}`]
```

`export const refreshOn`, `export function refreshOn` and a list -
`export { refreshOn } from './names'` - all count. `export * from` does not:
the build reads the page, not what it re-exports wholesale, so name it in a
list.

That is the whole feature for an app that is only JavaScript. With a Go or
Laravel backend the backend says it instead -
[`reg.Changed(ctx, …)`](/hosts/go#saying-data-changed) or
[`Rsc::changed(…)`](/hosts/laravel#saying-data-changed) - and the page is the same.

## Whose data a name shows

A name is a signal, not data and not a permission. Hearing that
`conversation:42` changed tells a tab only to ask for its section again; what
comes back is rendered for that tab's visitor, through their own session, by
the same queries and guards as the first render. So two people never see each
other's data through a name - they see whatever their own render shows.

A chat between Ada and Ben:

```tsx title="src/app/chats/[id]/messages.section.tsx"
export default section('messages', async function Messages({ params }) {
  const { id } = await params
  const messages = await rpc('Chats.messages', id)   // the backend checks the viewer is in it

  return <Thread messages={messages} />
}, { refreshOn: ({ params }) => [`conversation:${params.id}`] })
```

```tsx title="src/app/inbox/page.tsx"
// Each person's own list of conversations, with unread counts.
export const refreshOn = async () => [`inbox:${await currentUserId()}`]
```

```go
// Ada sends a message.
reg.Changed(ctx, "conversation:42", "inbox:"+ben.ID, "inbox:"+ada.ID)
```

- Both have conversation 42 open, so both tabs refresh it, and each render
  asks `Chats.messages` as its own visitor. If the thread shows "you" and
  "them", each sees it from their side.
- Ben's inbox refreshes; so does Ada's. Nobody else's does: their pages were
  rendered with their own `inbox:` names.
- Someone who is not in the conversation cannot open the page - its guards
  refuse - so no render ever hands them `conversation:42` to listen for. A
  tab can only listen for names its page was rendered with: the renderer
  signs them, and a name a browser makes up is refused.

**Name the data, as narrowly as the data.** One name per thing that changes
together: `conversation:{id}`, `inbox:{userId}`, `team:{id}:repos`. Two
different things sharing one name only refresh too often; one thing split
across names refreshes too little. Use ids, not emails or titles - a name
sits in the page and in the stream's url, and its version says when it last
changed, so a name must not be something its visitor should not see.

A section that shows anything per visitor - "you", their unread count, what
they may do - must never be `shared`: that is the one place a render is
handed from one visitor to another.

**A change to a child is a change to its parent's list.** Renaming an app
changes the app's own page and the team's list of apps. Say both where the
write happens, rather than making either region watch the other's names:

```ts
await renameApp(app.id, name)
await changed(`app:${app.id}`, `team:${app.teamId}:apps`)
```

```tsx
// The app's page: refreshOn = ({ params }) => [`app:${params.app}`]
// The team's list: refreshOn = ({ team }) => [`team:${team}:apps`]
```

Each region names exactly what it shows, and the write - the one place that
knows what it touched - names everything that did. A region that watched
every child's name would hand the tab a name per row, and miss a child added
after it rendered.

**Not everything can announce itself.** A host's runtime logs, a third-party
status page, anything nothing tells you about: there is no write to call
`changed()` from, so poll it - `usePolling` - and keep `refreshOn` for data
your own code changes.

## Testing what a page watches

`createTestApp` renders the page as it is deployed, and `watched()` says what
each region refreshes on for that url - `page` for the page's own, a
section's name for each section's:

```ts title="tests/live.test.ts"
import { createTestApp } from '@rsc-kit/core/testing'

const app = await createTestApp()

test('the team page watches the team and its apps', async () => {
  expect(await app.watched('/teams/acme')).toEqual({
    page: ['team:acme'],
    apps: ['team:acme:apps'],
  })
})
```

A region whose `refreshOn` gave no names is there with `[]` - and said in the
server's log in development, since that is usually a param read under the
wrong name. To check what a change does, say it - `changed()` in an app
that keeps its own versions, `testChanges()` with a test backend - and fetch
the section again: [What a page watches](/guides/testing#what-a-page-watches).

## How a tab finds out

Each name has a version, a number that moves when something says the name
changed. Nothing else travels - not what changed, not the data.

1. The page renders, reads the version of each name it shows, and hands them
   to the tab, signed.
2. The tab opens one stream, `/_rsc/changes`, for every name on the page. Only
   a page with `refreshOn` opens one, and only while the tab is visible.
3. The server asks where the versions live - "which of these differ from what
   I hold?" - once for every open tab it is serving, and again on an interval.
4. When a version has moved, the stream says so in one line, and the tab asks
   for exactly the sections showing that name, the way `refresh('repos')` does.

A name belongs to the data, not to a section or a page. Any number of
sections, on any number of pages, can refresh on the same name: one
`changed('team:1:repos')` moves its version once, and every open tab showing
any of them refreshes the ones it has. Section *names* are separate - two
pages may both have a section called `stats`; each is resolved through its own
page, and a shared render is never handed from one page to the other.

The data is never pushed: the section is rendered fresh, through its own
queries and its own guards, as any refresh is. That is also why this runs
on a Worker - the stream holds no state, and a version is a read.

## Where the versions live

**One server, no backend:** in that server's memory. Nothing to set up - but
in production rsc-kit says so in its log, once, because the same default
fails silently the moment there are two instances. If the deploy really is
one instance, say so and the warning goes:

```ts title="src/instrumentation.ts"
import { installVersionSource, memoryVersions } from '@rsc-kit/core/changed'

export function register() {
  installVersionSource(memoryVersions())   // one instance, on purpose
}
```

**More than one instance, or a worker process:** this is the case to
plan for. In-memory versions fail silently the moment a load balancer adds a
second instance - a change made on one never reaches the tabs held by the
other - and a job finishes in a process that serves no pages at all. Keep
the versions somewhere they all share - any database you already have, through
the client you already use. rsc-kit ships no driver; you hand it yours:

| Your database | The store | Another instance's change arrives |
| --- | --- | --- |
| Postgres, with postgres.js or `Bun.sql` (Bun 1.4+) - or the one under Drizzle | `postgresVersions(sql)`, or `postgresVersions(db.$client)` | at once, through LISTEN/NOTIFY; one statement per change |
| Postgres, with another client | `sqlVersions({ query, placeholder: (n) => '$' + n })` | within a second |
| MySQL, MariaDB | `sqlVersions({ query, dialect: 'mysql' })` | within a second; one statement per change |
| SQLite, libSQL, Turso, D1 | `sqlVersions({ query, dialect: 'sqlite' })` | within a second; one statement per change |
| Redis | `createVersions({ read, bump, listen, notify })` | at once, through pub/sub |
| An ORM: Drizzle, Prisma, Kysely, Knex | `createVersions` over its query builder, or `sqlVersions` over its raw query | as its database |

`sqlVersions` takes your driver as one function of SQL text and parameters.
Say which database with `dialect`, and a change is one upsert of every name it
moves; leave it out and it uses only SQL every database has, a read and a
write per name:

```ts title="src/versions.ts"
import { sqlVersions } from '@rsc-kit/core/changed'

// MySQL, mysql2
export const versions = sqlVersions({ dialect: 'mysql', query: async (text, params) => (await pool.query(text, params))[0] })

// SQLite, bun:sqlite or better-sqlite3
export const versions = sqlVersions({ dialect: 'sqlite', query: async (text, params) => db.query(text).all(...params) })

// libSQL / Turso
export const versions = sqlVersions({ dialect: 'sqlite', query: async (sql, args) => (await client.execute({ sql, args })).rows })
```

and with postgres.js it is one line:

```ts title="src/versions.ts"
import postgres from 'postgres'
import { postgresVersions } from '@rsc-kit/core/changed'

// A function, so the store - and its database client - is made on first use.
export const versions = () => postgresVersions(postgres(process.env.DATABASE_URL!))
```

A SQLite file is shared by the processes on one machine - a web server and a
worker on the same box. Instances on several machines need a database they
all reach over the network. The table every one of these reads is described
[below](#the-table).

postgres.js and `Bun.sql` both LISTEN, and `postgresVersions` uses it when the
client has it: a change on one instance - or in a worker - reaches the tabs on
every other at once. A listening server still reads the table now and then, in
case its listening connection dropped without a word; it is not how changes
normally arrive.

**Any database, any ORM, or no SQL at all.** rsc-kit needs three things from
your storage - read some versions, move some versions, and, if it can,
say the moment one moved - and does the comparing, waiting and waking itself.
`createVersions` takes exactly those:

With Drizzle, use its query builder rather than raw SQL - the table is one
more table in your schema:

```ts title="src/db/schema.ts"
import { bigint, pgTable, text } from 'drizzle-orm/pg-core'

export const rscVersions = pgTable('rsc_versions', {
  name: text('name').primaryKey(),
  version: bigint('version', { mode: 'number' }).notNull(),
})
```

```ts title="src/versions.ts"
import { inArray, sql } from 'drizzle-orm'
import { createVersions } from '@rsc-kit/core/changed'
import { db } from './db'
import { rscVersions } from './db/schema'

export const versions = createVersions({
  read: async (names) =>
    Object.fromEntries(
      (await db.select().from(rscVersions).where(inArray(rscVersions.name, names)))
        .map((row) => [row.name, Number(row.version)]),
    ),
  bump: async (names) => {
    await db.insert(rscVersions)
      .values(names.map((name) => ({ name, version: Date.now() })))
      .onConflictDoUpdate({
        target: rscVersions.name,
        set: { version: sql`GREATEST(${rscVersions.version} + 1, excluded.version)` },
      })
  },
})
```

```ts title="Prisma"
import { sqlVersions } from '@rsc-kit/core/changed'

// Raw SQL through Prisma; the table is a model in its schema - see "The table" below.
export const versions = sqlVersions({
  query: (text, params) => prisma.$queryRawUnsafe(text, ...params),
  placeholder: (n) => '$' + n,   // Postgres; leave out for MySQL and SQLite
})
```

```ts title="Redis"
import { createVersions } from '@rsc-kit/core/changed'

const key = (name: string) => 'rsc:' + name
const BUMP = `local v = math.max(tonumber(redis.call('GET', KEYS[1]) or '0') + 1, tonumber(ARGV[1]))
redis.call('SET', KEYS[1], v, 'EX', ARGV[2])
return v`

export const versions = createVersions({
  read: async (names) => {
    const values = await redis.mget(names.map(key))
    return Object.fromEntries(names.map((name, i) => [name, Number(values[i] ?? 0)]))
  },
  // One past where it was, or now if that is larger - see "Cleaning up".
  bump: async (names) => {
    await Promise.all(names.map((name) => redis.eval(BUMP, 1, key(name), Date.now(), 30 * 86400)))
  },
  // Instant across instances: a subscriber connection hears every bump.
  listen: (wake) => subscriber.subscribe('rsc:versions', wake),
  notify: () => redis.publish('rsc:versions', ''),
})
```

`sqlVersions({ query })` takes any SQL driver as a function of text and
parameters - node-postgres, mysql2, Kysely, Knex, D1 - and `createVersions`
takes anything else.

Install it in every process - the web server once, before the first request.
Pass the function, not a store: `register()` also runs during the build,
usually without the database's settings, and a store made there makes its
client there too. Given a function, rsc-kit makes the store the first time
versions are read - which a build never does.


```ts title="src/instrumentation.ts"
import { installVersionSource } from '@rsc-kit/core/changed'
import { versions } from './versions'

export function register() {
  installVersionSource(versions)
}
```

and the worker, which then says what it finished:

```ts title="worker.ts"
import { changed, installVersionSource } from '@rsc-kit/core/changed'
import { versions } from './src/versions'

installVersionSource(versions)

queue.on('restoration.done', async (job) => {
  await changed(`restoration:${job.id}`)
})
```

Without `listen` and `notify` - MySQL, SQLite, or a driver that cannot listen -
a waiting server reads the table every second instead (`poll` changes it).

**From any process, without rsc-kit:** the table is the contract. A cron job,
a service in another language, a database trigger - anything that can write
to it can say a name changed:

```sql
-- Postgres
INSERT INTO rsc_versions (name, version)
  VALUES ('restoration:42', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
  ON CONFLICT (name) DO UPDATE SET version = GREATEST(rsc_versions.version + 1, EXCLUDED.version);
NOTIFY rsc_versions;   -- optional: wakes the listening servers at once

-- MySQL, MariaDB
INSERT INTO rsc_versions (name, version)
  VALUES ('restoration:42', FLOOR(UNIX_TIMESTAMP(NOW(3)) * 1000))
  ON DUPLICATE KEY UPDATE version = GREATEST(version + 1, VALUES(version));

-- SQLite
INSERT INTO rsc_versions (name, version)
  VALUES ('restoration:42', CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER))
  ON CONFLICT (name) DO UPDATE SET version = MAX(version + 1, excluded.version);
```

The new version is one past the old, or the current time in milliseconds if
that is larger - so a version never repeats, which is what makes it safe to
delete old rows ([Cleaning up](#cleaning-up)). Every writer must bump this
way; a plain `version + 1` is a counter, and a counter repeats once a row is
deleted. Go's `SQLVersions` uses the same table, so a Go service and a
JavaScript app can share one.

**LISTEN through an ORM, or another driver.** An ORM builds queries; listening
is its driver's job, so pass `listen` and `notify` from the client underneath -
the one you handed the ORM:

```ts title="src/versions.ts"
import { SQL } from 'bun'
import { drizzle } from 'drizzle-orm/bun-sql'

const client = new SQL(process.env.DATABASE_URL!)
export const db = drizzle({ client })

export const versions = createVersions({
  read,                                                     // the Drizzle read and bump above
  bump,
  listen: (wake) => client.listen('rsc_versions', wake),
  notify: () => client.notify('rsc_versions', ''),
})
```

On node-postgres (`pg`), keep one client for listening alone:

```ts
const listener = new pg.Client(process.env.DATABASE_URL)
await listener.connect()

listen: async (wake) => {
  listener.on('notification', wake)
  await listener.query('LISTEN rsc_versions')
},
notify: () => pool.query('NOTIFY rsc_versions'),
```

A `NOTIFY` sent inside a transaction is only delivered when it commits, so a
listening tab is never woken before the data it will read is there - the
[after-commit](#say-it-after-the-write-commits) rule, kept by the database.
Redis has the same shape with SUBSCRIBE and PUBLISH (the example above).

## Connection poolers

A pooler in **transaction mode** - PgBouncer, and the pooled connection
DigitalOcean, Supabase and Neon offer - hands the database connection back
after every statement. Reads and writes are fine; even sending a NOTIFY is.
But a LISTEN lands on a connection the pooler takes back, and the listener
hears nothing - silently. Changes from other instances would then wait for the
thirty-second safety net.

rsc-kit checks: as `postgresVersions` starts listening it sends itself a probe,
and if the probe does not come back it says so in the log - naming the cause
and the fix - and goes back to reading every second. The fix is to listen
through a connection that keeps its session - a direct one, or a pool in
session mode - and leave everything else on the pool:

```ts title="src/versions.ts"
import { SQL } from 'bun'
import { postgresVersions } from '@rsc-kit/core/changed'

export const versions = () =>
  postgresVersions(new SQL(process.env.DATABASE_URL!), {           // the pool: reads and writes
    listenWith: new SQL(process.env.DATABASE_LISTEN_URL!),          // direct: listening only
  })
```

That is one extra connection per process. On DigitalOcean the direct port is
25060 and the pool's 25061; on Supabase, 5432 and 6543. Use the app's own
database user for it, not the one migrations run as.

If direct connections are too scarce to spend one per process, don't listen -
say so, and rsc-kit reads every second instead, with no probe and no warning:

```ts
postgresVersions(pool, { listen: false })
```

That is one small indexed read per second per process, however many tabs it
holds. A change made in a process still reaches that process's tabs at once;
one made elsewhere - another instance, the worker - within about a second.

`await connection()` in a page is unrelated - despite the name, it is about
rendering per request, not database connections.

## On Workers and serverless

The stream needs nothing kept between requests - names are signed, not
looked up - so it runs anywhere a response can stream. What differs is that
there is no single long-lived process:

- **Every isolate or instance watches for its own tabs.** Versions in memory
  belong to one isolate, so a `changed()` handled by one never reaches tabs
  held by another. Use a shared store - D1, Postgres, your backend - which the
  production warning asks for if there is none. On Workers, [one hub](#one-hub-on-workers)
  can hold every tab instead.
- **Connections are cut.** Platforms bound how long a request may run; a
  stream that is cut reconnects on its own, and the tab catches up from its
  versions. On a platform that bills a function for every second it is open,
  each watching tab is billed for as long as it watches.
- **Listening is unlikely.** Hyperdrive and serverless Postgres drivers go
  through poolers; the probe finds this and falls back to reading every second,
  or say `listen: false` up front.

On Workers, bindings come from `cloudflare:workers`, imported inside a
request - when they exist, and never in the build:

```ts title="src/versions.ts"
import { sqlVersions } from '@rsc-kit/core/changed'

// The binding, imported inside the request: the build prerenders in Node,
// which runs register() and cannot load cloudflare:workers.
const db = async () => (await import('cloudflare:workers')).env.DB

// D1: the table is the same as anywhere else.
export const versions = () =>
  sqlVersions({
    dialect: 'sqlite',
    query: async (text, params) => (await (await db()).prepare(text).bind(...params).all()).results,
  })
```

Then the binding, the table and the secret:

```jsonc title="wrangler.jsonc"
{
  // Nitro merges this into the Worker's config.
  "d1_databases": [
    { "binding": "DB", "database_name": "my-app", "database_id": "<from wrangler d1 create>", "migrations_dir": "migrations" }
  ]
}
```

```sql title="migrations/0001_rsc_versions.sql"
CREATE TABLE IF NOT EXISTS rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
```

```sh
npx wrangler d1 create my-app                       # once; put its id in wrangler.jsonc
npx wrangler d1 migrations apply DB --remote        # --local for wrangler dev
npx wrangler secret put RSC_SIGNING_SECRET          # production; .dev.vars for wrangler dev
```

and install it as anywhere else - `installVersionSource(versions)` in
`instrumentation.ts`. A section the store serves needs `await connection()`
when it reads D1 itself: the data is only there per request.

The Cloudflare example's `/live` page is all of this, end to end, and was run
on `wrangler dev`: a change from its webhook reaches an open tab, and the
section refreshes with the new value.

### One hub on Workers

Each isolate watches only the tabs it happens to hold, and on Workers that is
often one. So by default every open tab costs its own ask of the store, every
two seconds, and a `wakeOn` listener runs once per isolate. A Durable Object
is one place every isolate can reach. Name it, and every tab's stream goes to
one instance, which watches all of them:

```ts title="vite.config.ts"
// cloudflare_module, plus the Durable Object class the hub runs in.
nitro({ preset: 'cloudflare_durable', serveStatic: 'inline' })
```

```jsonc title="wrangler.jsonc"
{
  "durable_objects": {
    "bindings": [{ "name": "$DurableObject", "class_name": "$DurableObject" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["$DurableObject"] }],
  "vars": { "RSC_CHANGES_HUB": "$DurableObject" }
}
```

Nothing changes in the app. `RSC_CHANGES_HUB` names the binding, and rsc-kit
does not look for one on its own: without it, each isolate watches its own
tabs as before. A name with no binding behind it is said once in the log, and
the isolate falls back to that.

What changes, against each isolate watching its own tabs:

| | Each isolate (default) | One hub |
| --- | --- | --- |
| Asks of the store or backend | one per open tab, every 2s | one for every tab, every 2s |
| A `changed()` reaches the tabs | at each isolate's next read, within a second or two | at once: `changed()` wakes the hub |
| A `wakeOn` listener or broadcast | one connection per isolate | one connection |
| Cost of a store with no LISTEN (D1) | grows with tabs | flat |
| A Laravel backend | one PHP request per tab, every 2s | one, for every tab |

- **Asks stop growing with tabs.** A thousand open tabs cost the store, or
  your backend, one ask every two seconds instead of a thousand. On a backend
  that answers each ask with a PHP request, this is the difference that
  matters.
- **Changes arrive at once without LISTEN.** D1 cannot announce a change.
  With the hub, `changed()` in any isolate - a webhook, an action - pokes the
  hub after the write, and every tab hears it immediately instead of at the
  next read.
- **One listener.** A broadcast server or `wakeOn` listener runs in the hub,
  one connection for the deployment, rather than one per isolate that
  happens to hold a tab.

What it costs, and its limits:

- **Durable Object time.** The hub stays active while any tab watches, and a
  Durable Object is billed for the time it is active - for one instance open
  all month, a few dollars on Cloudflare's paid plan. With no tab open it
  costs nothing.
- **One location.** Every tab's stream goes to the one instance, wherever
  Cloudflare placed it. An event crosses one more hop, tens of milliseconds;
  the pages themselves are still rendered by the nearest isolate.
- **One instance's limits.** A Durable Object runs on one thread, and
  Cloudflare documents a soft limit of about 1,000 requests a second for
  one. A site whose tabs connect faster than that should stay on the
  default flow, which spreads them across isolates.
- **Versions still live in a shared store.** The hub holds the tabs, not the
  versions: D1, your database or your backend still keeps them, so a hub that
  restarts loses nothing.

The forwarded requests carry a proof signed with `RSC_SIGNING_SECRET`, so a
browser cannot reach the hub's side of the endpoint directly. The Cloudflare
example runs this way, and was checked on `wrangler dev`: three tabs' streams
held by the hub, one webhook, and all three hearing the change.

Where a response cannot stream at all, use `usePolling` instead.

## The table

A shared store keeps one row per name. Your app owns the table: rsc-kit never
creates, alters or migrates it at runtime - make it with your own migrations,
in your own schema, with whatever your ORM calls these types. (Laravel ships
one you publish into your own migrations, `--tag=rsc-migrations`; after that
it is yours too.)

| Column | Type | |
| --- | --- | --- |
| `name` | text, `PRIMARY KEY` (or a unique index) | the name a section refreshes on |
| `version` | `BIGINT NOT NULL` | when it last changed, in ms - or one past the last value, if that is larger |

```sql
-- Postgres, SQLite
CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
-- MySQL: an indexed TEXT needs a length
CREATE TABLE rsc_versions (name VARCHAR(255) PRIMARY KEY, version BIGINT NOT NULL);
```

- **Extra columns are fine** - an `updated_at`, say - as long as each has a
  default: rsc-kit and the documented upserts write only `name` and `version`.
- **Another name is fine:** `sqlVersions({ table })`, `postgresVersions(sql,
  { table })`, Go's `SQLVersions{Table}`, Laravel's `RSC_VERSIONS_TABLE`.
- **The NOTIFY channel** is `rsc_versions` whatever the table is called;
  `postgresVersions(sql, { channel })` changes it.
- The same table works for Go's `SQLVersions` and Laravel's
  `RSC_VERSIONS=database`, so a JavaScript app, a Go service and a PHP job
  can share one.

## Cleaning up

A row is kept for every name that ever changed. For a fixed set of names -
`team:1:repos` - that is nothing; for one per order, job or restoration it
grows for ever. Delete the old ones on a schedule:

```ts
await versions.prune()              // sqlVersions, postgresVersions: not changed in 30 days
await versions.prune(7 * 86400_000) // or any age, in ms
```

or from anything that can run SQL - the version is when the name last changed:

```sql
DELETE FROM rsc_versions WHERE version < (EXTRACT(EPOCH FROM now() - interval '30 days') * 1000)::bigint;
```

**Deleting is always safe.** A deleted name reads as 0, so a tab still
holding it sees a different version and refreshes once; changed again, the
name comes back at the current time - never at a value a tab is holding.
That is why a bump moves to the time rather than counting: a counter
restarted at 0 climbs back to values tabs still hold, and they would miss
the change.

The rest clean up on their own: `memoryVersions()` forgets a name not changed
in 30 days (`{ forgetAfter }`), the Redis example's keys expire, and the
server forgets every name the moment no open tab is watching it. Laravel and
Go have the same: `php artisan rsc:prune-versions` and `SQLVersions.Prune`.

A store of your own bumps with `nextVersion(current)` from
`@rsc-kit/core/changed` - never `+ 1`.

## Say it after the write commits

A tab that hears a name moved asks for its section at once. If the write
that changed the data has not committed yet, that render reads the old data -
and the tab is now at the new version, so it will not ask again until the
next change. Inside a transaction, say it changed **after** the transaction,
not inside it:

```ts
await db.transaction(async (tx) => {
  await tx.insert(conversations).values(row)
  // not here: this transaction may still roll back, and has not committed
})

await changed(`agent:${row.agentId}:conversations`)   // here
```

The same goes for a worker writing the table directly: in the same
transaction as the data, or after it - never before. In Laravel,
`DB::afterCommit(fn () => Rsc::changed(...))` does this inside a transaction.

**With a Go or Laravel backend:** the backend keeps them - a table in Go, the
cache in Laravel - and you install nothing here. The backend owns the data,
so it answers for its versions too: the renderer asks it which moved, once
for every tab it is serving. Go holds that question until a version moves,
so tabs hear at once. PHP cannot hold a request open, so Laravel answers at
once and is asked again about every two seconds while any tab is watching:
one small request - a cache read - per renderer process, however many tabs.
For almost any app that is nothing, and a change reaches the tabs within
about two seconds - or at once, with Laravel's [broadcasting](/hosts/laravel#saying-data-changed).

## Waking the renderer

Whatever keeps the versions, the renderer has to learn *when* to ask which
moved. Go holds the question until one does; a store that listens -
Postgres's LISTEN, Redis's pub/sub - wakes it; otherwise it asks on a timer.
Anything else that can say "something changed" can wake it too:

```ts title="src/instrumentation.ts"
import { listenToBroadcast, wakeOn } from '@rsc-kit/core/changed'

export function register() {
  // A broadcast server - anything speaking the Pusher protocol.
  wakeOn(listenToBroadcast({ url: process.env.RSC_BROADCAST_URL!, key: process.env.RSC_BROADCAST_KEY! }))

  // Or a Redis channel your backend publishes to.
  wakeOn((wake) => subscriber.subscribe('rsc:changed', wake))
}
```

`RSC_BROADCAST_URL` and `RSC_BROADCAST_KEY` in the renderer's environment do
the first with no code. A wake carries nothing - no names, no data - so it
can travel over a public channel: on a wake the renderer asks, as it always
does, and the versions say which names moved for whom. With something to wake
it, the renderer asks on its timer only every thirty seconds, as a safety net
for a dropped connection. Listeners start with the first watching tab, never
in a build.

**Private data stays private.** A wake decides nothing about who sees what.
On a wake the renderer asks which of *its tabs'* names moved - names each tab
got, signed, from its own render - and a tab that has one refreshes its
section through its own visitor's session and guards. Ada's `inbox:7` is never
a name Ben's tab holds, so a change to it never refreshes his page, broadcast
or not. All a public channel shows a subscriber is that the app changed and
when; if even that timing is sensitive, keep the wake on a channel only the
renderer can reach - a Redis channel, through `wakeOn` - rather than a
broadcast.

## The signing secret

The names a page hands the tab are signed, so a tab can only listen for the
names its page was rendered with - a browser cannot make one up. Every
instance has to sign with the same key, or a tab served by one is refused by
the next and never refreshes:

```sh
RSC_SIGNING_SECRET=… # the same on every instance: openssl rand -base64 32
```

It is its own secret, with or without a backend - not the backend's
`RSC_HOST_CALL_SECRET`, which authorises a different thing. In production, an
app that uses `refreshOn` without it refuses to serve, saying what to set: a
random key per instance would fail silently.

That refusal comes on the first request, because on some platforms - Workers
- the environment is only there once a request arrives. Under Kubernetes or
any orchestrator with a readiness check, that is too late: the pod is already
taking traffic. Make the deploy itself fail instead, by declaring the secret
where every other variable is - in `env.ts`, which refuses a missing variable
before the server starts:

```ts title="src/env.ts"
export const env = createEnv({
  server: {
    // Signs refreshOn's names. Required in production; in development a
    // random key is fine, and what rsc-kit uses without one.
    RSC_SIGNING_SECRET:
      process.env.NODE_ENV === 'production' ? z.string().min(32) : z.string().optional(),
    // ...
  },
  // ...
})
```

An app without an `env.ts` gets the same from `assertSigningSecret()`, from
`@rsc-kit/core/changed`, called in `register()`. In development a random key
is fine, and is what you get.

How to generate it, where to keep it, and what rotating it does:
[Secrets](/hosts/deployment#secrets).

Names are signed when the page is served, never at build: a page stored at
build keeps everything else stored, and the part that carries the names is
filled per request. So the build does not need the secret.

## When nothing refreshes

In development the browser console says what the page is watching, region
by region, each time that changes:

```
[rsc-kit] refreshOn watching, by region:
  repos: team:1:repos @3
  page: inbox:ada @0
```

A region that declared `refreshOn` but is missing from that list rendered no
names, and the server's log says why, once - including when its function
returned none at all. And watching **stops while the
tab is hidden** - a background tab holds no connection - which the console
also says. Nothing is missed: shown again, the tab reconnects at the versions
it holds and refreshes whatever moved meanwhile.

## When many tabs show the same thing

When a name moves, every tab showing it asks for its sections again - 500 tabs
on one team's board are 500 renders. Each tab's render can differ by who is
looking, so by default each is its own. A section that is the same for
everyone allowed to see the page can say so:

```tsx title="src/app/status/board.section.tsx"
export default section('board', Board, { refreshOn: ['board'], shared: true })
```

Then the tabs asking because of the same change get one render between them:
the first tab's request renders it, and every other gets the same bytes.
Each tab's guards still run on its own request - a visitor who may not see
the page is still refused - and only a refresh a change triggered is shared,
so `refresh()` by hand, or after an action, always renders afresh.

Never set `shared` on a section that shows anything per visitor - their name,
their data, what they may do. The first tab's render is what every other tab
is shown, `rpc()` calls included: they run with the first visitor's session.

## What it costs

- **Per tab:** one open connection while the page is visible, closed when the
  tab is hidden and reopened when it is seen again. Idle, it carries a
  keepalive line every eight seconds ([set it lower](/hosts/deployment#streams-and-idle-timeouts)
  under a shorter idle timeout); a change is one line of about forty
  bytes.
- **Per change:** each tab showing the name asks for the sections that show
  it, once, however many names moved together. That request is the size of
  the section, not the page. A `shared` section renders once per change for
  every tab; any other renders once per tab.
- **On the server:** one ask of wherever the versions live, covering every tab
  that server holds - a thousand open tabs are one query, not a thousand. The
  ask may wait up to five seconds for a change: a database with `listen`, or a
  Go backend, answers the moment a version moves; a table without it is read
  once a second while the ask waits; Laravel answers at once and is asked again
  two seconds later. Plus one small read when each tab opens its stream.

Polling a section every two seconds instead costs a full render of it, per
tab, every two seconds, whether anything changed or not. The trade is the open
connection: cheap on Bun, Node and Workers; on a host that bills a function
for every second it is open, it is a second billed for as long as the tab is.

## Coming from Next.js

This is where `revalidateTag` was, and it is not the same thing. Next's tags
label entries in its Data Cache and `revalidateTag()` throws them away, so the
*next request* refetches; an open tab learns nothing until it navigates.
There is no data cache here - every render is fresh - so `refreshOn` names
what is *on screen*, and `changed()` refreshes every open tab showing it, now.
A port keeps its names: `tags: ['posts']` on the fetch becomes
`refreshOn: ['posts']` on the section, and `revalidateTag('posts')` becomes
`changed('posts')`.

A name's version reveals only that something with that name changed. Do not
put a secret in a name.
