Skip to the page

Reference · Project API

Live queries

Subscribe to read queries over one Server-Sent Events connection and get each change as a patch at commit.

In the schema
—

Live streams#

Every live evaluation re-runs as the authenticated caller against the latest database snapshot, so permission changes take effect in real time. If a user loses access to a shared record, the record leaves their open stream on the same commit.

Multiplexed live patches

One SSE connection streams commit-aligned row diffs across all active subscriptions.

In-memory object rooms

Callers permitted to read an object can share presence state and messages.

Open a multiplexed stream at POST /subscribe to receive initial snapshots and commit-aligned row patches over Server-Sent Events. See Live queries & presence for subscriptions, access, limits and rooms.

POST/subscribe#

Body

subscriptionsarrayrequired
List of read queries to multiplex onto the SSE stream.
subscriptions.idstringrequired
Client-chosen subscription identifier referenced in result, patch and error frames.
subscriptions.querystring
Ad-hoc read-only EdgeQL statement (when allowed by passthrough).
subscriptions.namestring
Deployed query name (used instead of query).
subscriptions.variablesobject
Parameter map for the query’s $name variables.
subscriptions.afterstring
Bookmark of the client’s cached snapshot (the floor from the last applied frame). Sends an initial diff instead of the full result when the change log covers that bookmark.
lsnstring
Optional opaque commit bookmark from a prior stream to guarantee monotonic reconnection without stale snapshots.

The server responds with Content-Type: text/event-stream. Every result and patch event carries an opaque lsn bookmark token (also set as the SSE id: field) for the causal snapshot position. Each event also carries floor, a lower-bound bookmark guaranteeing that every commit at or before floor is reflected in the frame (or null when unavailable). Treat both lsn and floor as opaque tokens: pass lsn unmodified when reconnecting, and store floor alongside locally cached rows.

Request · curl
curl -N https://notes.napalmdata.com/subscribe \  -H "Authorization: Bearer $SESSION" \  -H "Content-Type: application/json" \  -d {    "subscriptions": [      { "id": "notes", "query": "select Note { title, done } filter .owner = global caller order by .title" },      { "id": "note", "name": "getNote", "variables": { "id": "8f2c1e64-0b7a-4f4e-9d2b-3a6c5e1f7d90" } }    ]  }
SSE stream frames
event: openeddata: {"stream":"e2.k4Q9…","heartbeat_seconds":15} event: resultid: nbm_0192c3f4_7c3f1adata: {"lsn":"nbm_0192c3f4_7c3f1a","floor":"nbm_0192c3f4_7c3f1a","results":[  {"subscription":"notes","data":[{"id":"8f2c…","title":"Launch checklist","done":false}]},  {"subscription":"note","data":[{"id":"8f2c…","title":"Launch checklist","body":"…"}]}]} event: patchid: nbm_0192c3f4_9b2e4ddata: {"lsn":"nbm_0192c3f4_9b2e4d","floor":"nbm_0192c3f4_9b2e4d","patches":[  {"subscription":"notes","changed":[{"id":"8f2c…","done":true}],"removed":[]},  {"subscription":"note","changed":[{"id":"8f2c…","done":true}],"removed":[]}]}

Each open stream emits five Server-Sent Event types.

Event typePayload fieldsWhen emitted
openedstream, heartbeat_secondsWhen emittedSent immediately when the stream opens. Provides the stream handle for dynamic add/drop calls.
resultlsn, floor, resultsWhen emittedFull query results sent on open, on each added subscription and on reconnect. A subscription with after receives a patch instead whenever the change log covers that bookmark.
patchlsn, floor, patchesWhen emittedIncremental diff emitted when a commit modifies the result of one or more active subscriptions.
errorsubscription?, errorWhen emittedTerminates a single subscription (when subscription is set) or closes the entire stream (when omitted, e.g., on credential expiry).
heartbeatlsnWhen emittedSent every 15 seconds on idle streams to keep proxies and load balancers open.

Incremental diff patches#

For queries that return object shapes, patches are keyed by object id so clients transfer and update only the changed data.

changed
Objects newly entering the result set (with all selected fields) and existing objects whose fields changed (carrying id plus only the modified fields).
removed
Array of UUIDs for objects that were deleted or no longer match the query filter or access policy.
order
The result set’s object UUIDs in the new order. Included only when the relative sort order of existing rows changed.
data
Used instead of changed/removed when a query returns scalar or aggregate values without top-level object IDs (such as select count(Note)).

Commits that land close together coalesce into a single patch frame.

Multi-query snapshot consistency#

All subscriptions on a single stream advance in lockstep. When a transaction modifies rows affecting both a list query and a detail query on your screen, both updates are evaluated at the same snapshot and delivered in a single atomic patch event. Components never show a torn UI state.

Subscription changes#

POST/subscribe/{stream}#

POST /subscribe/{stream} adds and drops subscriptions on an open stream without a second SSE connection. Call the route with the same bearer token as users open and close views in your app. Added subscriptions emit an initial result frame on the open stream, and dropped subscriptions stop immediately. If the stream has already closed, the endpoint returns 404 not_found. Send your session’s Napalm-Bookmark with the call, and each added subscription’s first result includes your own writes up to that bookmark.

Request · curl
curl https://notes.napalmdata.com/subscribe/e2.k4Q9… \  -H "Authorization: Bearer $SESSION" \  -H "Content-Type: application/json" \  -d '{ "add": [{ "id": "drafts", "name": "listDrafts" }], "drop": ["note"] }'

Reconnection#

If a mobile or browser network connection drops, open a new POST /subscribe stream and pass the last received lsn in the JSON body (or in the standard SSE Last-Event-ID header). Napalm waits until the data reaches at least that lsn before sending the fresh result frame. Reconnecting clients never see state move backward.

A client that caches a subscription’s rows can pass the last frame’s floor as after. The subscription’s first frame is then a patch carrying each modified row in full plus order with every current result ID, so any cached row absent from order has left the result. If the bookmark predates the retained change log, the cluster keeps no change log or the branch spans multiple shards, Napalm sends a full result frame instead. POST /query/{name}/changes returns the same diff over a single HTTP call.

Access policies and limits#

Caller’s access
Each re-evaluation runs as the authenticated caller with the caller’s forced globals and access policies applied.
Passthrough enforcement
Any caller can subscribe to a deployed query by name. Subscribing with an ad-hoc query string requires the project’s passthrough to admit the caller. Otherwise, the subscription receives an error frame with deployed_query_required.
Read-only queries
Mutating statements (insert, update, delete) are rejected on /subscribe.
Actions
You cannot subscribe to a deployed query with a handler attached, because the query’s rows go only to the handler. Subscribing by name returns an error frame with action_not_live. An open subscription receives the same frame if the query becomes an action.
Subscription cap
A project holds up to 1,000 subscriptions at once for each GiB of engine memory, across every open stream and branch. A subscription past the limit returns 429 live_limit_reached.
Credential cutoff
When a service key is revoked or a user session expires, all streams using that credential are terminated within seconds with an error frame (key_revoked or session_ended).

Presence and messages#

Every object has an in-memory room keyed by the object’s UUID. A stream that joins a room sees active members and their ephemeral state, and can broadcast messages to the room. Joining evaluates select access as the stream’s caller, and revoking read access removes the member on the same commit. Presence state and messages are never written to PostgreSQL.

POST/subscribe/{stream}/presence#

Body

joinarray
Rooms to join, each { "channel": <object id>, "state": {…} }. Include "resume" from the prior connection to keep the same member ID, and add "after" with the last received position to replay missed messages.
setarray
Updated state for joined rooms, each { "channel", "state" }. Replaces the member’s previous state.
sendarray
Messages to a room’s members, each { "channel", "message" }. Messages are delivered at most once. A room keeps messages for 10 seconds for a member who reconnects.
leavearray
Object IDs of rooms to leave.
watcharray
Object IDs of rooms to watch without joining. Emits the person count and the first 5 people whenever room membership changes, without adding the watcher as a visible member.
unwatcharray
Object IDs of rooms to stop watching.

Returns { "channels": n, "dropped": n } counting joined rooms and messages dropped because the caller had not joined yet or exceeded the rate limit (plus "watching": n when watching rooms). POST /subscribe also accepts "presence": { "join": […], "watch": […] } alongside subscriptions so a stream can join and watch rooms when opening. Room events arrive across five SSE frame types.

EventFieldsWhen
presencechannel, self, resume, members, position, is_continuous?WhenSent on initial join or after falling behind. Lists every member as { id, kind, identity, person, state }, where kind is session, agent or key (keys omit identity) and "is_away": true marks a stream disconnected for more than 2 seconds. Also returns the member’s resume token, message position and is_continuous (false if messages were missed since after).
presencechannel, changed, removedWhenchanged lists the current state of members who joined, updated state, went away or reconnected. removed lists the IDs of members who left.
broadcastchannel, messages, positionWhenMessages sent to the room, in one order for the whole room. A member’s message is { from, message }, including the member’s own messages. A message from outside the room is { sender, message }, where sender is { kind, identity, person } as on a member.
watchchannelsWhenRooms the stream watches, each as { channel, person_count, people }, sent when the room’s people change. people lists the first 5 people, each as { kind, identity, person }. A room the caller cannot read comes once as { channel, error } with not_found and is dropped.
errorchannel, errorWhenThe stream is out of that room. not_found means the caller may no longer read the object. resumed means a newer stream took the member’s place. The stream itself stays open.

Presence rooms enforce the following membership, reconnection and rate-limit rules.

Members
A member is a stream’s place in a room, so two tabs are two members. person is the same on every member of one person or one key. Group by person to list people. identity is the person the project signed in, not a claim the member makes.
Reconnecting
When a member’s stream ends, the room holds the member’s place for 10 seconds. A new stream that joins with the member’s resume in that time is the same member, and nobody sees the member leave. If the new stream joins within 2 seconds, other members see no change. After 2 seconds, other members see "is_away": true on the member until the member reconnects. After 10 seconds, the member leaves. resume only preserves the member ID and never admits a caller who cannot read the object.
Messages while away
A room keeps the last 10 seconds of messages, up to 256 messages and 64 KiB. A stream that joins with resume and after gets the whole room, then one broadcast with the messages since that position, then new messages. "is_continuous": false on the room means some messages may be missing. Either more messages were sent than a room keeps, the member’s place was lost or a server failed. A stream that reconnects during a Napalm deploy misses nothing. Treat a position as opaque.
Watching a list
To show the people in each of fifty documents, watch the documents’ rooms instead of joining. A watcher gets a count and the first 5 people but never states or messages. A stream may watch up to 256 rooms (429 presence_limit_reached). A stream’s watched rooms count as one subscription per object type toward the project’s subscription limit (429 live_limit_reached). If the caller loses read access to a watched room, the room comes as not_found and is dropped. Watch the room again to check again.
Hidden objects
Unreadable objects and unknown IDs both return not_found, so room joins never reveal whether an object exists.
Limits
A state up to 4 KiB and a message up to 16 KiB (413 presence_too_large). 16 rooms per stream (429 presence_limit_reached). 200 members per room (channel_full). 32 messages a second from a member. Messages past that rate are dropped and counted. Each joined room counts as one subscription toward the project’s subscription limit (429 live_limit_reached).
Pace
A room sends at most one frame every 50 ms. States set in between collapse to the latest state.

Backend servers and action handlers acting as a caller can inspect room membership or broadcast messages over HTTP without opening an SSE stream. Both routes enforce the caller’s select policy on the target object and return 404 not_found when the object does not exist or cannot be read.

GET/presence/{object}#

Returns { "channel": <object id>, "members": […] } using the same member shape as a presence frame. An empty room returns an empty members array.

POST/presence/{object}#

Body

messageanyrequired
The message for the room’s members, up to 16 KiB (413 presence_too_large).

Answers { "member_count": n }, the number of members who received the message (zero in an empty room). Members receive the message in the same order as messages between members, and the caller appears as the message’s sender. One caller may send a room 32 messages a second and gets 429 presence_rate_reached past that rate. During a Napalm deploy, both routes can answer 503 project_unavailable for a moment. Retry the request.

Client SDKs and the CLI watcher#

napalm-client manages connection multiplexing, patch application and automatic reconnection with lsn tracking. Subscriptions share one bookmark with calls made through the client’s fetch, so a subscription opened after a write starts at or past that write.

app.ts
import { NapalmClient, deployed } from 'napalm-client' const napalm = new NapalmClient('https://notes.napalmdata.com', { token: () => session }) const notes = napalm.subscribe(deployed('listNotes'), {}, {  onRows: ({ rows }) => render(rows),  onError: (error) => console.error(error.code),}) // Later, when the component unmounts:notes.close()

napalm generate --lang ts generates typed subscription helpers in live.ts and React hooks in hooks.ts (--lang dart generates live.dart streams for Flutter).

Notes.tsx
import { useListNotes } from './napalm/hooks' export function Notes() {  const { rows = [], error } = useListNotes()  if (error) return <p>{error.message}</p>  return <ul>{rows.map((note) => <li key={note.id}>{note.title}</li>)}</ul>}

Watch any live query from your terminal with napalm watch.

Terminal
napalm watch notes "select Note { title, done } filter .done = false"

Type a word or two to search every docs page.