Many threads. One memory.
Cellar is a lightweight shared-memory library for multithreaded JavaScript. Threads share data, call each other, stream records and wait on each other without going through the event loop for every exchange.
Built for Bottlify, and useful wherever JavaScript workers share data and do work together. Browser-first, with Node.js support. No runtime dependencies. MPL-2.0.
| Primitive | What it does |
|---|---|
| Cache | Shared bodies by name in one WebAssembly.Memory, read in place, one memory budget, optional disk storage. |
| Account | One budget for every byte: the cache's segments and the memory it does not place (a WebAssembly memory, compiled code), by kind and by holder; a take that does not fit has cold bodies go first. |
| Remote keeper | The cache's keeper from another thread: one binary protocol over a channel or a link. |
| Channel | Blocking or asynchronous RPC between two threads. |
| Link | Calls both ways with values; a waiting side answers the other's calls meanwhile, and small word calls take turns in place. |
| Ring | A bounded one-writer, one-reader byte stream, with backpressure and in-place writing. |
| Journal | One writer, many readers; older records are overwritten, and the writer never waits for readers. |
| Table | Named integer counters and rows one thread stores and any thread reads, with no request to the writer; or slots any thread claims and releases, named by handles a reuse makes stale. |
| Bell | Wait on a shared word; notify only when a wait is registered. |
| Doorbell | One wait for several sources of work. |
The cache's keeper can hold a machine's memory itself. Give it the memory (openKeeper({ memory }), an arena or the host's own { memory, take, give }) and everything it holds lies there: its index, every body, its own account. Each thread is handed that memory and the index's root once (keeper.shared) and reads every body where it lies, so a guest's pages and the cache's bodies are one store under one budget, with no buffer outside it. The keeper is that machine's page file as well: evict writes pages out to the disk from where they lie and frees their memory, restore reads them back into place, and drop forgets a page freed, its copy on the disk with it (Cache). segmentAlign makes every segment start on a frame the host names, so a body can be mapped straight into a program's pages.
npm install @bottlify/cellarTwo entries: @bottlify/cellar is the primitives above; @bottlify/cellar/advanced is what a host that builds on the cache's own format needs (the saved index's files and packing, the placement words, the value codec). Each release also carries cellar.js, cellar.min.js, the TypeScript declarations and checksums, for a page without a bundler; its notes are the changelog. Every thread of a run uses the same version: the shared layouts are part of it.
A function in a worker, called from the page. The shared memory is handed over once with postMessage; requests and answers then travel through the channel.
page.js
import { createChannel, openClient } from '@bottlify/cellar';
const memory = createChannel({ slots: 16, slotBytes: 4096 });
const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
worker.postMessage({ memory });
const client = openClient(memory);
const sum = await client.call(Uint8Array.of(1, 2, 3), {
read: answer=>answer[0],
});
console.log(sum); // 6
client.close();worker.js
import { ChannelClosed, openServer } from '@bottlify/cellar';
self.onmessage = ({ data })=>{
const server = openServer(data.memory);
try
{
for (;;) server.serve(request=>[request.reduce((a, b)=>a + b, 0)]);
}
catch (e)
{
if (!(e instanceof ChannelClosed)) throw e;
}
};A worker may also use client.ask() to block for an answer, or server.serveAsync() to keep its event loop available. See Channel.
- Cache: resources used by many workers, under one budget; optionally cold on disk.
- Channel: ask another thread to do something and return an answer.
- Link: two threads that call each other, nested, with values or a few words at a time.
- Ring: deliver commands or batches without overwriting unread data; build directly in shared memory with
reserve()andcommit(). - Journal: logs, traces and measurements; each reader follows its own sequence and can miss old records without stopping the writer.
- Table: counters and figures a reader samples whenever it likes, stored where they change; with slots, a table of handles any thread claims and releases.
- Bell / Doorbell: wait for a change or for work from several rings.
Selected round-trip and memory measurements (Cellar 1.1.1, Node.js 22, 4-core x86 VM, median of three runs):
| Work | postMessage | Cellar |
|---|---|---|
| Small RPC | 37.6 µs | 2.0 µs |
| Idle event round trip | 44 µs | 2.0 µs |
| Sum 8 MiB of samples | 6.3 ms | 1.1 ms |
| Peak RSS, 8 MiB samples | 137 MiB | 74 MiB |
These measurements compare the example workloads, not every use of postMessage. The batch benchmarks also compare transferred buffers with copied and in-place ring writes. See Benchmarks for the full numbers, methods and limitations.
- Cross-origin isolation and
SharedArrayBufferfor sharing memory between browser threads. Without shared memory, the cache can run within one thread. WebAssembly.Memory(shared where memory is shared) for the cache.Atomics.waitAsyncis used where available; otherwise asynchronous waits poll. Node.js 22 or later at runtime; the development tooling (ESLint 10) needs Node 22.13 or later, and CI uses the latest 22.- Never block the browser's main thread. Use the asynchronous APIs there. Views handed out for reading or writing have limited lifetimes; follow each primitive's contract.
- Journal copies records into private scratch memory. Its cross-thread integrity check relies on how current engines implement sequentially consistent Atomics, not solely on the ECMAScript memory model. See Journal.
- Optional disk storage uses a single Keeper per directory. OPFS synchronous handles belong in a worker.
- The threads that share Cellar's memory are one program's and trust each other: a link's values, the remote keeper's requests and the shared words are read as the other side wrote them, with bounds checked against corruption, not against an adversary. Cellar is not an isolation boundary for untrusted code.
- A cache write reservation is its writer's until the writer commits it, abandons it or is said gone (
keeper.writerGone); the host says that only once the writer's thread has stopped. See Cache.
For browser isolation, a common starting configuration is Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp; ensure the page and its resources meet the policy.
API · Lifecycle · Cache · Account · Remote keeper · Channel · Link · Ring · Journal · Table · Bell and Doorbell · A video editor · Benchmarks
How Cellar works, drawn - diagrams and runnable examples.
npm ci
npm run checkThe check runs type checking, unit tests, integration gates, the speed gate and the build. npm run build writes the ES modules, declarations and checksums to dist/. GitHub CI runs the checks on a push to main; for a new version it makes the GitHub release and stages the version on npm, and a maintainer publishes it with 2FA (npm stage approve).
npm run test:browser runs the gates whose answer depends on the engine in a headless Chrome: the memory-ordering gate and its mutants, and the cases where a browser treats shared memory otherwise than Node.js (its text encoder and decoder refuse a shared view, its page thread may not block, OPFS's synchronous handles take shared views). They are the same case bodies Node.js runs (src/*.cases.fixture.js), served cross-origin isolated and driven over the DevTools protocol, so the gate needs a Chrome and no package. CHROME names the browser if it is not in a usual place. It is not part of npm run check; CI runs it on the arm Mac.
npm run test:bench is the speed gate (scripts/bench-gate.mjs): each workload of scripts/bench-workloads.mjs - a cache put, reserve and hit, a journal commit and read, a ring record, a table add, an account take, a channel and a link round trip - on this tree and on the commit bench/reference.json names, alternated round by round on the same machine. Each is judged alone: slower where the lower quarter of its rounds is above the upper quarter of the reference's and its median by more than 3%, then confirmed by twice the rounds; one the machine moves too much to tell (the reference's middle half spread past 20%) is named as not judged. A change slower on purpose, for a check it must make, moves the reference to it with the reason; any other slower change is not merged. It runs where the change is made, before it is pushed, not on CI's shared runners.