Skip to the page

Guides · App patterns

Realtime & collaboration

Keep a shared screen current with live queries, show a change before the commit, keep a draggable order and show who else is present.

In the schema
—

What you’ll build#

This page shares the first app’s notes across multiple people with one shared list order, instant updates, optimistic version checks that never silently overwrite another editor’s save and live active-viewer indicators. The list and edits run on rows and live queries while active viewers use in-memory presence rooms. Nothing else runs beside the database.

A live query is a deployed read the client keeps open. Every step runs under the viewer’s access rules inside PostgreSQL, so when a note is unshared, it vanishes from that viewer’s screen at that commit. Live queries & presence covers subscriptions, access, limits and rooms.

Share and order notes#

The first app’s schema takes three additions covering a note’s editors, a fractional sort position and an edit version counter.

dbschema/default.gel
using extension napalm; module default {  global caller := global ext::auth::ClientTokenIdentity;   # Project API statements cannot reference ext::auth types directly, so a schema function resolves an identity.  function identity_by_id(target: uuid) -> optional ext::auth::Identity    using (select ext::auth::Identity filter .id = target);   type Note {    required owner: ext::auth::Identity;    multi editors: ext::auth::Identity;    required title: str;    required body: str;    # Lexicographic sort key so a moved note fits between any two neighbors in one row write.    required position: str;    # Monotonic edit counter so concurrent saves detect intervening commits.    required version: int64 {      default := 0;    };     access policy owner_has_full_access      allow all      using (.owner ?= global caller);    access policy editors_can_read_and_change      allow select, update      using ((global caller in .editors) ?? false);  }}

Save each query as a file inside dbschema/queries.

dbschema/queries/notesInOrder.edgeql
select Note { id, title, body, position, version }order by .position then .id
dbschema/queries/shareNote.edgeql
# Only the note's owner may grant editor access.update Notefilter .id = <uuid>$note and .owner ?= global callerset { editors += identity_by_id(<uuid>$person) }

Push the schema and queries with napalm schema push notes. Then run npm run generate for a typed hook for each read.

Keep the list current#

Generated hooks multiplex every active read query on a page over one shared POST /subscribe SSE stream, advancing all mounted views together at each commit cut so list and detail panels never disagree.

Multiplexed POST /subscribe commit stream

Mounted hooks share one SSE connection and receive id-based insert, update and delete patches at each commit cut under the viewer’s access rules.

src/NoteList.tsx
// src/NoteList.tsximport { useNotesInOrder } from './generated/hooks' export function NoteList() {  // Delivers the initial list once, then incremental patches on every matching commit.  const { rows, changes, error } = useNotesInOrder()   // Track row IDs updated in the latest commit frame to highlight fresh edits.  const edited = new Set(changes.filter((change) => change.type === 'update').map((change) => change.id))   return (    <ul>      {rows?.map((note) => (        <li key={note.id} className={edited.has(note.id) ? 'just-edited' : undefined}>          {note.title}        </li>      ))}      {error && <li role="alert">{error.message}</li>}    </ul>  )}
rows
Undefined until the first result, then always the whole current list. After a lost connection, the hook keeps the last rows and resumes from the same commit on reconnect.
changes
The last step’s changes by id. Each change is an insert, update or delete with the row before and after. Use changes for transient UI feedback a plain re-render cannot express, such as flashing an updated row.
One connection
Every hook on the page shares one stream. Mounting a hook adds its query to the stream, and unmounting removes the query.
From a terminal
napalm watch notes "select Note { title } order by .position" prints the same steps. Use napalm watch to see the steps a change sends.

Show a move before the commit#

A dragged note should land at the drop point without waiting a round trip. The list shows the move at once and holds it until the live rows reflect the new position. If the write is refused, the note goes back.

src/useOrderedNotes.ts
// src/useOrderedNotes.tsimport { useEffect, useState } from 'react'import { generateKeyBetween } from 'fractional-indexing'import { useNotesInOrder } from './generated/hooks'import { call } from './napalm' /** Pending optimistic move keyed by target position and prior server position. */type Move = { to: string; from: string } // Match PostgreSQL bytewise codepoint order rather than localeCompare.const inOrder = (a: { position: string; id: string }, b: { position: string; id: string }) =>  a.position < b.position ? -1 : a.position > b.position ? 1 : a.id < b.id ? -1 : 1 export function useOrderedNotes() {  const { rows } = useNotesInOrder()  const [moves, setMoves] = useState<ReadonlyMap<string, Move>>(new Map())   // Clear optimistic overrides as soon as the live stream reflects a newer server position.  useEffect(() => {    setMoves((was) => {      const waiting = [...was].filter(([id, move]) => rows?.find((note) => note.id === id)?.position === move.from)      return waiting.length === was.size ? was : new Map(waiting)    })  }, [rows])   const notes = (rows ?? [])    .map((note) => ({ ...note, position: moves.get(note.id)?.to ?? note.position }))    .sort(inOrder)   /** Place a note between two neighbors; pass null for the start or end of the list. */  async function move(id: string, above: string | null, below: string | null) {    const from = notes.find((note) => note.id === id)?.position    if (from === undefined) return    const to = generateKeyBetween(above, below)    setMoves((was) => new Map(was).set(id, { to, from }))    try {      await call('moveNote', { note: id, position: to })    } catch (error) {      setMoves((was) => new Map([...was].filter(([moved]) => moved !== id)))      throw error    }  }   return { notes, move }}

The list holds the move until the rows change rather than until the write returns, because the write’s response can arrive a moment before the stream’s step. React’s useOptimistic drops the optimistic state when the write returns, so over a live query the hook can show the old order for that moment.

Keep a draggable order#

Numbering rows 1, 2, 3 rewrites every row when a note moves to the top, and halving numeric gaps exhausts floating-point precision after roughly fifty drops into one slot. A byte-ordered text sort key avoids both failure modes because a fresh midpoint key always fits between two neighbors, so dragging updates a single row.

Optimistic moves & fractional sort keys

Byte-ordered generateKeyBetween(above, below) keys insert a midpoint between neighbors in a single-row write while the UI holds the dragged position until the live stream confirms the commit.

dbschema/queries/moveNote.edgeql
update Notefilter .id = <uuid>$noteset { position := <str>$position }
Making keys
fractional-indexing’s generateKeyBetween(above, below) returns a key between two keys. Pass null for a key before the first or after the last. A new note at the bottom is generateKeyBetween(last, null).
Text order
Napalm orders strings by byte value, and these keys are made for byte order. Sort the same way in the app with <, because localeCompare puts a before B.
Duplicate keys
Two people who drop different notes between the same neighbours at the same moment get the same key. order by .position then .id keeps one order for everyone. The next move between those notes makes a fresh key.

Handle concurrent edits#

An update sets only the named fields, and the last commit wins each field. Last-write-wins suits a title or a position, whereas concurrent body edits need optimistic version checking so neither author silently overwrites the other. Have the save filter on the starting version number.

dbschema/queries/saveBody.edgeql
# Writes only over the starting version; an empty result signals a concurrent save.select (  update Note  filter .id = <uuid>$note and .version = <int64>$version  set { body := <str>$body, version := .version + 1 }) { id, version }
src/saveBody.ts
// src/saveBody.tsimport { call } from './napalm' /** Save a note body against the version read when editing started; false indicates a conflict. */export async function saveBody(note: { id: string; version: number }, body: string): Promise<boolean> {  const saved = await call<{ id: string }>('saveBody', { note: note.id, version: note.version, body })  return saved.length > 0}

When a save returns empty, the live row already holds the other editor’s text, so the UI can display both versions side by side. Optimistic version checks catch conflicts without merging keystrokes character by character. For character-level CRDT merging, store a collaborative editor document inside a note field.

Show active viewers#

Every object has an in-memory room. Only people permitted to read a note can join its room, so presence needs no separate permission model. Inside the room, each viewer shares a small state with peers that is never written to the database.

Ephemeral per-object presence room

Viewers permitted to read the note share an in-memory room for cursor state and transient pings, evicted on the exact commit access is removed.

src/Viewers.tsx
// src/Viewers.tsximport { usePresence } from 'napalm-client/react' /** Ephemeral state shared across members in the note's presence room. */type Here = { name: string; isTyping: boolean } export function Viewers({ note, name }: { note: string; name: string }) {  // Joins the note's room over the multiplexed live-query SSE connection.  const { people, peers, isJoined, update } = usePresence<Here>(note, { state: { name, isTyping: false } })  // Deduplicate multiple open tabs per person.  const names = people.map((person) => person.members[0].state.name).join(', ')   return (    <>      <p>{!isJoined ? 'Joining…' : people.length === 0 ? 'Only you' : `${names} here`}</p>      <textarea onFocus={() => update({ isTyping: true })} onBlur={() => update({ isTyping: false })} />      {peers.some((peer) => peer.state.isTyping) && <p>Someone is typing…</p>}    </>  )}
Members
people lists everyone else in the room, one entry per person. peers lists each connection and its state. Two tabs are one person with two members, identified by project sign-in.
Leaving
A member leaves when the page closes. A dropped connection keeps the member slot for 10 seconds so a phone switching networks does not flicker out and back in. A reconnect within two seconds shows no change, while past two seconds isAway turns true on the member (and on the person once every connection for that person is away) until reconnect or expiry.
Access
Joining reads the note as the caller. A person removed from the note leaves the room at that exact commit, just as the note leaves that person’s live queries.
States
set replaces your state, and update merges fields into your state. A state holds up to 4 KiB. Changes go out at most every 50 ms, and the last change wins. A cursor position fits within those limits.
Messages
send passes a one-time message to everyone in the room, such as a reaction or pointer ping. Messages are capped at 16 KiB each and 32 per second and are never written to disk. A connection returning within 10 seconds receives missed messages in order, and onMissed fires if messages aged out.
From your server
A server does not join a room. With a service key, napalm.broadcast(note, message) sends a message to everyone in the note’s room and napalm.members(note) reads active members. A handler can make both calls under the caller’s access.
Across a list
A list of notes can show each note’s members without joining any room. napalm.watch(ids) returns the number of people with each note open and the first 5 people, and keeps the result current. Watchers stay invisible to room members. A page can watch 256 notes.
Limits
A page can be in 16 rooms at once, and a room holds 200 members. Each joined room counts as one subscription toward the project’s subscription limit.

Stay within live query limits#

Current time
Only commits advance a live result. A query comparing against wall-clock time does not re-evaluate as seconds pass, so evaluate relative timestamps in the UI.
Writes
Only reads stay live. A deployed query with an attached handler cannot be subscribed to because matching rows go to the handler.
Open live queries
A project keeps up to 1,000 live queries open at once for each GiB of engine memory, across all users. Past that limit, Napalm refuses new live queries with live_limit_reached. Pass { isPaused: true } to a hook for off-screen content.

Live queries documents the stream’s frames, bookmarks and end conditions.

Check with two windows#

  1. Open the app in two windows as two people

    Share a note from the first person to the second with shareNote. The note appears in the second window’s list without a reload.

  2. Drag a note in one window

    The note lands at once in that window and moves in the other window a moment later. Drag two notes into the same gap from both windows. Both lists settle on the same order.

  3. Save over a stale version

    Edit the same note in both windows and save both. The second save comes back empty, and that window shows the first save’s text.

  4. Close one window

    The other window shows “Only you” at once. If you remove that person from the note instead, the note vanishes from that person’s screen at that commit.

Type a word or two to search every docs page.