You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Research: how reactive-query systems track reads, invalidate and push #308
How do reactive-query systems keep subscribed reads correct, and what does a small-team implementation over Postgres look like? Survey from primary sources and source code where open: Convex (read-set tracking, OCC, subscription re-execution), Zero and Replicache (query-driven sync, IVM), ElectricSQL (shapes, log-driven), LiveStore, Supabase Realtime and Postgres logical decoding, Liveblocks, Firebase/Firestore listeners, Meteor's oplog tailing as the cautionary tale. For each: what a subscription is keyed by, how the system learns what a query read (declared, traced, or inferred from SQL), invalidation granularity (table, row, predicate), re-run-and-diff versus push, coalescing under write bursts, reconnect and snapshot semantics, authorisation on delivery, and the known failure modes at dashboards-open-all-day scale. Then the shape that fits Patchy: request-scoped handlers, writes already passing one dispatch point, tables in Postgres per company, subscriptions owned by the server, delivery through a document-bound MessageChannel: what to track, where the after-commit hook sits, what the stream carries, and what the prototype must exercise.
Output: findings as the resolution comment on this ticket, with a recommended v1 model. Two models in parallel per the map's Notes.
R3 — How reactive-query systems track reads, invalidate and push
Research for #308 (part of #294). Primary sources only; every claim carries its URL. Verified by re-opening each cited page.
Summary
Convex is the only surveyed system that traces reads rather than having them declared: "After querying the index, we record the index range we scanned in the transaction's read set. The read set precisely records all of the data that a transaction queried" (stack.convex.dev/how-convex-works).
Convex invalidates by intersecting the write log against stored read sets — "Walk the log after the query's begin timestamp and see if any entry overlaps" — then "pushes a message to the appropriate sync worker session, which then reruns the query" and "passes the result back to the client over the WebSocket" (same). Invalidation is re-run-and-push, not diff-of-rows.
That trick is only affordable because Convex queries are deterministic and bounded: "the handler function must be deterministic" and "queries cannot fetch from third party APIs" (docs.convex.dev/functions/query-functions), with hard ceilings of 16 MiB data read, 32,000 documents scanned and 1 second of user code per transaction (docs.convex.dev/production/state/limits).
Convex's client-side promise is a whole-app consistent snapshot: "Your app will never render in an inconsistent state where only one of the useQuery call sites reflects the new data," and "If the internet connection drops, the client will handle reconnecting and re-establishing the Convex session automatically" (docs.convex.dev/client/react/overview).
Zero takes the opposite route: a full Postgres replica in SQLite, with "One or more view-syncer: serving client queries using a SQLite replica" and "One replication-manager: bridge between the Postgres replication stream and view-syncers"; hydration is "run the query against the replica and stream all matching rows into the pipeline," and view-syncers "keep hydrated query pipelines in memory" so sticky sessions matter (zero.rocicorp.dev/docs/deployment).
Zero's authorization is not a separate layer: "Zero does not have (or need) a first-class permission system like RLS" — "Read permissions in Zero are filter-based," evaluated from a request-time Context (zero.rocicorp.dev/docs/permissions). Its stated ceiling is a backend dataset under ~100GB (zero.rocicorp.dev/docs/when-to-use).
Replicache's Row Versioning strategy is the cheapest correct server-side model: "A Client View Record (CVR) is a minimal representation of a Client View snapshot"; the server "computes a new CVR for the latest server state and diffs the two CVRs to compute the delta." Crucially "The storage doesn't need to be durable — if the CVR is lost, the server can just send a reset patch," at the cost that "Pulls become more expensive" (doc.replicache.dev/strategies/row-version). Its push channel carries no data: "The poke doesn't contain any actual data" (doc.replicache.dev/concepts/how-it-works).
ElectricSQL keys a subscription by a declared shape — "a table, ... an optional where clause ... an optional columns clause" — and accepts two blunt constraints for it: "Shapes sync data from a single table" and "Shape definitions are currently immutable" (electric.ax/docs/guides/shapes).
Electric's transport is worth copying wholesale: offset=-1 requests "the whole log, from the start for a given shape," live=true "will hold open the connection, waiting for new data," an up-to-date control message means "the client has all the data that the server was aware of," and must-refetch "indicates that the client must throw away their local shape data and re-sync from scratch" (electric.ax/docs/api/http). Authorization sits at the shape request, with the definition "set server-side — table, queryable columns, and main WHERE clause" (electric.ax/docs/guides/auth).
LiveStore shows the cheapest invalidation granularity that still feels reactive: "Queries automatically re-run when their underlying tables change," with memoization at the edge — "if the new result equals the previous result, downstream dependents won't re-run" (docs.livestore.dev/building-with-livestore/reactivity-system).
Supabase's Postgres Changes is the clearest measured warning against per-subscriber authorization: "When you make a single change to a table with 100 subscribed users, Realtime performs 100 authorization checks — one per user," "Changes are also processed on a single thread to preserve their order," and above "~3,000 concurrent subscribers on the same changes, use Broadcast to stream database changes instead" (supabase.com/docs/guides/realtime/postgres-changes).
Logical decoding carries an operational liability Patchy should not take on for v1: slots "will prevent removal of required resources even when there is no connection using them," and "In extreme cases this could cause the database to shut down to prevent transaction ID wraparound" (postgresql.org/docs/current/logicaldecoding-explanation.html). Zero already lives with the consequence: a slot "does not survive promotion of a standby," after which zero-cache will "re-sync every replica from scratch" (zero.rocicorp.dev/docs/connecting-to-postgres).
LISTEN/NOTIFY gives the after-commit hook for free, with exactly the coalescing wanted: "the notify events are not delivered until and unless the transaction is committed"; "If the same channel name is signaled multiple times with identical payload strings within the same transaction, only one instance of the notification event is delivered"; payload "must be shorter than 8000 bytes"; a full queue (8GB default) means "transactions calling NOTIFY will fail at commit" (postgresql.org/docs/current/sql-notify.html).
Meteor is the cautionary tale: oplog tailing silently degrades to polling for whole classes of query — "Selectors containing geospatial operators, the $where operator, or any operator not supported by Minimongo," "Queries specifying the skip option," "Queries specifying the limit option without a sort specifier" (meteor/docs oplog-observe-driver.md) — and the guide admits "Each change to the database is processed by every Meteor server, so frequent changes can result in high CPU usage across the board" (guide.meteor.com/data-loading).
SSE is a legitimate transport but has one hazard that matters precisely at "dozens of dashboards open all day": under HTTP/1.1 the open-connection limit "is per browser and is set to a very low number (6)" per domain, while "When using HTTP/2, the maximum number of simultaneous HTTP streams ... defaults to 100" (MDN, Using server-sent events).
A subscription is keyed by (query function, arguments) and carries a read set plus a begin timestamp. Convex learns what a query read by tracing: every index scan records its range into the read set, and "The read set precisely records all of the data that a transaction queried." Invalidation granularity is therefore predicate-shaped but index-mediated: an index range, not a table and not a row. Detection is log intersection — "Walk the log after the query's begin timestamp and see if any entry overlaps" — the same algorithm the committer uses for OCC conflicts. The response is re-run-and-push, never a row diff: the subscription manager "pushes a message to the appropriate sync worker session, which then reruns the query," and "The sync worker then passes the result back to the client over the WebSocket" (how-convex-works).
Coalescing falls out of the timestamp model: "Each timestamp t defines a snapshot of the database," and a burst of writes at one timestamp applies atomically, so a client sees one transition, not N. Mutations use OCC on the same read/write sets — a conflicting commit aborts and "The function runner will then retry" at a new begin timestamp, giving "true serializability" (docs.convex.dev/database/advanced/occ).
This only works because queries are constrained: deterministic, no third-party fetch, and bounded at 16 MiB read / 32,000 documents scanned / 1 second of user code, with "Data not returned due to a filter counts as scanned" — so a query that scans the table has a read set the size of the table and will be invalidated by every write to it (limits, indexes and query performance). The known dashboards-open-all-day failure mode is exactly that: an unindexed query becomes a table-wide subscription that re-runs on every write, for every open tab.
Reconnect is client-managed and opaque — "the client will handle reconnecting and re-establishing the Convex session automatically" — with a whole-app consistent snapshot as the delivered guarantee (React overview). Authorization is not a delivery-time stage at all: it is code inside the query function, re-evaluated on every re-run.
Zero and Replicache — declared queries, IVM, client view records
Zero keys a subscription by a named query plus arguments ("Each Query has a queryName ... This name is later sent to your server to identify the query to run"), resolved server-side into ZQL; "zero-cache receives updates from Postgres via logical replication. It updates affected queries and sends row changes back to the client" (reading-data). So reads are declared, and the delivery unit is a row-level diff (add / remove / edit), not a re-run result.
The architecture is a replica: "One or more view-syncer: serving client queries using a SQLite replica," "One replication-manager: bridge between the Postgres replication stream and view-syncers," which "Owns replication slot." Hydration is "run the query against the replica and stream all matching rows into the pipeline," after which the pipeline stays resident — "hydrated query pipelines in memory" — which is why "If you are seeing a lot of Rehome errors, you may need to enable sticky sessions" (deployment). Per-client state lives in a CVR database; the view-syncer must flush the CVR before sending results, so a distant CVR database is a latency bottleneck (slow-queries).
Authorization is filter-based and request-scoped — "you implement permissions by authenticating the user in your queries and mutators endpoints, and creating a Context object" (permissions). Failure modes: hydration cost per query per client, memory per resident pipeline, the ~100GB replica ceiling (when-to-use), and slot fragility — a slot "does not survive promotion of a standby," after which zero-cache will "re-sync every replica from scratch" (connecting-to-postgres).
Replicache, Zero's predecessor, is the version a two-person team can actually build. Subscriptions are local standing queries over a key-value client view: "Whenever the data in Replicache changes such that a subscription is potentially out of date ... the subscription function re-runs." The network protocol has three moving parts — push (mutations), pull (a cookie, a patch, and lastMutationIDChanges), and poke, where "The poke doesn't contain any actual data. All the poke does is tell the client that it should pull again soon" (how-it-works). The Row Versioning strategy makes the server side stateless-ish: keep a CVR per pull, "diff the two CVRs to compute the delta," and accept that "The storage doesn't need to be durable — if the CVR is lost, the server can just send a reset patch." The stated price is "Pulls become more expensive because they require a few queries"; the stated prize is that "The Client View can be computed dynamically — it can be any arbitrary query over the database, including filters, joins, windows, auth, etc." (row-version).
The separation of notify from fetch is the single most transferable idea in this survey: the push channel need only be a hint, so it can be lossy, cheap and unauthenticated-in-content, while the authoritative read stays on the ordinary request path that already enforces authorization.
ElectricSQL — declared shapes, a log, and a refetch escape hatch
A shape is keyed by a table, an optional where clause, optional columns and a queryable-columns allow-list; "A shape contains all of the rows in the table that match the where clause." Reads are entirely declared; invalidation is row-level within the shape, computed server-side from the replication stream. The constraints are deliberately blunt: "Shapes sync data from a single table," "Shape definitions are currently immutable," and many operators (JSONB, full-text, geometric) and non-deterministic functions like now() are unsupported (shapes).
The wire protocol is the part worth stealing: initial sync with offset=-1 for "the whole log, from the start for a given shape"; then live=true, which "will hold open the connection, waiting for new data"; an up-to-date control message meaning "the client has all the data that the server was aware of when fulfilling the request"; and must-refetch, which "indicates that the client must throw away their local shape data and re-sync from scratch." Responses are cacheable HTTP, so request collapsing happens at the CDN "instead of Electric holding open a connection per client" (http api).
Authorization is at the shape request, not per row: route the request through your proxy, "Set the table server-side - not from client params," "Set shape definition server-side," and handle 401/403 on token expiry (auth). Revocation mid-stream is therefore only as fast as token expiry — a real weakness for internal tools where access changes are the point.
Documented failure modes at scale are operational, not logical: WAL accumulation when the slot does not advance, shape-storage corruption on network filesystems, 503s when in-flight requests exceed the limit, and slot invalidation which means "all existing shapes are invalidated. Clients will receive 409 (must-refetch) responses and must perform a full resync" (troubleshooting).
LiveStore — table-granular reactivity over a local SQLite
LiveStore is event-sourced: "All data modifications are captured as an immutable, ordered sequence of events," materialized into a local SQLite database, and "Changes to the SQLite database trigger the reactivity system" (how-livestore-works). Sync is git-shaped — pull before push, rebase pending local events, last-write-wins by default with custom merge available.
For the invalidation question, LiveStore's answer is the coarsest one that still works: "Queries automatically re-run when their underlying tables change," with dependencies tracked implicitly via get() and explicitly via a deps option, and value-equality memoization at the boundary — "if the new result equals the previous result, downstream dependents won't re-run" (reactivity-system). Table-granular invalidation plus result-equality suppression is remarkably close to the right answer for internal tools, where per-patch tables are small and writes are human-paced.
Supabase Realtime and Postgres logical decoding
Supabase Realtime acquires "a Postgres logical replication slot ... when connecting to your database" and "delivers changes by polling the replication slot and appending channel subscription IDs to each wal record," over a globally distributed Elixir cluster (architecture). A subscription is keyed by schema/table/event/filter, evaluated server-side so "filtered-out events never leave the database," and it is pure push of the changed row: no query, no re-run, no diff (postgres-changes).
Authorization is per-subscriber per-event, and the docs quantify the cost: "When you make a single change to a table with 100 subscribed users, Realtime performs 100 authorization checks — one per user." Combined with "Changes are also processed on a single thread to preserve their order, which means larger compute add-ons don't meaningfully increase Postgres Changes throughput," this yields the explicit advice to switch above "~3,000 concurrent subscribers on the same changes" to Broadcast, which "sends each change once and fans it out to all subscribers." Delete filtering additionally requires replica identity set to full. Quotas are plan-bound: 500 concurrent connections and 500 messages/second on Pro, 100 channels per connection, 1,024 KB Postgres change payload (quotas).
The underlying Postgres facts matter independently of Supabase. A slot "represents a stream of changes that can be replayed to a client in the order they were made on the origin server"; changes are emitted at commit; "A logical slot will emit each change just once in normal operation," but "in the case of a crash the slot might return to an earlier LSN," so "Logical decoding clients are responsible for avoiding ill effects from handling the same message more than once." And the liability: slots "will prevent removal of required resources even when there is no connection using them ... In extreme cases this could cause the database to shut down to prevent transaction ID wraparound" (logical decoding).
NOTIFY is the far smaller tool with the right semantics for an after-commit hook. Events "are not delivered until and unless the transaction is committed"; identical channel+payload within one transaction folds to a single delivery, while "Notifications from different transactions will never get folded into one notification"; ordering within a transaction is preserved; payloads "must be shorter than 8000 bytes"; and a full queue (8GB default, warnings at half) means "transactions calling NOTIFY will fail at commit" (NOTIFY). The delivery guarantee is weaker than a slot's — notifications are not durable across a listener being disconnected — which is fine for a Replicache-style poke and fatal for anything that is the only source of truth.
Liveblocks — rooms, not queries
Liveblocks is a different shape of problem and is included mainly to mark the boundary. A subscription is keyed by a room: "A room is a stateful WebSocket server on the edge" (how-liveblocks-works), deployed on Cloudflare Workers "spanning 300 cities and 100+ countries, enabling a ~50ms connection to 95% of the world's internet-connected population" (websocket-infrastructure). There is no query, no read set and no invalidation: clients subscribe to conflict-free structures (LiveObject, LiveList, LiveMap) and to specific storage items, with an origin marker to "tell changes made by this client apart from changes made by others" (client API). Reconnect is a state machine — connected → reconnecting → connected, with a distinct event for prolonged loss.
Authorization is at room join, via ID tokens or access tokens, with defaultAccesses, groupsAccesses and usersAccesses where "each level further down will override access levels defined above" (authentication). Limits are per-room: 2 MB per LiveObject/LiveText and per LiveMap/LiveList item, 32 MB broadcast events on recent clients (limits). The lesson for Patchy: room-keyed presence is a separate, much easier product from query-keyed data reactivity, and conflating them buys nothing.
Firestore — reverse query matching with rules on the delivery path
A listener attaches to a document or a query; the first callback "creates a document snapshot immediately with the current contents," and subsequent changes deliver snapshots plus docChanges, with metadata.hasPendingWrites distinguishing unacknowledged local writes (listen). Offline, "your listeners will receive listen events when the locally cached data changes," and fromCache marks data that "might be stale or incomplete" (enable-offline).
The scale document is the useful one. Writes commit, then a changelog entry is created (guaranteeing strict ordering), then the change fans out to subscription handlers, which perform reverse query matching to find affected listeners, and Security Rules are evaluated before delivery. "Cloud Firestore's scalability depends on the fan-out from the changelog to the subscription handlers and the frontend servers," and as write volume grows "the changelog is split across multiple servers." Listeners have two modes, an initial polling query and a listen mode, and may silently "revert to polling during changelog rebalancing, server restarts, or write hotspots." Billing is per document returned, "not for maintaining an open connection," which is why the guidance is to hold long-lived listeners rather than repeat one-shot queries (real-time queries at scale). The named anti-patterns are listening to a high-churn large collection, slow polling queries, and large documents or batches.
Authorization deserves separate emphasis: "security rules are not filters—queries are all or nothing," and Firestore "evaluates a query against its potential result set instead of the actual field values" (rules-query). Static provability is powerful and deeply unfriendly to agent-written code.
Meteor — the cautionary tale
Meteor's OplogObserveDriver tails the MongoDB oplog and maintains a published set plus an unpublished buffer, applying the query's matcher to each oplog entry — inserts via self._matcher.documentMatches(op.o), updates via a check on whether the modifier could change selector relevance — and falling back to _needToPollQuery() when it cannot decide, when it detects skipped entries, or on failover (oplog_observe_driver.js).
The failure modes are three, and every one of them is a hazard Patchy can inherit if it is careless.
Silent degradation. Whole classes of query fall back to polling: "Selectors containing geospatial operators, the $where operator, or any operator not supported by Minimongo (such as $text)," "Queries specifying the skip option," "Queries specifying the limit option without a sort specifier or with a sort based on $natural order," $slice-style specifiers, and ordered observeChanges callbacks (meteor/docs long-form). A builder cannot see which mode they are in.
Fan-out to every server. "Each change to the database is processed by every Meteor server, so frequent changes can result in high CPU usage across the board," and "your database will come under higher load as all your servers keep fetching data from the oplog" (guide.meteor.com/data-loading). Observers are only multiplexed when queries are byte-identical: "Creating them is an expensive operation, so you want to make sure that Meteor reuses them as much as possible" (performance-improvement).
Infrastructure coupling. "Your MongoDB servers must be configured as a replica set ... Your cluster may not use Mongo sharding," and the oplog user "will be able to see all changes to all databases in your cluster" — a tenancy problem stated as a deployment requirement. Field reports of the driver pinning MongoDB at 100% CPU with COLLSCAN oplog queries that accumulate until the app is stopped are on the tracker (meteor#11993).
The generalisable lesson: a log-tailing reactive layer whose matcher cannot decide every case degrades into a polling layer that nobody can observe, and the degradation is invisible in exactly the workload — long-lived dashboards — where it costs most.
The shape that fits Patchy
Four properties of the existing system decide almost everything.
Writes already pass one dispatch point.packages/runtime/src/Runtime.ts classifies every operation as kind: "read" | "mutation" | "integration" and already carries per-operation metadata — resource?: (args) => string | null, rowCount, connectionId, sql. Mutations and integrations already run through options.record(execution, run), which wraps execution with the Execution record (input, operation, binding, deadline). Patchy does not need a changelog, a replication slot or an oplog tailer to know a write happened: it has a function call. The after-commit hook belongs inside the record wrapper, after a successful Exit, not in the database. Note the existing correctness rule the hook must respect: interruption is not failure ("do not claim the write failed"), so publish only on Exit.isSuccess.
Reads are already named and argument-typed. The tier 1 path admits a fixed set of operations — me, seven owned-table operations, three shared-table reads, four file operations, four Postgres operations (docs/product.md § Tier 1). A subscription can therefore be keyed by (patchId, versionId, op, canonical(args)), hashed for identity. Reads are declared in Zero's sense, not traced in Convex's. Do not build read-set tracing: it buys predicate-granular invalidation that patch-owned tables of a few thousand rows do not need, and it costs a tracing SQL layer that agent-written code can defeat.
Patch code cannot open its own stream. ADR-0010 fixes the content CSP at connect-src 'none', and the shell transfers exactly one MessageChannel port to the document, closed on a second load. So the shell owns the stream and forwards events over the existing port as another envelope kind. This is a gift: one transport per open document, regardless of how many subscriptions the patch holds, plus the existing bounds (32 outstanding requests, 64 MiB held bytes) and the existing stop conditions (access_denied, session_expired, principal_changed).
One Postgres per company. Cross-patch fan-out is naturally bounded by the company boundary (ADR-0009). A single LISTEN connection per company database, with NOTIFY issued in the mutation's transaction, gives commit-ordered, commit-gated, duplicate-folded delivery with no slot to babysit.
What to track
Per open subscription, on the server: the subscription key, the binding it was created under (patch, version, company, principal), the resource keys the operation touches (derived from the same resource(args) metadata the handler already declares), and a hash of the last delivered result. Nothing else. Table-granular resource keys — table:<patchTableId> and store:<fileStoreId> — are the right v1 granularity: LiveStore is proof that table granularity plus result-equality suppression reads as fine-grained, and the writes here are human-paced.
Where the after-commit hook sits
In the record wrapper, after success: compute the resource keys the mutation touched from its own resource(args), and NOTIFY patchy_change, '<company-scoped payload>'. Because notifications fold on identical payloads within a transaction and are withheld until commit, a batched write that touches one table twice yields one wakeup. Keep the payload well inside 8000 bytes: send keys only, never rows. The Replicache poke is the model — the notification is a hint, and the authoritative read happens on the normal request path afterwards. That single decision removes the entire class of bugs where a pushed row leaks past an authorization check.
Postgres connections (the company's own database, which Patchy does not own) cannot be hooked. Those reads are either non-reactive in v1 or poll on an explicit interval, and the SDK must say which — no silent degradation, per the Meteor lesson.
What the stream carries
Per subscription event: { key, revision, kind: "changed", } and then the re-run result, or — simpler and preferable — the server re-runs the read itself and sends { key, revision, value }, with value omitted and a stale flag set if the result exceeds the operation's existing byte cap. Also needed: an up-to-date-style marker after the initial snapshot (Electric's control message, worth copying), and a must-resync for the cases where the server cannot establish continuity. No row-level diffs in v1: the diff is a client concern and IVM is a whole research programme.
Re-running the read through the same Runtime dispatch, under the same binding, makes recomputation and re-authorization the same act. A reader whose access was revoked gets an AccessDenied on the re-run, which is an access-class stopping notice already defined in ADR-0010. Supabase's "100 authorization checks" warning is about per-subscriber authorization of a pushed row; here the check is not extra work, it is the work. The cost to watch is instead Convex's: a re-run per subscription per invalidation.
SSE versus WebSocket
SSE fits better for v1. The upstream direction already exists — the broker POSTs operations with same-origin credentials and the two X-Patchy-* headers — so the stream only needs one direction. SSE gives automatic reconnection and Last-Event-ID in the platform (MDN), rides the existing Effect HTTP stack, cookies and Origin checks with no second auth path, and dies cleanly when the session expires because it is an ordinary same-origin request. The one hazard is precisely the target workload: under HTTP/1.1 the limit "is per browser and is set to a very low number (6)" per domain, and Patchy serves every patch from one host. Under HTTP/2 the negotiated default is 100 streams. So SSE is correct conditional on HTTP/2 being terminated in front of the server, which the prototype must verify rather than assume. WebSocket avoids the cap and would be the fallback; it costs a second authentication path, its own heartbeat and reconnect logic, and a message framing the repo does not have.
What the prototype must exercise
Two tabs, one table. A tier 1 patch open in two documents; a mutation in one appears in the other. Measure end-to-end latency from Exit.isSuccess to the frame's onmessage.
Burst coalescing. 200 row writes in 5 seconds against a subscription. Assert the client receives far fewer than 200 updates, that no re-run overlaps its predecessor for the same subscription (one in flight, trailing re-run scheduled), and that the last delivered value is correct.
Authorization revocation mid-stream. Deactivate the viewer, or remove patch access, while the stream is open. The next re-run must fail closed and surface the existing access_denied stopping notice, not a stale value.
Session expiry and principal change. Confirm the stream stops before another operation executes, matching ADR-0010's existing rule, and that a replacement document inherits neither port nor stream.
Reconnect. Kill the connection for 60 seconds. On resume, every subscription re-runs and delivers a full snapshot; nothing claims continuity it cannot prove. Verify no duplicate-delivery bug and no lost wakeup across the gap.
Cost at dashboard scale. 30 open documents × 5 subscriptions each = 150 subscriptions on one company database. Measure re-runs per write, Postgres connection count, and whether the 300-calls-per-viewer-per-minute limit is hit by re-runs (decide explicitly whether re-runs consume that budget — they should not, but they need their own ceiling).
NOTIFY boundaries. Payload near 8000 bytes; a transaction touching many tables; a listener disconnected across a write, to observe exactly what is lost and confirm the reconnect path covers it.
The unsupported case, loudly. A subscription over a company Postgres connection must refuse or poll visibly, never appear live and silently stall.
Open questions
Whether Patchy's production ingress terminates HTTP/2 to browsers today. The SSE recommendation depends on it and this could not be established from the repo alone.
Whether Execution metadata is sufficient to name every resource a mutation touched, or whether some handlers mutate more than their resource(args) reports. Needs a read of each packages/runtime handler, out of scope for a source survey.
Cost and behaviour of one long-lived LISTEN connection per company database against the pooling model used today — whether a listener can share the platform pool or needs a dedicated connection per company.
Zero's exact IVM operator semantics. The public docs describe hydration and pipelines but do not publish the algorithm; the earlier search snippet describing "hydrate once, then incrementally push diffs" could not be verified verbatim on any Rocicorp page and is not relied on above.
Liveblocks' documented per-room concurrent-connection numbers: the limits page renders them as plan-dependent component variables, so exact figures could not be read.
Whether re-run results should be diffed server-side before sending. No surveyed system that re-runs (Convex) diffs; every system that diffs (Zero, Electric, Replicache) never re-runs. Patchy should measure before choosing.
Tier 2's server-side handlers will want subscriptions too. Whether the v1 model extends to a patch-identity subscriber, or whether that is a separate mechanism, is undecided.
Recommended v1 model
Declared subscriptions, table-granular invalidation, server re-run through the existing dispatch, hint-only notification, one SSE stream per document forwarded over the existing MessageChannel.
Concretely:
A subscription is a read operation the patch already knows how to call, marked subscribe: true at the SDK. Key = hash of (patchId, versionId, op, canonical args). No new query language, no read-set tracing, no replica, no logical replication slot.
The server holds subscription state in memory per connection: key, binding, declared resource keys, last result hash. Losing it is survivable — on reconnect, re-run everything and send snapshots, which is Replicache's "if the CVR is lost, the server can just send a reset patch" applied one level up.
Invalidation is published in the mutation's transaction via NOTIFY on a per-company channel, payload = resource keys only, capped well under 8000 bytes. Commit-gated and duplicate-folded by Postgres.
On a matching key, schedule a re-run with a trailing debounce (start at 100 ms) and at most one re-run in flight per subscription; skip delivery when the result hash is unchanged (LiveStore's equality suppression). Give re-runs their own rate ceiling, separate from the viewer's 300 calls/minute.
Re-run goes through Runtime.call with the original binding, so authorization, limits, byte caps and error classification are the ones already shipped and tested. An access-class failure stops the patch through the existing notice path.
Delivery: one SSE response per open document, authenticated as the ordinary same-origin request it is; the shell forwards each event to the frame as a new envelope kind on the existing port, subject to the existing bounds. A second document load closes both, exactly as today.
Explicitly out of scope for v1: row-level diffs, IVM, predicate-granular invalidation, offline writes, optimistic local mutation, subscriptions over company Postgres connections, cross-company fan-out, and any form of client-side replica.
The correctness model an agent has to hold is one sentence: a subscription is a read that re-runs when a table it named changes, and it re-runs as you. Every surveyed system that scaled its reactive layer beyond a prototype either accepted that kind of coarseness (LiveStore, Electric) or paid for precision with a whole replicated execution engine (Convex, Zero). For dozens of internal dashboards over patch-owned tables in a company database, coarseness is the correct purchase.
Report B: astra via omp, with tools (full findings)
Reactive queries for Patchy
Research for issue 308, checked 2026-09-19. Builds on the isolation, Daytona and company-database findings in #13, #24 and #178, without repeating those surveys. Vendor behavior below comes from primary documentation and source. The Patchy model is a proposal, not an implemented or benchmarked system.
Summary
Recommend server-traced table/store dependencies, commit-coupled revisions, coalesced reruns and full result replacement. This fits Patchy's decided request-scoped, broker-only handler model without another database or hosted service. decisiondb
Convex traces index ranges, including empty ranges, and reruns affected functions. Mutation OCC uses related overlap machinery but is separate from subscription scheduling. C1C2
Convex also coordinates multiple subscribed results into a consistent client view. Table-level invalidation alone does not reproduce that guarantee. C3
Zero declares ZQL queries and maintains their results incrementally over a replicated database. Its data-bearing synchronization protocol is not Replicache's empty poke. Z1Z4Z5R1
Replicache traces local key/range reads, reruns subscriptions and suppresses unchanged results. The application supplies authenticated pull responses and an optional poke channel. R1R2R3R4
Electric streams declared Postgres shapes with snapshot/offset recovery. Current shapes support related-table subqueries, but remain single-root-table streams rather than arbitrary query functions. E1E2
LiveStore discovers SQLite table dependencies and reruns SQL at table grain. Its remote synchronization exchanges events, not arbitrary Postgres query results. L1L2
Supabase Postgres Changes pushes row events with per-subscriber authorization work. Broadcast has different, connection-cached authorization. Neither is a maintained SQL result. S1S2
Logical decoding supplies a snapshot/change-stream seam, but slots retain WAL and may resend after crashes. LISTEN/NOTIFY is commit-safe signaling, not durable replay. P1P2P3
Liveblocks synchronizes room documents and CRDT operations. Its batching and reconnection are useful references, not a Postgres query implementation. B1B2B3
Firestore reverse-matches writes to declared listeners and checks rules before forwarding. Reconnects can trigger full-query billing, and rule deployment to active listeners can take ten minutes. F1F2F3
Meteor's oplog driver demonstrates the cost of broad change observation and fallback requeries. Current Meteor also has change-stream and polling drivers; describing it as oplog-only would be stale. M1M2
Detail
Convex
Subscriptions identify a function and arguments within a client session. Execution traces database reads as index intervals, not SQL or a developer-maintained dependency list. An empty scanned range still matters: a later matching insert overlaps that range. Mutations check reads against intervening writes using OCC; subscribed queries instead invalidate and rerun the function. C1C2C3
The client receives updated return values, not an incremental relational plan. Convex React coordinates affected queries so the screen does not combine old and new database states. Its client automatically reconnects and re-establishes the session. Authorization belongs inside functions through ctx.auth; a subscription is not a substitute for that check. C1C3C4
Source code staggers large invalidation fan-outs. This is not a documented promise to deliver every intermediate write. Broad reads increase invalidation work, so all-day dashboards need selective indexed reads rather than scans. The transferable idea is traced dependencies plus rerun, not rebuilding Convex's interval indexes or OCC engine. C1C5
Zero
A named query plus arguments expands through the application's query endpoint into declared ZQL. Zero runs it against its replica and propagates row changes. Its incremental view-maintenance pipelines handle result membership rather than tracing arbitrary handler execution. Z1Z5
Source code groups row patches into pokeStart/parts/pokeEnd, with cookies identifying client-view versions. Interrupted delivery reconnects from the prior base version. This batching is different from rerunning a JavaScript function after each write. Initial local results can be incomplete; the query's completion state distinguishes missing cached data from an authoritative empty result. Z1Z4
Server-derived context supplies permission filters. The configurable periodic authentication revalidation and query retransformation intervals both default to unset. Existing replicated data and an open connection must not be mistaken for fresh authorization. Cached queries continue consuming maintenance work until eviction; long TTLs and slow pipeline hydration are dashboard risks. Z1Z2Z3Z5
Replicache
A subscription is a local callback over the client view. The server sees a client group and pull cookie, not the callback's query. Source records get/has keys before reading, including misses, and scan ranges. Matching changes trigger full callback reruns; equality suppresses unchanged notifications. R1R2R3R4
Pull returns key/value patches. The usual poke carries no data and merely requests a pull. The connection loop debounces sends, allowing multiple wake-ups to share a pull. Recovery uses cookies and application-defined patches, including clear plus replacement data when appropriate. R1R4R5
Authentication and data selection belong to the application's pull endpoint; poke transport is also application-owned. A broad local scan over-invalidates, and losing the pull baseline can require rebuilding the client view. The useful pattern for Patchy is a cheap wake followed by an authorized read, without adopting Replicache's client cache or synchronization backend. R1R3R4
ElectricSQL
Current Electric shapes declare a root table, predicate and optional columns. Definitions are immutable; continuation uses a shape handle and offset. Reads are declared, not traced from Patchy handlers. Related-table subqueries can change membership when another table changes, so "single table" does not mean "no dependency on another table." E1
The log carries insert/update/delete operations. Matching inserts enter the shape and predicate exits leave it. Initial synchronization ends at up-to-date; invalid handles and must-refetch require discarding the baseline and resynchronizing. Responses batch log entries, and compatible caches can collapse identical live requests. Neither mechanism promises one result per write. E1E2
A trusted proxy constrains the shape and authorizes requests. Cache variation must include authorization context. Inference: authorizing the request alone does not establish revocation checks throughout an open stream. Documented operational problems include WAL growth, invalid-handle loops and proxy/connection behavior. Electric solves the read path; Patchy would still own mutations and broker admission. E2E3E4
LiveStore
A store owns live query definitions and dependencies. Source derives query identity from the query definition and dependency values, discovers referenced SQLite tables through getTablesUsed, and subscribes to table references. This is SQL/table introspection, not row or predicate tracking. A write anywhere in a referenced table can rerun SQL, including previously empty queries. Schema-derived result equality prevents unnecessary downstream updates. L1
The reactive graph supports deferred refresh/effect flushing. That is local batching, not distributed commit notification. Remote synchronization exchanges ordered events and rebases pending work; local SQLite materializers reconstruct state. Backend-reset detection can clear local storage and require restart rather than pretend an old baseline remains valid. L2L3L4
Authorization is application-defined. The documented Cloudflare example validates once per connection and explicitly requires verification again in push/pull handling. Hot-table reruns, event history and schema evolution remain costs for long-lived clients. Event definitions cannot simply be removed. L2L5
Supabase Realtime
Postgres Changes subscriptions declare schema/table/event filters on a channel. They receive row events, not traced reads or a SQL result. A matching INSERT can arrive, but a join, aggregate or top-N result still needs application maintenance or requery. DELETE handling depends on old-row availability; current docs require FULL replica identity for delete filtering and explicitly warn that table RLS does not apply to deleted rows. S1
Postgres Changes checks access per subscriber and processes changes on one thread to preserve order. No write-burst result-coalescing guarantee is documented. Supabase's source explicitly disclaims guaranteed message delivery, so reconnection must not silently imply that a separately fetched query snapshot is current. S1S3
Broadcast/Presence instead cache channel access policies until a join or new JWT; JWT expiry disconnects clients without refresh. That is not the same as Postgres Changes' row authorization. Authorization fan-out, token lifecycle and missing-event recovery are the relevant all-day risks. S1S2S3
PostgreSQL logical decoding and LISTEN/NOTIFY
Logical slots identify a change stream from one database, with one active receiver per slot. Output plugins/publications declare what changes to expose; they do not discover query reads. Row changes and replica identity can support a downstream query engine, but are not that engine. UPDATE/DELETE publication needs usable replica identity. Replication uses a replication role, not each dashboard viewer; publisher RLS can run for that role. It does not automatically provide per-viewer delivery authorization. P1P4P6
Slot creation can export a snapshot whose subsequent changes appear in the stream. Crash recovery can resend changes; consumers must tolerate duplicates. Slots persist without connected consumers and retain required WAL/catalog data. Burst batching and downstream result coalescing are consumer concerns. With databases per company, slot count and retained WAL become additional shared-server operating budgets. P1db
LISTEN instead keys a session to a channel. NOTIFY delivers only after commit, folds identical channel/payload pairs within one transaction, and never folds different transactions. It has no query read set or payload authorization. Session loss removes LISTEN registrations. PostgreSQL explicitly prescribes committing LISTEN before taking the initial snapshot. A long listener transaction can obstruct queue cleanup and eventually fail notifying commits. P2P3
Liveblocks
A subscription joins a room and selects data from its persistent Storage document. Live nodes carry CRDT operations; selectors observe the local document rather than SQL predicates. Key deletion and insertion are document operations, not relational membership inference. B1B3
room.batch groups synchronous operations, while the client defaults to a 100 ms WebSocket update throttle. Storage loading/synchronization status is distinct from connection status. Offline edits queue and reconcile in server-arrival order; automatic reconnect is not proof that the document has finished loading. B2B3
Access is room-scoped through authentication and room permissions. client.logout() clears tokens and forces connected rooms to reauthorize. Immediate server-side eviction after an arbitrary permission edit was not established. Long-lived local state, pending edits and background connections need explicit lifecycle handling. This is collaboration storage, not a general query-subscription backend. B1B2B4
Firebase/Firestore listeners
onSnapshot subscribes to a document path or declared collection query. The server bootstraps the result, registers the listener, reverse-matches committed document changes, and checks Security Rules before forwarding. Snapshots expose added/modified/removed changes; the initial query snapshot lists every match as added. Predicate exits are removals, not only document deletes. F1F4
No fixed client-visible burst-coalescing contract was established. Google's guidance warns that large write batches and hotspots delay listeners. Connections recover automatically and may return to polling/bootstrap after infrastructure changes. Cached initial data must be distinguished from server-confirmed data. F1F4
With persistence enabled, disconnects longer than 30 minutes incur fresh-query billing; without persistence, every reconnect does. Rule-dependent reads can add charges. New rules can take up to ten minutes to affect active listeners. These are documented dashboard costs and revocation delays, not Patchy measurements. F2F3
Meteor's oplog caution
A subscription names a publication and arguments. The publication returns Mongo cursors with declared selectors and projections. It can use this.userId; login/logout reruns the publication. Authorization therefore depends on what the publication admits, not a generic delivery-time ACL. M3
DDP distributes initial documents and later document changes. The legacy oplog driver tails the database oplog and filters in the application. Source refuses unsupported cursor shapes, including skip, and requeries after skipped oplog entries or failover. The polling driver reruns and diffs results, with defaults of 50 ms throttling and a 10-second interval. M1M2M4
Current Meteor chooses change streams, then oplog, then polling. Broad selectors and database-wide churn remain expensive whichever layer does the filtering. The lesson is not "CDC cannot work"; it is that fallback queries, observer reuse, bounded results and recovery remain necessary after adopting CDC. M1M2
What Patchy should track, commit and stream
The following is the proposed v1 contract, extending the decisions in #295. Existing company leases and document-bound broker authority remain constraints. decisiondbbroker
Key a subscription by company, patch/version, initiating viewer/effective authority, function, canonical arguments and document generation. Do not share cached results across viewers in v1. Trusted broker callbacks record canonical source table/store identities, even for empty reads. Begin with whole-resource dependencies, including shared-source liveness and sharing metadata. Patch code cannot report its own read set.
Run all data callbacks for one query on one short read-only REPEATABLE READ company transaction. PostgreSQL's default READ COMMITTED permits different snapshots between statements. Keep external Postgres/integration calls as actions, not implicitly reactive queries; prohibit untracked time/randomness from deciding subscribed results. P5decision
Within the outer mutation transaction, increment durable revisions for every changed table or file-store index. Cover tier 1 writes too. Wake local subscribers immediately after the actual commit, before response/audit completion. RuntimeProduction currently executes work before log.finish, and a finish failure becomes UnknownOutcome. Therefore HTTP success is the wrong invalidation condition. runtime
Poll revision rows only for active companies, in bounded batches across replicas. Prototype a one-second tick, not a promised freshness SLA. The fast wake is expendable; revisions survive a crash between commit and wake. Avoid dedicated LISTEN connections per browser/company initially. Out-of-band SQL writes are outside this guarantee unless they also advance revisions. NOTIFY can become an optimization, never the recovery record. Revision updates must share the data transaction; hot-resource counter contention is a trade-off. P2P3db
Close the setup race: collect data and revision values in the same snapshot, install the discovered dependencies, then compare fresh revisions outside that snapshot. A concurrent commit either appears in the comparison or a later poll. Repeat when a rerun discovers different dependencies. Keep one execution plus a dirty flag per subscription; coalesce bursts without clearing invalidations received during execution.
Use one authenticated same-origin fetch/SSE stream per shell document, multiplexed by subscription ID. POSTs manage subscriptions and mutations. Send full replacement results, typed errors and reset/stop messages with document generation and monotonic subscription sequence. Suppress equal results. Bound pending bytes and use broker acknowledgements so a frozen iframe cannot accumulate unlimited MessageChannel deliveries. No raw WAL rows, credentials or mutation replay. broker
Re-admit at subscribe, rerun, lease renewal and immediately before queuing delivery. Lifecycle changes can revoke access without touching data. Drop queued results on denial and use the shell's stopping notice. Reconnect takes fresh authorized snapshots; navigation destroys subscriptions. Expiring presence leases release server state when a client vanishes. This promises coherent per-query snapshots and eventual latest state, not every intermediate state or atomic refresh across independent queries. decisionbrokerC3
What the prototype must exercise
Start with #313's two users, setup race, differing authority, mid-stream revocation, fresh-snapshot reconnect and fifty-write burst. Add two server replicas and a crash after commit but before wake. prototype
Exercise empty-read then insert, predicate entry/exit, ordered-limit boundary changes, joins and changing dependencies; rollback emits nothing; equal results stay quiet. Race revocation against queued delivery. Freeze a frame, drop the stream, publish another version, then close every viewer and check that work stops. Include query errors, pool exhaustion and proxy buffering. Compare final results with fresh authorized queries, not notification counts.
Run an all-day soak with realistic query cardinality and write fan-out. Measure commit-to-visible latency, reruns per burst, query/callback time, revision contention, database connections, queued bytes and memory after disconnect. Verify the builder needs only a pure query and subscription cleanup, not a manual dependency list. These are proposed experiments; none was run for this research.
What each candidate cannot do
These are fit judgments, not claims that the products are defective.
Candidate
Missing capability for Patchy's contract
Convex
Reactivity over existing company SQL through arbitrary Patchy broker callbacks. It owns its database/query runtime. C1
Zero
Trace arbitrary handler reads. It requires declared ZQL and replica maintenance. Z1Z5
Replicache
Maintain server-owned subscriptions or supply CDC/pull authorization automatically. R1R4
Electric
Execute arbitrary joined/aggregate handler return values or provide the write path. E1E2
LiveStore
Turn existing Postgres tables into its local event/materializer model without a different data architecture. L1L2
Supabase Realtime
Guarantee a current SQL result or lossless client delivery from row events alone. S1S3
Logical decoding / NOTIFY
Infer query dependencies or authorize results for each viewer; NOTIFY also lacks replay. P1P2P3
Liveblocks
Subscribe to Postgres queries instead of room documents. B1
Firestore
Run Patchy SQL/handler queries against its document listener interface. F1F4
Meteor
Reuse its Mongo observer implementation directly over Postgres. M1M2
Client replication is not inherently disqualified by IndexedDB alone, since adapters can vary. The actual mismatch is Patchy's broker-only authority and server-owned query execution, not a claim that every candidate requires one particular browser storage API. decisionbroker
Open questions
What active-company/query counts and write fan-out must v1 sustain? No primary source establishes Patchy's capacity, polling interval or hot-table revision contention.
What maximum revocation delay should session expiry, account deactivation and source unsharing guarantee? Platform authorization and company data are separate databases, not one atomic snapshot. db
Does the product require read-your-writes fences or atomic updates across several subscriptions? The proposed per-query guarantee is weaker than Convex's coordinated view. C3
Convex's exact invalidation-delay defaults, Firestore's internal matcher and immediate Liveblocks room-permission eviction were not established. Do not infer these from the existence of a live socket. C5F1B4
LiveStore's source caches its discovered table set; behavior for dynamically changing SQL dependencies needs a targeted check before copying that implementation. L1
Recommendation for Patchy
Build the proposed table/store-level rerun loop inside Patchy's server, beside the credential-free executor. Keep company Postgres authoritative. Adopt no surveyed vendor as the query layer for v1. Azure/AWS portability and the existing credits favor this deployment, but the deciding reason is the already-controlled broker/write path. decisiondb
Accept extra reruns, full-result bandwidth and cross-replica polling latency to avoid IVM, client replicas, replication slots and another authorization system. Durable revisions are the minimum addition that prevents a lost after-commit wake becoming permanent staleness. Start coarse; consider indexed-range tracking only after the prototype demonstrates unacceptable fan-out. Do not change the isolation/runtime decision to obtain reactivity. C1P1decision
Verification: every cited source was reopened and checked against the retained claim. Current documentation supersedes older architectural descriptions. Source-only observations are identified above; missing guarantees remain open. No cloud resources, repository files or GitHub state were changed by this research.
Two reports ran in parallel (Opus and astra with tools, full text above); this is the merge with the charting session's own checks and opinion. The two converged on the same v1 model from different surveys, which is the strongest signal on this map so far.
The v1 model both recommend
A subscription is a read operation the patch already knows, marked subscribe; the server re-runs it through the same dispatch under the same binding when a table or store it named changes; delivery is full result replacement with unchanged results suppressed. No read-set tracing, no client replica, no incremental view maintenance, no logical replication slot, no second authorisation system. Concretely:
Keyed by patch, version, operation and canonical arguments. Dependencies are the resource keys the operation already declares (table:<id>, store:<id>): table-granular, the grain LiveStore proves reads as reactive once unchanged results are suppressed.
The after-commit hook sits in the runtime's single dispatch point, which every writer already passes; the notification carries keys only, never rows (Replicache's poke). The authoritative read happens on the normal path afterwards.
Re-runs are coalesced (trailing debounce, one in flight per subscription), have their own ceiling separate from the viewer's 300 calls per minute, and re-authorise by construction: a revoked viewer's re-run fails closed into the existing access-class stopping notice. Supabase's "100 authorization checks per change" warning does not apply because the check is the work, not extra work.
One stream per open document, forwarded over the existing MessageChannel as a new envelope kind; a second document load closes both, as today. Electric's control messages are worth copying wholesale: an up-to-date marker after the initial snapshot and a must-resync when continuity cannot be proven.
Reconnect re-runs everything and sends snapshots; subscription state is in memory and losing it is survivable.
Company Postgres connections cannot be hooked: subscriptions over them refuse in v1, never silently degrade (Meteor's lesson). Polling on an interval is a later feature, not a fallback.
Where they differ, and the call
Transport. Opus recommends SSE (one direction is enough, the upstream path already exists, automatic reconnection, dies with the session as an ordinary same-origin request) with one hazard: HTTP/1.1 caps open connections at six per origin, so production ingress must terminate HTTP/2. Astra does not choose. SSE, with the HTTP/2 check as a task on the prototype.
The wake signal. Opus proposes Postgres NOTIFY per company database (commit-gated, duplicate-folded, under 8,000 bytes). The charting session checked the PgBouncer matrix: LISTEN is never supported under transaction pooling, and one dedicated listener per company database is a real cost. With one hosting replica today an in-process after-commit event is sufficient; NOTIFY is the named upgrade when the server runs more than one replica. Astra adds the piece that makes either safe: durable per-table revisions coupled to the commit, so a lost wake becomes a late re-run rather than permanent staleness, and cross-replica polling of revisions is a valid fallback.
Consistency across subscriptions. Astra notes Convex coordinates every subscribed result into one consistent client view, and table-level re-runs do not reproduce that. Accepted for v1: each subscription is its own read, two screens may briefly disagree, and the spec says so. Whole-app snapshots return only if the CRM shows the disagreement to be visible.
Server-side subscribers. Whether a tier 2 handler itself can subscribe is undecided in both reports. Out of v1: subscriptions belong to open clients, which is what "while a viewer has the patch open" means.
Cautionary facts worth keeping
Logical decoding slots retain WAL and can in the extreme shut a database down; Zero re-syncs every replica from scratch after a standby promotion. Firestore's rules deploy to active listeners in up to ten minutes and reconnects can bill a full query. Convex affords read-set tracing only because queries are deterministic and capped (16 MiB read, 32,000 documents, 1 s).
What the prototype must exercise
Two tabs, one table, measured end to end; 200 writes in five seconds coalesced with a correct final value; revocation mid-stream failing closed; session expiry and principal change stopping the stream before another operation; a 60-second disconnect resumed with full snapshots and no duplicate or lost wake; 30 documents times five subscriptions on one company database with re-runs per write and connection count measured; a subscription over a company Postgres connection refusing loudly.
The agent's model, in one sentence: a subscription is a read that re-runs when a table it named changes, and it re-runs as you.
Merged by Claude Fable 5.1 via Claude Code, 2026-09-19.
Activity
allisonmahmood commentedon Sep 19, 2026
Report A: Claude Opus 5 (full findings)
R3 — How reactive-query systems track reads, invalidate and push
Research for #308 (part of #294). Primary sources only; every claim carries its URL. Verified by re-opening each cited page.
Summary
fetchfrom third party APIs" (docs.convex.dev/functions/query-functions), with hard ceilings of 16 MiB data read, 32,000 documents scanned and 1 second of user code per transaction (docs.convex.dev/production/state/limits).Context(zero.rocicorp.dev/docs/permissions). Its stated ceiling is a backend dataset under ~100GB (zero.rocicorp.dev/docs/when-to-use).offset=-1requests "the whole log, from the start for a given shape,"live=true"will hold open the connection, waiting for new data," anup-to-datecontrol message means "the client has all the data that the server was aware of," andmust-refetch"indicates that the client must throw away their local shape data and re-sync from scratch" (electric.ax/docs/api/http). Authorization sits at the shape request, with the definition "set server-side — table, queryable columns, and main WHERE clause" (electric.ax/docs/guides/auth).LISTEN/NOTIFYgives the after-commit hook for free, with exactly the coalescing wanted: "the notify events are not delivered until and unless the transaction is committed"; "If the same channel name is signaled multiple times with identical payload strings within the same transaction, only one instance of the notification event is delivered"; payload "must be shorter than 8000 bytes"; a full queue (8GB default) means "transactions callingNOTIFYwill fail at commit" (postgresql.org/docs/current/sql-notify.html).$whereoperator, or any operator not supported by Minimongo," "Queries specifying theskipoption," "Queries specifying thelimitoption without asortspecifier" (meteor/docs oplog-observe-driver.md) — and the guide admits "Each change to the database is processed by every Meteor server, so frequent changes can result in high CPU usage across the board" (guide.meteor.com/data-loading).Detail
Convex — traced read sets, log intersection, re-run
A subscription is keyed by (query function, arguments) and carries a read set plus a begin timestamp. Convex learns what a query read by tracing: every index scan records its range into the read set, and "The read set precisely records all of the data that a transaction queried." Invalidation granularity is therefore predicate-shaped but index-mediated: an index range, not a table and not a row. Detection is log intersection — "Walk the log after the query's begin timestamp and see if any entry overlaps" — the same algorithm the committer uses for OCC conflicts. The response is re-run-and-push, never a row diff: the subscription manager "pushes a message to the appropriate sync worker session, which then reruns the query," and "The sync worker then passes the result back to the client over the WebSocket" (how-convex-works).
Coalescing falls out of the timestamp model: "Each timestamp
tdefines a snapshot of the database," and a burst of writes at one timestamp applies atomically, so a client sees one transition, not N. Mutations use OCC on the same read/write sets — a conflicting commit aborts and "The function runner will then retry" at a new begin timestamp, giving "true serializability" (docs.convex.dev/database/advanced/occ).This only works because queries are constrained: deterministic, no third-party
fetch, and bounded at 16 MiB read / 32,000 documents scanned / 1 second of user code, with "Data not returned due to afiltercounts as scanned" — so a query that scans the table has a read set the size of the table and will be invalidated by every write to it (limits, indexes and query performance). The known dashboards-open-all-day failure mode is exactly that: an unindexed query becomes a table-wide subscription that re-runs on every write, for every open tab.Reconnect is client-managed and opaque — "the client will handle reconnecting and re-establishing the Convex session automatically" — with a whole-app consistent snapshot as the delivered guarantee (React overview). Authorization is not a delivery-time stage at all: it is code inside the query function, re-evaluated on every re-run.
Zero and Replicache — declared queries, IVM, client view records
Zero keys a subscription by a named query plus arguments ("Each Query has a
queryName... This name is later sent to your server to identify the query to run"), resolved server-side into ZQL; "zero-cache receives updates from Postgres via logical replication. It updates affected queries and sends row changes back to the client" (reading-data). So reads are declared, and the delivery unit is a row-level diff (add/remove/edit), not a re-run result.The architecture is a replica: "One or more view-syncer: serving client queries using a SQLite replica," "One replication-manager: bridge between the Postgres replication stream and view-syncers," which "Owns replication slot." Hydration is "run the query against the replica and stream all matching rows into the pipeline," after which the pipeline stays resident — "hydrated query pipelines in memory" — which is why "If you are seeing a lot of Rehome errors, you may need to enable sticky sessions" (deployment). Per-client state lives in a CVR database; the view-syncer must flush the CVR before sending results, so a distant CVR database is a latency bottleneck (slow-queries).
Authorization is filter-based and request-scoped — "you implement permissions by authenticating the user in your queries and mutators endpoints, and creating a
Contextobject" (permissions). Failure modes: hydration cost per query per client, memory per resident pipeline, the ~100GB replica ceiling (when-to-use), and slot fragility — a slot "does not survive promotion of a standby," after which zero-cache will "re-sync every replica from scratch" (connecting-to-postgres).Replicache, Zero's predecessor, is the version a two-person team can actually build. Subscriptions are local standing queries over a key-value client view: "Whenever the data in Replicache changes such that a subscription is potentially out of date ... the subscription function re-runs." The network protocol has three moving parts — push (mutations), pull (a cookie, a patch, and
lastMutationIDChanges), and poke, where "The poke doesn't contain any actual data. All the poke does is tell the client that it should pull again soon" (how-it-works). The Row Versioning strategy makes the server side stateless-ish: keep a CVR per pull, "diff the two CVRs to compute the delta," and accept that "The storage doesn't need to be durable — if the CVR is lost, the server can just send a reset patch." The stated price is "Pulls become more expensive because they require a few queries"; the stated prize is that "The Client View can be computed dynamically — it can be any arbitrary query over the database, including filters, joins, windows, auth, etc." (row-version).The separation of notify from fetch is the single most transferable idea in this survey: the push channel need only be a hint, so it can be lossy, cheap and unauthenticated-in-content, while the authoritative read stays on the ordinary request path that already enforces authorization.
ElectricSQL — declared shapes, a log, and a refetch escape hatch
A shape is keyed by a table, an optional where clause, optional columns and a queryable-columns allow-list; "A shape contains all of the rows in the table that match the where clause." Reads are entirely declared; invalidation is row-level within the shape, computed server-side from the replication stream. The constraints are deliberately blunt: "Shapes sync data from a single table," "Shape definitions are currently immutable," and many operators (JSONB, full-text, geometric) and non-deterministic functions like
now()are unsupported (shapes).The wire protocol is the part worth stealing: initial sync with
offset=-1for "the whole log, from the start for a given shape"; thenlive=true, which "will hold open the connection, waiting for new data"; anup-to-datecontrol message meaning "the client has all the data that the server was aware of when fulfilling the request"; andmust-refetch, which "indicates that the client must throw away their local shape data and re-sync from scratch." Responses are cacheable HTTP, so request collapsing happens at the CDN "instead of Electric holding open a connection per client" (http api).Authorization is at the shape request, not per row: route the request through your proxy, "Set the table server-side - not from client params," "Set shape definition server-side," and handle 401/403 on token expiry (auth). Revocation mid-stream is therefore only as fast as token expiry — a real weakness for internal tools where access changes are the point.
Documented failure modes at scale are operational, not logical: WAL accumulation when the slot does not advance, shape-storage corruption on network filesystems, 503s when in-flight requests exceed the limit, and slot invalidation which means "all existing shapes are invalidated. Clients will receive 409 (must-refetch) responses and must perform a full resync" (troubleshooting).
LiveStore — table-granular reactivity over a local SQLite
LiveStore is event-sourced: "All data modifications are captured as an immutable, ordered sequence of events," materialized into a local SQLite database, and "Changes to the SQLite database trigger the reactivity system" (how-livestore-works). Sync is git-shaped — pull before push, rebase pending local events, last-write-wins by default with custom merge available.
For the invalidation question, LiveStore's answer is the coarsest one that still works: "Queries automatically re-run when their underlying tables change," with dependencies tracked implicitly via
get()and explicitly via adepsoption, and value-equality memoization at the boundary — "if the new result equals the previous result, downstream dependents won't re-run" (reactivity-system). Table-granular invalidation plus result-equality suppression is remarkably close to the right answer for internal tools, where per-patch tables are small and writes are human-paced.Supabase Realtime and Postgres logical decoding
Supabase Realtime acquires "a Postgres logical replication slot ... when connecting to your database" and "delivers changes by polling the replication slot and appending channel subscription IDs to each wal record," over a globally distributed Elixir cluster (architecture). A subscription is keyed by schema/table/event/filter, evaluated server-side so "filtered-out events never leave the database," and it is pure push of the changed row: no query, no re-run, no diff (postgres-changes).
Authorization is per-subscriber per-event, and the docs quantify the cost: "When you make a single change to a table with 100 subscribed users, Realtime performs 100 authorization checks — one per user." Combined with "Changes are also processed on a single thread to preserve their order, which means larger compute add-ons don't meaningfully increase Postgres Changes throughput," this yields the explicit advice to switch above "~3,000 concurrent subscribers on the same changes" to Broadcast, which "sends each change once and fans it out to all subscribers." Delete filtering additionally requires
replica identityset tofull. Quotas are plan-bound: 500 concurrent connections and 500 messages/second on Pro, 100 channels per connection, 1,024 KB Postgres change payload (quotas).The underlying Postgres facts matter independently of Supabase. A slot "represents a stream of changes that can be replayed to a client in the order they were made on the origin server"; changes are emitted at commit; "A logical slot will emit each change just once in normal operation," but "in the case of a crash the slot might return to an earlier LSN," so "Logical decoding clients are responsible for avoiding ill effects from handling the same message more than once." And the liability: slots "will prevent removal of required resources even when there is no connection using them ... In extreme cases this could cause the database to shut down to prevent transaction ID wraparound" (logical decoding).
NOTIFYis the far smaller tool with the right semantics for an after-commit hook. Events "are not delivered until and unless the transaction is committed"; identical channel+payload within one transaction folds to a single delivery, while "Notifications from different transactions will never get folded into one notification"; ordering within a transaction is preserved; payloads "must be shorter than 8000 bytes"; and a full queue (8GB default, warnings at half) means "transactions callingNOTIFYwill fail at commit" (NOTIFY). The delivery guarantee is weaker than a slot's — notifications are not durable across a listener being disconnected — which is fine for a Replicache-style poke and fatal for anything that is the only source of truth.Liveblocks — rooms, not queries
Liveblocks is a different shape of problem and is included mainly to mark the boundary. A subscription is keyed by a room: "A room is a stateful WebSocket server on the edge" (how-liveblocks-works), deployed on Cloudflare Workers "spanning 300 cities and 100+ countries, enabling a ~50ms connection to 95% of the world's internet-connected population" (websocket-infrastructure). There is no query, no read set and no invalidation: clients subscribe to conflict-free structures (
LiveObject,LiveList,LiveMap) and to specific storage items, with an origin marker to "tell changes made by this client apart from changes made by others" (client API). Reconnect is a state machine —connected→reconnecting→connected, with a distinct event for prolonged loss.Authorization is at room join, via ID tokens or access tokens, with
defaultAccesses,groupsAccessesandusersAccesseswhere "each level further down will override access levels defined above" (authentication). Limits are per-room: 2 MB perLiveObject/LiveTextand perLiveMap/LiveListitem, 32 MB broadcast events on recent clients (limits). The lesson for Patchy: room-keyed presence is a separate, much easier product from query-keyed data reactivity, and conflating them buys nothing.Firestore — reverse query matching with rules on the delivery path
A listener attaches to a document or a query; the first callback "creates a document snapshot immediately with the current contents," and subsequent changes deliver snapshots plus
docChanges, withmetadata.hasPendingWritesdistinguishing unacknowledged local writes (listen). Offline, "your listeners will receive listen events when the locally cached data changes," andfromCachemarks data that "might be stale or incomplete" (enable-offline).The scale document is the useful one. Writes commit, then a changelog entry is created (guaranteeing strict ordering), then the change fans out to subscription handlers, which perform reverse query matching to find affected listeners, and Security Rules are evaluated before delivery. "Cloud Firestore's scalability depends on the fan-out from the changelog to the subscription handlers and the frontend servers," and as write volume grows "the changelog is split across multiple servers." Listeners have two modes, an initial polling query and a listen mode, and may silently "revert to polling during changelog rebalancing, server restarts, or write hotspots." Billing is per document returned, "not for maintaining an open connection," which is why the guidance is to hold long-lived listeners rather than repeat one-shot queries (real-time queries at scale). The named anti-patterns are listening to a high-churn large collection, slow polling queries, and large documents or batches.
Authorization deserves separate emphasis: "security rules are not filters—queries are all or nothing," and Firestore "evaluates a query against its potential result set instead of the actual field values" (rules-query). Static provability is powerful and deeply unfriendly to agent-written code.
Meteor — the cautionary tale
Meteor's
OplogObserveDrivertails the MongoDB oplog and maintains a published set plus an unpublished buffer, applying the query's matcher to each oplog entry — inserts viaself._matcher.documentMatches(op.o), updates via a check on whether the modifier could change selector relevance — and falling back to_needToPollQuery()when it cannot decide, when it detects skipped entries, or on failover (oplog_observe_driver.js).The failure modes are three, and every one of them is a hazard Patchy can inherit if it is careless.
$whereoperator, or any operator not supported by Minimongo (such as$text)," "Queries specifying theskipoption," "Queries specifying thelimitoption without asortspecifier or with a sort based on$naturalorder,"$slice-style specifiers, and orderedobserveChangescallbacks (meteor/docs long-form). A builder cannot see which mode they are in.COLLSCANoplog queries that accumulate until the app is stopped are on the tracker (meteor#11993).The generalisable lesson: a log-tailing reactive layer whose matcher cannot decide every case degrades into a polling layer that nobody can observe, and the degradation is invisible in exactly the workload — long-lived dashboards — where it costs most.
The shape that fits Patchy
Four properties of the existing system decide almost everything.
Writes already pass one dispatch point.
packages/runtime/src/Runtime.tsclassifies every operation askind: "read" | "mutation" | "integration"and already carries per-operation metadata —resource?: (args) => string | null,rowCount,connectionId,sql. Mutations and integrations already run throughoptions.record(execution, run), which wraps execution with theExecutionrecord (input, operation, binding, deadline). Patchy does not need a changelog, a replication slot or an oplog tailer to know a write happened: it has a function call. The after-commit hook belongs inside therecordwrapper, after a successfulExit, not in the database. Note the existing correctness rule the hook must respect: interruption is not failure ("do not claim the write failed"), so publish only onExit.isSuccess.Reads are already named and argument-typed. The tier 1 path admits a fixed set of operations —
me, seven owned-table operations, three shared-table reads, four file operations, four Postgres operations (docs/product.md§ Tier 1). A subscription can therefore be keyed by(patchId, versionId, op, canonical(args)), hashed for identity. Reads are declared in Zero's sense, not traced in Convex's. Do not build read-set tracing: it buys predicate-granular invalidation that patch-owned tables of a few thousand rows do not need, and it costs a tracing SQL layer that agent-written code can defeat.Patch code cannot open its own stream. ADR-0010 fixes the content CSP at
connect-src 'none', and the shell transfers exactly oneMessageChannelport to the document, closed on a second load. So the shell owns the stream and forwards events over the existing port as another envelope kind. This is a gift: one transport per open document, regardless of how many subscriptions the patch holds, plus the existing bounds (32 outstanding requests, 64 MiB held bytes) and the existing stop conditions (access_denied,session_expired,principal_changed).One Postgres per company. Cross-patch fan-out is naturally bounded by the company boundary (ADR-0009). A single
LISTENconnection per company database, withNOTIFYissued in the mutation's transaction, gives commit-ordered, commit-gated, duplicate-folded delivery with no slot to babysit.What to track
Per open subscription, on the server: the subscription key, the binding it was created under (patch, version, company, principal), the resource keys the operation touches (derived from the same
resource(args)metadata the handler already declares), and a hash of the last delivered result. Nothing else. Table-granular resource keys —table:<patchTableId>andstore:<fileStoreId>— are the right v1 granularity: LiveStore is proof that table granularity plus result-equality suppression reads as fine-grained, and the writes here are human-paced.Where the after-commit hook sits
In the
recordwrapper, after success: compute the resource keys the mutation touched from its ownresource(args), andNOTIFY patchy_change, '<company-scoped payload>'. Because notifications fold on identical payloads within a transaction and are withheld until commit, a batched write that touches one table twice yields one wakeup. Keep the payload well inside 8000 bytes: send keys only, never rows. The Replicache poke is the model — the notification is a hint, and the authoritative read happens on the normal request path afterwards. That single decision removes the entire class of bugs where a pushed row leaks past an authorization check.Postgres connections (the company's own database, which Patchy does not own) cannot be hooked. Those reads are either non-reactive in v1 or poll on an explicit interval, and the SDK must say which — no silent degradation, per the Meteor lesson.
What the stream carries
Per subscription event:
{ key, revision, kind: "changed", }and then the re-run result, or — simpler and preferable — the server re-runs the read itself and sends{ key, revision, value }, withvalueomitted and astaleflag set if the result exceeds the operation's existing byte cap. Also needed: anup-to-date-style marker after the initial snapshot (Electric's control message, worth copying), and amust-resyncfor the cases where the server cannot establish continuity. No row-level diffs in v1: the diff is a client concern and IVM is a whole research programme.Re-running the read through the same
Runtimedispatch, under the same binding, makes recomputation and re-authorization the same act. A reader whose access was revoked gets anAccessDeniedon the re-run, which is an access-class stopping notice already defined in ADR-0010. Supabase's "100 authorization checks" warning is about per-subscriber authorization of a pushed row; here the check is not extra work, it is the work. The cost to watch is instead Convex's: a re-run per subscription per invalidation.SSE versus WebSocket
SSE fits better for v1. The upstream direction already exists — the broker POSTs operations with same-origin credentials and the two
X-Patchy-*headers — so the stream only needs one direction. SSE gives automatic reconnection andLast-Event-IDin the platform (MDN), rides the existing Effect HTTP stack, cookies and Origin checks with no second auth path, and dies cleanly when the session expires because it is an ordinary same-origin request. The one hazard is precisely the target workload: under HTTP/1.1 the limit "is per browser and is set to a very low number (6)" per domain, and Patchy serves every patch from one host. Under HTTP/2 the negotiated default is 100 streams. So SSE is correct conditional on HTTP/2 being terminated in front of the server, which the prototype must verify rather than assume. WebSocket avoids the cap and would be the fallback; it costs a second authentication path, its own heartbeat and reconnect logic, and a message framing the repo does not have.What the prototype must exercise
Exit.isSuccessto the frame'sonmessage.access_deniedstopping notice, not a stale value.Open questions
Executionmetadata is sufficient to name every resource a mutation touched, or whether some handlers mutate more than theirresource(args)reports. Needs a read of eachpackages/runtimehandler, out of scope for a source survey.LISTENconnection per company database against the pooling model used today — whether a listener can share the platform pool or needs a dedicated connection per company.Recommended v1 model
Declared subscriptions, table-granular invalidation, server re-run through the existing dispatch, hint-only notification, one SSE stream per document forwarded over the existing MessageChannel.
Concretely:
subscribe: trueat the SDK. Key = hash of(patchId, versionId, op, canonical args). No new query language, no read-set tracing, no replica, no logical replication slot.NOTIFYon a per-company channel, payload = resource keys only, capped well under 8000 bytes. Commit-gated and duplicate-folded by Postgres.Runtime.callwith the original binding, so authorization, limits, byte caps and error classification are the ones already shipped and tested. An access-class failure stops the patch through the existing notice path.The correctness model an agent has to hold is one sentence: a subscription is a read that re-runs when a table it named changes, and it re-runs as you. Every surveyed system that scaled its reactive layer beyond a prototype either accepted that kind of coarseness (LiveStore, Electric) or paid for precision with a whole replicated execution engine (Convex, Zero). For dozens of internal dashboards over patch-owned tables in a company database, coarseness is the correct purchase.
allisonmahmood commentedon Sep 19, 2026
Report B: astra via omp, with tools (full findings)
Reactive queries for Patchy
Research for issue 308, checked 2026-09-19. Builds on the isolation, Daytona and company-database findings in #13, #24 and #178, without repeating those surveys. Vendor behavior below comes from primary documentation and source. The Patchy model is a proposal, not an implemented or benchmarked system.
Summary
Detail
Convex
Subscriptions identify a function and arguments within a client session. Execution traces database reads as index intervals, not SQL or a developer-maintained dependency list. An empty scanned range still matters: a later matching insert overlaps that range. Mutations check reads against intervening writes using OCC; subscribed queries instead invalidate and rerun the function. C1 C2 C3
The client receives updated return values, not an incremental relational plan. Convex React coordinates affected queries so the screen does not combine old and new database states. Its client automatically reconnects and re-establishes the session. Authorization belongs inside functions through
ctx.auth; a subscription is not a substitute for that check. C1 C3 C4Source code staggers large invalidation fan-outs. This is not a documented promise to deliver every intermediate write. Broad reads increase invalidation work, so all-day dashboards need selective indexed reads rather than scans. The transferable idea is traced dependencies plus rerun, not rebuilding Convex's interval indexes or OCC engine. C1 C5
Zero
A named query plus arguments expands through the application's query endpoint into declared ZQL. Zero runs it against its replica and propagates row changes. Its incremental view-maintenance pipelines handle result membership rather than tracing arbitrary handler execution. Z1 Z5
Source code groups row patches into
pokeStart/parts/pokeEnd, with cookies identifying client-view versions. Interrupted delivery reconnects from the prior base version. This batching is different from rerunning a JavaScript function after each write. Initial local results can be incomplete; the query's completion state distinguishes missing cached data from an authoritative empty result. Z1 Z4Server-derived context supplies permission filters. The configurable periodic authentication revalidation and query retransformation intervals both default to unset. Existing replicated data and an open connection must not be mistaken for fresh authorization. Cached queries continue consuming maintenance work until eviction; long TTLs and slow pipeline hydration are dashboard risks. Z1 Z2 Z3 Z5
Replicache
A subscription is a local callback over the client view. The server sees a client group and pull cookie, not the callback's query. Source records
get/haskeys before reading, including misses, and scan ranges. Matching changes trigger full callback reruns; equality suppresses unchanged notifications. R1 R2 R3 R4Pull returns key/value patches. The usual poke carries no data and merely requests a pull. The connection loop debounces sends, allowing multiple wake-ups to share a pull. Recovery uses cookies and application-defined patches, including
clearplus replacement data when appropriate. R1 R4 R5Authentication and data selection belong to the application's pull endpoint; poke transport is also application-owned. A broad local scan over-invalidates, and losing the pull baseline can require rebuilding the client view. The useful pattern for Patchy is a cheap wake followed by an authorized read, without adopting Replicache's client cache or synchronization backend. R1 R3 R4
ElectricSQL
Current Electric shapes declare a root table, predicate and optional columns. Definitions are immutable; continuation uses a shape handle and offset. Reads are declared, not traced from Patchy handlers. Related-table subqueries can change membership when another table changes, so "single table" does not mean "no dependency on another table." E1
The log carries insert/update/delete operations. Matching inserts enter the shape and predicate exits leave it. Initial synchronization ends at
up-to-date; invalid handles andmust-refetchrequire discarding the baseline and resynchronizing. Responses batch log entries, and compatible caches can collapse identical live requests. Neither mechanism promises one result per write. E1 E2A trusted proxy constrains the shape and authorizes requests. Cache variation must include authorization context. Inference: authorizing the request alone does not establish revocation checks throughout an open stream. Documented operational problems include WAL growth, invalid-handle loops and proxy/connection behavior. Electric solves the read path; Patchy would still own mutations and broker admission. E2 E3 E4
LiveStore
A store owns live query definitions and dependencies. Source derives query identity from the query definition and dependency values, discovers referenced SQLite tables through
getTablesUsed, and subscribes to table references. This is SQL/table introspection, not row or predicate tracking. A write anywhere in a referenced table can rerun SQL, including previously empty queries. Schema-derived result equality prevents unnecessary downstream updates. L1The reactive graph supports deferred refresh/effect flushing. That is local batching, not distributed commit notification. Remote synchronization exchanges ordered events and rebases pending work; local SQLite materializers reconstruct state. Backend-reset detection can clear local storage and require restart rather than pretend an old baseline remains valid. L2 L3 L4
Authorization is application-defined. The documented Cloudflare example validates once per connection and explicitly requires verification again in push/pull handling. Hot-table reruns, event history and schema evolution remain costs for long-lived clients. Event definitions cannot simply be removed. L2 L5
Supabase Realtime
Postgres Changes subscriptions declare schema/table/event filters on a channel. They receive row events, not traced reads or a SQL result. A matching INSERT can arrive, but a join, aggregate or top-N result still needs application maintenance or requery. DELETE handling depends on old-row availability; current docs require FULL replica identity for delete filtering and explicitly warn that table RLS does not apply to deleted rows. S1
Postgres Changes checks access per subscriber and processes changes on one thread to preserve order. No write-burst result-coalescing guarantee is documented. Supabase's source explicitly disclaims guaranteed message delivery, so reconnection must not silently imply that a separately fetched query snapshot is current. S1 S3
Broadcast/Presence instead cache channel access policies until a join or new JWT; JWT expiry disconnects clients without refresh. That is not the same as Postgres Changes' row authorization. Authorization fan-out, token lifecycle and missing-event recovery are the relevant all-day risks. S1 S2 S3
PostgreSQL logical decoding and LISTEN/NOTIFY
Logical slots identify a change stream from one database, with one active receiver per slot. Output plugins/publications declare what changes to expose; they do not discover query reads. Row changes and replica identity can support a downstream query engine, but are not that engine. UPDATE/DELETE publication needs usable replica identity. Replication uses a replication role, not each dashboard viewer; publisher RLS can run for that role. It does not automatically provide per-viewer delivery authorization. P1 P4 P6
Slot creation can export a snapshot whose subsequent changes appear in the stream. Crash recovery can resend changes; consumers must tolerate duplicates. Slots persist without connected consumers and retain required WAL/catalog data. Burst batching and downstream result coalescing are consumer concerns. With databases per company, slot count and retained WAL become additional shared-server operating budgets. P1 db
LISTEN instead keys a session to a channel. NOTIFY delivers only after commit, folds identical channel/payload pairs within one transaction, and never folds different transactions. It has no query read set or payload authorization. Session loss removes LISTEN registrations. PostgreSQL explicitly prescribes committing LISTEN before taking the initial snapshot. A long listener transaction can obstruct queue cleanup and eventually fail notifying commits. P2 P3
Liveblocks
A subscription joins a room and selects data from its persistent Storage document. Live nodes carry CRDT operations; selectors observe the local document rather than SQL predicates. Key deletion and insertion are document operations, not relational membership inference. B1 B3
room.batchgroups synchronous operations, while the client defaults to a 100 ms WebSocket update throttle. Storage loading/synchronization status is distinct from connection status. Offline edits queue and reconcile in server-arrival order; automatic reconnect is not proof that the document has finished loading. B2 B3Access is room-scoped through authentication and room permissions.
client.logout()clears tokens and forces connected rooms to reauthorize. Immediate server-side eviction after an arbitrary permission edit was not established. Long-lived local state, pending edits and background connections need explicit lifecycle handling. This is collaboration storage, not a general query-subscription backend. B1 B2 B4Firebase/Firestore listeners
onSnapshotsubscribes to a document path or declared collection query. The server bootstraps the result, registers the listener, reverse-matches committed document changes, and checks Security Rules before forwarding. Snapshots expose added/modified/removed changes; the initial query snapshot lists every match as added. Predicate exits are removals, not only document deletes. F1 F4No fixed client-visible burst-coalescing contract was established. Google's guidance warns that large write batches and hotspots delay listeners. Connections recover automatically and may return to polling/bootstrap after infrastructure changes. Cached initial data must be distinguished from server-confirmed data. F1 F4
With persistence enabled, disconnects longer than 30 minutes incur fresh-query billing; without persistence, every reconnect does. Rule-dependent reads can add charges. New rules can take up to ten minutes to affect active listeners. These are documented dashboard costs and revocation delays, not Patchy measurements. F2 F3
Meteor's oplog caution
A subscription names a publication and arguments. The publication returns Mongo cursors with declared selectors and projections. It can use
this.userId; login/logout reruns the publication. Authorization therefore depends on what the publication admits, not a generic delivery-time ACL. M3DDP distributes initial documents and later document changes. The legacy oplog driver tails the database oplog and filters in the application. Source refuses unsupported cursor shapes, including
skip, and requeries after skipped oplog entries or failover. The polling driver reruns and diffs results, with defaults of 50 ms throttling and a 10-second interval. M1 M2 M4Current Meteor chooses change streams, then oplog, then polling. Broad selectors and database-wide churn remain expensive whichever layer does the filtering. The lesson is not "CDC cannot work"; it is that fallback queries, observer reuse, bounded results and recovery remain necessary after adopting CDC. M1 M2
What Patchy should track, commit and stream
The following is the proposed v1 contract, extending the decisions in #295. Existing company leases and document-bound broker authority remain constraints. decision db broker
RuntimeProductioncurrently executes work beforelog.finish, and a finish failure becomesUnknownOutcome. Therefore HTTP success is the wrong invalidation condition. runtimeWhat the prototype must exercise
Start with #313's two users, setup race, differing authority, mid-stream revocation, fresh-snapshot reconnect and fifty-write burst. Add two server replicas and a crash after commit but before wake. prototype
Exercise empty-read then insert, predicate entry/exit, ordered-limit boundary changes, joins and changing dependencies; rollback emits nothing; equal results stay quiet. Race revocation against queued delivery. Freeze a frame, drop the stream, publish another version, then close every viewer and check that work stops. Include query errors, pool exhaustion and proxy buffering. Compare final results with fresh authorized queries, not notification counts.
Run an all-day soak with realistic query cardinality and write fan-out. Measure commit-to-visible latency, reruns per burst, query/callback time, revision contention, database connections, queued bytes and memory after disconnect. Verify the builder needs only a pure query and subscription cleanup, not a manual dependency list. These are proposed experiments; none was run for this research.
What each candidate cannot do
These are fit judgments, not claims that the products are defective.
Client replication is not inherently disqualified by IndexedDB alone, since adapters can vary. The actual mismatch is Patchy's broker-only authority and server-owned query execution, not a claim that every candidate requires one particular browser storage API. decision broker
Open questions
Recommendation for Patchy
Build the proposed table/store-level rerun loop inside Patchy's server, beside the credential-free executor. Keep company Postgres authoritative. Adopt no surveyed vendor as the query layer for v1. Azure/AWS portability and the existing credits favor this deployment, but the deciding reason is the already-controlled broker/write path. decision db
Accept extra reruns, full-result bandwidth and cross-replica polling latency to avoid IVM, client replicas, replication slots and another authorization system. Durable revisions are the minimum addition that prevents a lost after-commit wake becoming permanent staleness. Start coarse; consider indexed-range tracking only after the prototype demonstrates unacceptable fan-out. Do not change the isolation/runtime decision to obtain reactivity. C1 P1 decision
Verification: every cited source was reopened and checked against the retained claim. Current documentation supersedes older architectural descriptions. Source-only observations are identified above; missing guarantees remain open. No cloud resources, repository files or GitHub state were changed by this research.
allisonmahmood commentedon Sep 19, 2026
Resolution
Two reports ran in parallel (Opus and astra with tools, full text above); this is the merge with the charting session's own checks and opinion. The two converged on the same v1 model from different surveys, which is the strongest signal on this map so far.
The v1 model both recommend
A subscription is a read operation the patch already knows, marked subscribe; the server re-runs it through the same dispatch under the same binding when a table or store it named changes; delivery is full result replacement with unchanged results suppressed. No read-set tracing, no client replica, no incremental view maintenance, no logical replication slot, no second authorisation system. Concretely:
table:<id>,store:<id>): table-granular, the grain LiveStore proves reads as reactive once unchanged results are suppressed.Where they differ, and the call
NOTIFYper company database (commit-gated, duplicate-folded, under 8,000 bytes). The charting session checked the PgBouncer matrix:LISTENis never supported under transaction pooling, and one dedicated listener per company database is a real cost. With one hosting replica today an in-process after-commit event is sufficient;NOTIFYis the named upgrade when the server runs more than one replica. Astra adds the piece that makes either safe: durable per-table revisions coupled to the commit, so a lost wake becomes a late re-run rather than permanent staleness, and cross-replica polling of revisions is a valid fallback.Cautionary facts worth keeping
Logical decoding slots retain WAL and can in the extreme shut a database down; Zero re-syncs every replica from scratch after a standby promotion. Firestore's rules deploy to active listeners in up to ten minutes and reconnects can bill a full query. Convex affords read-set tracing only because queries are deterministic and capped (16 MiB read, 32,000 documents, 1 s).
What the prototype must exercise
Two tabs, one table, measured end to end; 200 writes in five seconds coalesced with a correct final value; revocation mid-stream failing closed; session expiry and principal change stopping the stream before another operation; a 60-second disconnect resumed with full snapshots and no duplicate or lost wake; 30 documents times five subscriptions on one company database with re-runs per write and connection count measured; a subscription over a company Postgres connection refusing loudly.
The agent's model, in one sentence: a subscription is a read that re-runs when a table it named changes, and it re-runs as you.
Merged by Claude Fable 5.1 via Claude Code, 2026-09-19.