Guides · App patterns
Realtime & collaboration
Keep shared screens synchronized with live queries, apply optimistic UI updates, maintain fractional card ordering and share in-memory presence.
- CLI
napalm watch- 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. Lists and edits run on database rows and live queries, while active-viewer indicators use in-memory presence rooms. You do not run a separate realtime server beside the database.
A live query is a deployed read query that the client keeps open over Server-Sent Events. Every update runs under the viewer’s access policies inside PostgreSQL, so unsharing a note removes that note from the viewer’s screen at that exact commit. Live queries & presence covers subscriptions, access, limits and rooms.
Share and order notes#
Extend the starter schema with three fields on Note: a multi-link of permitted editors, a fractional sort position and an optimistic concurrency version counter.
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.
select Note { id, title, body, position, version }order by .position then .id# 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 to build typed React hooks.
Subscribe to live updates#
Generated hooks multiplex every active read query on a page over one shared POST /subscribe SSE stream. All mounted views advance together at each commit cut so list and detail panels never disagree.
Shared live stream
Mounted hooks share one SSE stream and receive patches at each commit.
Call the generated useNotesInOrder hook in your list component and highlight rows updated in the latest commit frame.
// 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- Starts
undefineduntil the initial snapshot arrives, then holds the complete current array. After a network drop, the hook preserves the last rows on screen and resumes from the stored commit bookmark. changes- Lists row-level
insert,updateanddeleteevents from the latest commit frame, including before and after values. Usechangesfor transient animations such as highlighting an edited row. - Shared stream
- Every mounted hook on the page shares one
POST /subscribeconnection. Mounting a hook subscribes the query, and unmounting unsubscribes it. - CLI inspection
napalm watch notes "select Note { title } order by .position"streams the same frames in your terminal so you can inspect live patches as commits land.
Apply optimistic updates#
A dragged note should land at its drop target immediately without waiting for a network round trip. Record the pending move in local state and keep that override active until the live query rows reflect the committed position, or roll back if the mutation fails.
// 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) /** Places a note between two neighbor keys (pass null at the start or end). */ 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 }}Hold the optimistic override until rows updates rather than clearing state as soon as the HTTP mutation resolves. Because the HTTP response can arrive a few milliseconds ahead of the SSE commit frame, React’s built-in useOptimistic can briefly snap back to the old order in between.
Order items with fractional keys#
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.
Fractional sort keys
Byte-ordered midpoint keys reorder items in a single-row update without renumbering neighbors.
Moving a note updates only that note’s position string.
update Notefilter .id = <uuid>$noteset { position := <str>$position }- Generating keys
- fractional-indexing provides
generateKeyBetween(above, below)to compute a midpoint string between two neighbors. Passnullat the start or end of the list, such asgenerateKeyBetween(last, null)to append. - Byte-order sorting
- PostgreSQL orders fractional keys by raw byte value. Sort client arrays with
<and>rather thanlocaleCompare, which sorts case-insensitively and placesabeforeB. - Concurrent drops
- If two users drop different notes into the exact same gap simultaneously, both rows receive the same midpoint key. Ordering by
.position then .idbreaks ties deterministically for every viewer until the next drag assigns 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.
# Updates only when .version matches $version, returning empty on a concurrent edit.select ( update Note filter .id = <uuid>$note and .version = <int64>$version set { body := <str>$body, version := .version + 1 }) { id, version }// src/saveBody.tsimport { call } from './napalm' /** Saves a note body against its starting version and returns false on 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.
In-memory presence rooms
Permitted viewers share live cursors and reactions in memory without database writes.
Pass the note ID and initial viewer state to usePresence to show who has the note open and who is typing.
// 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
peoplelists everyone else in the room, one entry per person.peerslists 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
isAwayturns 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
setreplaces your state, andupdatemerges 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
sendpasses 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, andonMissedfires 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 andnapalm.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 live updates across two windows#
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.Drag a note in one window
The note moves immediately in the first window and updates in the second window as soon as the commit streams back. Dragging two notes into the same gap simultaneously settles on the same deterministic order in both windows.
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.
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.