Skip to content
Source
Sign inSign up
TanStack/db

Lazy join demand is recomputed over all demanded keys on every batch (O(N) per batch) #2321

Openjohn-rtr(GitHub profile, opens in a new tab) opened this issue 0 comments

Validated against @tanstack/db 1.0.0-rc.1 and 1.0.0-rc.1.1. The same code is on main (15d2d2d) in packages/db/src/query/compiler/joins.ts and packages/db/src/query/live/subset-demand-controller.ts.

This is a performance issue, not a correctness bug.

What happens

For a lazy join, the tap on the active pipeline (joins.ts, around line 502) runs on every batch the active side emits. After updating demandWeights for the batch, it rebuilds the whole demanded key set and passes it to setDemand:

const keys = new Set(
  [...demandWeights.values()].filter(({ weight }) => weight > 0).map(({ key }) => key),
)
callbacks[target.sourceId]?.setDemand?.(demandPlans[index]!, keys)

SubsetDemandController.setDemand then makes several more passes over the whole set:

  • canonicalizeKeys(keys) serializes every key;
  • equalKeySets(previous.keys, nextKeys);
  • coveredKeys flattens every segment's keys;
  • added filters every key, and removed scans every previous key.

So each batch costs O(total demanded keys) per lazy join, even when the batch adds only a few keys. Writing N rows into the active side in batches of size B costs about O(N² / B) per lazy join.

Measured

A local-first app writes ~21k rows into a collection that is the main source of a live query with several lazy left joins (all collections fully loaded locally, eager sync). The rows go in batches of 2,000 (one begin/write/commit per batch) so the page stays responsive.

Chrome profile of the main thread while those batches are written (~2.9 s busy):

FunctionSelf time
canonicalizeKeys (subset-demand-controller.js:167 in dist)228 ms
setDemand96 ms
the demand tap in joins.js133 ms

That is ~450 ms, about 16% of the work, spent recomputing demand that changed by one batch.

It also stops us from using smaller batches, which would keep input latency lower: with 500-row batches the same write takes ~4 s instead of ~1.6 s, because every batch pays the full O(N) demand cost again.

Possible fix

Make demand incremental, so a batch costs O(keys it changes):

  1. In the tap, record which keys crossed from weight 0 to positive (added) and from positive to 0 (removed) in this batch. If neither set is empty, call the controller with them; if both are empty, skip setDemand entirely.
  2. Give SubsetDemandController an incremental entry point, e.g. updateDemand(subscription, plan, added, removed), that keeps its canonical key map across calls, canonicalizes only the changed keys, and requests a segment only for added keys no live segment covers. Removals and failed segments can keep today's full path.

Happy to provide a reduced repro or a PR if that helps.

Sign in to join this conversation.