# Realtime: a live check-ins board

This chapter continues the brewery from [Getting Started](getting-started.md)
and builds on the `brewery_member` setup from
[Authentication](authentication.md) (schema in [`brewery.sql`][brewery-sql]).
Regulars already post check-ins as `brewery_member`; now we'll push each new
one to a browser the moment it lands — a live check-ins board — over Bier's
SSE endpoint.

We'll build it twice. Steps 1–4 use a trigger and PostgreSQL's
`LISTEN`/`NOTIFY`, which works on any PostgreSQL with no server settings to
change. Step 5 drops the trigger and streams the table's own changes from
the write-ahead log, which also carries the row itself and lets a
reconnecting client catch up on what it missed.

[brewery-sql]: https://github.com/milmazz/bier/blob/main/docs/tutorials/brewery.sql

## 1. Expose a channel

Add `events_channels` to the options you already booted Bier with in
[Getting Started](getting-started.md) (or
[Authentication](authentication.md), if you've since added `jwt_secret`) —
keep every other option exactly as it was:

```elixir
{Bier,
 name: Tutorial,
 router: [port: 4040, scheme: :http],
 database: "bier_tutorial",
 username: "authenticator",
 password: "mysecretpassword",
 db_schemas: ["api"],
 db_anon_role: "web_anon",
 jwt_secret: "the-tutorial-jwt-secret-change-me-please",
 events_channels: ["new_check_ins"]}
```

## 2. Notify on insert

The payload is a key, not the row — NOTIFY payloads are capped at 8000
bytes, and sending just the id lets the client fetch exactly the columns it
wants through the API it already knows. Add this trigger to your database:

```sql
create or replace function api.notify_new_check_in()
returns trigger language plpgsql as $$
begin
  perform pg_notify('new_check_ins', new.id::text);
  return new;
end;
$$;

create trigger check_ins_notify
  after insert on api.check_ins
  for each row execute function api.notify_new_check_in();
```

## 3. Listen in the browser

```javascript
const es = new EventSource("/events?channel=new_check_ins");

es.addEventListener("new_check_ins", async (e) => {
  // web_anon has `select` on both check_ins and beers (needed for the
  // embed), so this fetch works with no token even though posting one
  // does not.
  const res = await fetch(
    `/check_ins?id=eq.${e.data}&select=id,drinker,rating,comment,beers(name)`
  );
  const [checkIn] = await res.json();
  renderRow(checkIn); // your UI code
});
```

## 4. Try it

Posting still requires the `brewery_member` token from
[Authentication](authentication.md#mint-a-token) — mint one there if you
don't already have `$TOKEN` set:

```bash
curl -X POST "http://localhost:4040/check_ins" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"beer_id": 2, "drinker": "jamie", "rating": 4, "comment": "Hazy and delicious"}'
```

The `new_check_ins` event fires, the browser fetches the row — beer name and
all — and the board updates: no polling, no extra realtime service.

That board has three soft spots, all inherited from `NOTIFY`: every table
you want live needs its own trigger, the payload is capped at 8000 bytes
(which is why it carries only an id), and a check-in posted while the
browser was offline is simply never announced. The next step removes all
three.

## 5. Skip the trigger: stream the table itself

PostgreSQL already records every change to `check_ins` in its write-ahead
log (WAL). Bier can stream that record as a **change feed**: one event per
inserted, updated or deleted row, carrying the row, with a cursor a client
can resume from.

### Turn on logical replication

This part is one-time database setup, and it needs a superuser — run it as
the account you loaded `brewery.sql` with, not as `authenticator`. First
check the server's WAL level:

```sql
show wal_level;
```

If it does not say `logical`, change it and **restart PostgreSQL** — the
setting only takes effect on a restart:

```sql
alter system set wal_level = logical;
```

Then name the tables to stream in a *publication*, and let the role Bier
connects as open a replication connection:

```sql
create publication bier_events for table api.check_ins;
alter role authenticator replication;
```

Bier never runs any of this for you. The publication is the allowlist: a
table that is not in it cannot be subscribed, whatever a client asks for.

### Point Bier at the publication

Add `events_publication` to the same options — `events_channels` can stay,
the two work side by side:

```elixir
{Bier,
 name: Tutorial,
 router: [port: 4040, scheme: :http],
 database: "bier_tutorial",
 username: "authenticator",
 password: "mysecretpassword",
 db_schemas: ["api"],
 db_anon_role: "web_anon",
 jwt_secret: "the-tutorial-jwt-secret-change-me-please",
 events_channels: ["new_check_ins"],
 events_publication: "bier_events"}
```

If a prerequisite is missing, Bier refuses to boot and names the statement
to run — skip the `alter role` above, for instance, and startup fails with:

```text
** (ArgumentError) the connection role lacks the REPLICATION attribute — run: ALTER ROLE <role> REPLICATION;
```

### Watch a change arrive

Subscribe with `table=` instead of `channel=`. `curl -N` keeps the
connection open and prints events as they come:

```bash
curl -N "http://localhost:4040/events?table=check_ins"
```

In a second terminal, post a check-in exactly as in step 4:

```bash
curl -X POST "http://localhost:4040/check_ins" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"beer_id": 3, "drinker": "jamie", "rating": 5, "comment": "Crisp"}'
```

The first terminal prints the change:

```text
event: check_ins
id: 0/1B80CF08.0
data: {"commit_at":"2026-11-29T20:24:50.943523Z","row":{"beer_id":3,"comment":"Crisp","created_at":"2026-11-29 20:24:50.907443+00","drinker":"jamie","id":8,"rating":5},"schema":"api","table":"check_ins","type":"INSERT","unchanged":[]}
```

* `event:` is the table's name, so one connection can carry several
  published tables (`table=a,b`) and channels (`channel=new_check_ins`) at
  once.
* `id:` is a cursor into the stream. Yours will differ; hold on to it for
  the next section.
* `data:` is the change. `type` is `INSERT`, `UPDATE`, `DELETE` or
  `TRUNCATE`, and `row` is the new row — the whole thing, no 8000-byte cap,
  no trigger.

No token was needed to subscribe: the request ran as `web_anon`, which has
`select` on `check_ins`, and `row` carries exactly the columns the
subscriber's role may select. A role with no `select` on the table — or a
request for a table that is not in the publication, such as
`table=beers` here — gets a `404` instead of a stream.

Updates and deletes arrive the same way. `brewery_member` may only insert,
so make these from `psql`:

```sql
update api.check_ins set rating = 4 where id = 8;
delete from api.check_ins where id = 8;
```

```text
event: check_ins
id: 0/1B80D0E8.0
data: {"commit_at":"2026-11-29T20:26:49.642577Z","row":{"beer_id":3,"comment":"Crisp","created_at":"2026-11-29 20:24:50.907443+00","drinker":"jamie","id":8,"rating":4},"schema":"api","table":"check_ins","type":"UPDATE","unchanged":[]}

event: check_ins
id: 0/1B80D158.0
data: {"commit_at":"2026-11-29T20:26:49.646168Z","old":{"id":8},"old_kind":"key","schema":"api","table":"check_ins","type":"DELETE"}
```

A delete has no `row`; its `old` holds the primary key of the row that went
away. (How much of the previous row `old` carries is the table's
`REPLICA IDENTITY` — see the
[guide](../guides/realtime_events.md#replica-identity-and-old).)

### Catch up after a disconnect

Stop the first `curl` (`Ctrl+C`), post another check-in or two, then
subscribe again and hand back the last `id:` you saw:

```bash
curl -N "http://localhost:4040/events?table=check_ins&last_event_id=0/1B80D158.0"
```

Everything committed after that cursor is replayed first, then the stream
carries on live. This is the part `NOTIFY` cannot do. `EventSource` does it
for you: when its connection drops it reconnects with the last `id:` it
received in a `Last-Event-ID` header.

Replay comes from a bounded in-memory window (the last 1024 changes per
table by default, `events_buffer_size`), and it does not survive a restart
of Bier. When a cursor can no longer be honored, Bier does not skip
silently — it says so with a control event, then continues from the
present. Restart Bier and repeat the `curl` above to see one:

```text
event: bier:reset
data: {"reason":"stream_restarted"}
```

(`history_evicted` is the other reason you will meet: the cursor is from
the running stream, but has aged out of the window.)

### The board, without the trigger

```javascript
const es = new EventSource("/events?table=check_ins");

es.addEventListener("check_ins", (e) => {
  const change = JSON.parse(e.data);
  if (change.type === "INSERT") renderRow(change.row); // your UI code
});

// Some history could not be replayed: reload the board from the API, then
// keep listening — the connection stays open.
es.addEventListener("bier:reset", () => reloadBoard());

// The server ended the stream on purpose (the token expired, say). Close
// it, or EventSource will keep reconnecting into a refusal.
es.addEventListener("bier:closed", () => es.close());
```

`change.row` is the `check_ins` row and nothing else — `beer_id`, not the
beer's name. Either keep the beers you already loaded in a map and look the
name up, or do what step 3 did and fetch
`/check_ins?id=eq.${change.row.id}&select=...,beers(name)`: the event tells
you *that* something changed and the API fetches the shape you want.

Two details to know before relying on `row`:

* Values are PostgreSQL's own text form, which is not always what the REST
  API returns. `created_at` above is `2026-11-29 20:24:50.907443+00`; the
  same row from `GET /check_ins` says `2026-11-29T20:24:50.907443+00:00`.
  Integers, booleans and JSON columns come through as JSON; everything else
  — timestamps, `numeric`, arrays — is a string.
* A table with row-level security enabled cannot be subscribed in this
  release.

### Which one should I use?

* **`channel=` (NOTIFY)** when you want to announce something that is not a
  row change, when you would rather send a small custom payload, or when
  you cannot change `wal_level` — it needs no server configuration.
* **`table=` (change feed)** when the event *is* the row change: no trigger
  to maintain per table, no payload cap, updates and deletes for free, and
  a client that reconnects catches up instead of missing events.

For authentication, multiplexing, delivery guarantees, every control event,
partitioned tables, limits and telemetry, see the
[Realtime events guide](../guides/realtime_events.md).
