Your app talks to its backend over REST and it works — until a screen has to update because someone else wrote. Chat is the canonical case, and it changes the questions: what delivery latency should you design for, what happens to messages sent across a reconnect, and who else can listen?
Parse LiveQuery is a WebSocket channel on which the server pushes create, update and delete events for a query you subscribed to — events, not state: it tells you what just changed and nothing about what you missed. That one sentence decides most of the design below.
On November 2, 2026 we built a private-room chat on a live Back4app backend and measured it with raw REST and raw WebSocket frames — no SDK, only what a browser holds. Two fictitious companies, ACME and Borealis, chat in rooms that are ACL-scoped channels; every claim here is an observation from those runs, with its margin stated, never a guarantee.
Run it yourself: the lab is at github.com/templates-back4app/chat-lab — every number in this post is a script you can point at your own backend.
What should you design for when a message must appear on another open screen?
Design for roughly half a second of delivery, for a client that recovers its own gaps because the server will not, and for membership changes that take effect in seconds, not milliseconds, on already-open subscriptions. Those are this campaign’s observations, condensed:
| What you need to know | Observed in these tests (November 2, 2026, free plan) |
|---|---|
| Delivery to another open screen | 404.6 ms p50 / 507.6 ms p95 send-start → event; the same-session REST round trip alone was 403.6 ms p50 |
| Loss and duplicates | 0 lost, 0 duplicated across 6,300 expected deliveries (1, 10 and 50 subscribers) |
| Who can listen | room members only: outsider subscriptions, filtered and unfiltered, received 0 events |
| Messages sent while offline | never pushed on resubscribe — a paginated catch-up query is mandatory (the client ships one) |
| Removing a member | fresh requests refused once removeMember returns; the open subscription drains over a few seconds |
The working pattern has three parts. Clients subscribe to the Message class filtered by room, authenticated with their session token. Every write goes through a guarded Cloud function — no client ever writes a class directly. And every connect, the first one included, runs the same recovery sequence:
// Stack: Parse Server 7.5.2 on Back4app, raw LiveQuery protocol | File: usage of client/chat-client.mjs (condensed)
const chat = createChatClient({ serverUrl, appId, jsKey, sessionToken, roomId, lqUrl });
await chat.connect(); // subscribe → await the ack → buffer live events →
// paginated catch-up → dedup by objectId → reconcile
await chat.sendMessage('shipping at noon?'); // a guarded Cloud function, never a direct write
// after any disconnect: await chat.connect() again — the first connect IS a reconnect from the epoch
The setup checklist, in order — each step is expanded later in the post:
- Upload the three Cloud Code files, then prove the deploy with a request:
myRoomsmust answer code209, not141. - Create the schema through the token-gated
setupSchemafunction — the master key never leaves the dashboard. - Enable Live Query for the class
Messagein the dashboard and note thewss://subdomain. - Prove the subscription with an event — subscribe, send one message through the function, see the frame — before trusting anything real-time.
- When the backend outlives the campaign, disable the setup gate and verify it answers
SETUP_DISABLED.
How is the room built so only its members can listen?
With layers that each do one thing, composed — none is claimed to hold alone. Three classes: Room, RoomMembership (one row per user × room) and Message (room, author, a length-capped body, soft-delete fields). Two roles per room, where room_<id>_member contains room_<id>_moderator, so moderators inherit member reads and never the reverse.
| Layer | One responsibility | Where it lives |
|---|---|---|
| Class-level permissions | no anonymous reads; no client writes at all | the schema (cloud/config.js) |
| Row ACLs | Room and Message readable by the room’s member role only, written only by the server | beforeSave hooks |
| Roles per room | member contains moderator; names carry the room’s id, never user text | created with the room |
| Cloud functions + hooks | the single write path; every function declares its guard, hooks re-validate even master-key writes | cloud/main.js, cloud/guards.js |
| LiveQuery | subscriptions filtered per subscriber by ACL — a hypothesis we test, never assume | enabled per class in the dashboard |
The write path is small enough to read whole. sendMessage takes no author parameter at all — the author is always the caller — and the hook behind it re-checks membership even for master-key writes:
// Stack: Parse Server 7.5.2, Cloud Code on Node 19 | File: cloud/main.js (condensed)
define('sendMessage', {
roomFrom: 'params', // the guard resolves the caller's active membership first
handler: async function (request, ctx) {
const body = requireBody(request.params.body); // type-checked, length-capped
const message = new Parse.Object('Message');
message.set('room', ctx.room);
message.set('author', ctx.user); // always the caller — a spoofed author is ignored
message.set('body', body);
message.set('deleted', false);
await message.save(null, MASTER); // the hook stamps the ACL: member-role read, no writes
return messageJson(message);
},
});
define is not sugar. Every Cloud function must appear in a GUARDS registry naming its guard — member, moderator, authenticated or setup — and a function missing from the table throws while Cloud Code loads. A forgotten guard fails the deploy, not the room.
This post does not re-teach class-level permissions and ACLs — locking down a single-tenant backend is the groundwork.
The room model is the multi-tenant pattern at chat scale: membership rows as the source of truth, roles only granting row reads.
How do you prove the deploy and the subscription actually work?
With a request and an event — never with a dashboard dialog. On a fresh backend the first Cloud Code deploy can report Success while shipping nothing, so after uploading cloud/main.js, cloud/config.js and cloud/guards.js and deploying, send the probe:
# Stack: curl | Target: the live Parse REST API, client keys only
curl -s -X POST https://parseapi.back4app.com/functions/myRooms \
-H "X-Parse-Application-Id: $APP_ID" \
-H "X-Parse-REST-API-Key: $REST_KEY" \
-H "Content-Type: application/json" -d '{}'
Code 209 means the function exists and refuses anonymous callers — deployed. Code 141 Invalid function means the deploy shipped nothing: reload the Cloud Code page, make each file dirty again, confirm the badge Files pending deploy (3), Deploy again.
LiveQuery is its own silent trap: it is enabled per class (App Settings → Server Settings → Live Query → add Message), and it serves on a separate wss://<subdomain>.b4a.io URL. The proof is an event: subscribe, send one message through sendMessage, and watch the op:create frame arrive. The lab’s first positive test does exactly that before any measurement runs.
The administrative functions deserve one more sentence. setupSchema, testInspect and testCleanup follow the gated-admin pattern from the multi-tenant post, hardened one step further here.
Besides the SETUP_ENABLED flag, each administrative call must carry a setup token whose SHA-256 is compared server-side. The flag alone opens nothing — we probed it live with wrong tokens, four refusals.
Teardown is part of the design: every run stamps a random prefix on its usernames and room names, and testCleanup deletes only objects carrying it. Before real users arrive, set SETUP_ENABLED to 0 and confirm setupSchema answers SETUP_DISABLED.
Who received the messages — and who received nothing?
Exactly the room’s members, in every live run. The suite ran 34 tests against the live backend on November 2, 2026 — 28 passed, 0 failed, and 6 that need the master key or SQL below the API skipped with a printed reason and ran against a local parse-server instead. The full matrix, with raw frames, is in the repo’s evidence files; this is the shape of it:
| Persona | Attempt | Observed |
|---|---|---|
| ACME member | history, send, open subscription | all succeed; the event carries the body; stored ACL names only the member role |
| dual-room user | subscribed to ACME and Borealis at once | each event arrived exactly on the matching subscription, zero cross-deliveries |
| anonymous | REST reads; LiveQuery subscribe without a session | reads refused; subscribe acknowledged — then zero events delivered |
| outsider (valid session) | find, get, where and count probes | 0 rows, 404 code 101, counts scoped — ids are no existence oracle |
| outsider | open subscription, with the room filter and with none | 0 events while members sent 3 messages — the load-bearing row |
| member | direct REST POST/PUT/DELETE on Message | refused by the class-level permissions |
| member | spoofed author, forged ACL, foreign room, 2,001-char body | ignored or refused; database state asserted after each |
Two findings in that table earn their own paragraphs. First: a subscribed acknowledgment is not authorization. The LiveQuery server acked an anonymous connect and subscribe without complaint — and then delivered nothing. Rejection happens at event time, silently. If your client treats the ack as “I am receiving messages now”, it will wait forever without an error.
Second, whether LiveQuery filters events per subscriber by ACL is the load-bearing security property of this whole design, so the matrix attacks it directly rather than assuming it. In this run it held: the outsider’s filtered and unfiltered subscriptions stayed silent while a member control subscription received every message, sentinel included.
The lab also ships the bug on purpose. demoSendMessage skips the membership check the way a hurried Cloud function would — and in the flagged local demo, an outsider’s message landed in the room and members received it live. A missing authorization check can leak room data past every layer below it. In a default deploy the function is not even registered: the live run answered 141.
For the same probing applied to any backend with only its public keys, see the App-ID audit post. All scripted traffic here stayed under a polite 16 requests/s; this campaign did not measure the platform’s throttle ceiling, so this post makes no claim about it.
How long does a message take to reach another open screen?
404.6 ms at the median, 507.6 ms at p95 — measured from the moment the send request started to the event arriving on the other, already-open connection, over 100 timed runs after 20 discarded warm-ups, with 0 lost and 0 duplicated.
The number that gives it meaning is the contemporaneous baseline: in the same session, on the same machine, the plain sendMessage REST round trip with no subscriber measured 403.6 ms p50 / 475.3 ms p95. Delivery to an open subscription cost almost nothing on top of the write itself in these runs.
How we measured: sender and receiver run in one process on one machine, both connected to the live backend, every timestamp from one monotonic clock — so no cross-machine skew can fake a number. The definition includes the sender’s request tail, and both clients share one uplink: geographically separated users will see more than this.
We also pre-registered what would count as “a meaningful tail” before any live run: p95 − p50 greater than max(50 ms, half the p50). The observed gap was 103 ms against a 202 ms margin — so by our own rule, these runs show no meaningful tail. The p95 is about a quarter over the p50; we expected worse and report what we got.
Joining a room has its own latency: the subscribe acknowledgment came in 371.5 ms p50, and a message sent immediately after the ack arrived in 410.6 ms p50 — with 0 of 100 first messages lost. In these runs the ack was an actionable “joined” signal, not a polite fiction.
What does fan-out to 50 subscribers do to delivery?
Very little, at this size, from this one machine. We repeated the delivery measurement with 1, 10 and 50 open subscribers on the room — subscriber count the only factor varied — and recorded every arrival:
| Subscribers | Per-subscriber p50 / p95 (send-start → event) | Spread, last − first receiver, p50 / p95 | Lost / duplicated / disconnects |
|---|---|---|---|
| 1 | 406.5 / 509.3 ms | 0.0 / 0.0 ms | 0 / 0 / 0 (n = 100) |
| 10 | 413.1 / 510.7 ms | 2.4 / 27.0 ms | 0 / 0 / 0 (n = 1,000) |
| 50 | 415.1 / 515.0 ms | 5.8 / 48.4 ms | 0 / 0 / 0 (n = 5,000) |
At 50 subscribers, every one of 5,000 expected deliveries arrived, exactly once, with no connection dropped, and the last receiver of a message trailed the first by 5.8 ms at the median. How we measured: 100 messages per rung, 20 warm-ups discarded, free plan, all subscribers in one process on one machine, November 2, 2026.
50 is a tested configuration, not a ceiling. We stopped there by design; the table says what was tested and nothing about where the platform stops. If your rooms are broadcast-shaped — thousands of listeners — measure that shape before promising it, or see the counter-case below.
What happens to messages sent while you were disconnected?
They never arrive as events — and nothing tells you so. LiveQuery delivers events, not state: in the live runs, messages sent during an outage were not replayed on resubscribe, in any run. The silence after reconnecting looks exactly like a quiet room. Recovery is therefore the client’s job, and the naive version has races the lab reproduced one by one.
The shipped algorithm closes them in five steps: resubscribe → await the subscription acknowledgment → buffer incoming live events → paginated catch-up query → dedup by objectId → reconcile the buffer against the catch-up.
Buffering starts at the ack because the server may push at any moment after it. A message that arrives mid-recovery lands in the buffer and the catch-up page — the dedup applies it exactly once, which the live run asserted with sends injected into that exact window.
Two details are easy to get wrong. The catch-up cursor is keyed on (updatedAt, objectId) — not createdAt — because a message deleted while you were offline has an old createdAt and a fresh updatedAt; a createdAt cursor provably misses the redaction.
And the cursor is rewound by a 2 s overlap before each catch-up, because events arrive in commit order, which under concurrent writers is not timestamp order. The dedup absorbs the replayed overlap — visible as one ignored duplicate in every run, the overlap working as designed.
In 10 live runs with a 5 s outage and 10 messages sent during each, 0 of the 100 missed messages arrived as replayed live events on resubscribe, and the paginated catch-up recovered 100 of 100 — each applied exactly once by the dedup. The 10 clean-close runs converged on the same path: 0 replayed, 100 of 100 recovered.
Recovery had a cost worth knowing: the catch-up query itself took 413 ms at the median, and the whole reconnect — socket, subscribe, acknowledgment, catch-up — 2,906 ms, with the wait for the subscription acknowledgment as the dominant share. How we measured: measure-reconnect.mjs, 10 runs per disconnect kind, free plan, November 2, 2026.
One more thing these runs did not show: ordering problems. Fifty interleaved messages from two senders arrived live with zero inversions against (createdAt, objectId) order — but the same test on our local mirror saw inversions at 22 of 50 positions.
Timestamp ordering does not establish a total order of writes. We observed no counterexample live; that is an observation, never a guarantee, and the client is built as if inversions happen.
What does deleting a message actually delete?
The body — from every accessible surface, permanently. This lab’s soft delete is defined before it is measured: the body is redacted from accessible storage (overwritten server-side), while deletedAt, deletedBy and the author survive as moderation metadata. Hidden-in-the-UI was not an option on the table; a deleted body that still answers a REST read is not deleted.
The live run asserted every read path on November 2, 2026: the direct REST read carries the redacted body, the history page carries it, and LiveQuery told open subscribers via an op:update event carrying the redacted body.
An update, not a leave — the test recorded whichever came. The deleted message still matches the subscription, so clients render the tombstone instead of watching the message silently vanish.
Deletion is also terminal, even under the master key: the hook admits exactly one update transition — the redaction — so an un-delete attempt was refused in the live run, and there is no message editing at all. That is what turns “redacted from accessible storage” from a UI promise into an invariant a test can assert.
The redaction survives offline windows too: a client that was disconnected while a message it had rendered was deleted came back to the redacted version through the catch-up — the updatedAt cursor at work. And because bodies are stored verbatim as data, rendering is the client’s job: the shipped renderer escapes everything, asserted with a hostile-markup fixture.
How fast is a removed member actually out?
Define it first, then measure it. The accepted behavior in this lab: fresh requests are refused once removeMember returns; the open subscription’s drain is a measured delay, never claimed instant; and content already delivered is unrecoverable by definition — revocation governs new delivery only.
Against that definition, over 10 live runs on November 2, 2026: the first refused fresh read came 412 ms after removeMember returned at the median (min 400 ms, max 514 ms), and 0 of the 10 runs served a read before the first refusal. The open subscription delivered its last event 4.4 s after removal at the median and was verifiably silent by 7.7 s.
The mechanism explains the two timescales. Removal flips the membership row first — so Cloud-function calls die at the return — then removes the role entries, and the LiveQuery server’s session-role cache (five seconds by default in Parse Server) is the seconds-long tail on the already-open socket. A fresh subscription opened after removal received zero events.
The grant direction mirrors it: a subscription opened before membership stayed silent, and after addMember returned, the open subscription started delivering 4.9 s later in the live run — while a freshly opened subscription delivered immediately. If your UI adds someone to a room, open a new subscription instead of waiting for the old one to notice.
For context, not as this post’s evidence: the multi-tenant post measured the same revocation shape in its tenant model on October 29, 2026 — 0.42 s median to the first refused read, drained by ~3.7 s.
Those figures are observations of one workload on one date, never a platform floor. This post’s numbers re-measure the window in this room model, on this date, rather than inheriting them.
Races are stated, not hidden: six sends fired concurrently with a removal split 2 accepted (both with correct ACLs) and 4 refused NOT_A_MEMBER in the live run. The split is scheduling, not a guarantee — hooks are validation, not database constraints, and the lab’s concurrency rows exist to show exactly that window.
Does history pagination hold up at 10,000 messages?
The room’s history is a getMessages page — newest-first, keyed on (createdAt, objectId) descending — and the catch-up is the same function in since mode on (updatedAt, objectId) ascending, one index each. We measured a 50-row page at two room sizes, data volume the only factor varied:
| Messages in the room | First page, p50 / p95 | Deep catch-up page, p50 / p95 |
|---|---|---|
| 1,000 | 410.5 / 512.8 ms | 425.3 / 517.2 ms |
| 10,000 | 442.8 / 515.4 ms | 418.9 / 502.4 ms |
How we measured: measure-history.mjs, 20 warm-ups discarded, 100 timed runs per cell, free plan, November 2, 2026; the 10,000 messages were seeded through a gated server-side function that still runs every row through the hooks.
Our local mirror produced a question this table answers: on PostgreSQL, the first page got slower with room size while the deep cursor page did not — query shape mattered more than data volume.
Whatever the live MongoDB numbers show, the design lesson stands: paginate on a tuple cursor backed by an index. The indexing post explains why the index is not optional.
Which errors did we hit on purpose, and what do they mean?
Every one of these came out of the live runs — most of them provoked deliberately, all of them worth recognizing on sight.
141 Invalid function — the deploy shipped nothing, or the function is not registered. On a fresh backend the first Cloud Code deploy can report Success while doing this; reload, dirty the files, confirm the pending-deploy badge, deploy again, and prove it with a request.
209 Invalid session token — here, mostly a good sign: the function exists and refused an anonymous caller. The deploy probe counts on it. It is also what the catch-up query answers after a session expires — the recovery fails loudly rather than silently succeeding unauthenticated.
NOT_A_MEMBER (code 119) — the caller has no active membership in the target room: foreign sends, outsider history reads, and the losing side of a removal race all answer it. Refusals for a room you cannot see are identical to refusals for one that does not exist.
BODY_LENGTH (code 119) — the message body missed the cap (1–2,000 characters here). The hook enforces it even for master-key writes, so no future function can smuggle an oversized body.
MESSAGE_DELETED / MESSAGE_IMMUTABLE (code 119) — a write touched a deleted message, or tried to edit one at all. Deletion is terminal and the only legal update is the redaction; both refusals held under the master key in the local hook probes.
SETUP_TOKEN_INVALID / SETUP_DISABLED (code 119) — the administrative gate at work: wrong token with the flag on, or any call with it off. If you see these in production, someone is probing your setup functions — which is exactly why they fail closed.
When is LiveQuery the wrong tool for a chat?
When your requirements name the properties it does not promise. Five categories, each with what the alternative buys:
- Hard ordering or exactly-once delivery. LiveQuery promises neither; our runs lost nothing and showed no inversions, but the local mirror did, and the client is built on dedup for a reason. A log-structured message broker buys you offsets and replay.
- End-to-end encryption. The server reads every body by design here — it enforces the length cap and the redaction. E2E chat needs client-held keys and a server that never sees plaintext, which is a different architecture, not a setting.
- Broadcast fan-out. 50 subscribers is where our measurement stopped, by design. Rooms with thousands of listeners are the territory of dedicated realtime message services or self-managed WebSocket infrastructure, where fan-out is the product.
- Offline-first sync. Our catch-up recovers a linear room history; it is not conflict resolution. If clients write offline and merge later, you want a sync engine with CRDTs or operational transforms, not an event stream.
- Compliance-grade retention. Our soft delete destroys the body on purpose. If regulation requires retaining message content under legal hold, redaction-on-delete is the opposite of your requirement — design retention first.
None of these thresholds comes from a measurement we did not run; the fan-out boundary is simply where our tested configuration ended.
What did we not build, and what should you run first?
Presence — “who is online” — is out of scope, stated rather than faked. Honest presence needs a server-observed disconnect or a heartbeat-and-TTL design, and measuring its staleness properly (heartbeat interval against reported-online lag, crash against clean close) is its own campaign. Shipping an unmeasured heartbeat demo would break this post’s one rule.
Typing indicators, read receipts, attachments and push notifications sit outside the scope too — for push, start with the Flutter backend post.
If you take one transferable habit from this post: prove the invisible steps with requests and events, never with dialogs — the deploy that reports Success while shipping nothing and the subscribe ack that authorizes nothing are the same trap in two costumes.
Then run the lab against your own backend. The suite records every frame, the measurement scripts regenerate every table in this post, and the evidence files land in your repo with your dates: 34 tests, six measurements, one afternoon.
Run the chat lab on Back4app — a free backend app covered this entire campaign: the request-budget inventory put the suite plus all measurements at about 6,750 HTTP requests, and teardown is built in.