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. Live queries & presence explains subscriptions, access, limits and rooms.

Commit-aligned SSE patches

POST /subscribe multiplexes read queries onto one event stream, emitting id-keyed diffs and lsn bookmarks in lockstep as transactions commit.

Ephemeral per-object rooms

Any caller permitted to read an object can join or watch its in-memory room for live member state and low-latency messages without writing to disk.

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
The bookmark a stored copy of the rows stands at: the floor of the last frame the copy applied. The first frame is then the changes since that bookmark, not the whole result.
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: every commit at or before that bookmark is in the frame’s rows, or null when the project cannot assign a lower-bound bookmark. Treat both lsn and floor as opaque tokens. Pass lsn back unmodified when reconnecting, and keep floor beside a stored copy of the 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":[]}]}
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 a room named by the object’s id. A stream that joins a room sees the room’s other members and each member’s small state, and can send messages to those members. Joining reads the object as the stream’s caller, so any caller who may read the object may join. A member is removed at the commit that takes away read access. Nothing in a room is written to the database.

POST/subscribe/{stream}/presence#

Body

joinarray
Rooms to join, each { "channel": <object id>, "state": {…} }. To keep the member’s id, add the "resume" value the stream’s last connection received for that room. To get the messages sent since, also add "after" set to the last position that connection received.
setarray
A new state in a room already joined, each { "channel", "state" }. The new state replaces the 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
Ids of rooms to leave.
watcharray
Ids of rooms to watch without joining. For each watched room, the stream gets the number of people and the first 5 people each time the room’s people change. Watching creates no member, so nobody in the room sees the watcher.
unwatcharray
Ids of rooms to stop watching.

The answer { "channels": n, "dropped": n } counts the rooms the stream has joined or is joining, and the messages that were not passed on. A message is not passed on when the sender is not a member yet or is past the rate limit. With rooms watched, the answer also has "watching": n. POST /subscribe also takes "presence": { "join": […], "watch": […] } beside the subscriptions, so a stream can join and watch rooms as it opens. Room events arrive on the stream across five frame types.

EventFieldsWhen
presencechannel, self, resume, members, position, is_continuous?WhenThe stream was let in or fell behind. Carries the whole room, with each member as { id, kind, identity, person, state }. kind is session, agent or key. A key has no identity. A member whose stream has been down for two seconds has "is_away": true. resume belongs to that member alone. position marks how far the stream has received the room’s messages. is_continuous comes with a join that named after and after the stream falls behind. The value is false when some messages since then were not sent.
presencechannel, changed, removedWhenchanged lists members who joined, changed state, went away or came back, as each member is now. 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.
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 two seconds, the others see no change. After two seconds, the others see "is_away": true on the member until the member is back. After 10 seconds, the member leaves. resume only keeps an id and never lets in 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
An object the caller cannot read and an id that names nothing get the same refusal, not_found. A room cannot reveal which objects exist.
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.

A server can use a room without joining. A service key or a handler acting as the caller can read the members of an object’s room or send the members a message. Access works as for joining, so the caller must be able to read the object. Other callers get 404 not_found, and so does an id that names nothing.

GET/presence/{object}#

Answers { "channel": <object id>, "members": […] }, with each member in the same form as a presence frame. An empty room has no members.

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.