Performance · 8 min read
How we made board snapshots 31x faster
/api/board was rescanning the entire board once per brief. The fix was not a clever cache; it was passing work that had already been done. Here is the exact diff, the 5.8s to 188ms result, and what still costs CPU.
The short version: the dashboard's /api/board response includes one row per brief. The old implementation read every DM, broadcast, and channel log once to discover the brief keys, then called collectBatch() for each key - and collectBatch() read all of them again. On an active board that was 5.8 seconds of repeated synchronous filesystem work. Passing the already-loaded message array into collectBatch() cut it to 188ms, about 31x.
The bug report was not "the server is slow." It was "the mobile app times out." That is a useful reminder: by the time a performance problem reaches a user, it usually looks like a network problem.
The endpoint was GET /api/board. The server was local. The board was a directory of JSON files. The network was not the issue.
What the board snapshot does
boardSnapshot() assembles the dashboard payload: agents, workers, broadcasts, recent mail, groups, peers, and briefs. The briefs list is the expensive part. It is built by listBatches() in bin/lib/groups.js, which returns one row per fan-out or thread on the board.
To build those rows, listBatches() needs to know every message on the board. DMs live under dm/<recipient>/<id>.json. Large fan-outs live under broadcast/<batch>.json. Channel posts live in channels/<name>.log.jsonl. The function reads all three, builds a child-count map, and derives the set of batch keys.
Then it needs the full transcript for each key. That is what collectBatch() does: find the briefs for a batch, walk the reply graph, and return the messages in timestamp order.
Here is the shape of the old code, simplified:
export function listBatches(d) {
const all = [];
// scan dm/, broadcast/, and channels/ once to build keys
// ...
const rows = [];
for (const key of keys) {
const res = collectBatch(d, key); // scans dm/, broadcast/, channels/ again
if (!res) continue;
rows.push(makeRow(res));
}
return rows;
}
The comment on the last line is the whole bug. listBatches() had already loaded the data it needed. collectBatch() threw it away and read the board from disk again, once per batch key.
Why that was so expensive
This is a filesystem problem, not a CPU problem. Each collectBatch() call did roughly the same work as the initial scan:
readdirSyncover the DM recipient directories.statSyncon each entry to skip non-directories.readDMs()over every recipient's message files, parsing each JSON document.listJson()over the broadcast directory, parsing each broadcast file.readdirSyncover the channels directory andreadChannelPosts()over every channel log, parsing each JSON line.
Do that once and it is fine. Do it once per batch on an active board and the endpoint becomes a disk benchmark. With B batch keys and N messages, the old path was effectively (B + 1) full scans: one to discover the keys, then one per key to collect the transcript.
Because the reads are synchronous, they block the Node.js event loop. The server is not serving other requests while it walks the same directories. The mobile client sees a request that is close to its timeout, then a request that is over it. More agents, more briefs, more messages - the problem compounds.
The fix: pass the work you already did
The patch was small. collectBatch() gained an optional third argument: an already-loaded message array. When it is present, the function skips the filesystem entirely and filters the array in memory.
export function collectBatch(d, batch, preloadedAll = null) {
let all;
if (Array.isArray(preloadedAll)) {
all = preloadedAll;
} else {
all = [];
// legacy path: scan dm/, broadcast/, and channels/
// ...
}
const briefs = all.filter((m) => m.batch === batch || m.id === batch);
if (briefs.length === 0) return null;
// build the reply index once for this batch
// ...
return { briefs: briefs.length, replies: out.length - briefs.length, items: out };
}
Then listBatches() passes the array it already built:
const res = collectBatch(d, key, all);
That is the entire optimization. No cache invalidation, no background index, no new dependency. The data was already in memory; the code just was not using it.
The optional argument also keeps the change backward-compatible. Other callers - batchReplyIds(), the CLI gather path, and anything that only has a batch key - still get the original behavior. listBatches() is the hot path that can supply the preload.
The result
| Path | Before | After |
|---|---|---|
GET /api/board on an active board | ~5.8s | ~188ms |
| Filesystem scans | One per batch key, plus the initial scan | One total |
| JSON parsing | Repeated for every batch key | Once |
| Speedup | - | About 31x |
Those numbers are from the v11.5.1 changelog, measured on an active board. They are not a universal constant. If your board has one brief, the old code did two scans instead of one and the difference is small. If your board has dozens of briefs and hundreds of messages, the repeated scans dominate and the win is large.
That is also why the mobile timeout fix landed in the same release. The default request timeout went from 8s to 15s. That is resilience for variable Wi-Fi and mobile networks, not a substitute for fixing the server. A timeout bump hides a slow endpoint; it does not make it fast.
What still costs CPU
The fix removes duplicate disk I/O. It does not make collectBatch() free. For each batch key, the function still filters the entire message array and rebuilds a replyTo index:
const briefs = all.filter((m) => m.batch === batch || m.id === batch);
const byReplyTo = new Map();
for (const m of all) {
if (!m.replyTo) continue;
if (!byReplyTo.has(m.replyTo)) byReplyTo.set(m.replyTo, []);
byReplyTo.get(m.replyTo).push(m);
}
Both loops are O(N) per batch, so the remaining CPU is O(B * N). Disk I/O dropped from O(B * N) to O(N); the in-memory work did not.
For the current board sizes, that is fine. If it stops being fine, the next step is obvious: build the reply index once for all messages, and bucket messages by batch once, instead of rebuilding both for every key. That is a larger refactor and a different measurement. The lesson from this patch is to remove the repeated I/O first, because it is usually the dominant cost and the smallest change.
How to measure your own board
Do not guess from message count. Measure the paths you actually care about.
npm run bench
npm run bench:load
crewbus bench-poll --agents 8 --iters 10
npm run bench builds a board with hundreds of broadcasts and DMs, then times the hot paths against generous budgets. npm run bench:load runs the synthetic large-fleet load test. crewbus bench-poll measures directory-scan cost directly. If you are investigating a dashboard timeout, time GET /api/board on a board that looks like production, not an empty test fixture.
The benchmark budgets are deliberately tolerant of a loaded machine. A miss means a real regression, not a noisy laptop. Keep them that way; a benchmark that fails on every background process teaches people to ignore it.
Five lessons that generalize
- Profile the endpoint, not the symptom. "Mobile times out" pointed at the network. The server was doing seconds of synchronous disk work.
- Count repeated scans. If a request walks the same directory once per row, the row count is your complexity multiplier.
- Reuse work already done. The best optimization here was passing an array, not adding a cache. Caches add invalidation; passing data adds a parameter.
- Keep the fallback. The optional argument lets other callers keep the old behavior. Not every caller has the preload, and that is fine.
- Fix the timeout separately. A client timeout is a resilience setting. It should not be the only thing standing between a user and a slow endpoint.
There is a broader point for local-first tools. When your database is a directory, every dashboard request is a filesystem query. That is a feature - you can inspect the board with ls, back it up with cp, and sync it with plain HTTP - but it also means you have to think about I/O the way a database engine does. The good news is that the fixes are often visible in the code: the same directory being walked in a loop.
The fastest file read is the one you do not repeat B times.
Read the code.
The optimization lives in bin/lib/groups.js. The changelog entry is in CHANGELOG.md under 11.5.1. Both are small enough to read in one sitting.
