One document database for the browser, Node.js and Bun.
defuss-db stores documents in a browser worker, a Node.js process or a Bun process, with the same API in each. A transaction commits several collections together, a reader sees one snapshot, and a commit to a directory returns after it is flushed. The database runs inside your application, on one machine, with no server to operate.
The order and the stock reservation commit together or not at all. The page reads the customer's newest orders from the compound index. Only the import and the line that opens the database differ between the browser, a server and memory.
An embedded database for web apps
Choose defuss-db when your documents belong to one machine: a user's browser, a desktop or edge device, or a single server. The database is a library, so a read by ID costs no network round trip and there is no database server to deploy, secure or upgrade. When your rows already sit in a JavaScript array and need neither persistence nor indexes, query the array with DataView instead.
The same API in the browser and on the server
Collections, queries, indexes, transactions and history work the same in a dedicated browser worker, in Node.js and in Bun. A database opened with openMemory() in a test has the API of one opened with openOPFS() in a browser or openDirectory(path) on a server.
openOPFS() keeps collections in the browser's Origin Private File System, from a dedicated worker. openDirectory(path) keeps them in a directory under Node.js or Bun, and openMemory() in memory for tests and caches. On a directory a commit returns once its data is flushed, and a store reopens with every committed document, also after its process was killed.
One transaction changes several collections and their index entries together. At commit the database checks what the transaction read. If another commit changed a document it read, or if any commit landed after it scanned, the commit fails with CONFLICT and writes nothing.
A compound index on tenant and score seeks straight to one tenant, returns its highest scores first and resumes from a cursor. A unique index rejects a duplicate key, also when two concurrent transactions claim the same key. An ID page or a range count reads index entries without decoding documents.
Index pages store keys with shared prefixes and numbers as varints, about a tenth of the bytes of plain object pages. Commits log their key changes and write index pages only at checkpoints: loading 100,000 documents with one ordered index wrote 29 MiB instead of 107 MiB. Once the connection is idle, a background copy drops old versions and puts documents back in key order, without blocking writers.
Full-text search ranks matching terms with BM25. Vector search finds documents with similar supplied embeddings. Hybrid search combines both rankings. A filter decides which documents qualify before the top hits are chosen.
Enable history on a collection. Read the price that applied on a date, correct one interval, reproduce what a reader saw before the correction, or restore a deleted document. Opt-in: _createdAt and _updatedAt on every write.
Dates, maps, sets, bigints, typed arrays and cyclic references keep their JavaScript types in storage and in archives, so every runtime reads back the value that was written.
db.export() writes one snapshot as a Brotli archive, compressed by defuss-brotli's WebAssembly build, with or without document history; exportStream() yields it in blocks for a file or an upload. db.import(archive) restores it atomically and rebuilds every index, into an empty database or merged with a conflict policy. An archive from a browser imports on a server, and the other way round.
A database tool built with defuss-shadcn on defuss-db, in this browser. Query with MongoDB filters, edit documents, aggregate, read schemas and indexes, restore deleted documents, import and export.
The first visit writes the sample databases shop, analytics and cms, about 24 MB, to this site's private browser storage.
Both store schemaless documents with secondary indexes. MongoDB is a server that applications reach over the network; defuss-db is a library inside the application that uses it. Choose by where the data lives and how many machines must write it.
Choose defuss-db when
the data must live in the browser or keep working offline;
you want one data layer for browser and server code;
you need transactions across collections without running a replica set;
history, ranked search or native JavaScript values belong in the same store.
Choose MongoDB when
several machines or services must write the same data;
you need replication and failover;
query and write throughput matter more than running inside the application;
your code needs the MongoDB wire protocol, or operators and stages that defuss-db/mongo refuses, such as $lookup or $expr.
Both systems held the same documents with the same compound index and returned identical results. defuss-db ran in the benchmark process on directory storage. A defuss-db commit returns after its flush, so its writes compare with MongoDB's journaled writes (j: true); MongoDB's default (w: 1) acknowledges a write before the journal is flushed.
Measured with defuss-db 3.0.0; 3.1.0 has not been measured again. Measured on Apple M5 Max (darwin arm64) against MongoDB 9.0.8, a standalone wiredTiger server on the same machine, through driver 7.8.0. Reads run on warm caches; median of seven samples after two warmups; the collection load is a single run. Table view and method · Raw samples
Built to scale without the bloat
defuss-db grows on the machine it runs on. It does not replicate, shard or federate, so there is no cluster to run and no network partition to handle.
defuss-db scales up
Reads by ID and index pages cost about the same at 10,000 and 100,000 documents.
Full-scan aggregates split across worker threads.
Concurrent writers share one flush per commit group.
Several processes can write one directory without losing an update.
A backup is one Brotli archive.
MongoDB scales out
Replica sets copy every write to other machines.
Sharding spreads a collection across servers.
Every query crosses the network to a server process.
The cluster is yours to run, upgrade and monitor.
What a compound index saves
Return one tenant's 20 highest-scoring events from a collection of 4,096. Both query plans run on the same database and return the same complete documents. Choose the runtime and storage for both.
Runtime
Storage
Read one tenant's top 20
The first index field locates the tenant. The second already orders its events by descending score. The reader examines 20 results and one lookahead. A collection scan visits all 4,096 events.
Node.js · memory. Compound index 0.340 ms (21 rows examined). Collection scan 3.78 ms (4,096 rows examined).
Median of seven samples, two warmups, result cache off. Directory reads use a warm filesystem cache.
Committing 64 new events took 0.641 ms with the compound index and 0.323 ms with primary keys alone.
Search for five ranked documents
Three indexes on the same 256 articles. Each timing includes fetching the five matching documents with a warm search engine. The vector and hybrid queries use supplied eight-dimensional embeddings.
Full-text searchBM25 on indexed terms
Vector searchExact cosine similarity
Hybrid searchCombine text and vector rankings
Database timings, fixtures and raw samples
Measured with defuss-db 3.0.0 and defuss-dataview 0.7.0; 3.1.0 has not been measured again. History timings use 256 documents, four initial versions per ID and a 512-byte binary field. The performance guide also measures opening an existing directory, reading one committed event and closing it.
With support for an enterprise-grade history data model
A plan costs €100 from January 1 and €120 from February 1. A later correction sets the price to €110 from January 15. A tracked collection can reproduce all three amounts.
On January 20 the corrected price is €110. The earlier recorded revision returns €100. The live document returns €120.
Effective date
prices.at(date).get(id) reads the price that applied on that date using the latest recorded corrections.
Recorded revision
prices.at(date, { $asOfRevision }).get(id) reads the same date using only changes recorded through the specified revision.
How the query and storage layers fit together
DataView filters, sorts, projects and groups rows. The database supplies the rows visible to each transaction and selects which indexes to read.
defuss-dbCollections, temporal history, ordered cursors and cache validation.
defuss-dataviewFilter, sort, project and aggregate candidate rows.
defuss-searchCombine lexical and vector retrieval over indexed inputs.
defuss-dbsonlPin a revision, seek the B+tree and commit index entries with documents.
defuss-dsonEncode and decode JavaScript value graphs.
defuss-storageRead and write bytes in memory, a directory or OPFS.
100k orders, stored in-browser
Ledger keeps orders, reports, prices, accounts and a product catalog in one defuss-db store in your browser. Sort and page the orders through indexes, run prepared reports, correct a price and read it as of an earlier revision, move money between accounts in transactions, and search the catalog. The inspector shows the TypeScript call behind each view, its measured time and its access plan.
The first visit writes about 120 MB to this site's private browser storage; later visits reopen it, and edits survive a reload. Reset data in the playground deletes it.
The planner carries a query from a public descriptor to typed results. Each layer owns a different piece of the work.
Typed keys
The ID token keeps the type. The string "1", the number 1 and the bigint 1n can identify three documents.
Ordered tuples
Tuple components follow the declared sort directions. A typed ID breaks ties between equal tuples.
Candidate selection
A primary key, equality tuple or ordered range can narrow the input that DataView evaluates.
Pinned readers
The schema, index pointers and visible documents come from one read revision.
Query results
A bounded cache retains qualifying results. The collection's commit revision validates a hit after another collection changes.
Search generations
A changed search input updates its stored generation. A reader can reconstruct the engine for its own revision.
Follow one seek
An ID page with a continuation reads a bounded interval of a declared ordered index. It checks the collection version and returns typed IDs.
1PinOpen one read revision.
2ValidateCheck cursor scope and version.
3SeekRead from the previous full key.
4ReturnDecode IDs and issue a continuation.
Index and storage trade-offs
The choice of read API determines which bytes the database needs and how it detects a concurrent change.
When should I add an ordered index?
Use it for repetitive range scans or sorted pages. Every indexed document adds a pointer and a corresponding write when the tuple changes.
What does an exact index count read?
It scans entries in the interval. It skips document lookup and decoding. Set maxScannedEntries to reject a range that exceeds your budget.
Can an ID cursor resume a document page?
Yes. Supply the same collection, index and interval. A write to that collection makes a live cursor stale. A pinned snapshot can continue.
What do range bounds compare?
They compare sort-key buckets. A null prefix includes missing and undefined values. Ordinary DataView predicates apply their own equality rules.
When does a query hit the cache?
The default policy admits repeated queries that process enough input and return a small result. Streams and transaction reads bypass the result cache.
What does a search index store?
The database persists text and vector inputs. The first query after opening or eviction builds the in-memory engine for that generation.
How do I back up or move a database?
Export a Brotli archive from a snapshot and import it into an empty database, in the same or another runtime. The operations guide covers history activation and full-history restores.
Read only what you need
Each read API touches different data. An index pointer costs far less than a document, especially when documents carry large binary fields.
Single document
One typed key lookup.
get(id)
ID page
Up to the page limit in IDs and one lookahead pointer.
pageIdsByIndex()
Document page
The index page plus document lookups for the returned rows.
pageByIndex()
Interval count
One pass over the selected pointers in bounded batches.
countByIndex()
Warm aggregate
A qualifying cache hit still pins a revision and decodes a fresh result.
prepareAggregate()
Cold search
Rebuild the upstream engine from its persisted generation inputs.
search()
Tested across runtimes
The release suite uses real directory storage, packed Node.js and Bun consumers, and Chromium dedicated workers with OPFS. It has run on Linux x64 and macOS arm64. Coverage measures the Node.js test run.
Index equivalence
ID-only results match full document pages across mixed ID types, ties and changing page sizes.
Snapshot visibility
Tests exercise staged writes, rollback, stale cursors, old snapshots and compaction.
Interrupted writers
Four SIGKILL trials reopen a directory and audit document, equality, ordered and hybrid index state.
Browser interchange
Archives travel from Node and Bun to browser storage and back. The tests also exercise two competing workers.
These contracts hold for operations that complete successfully on the supported storage backends.
Atomic commit
A commit publishes every staged document and index change at once. A failed or aborted transaction publishes none of them.
Conflict detection
A commit fails with CONFLICT when a concurrent commit changed what the transaction read. The database never reruns your callback, so its side effects happen once; retry where that is safe.
Snapshot consistency
A query reads the schema, index entries and documents of one revision. An explicit snapshot keeps its revision until you close it.
Flushed commits
On directory storage a commit returns after one flush of its data, which ends in a checksummed commit record. After a killed process, the store reopens at the last commit whose record is intact. OPFS flushes its files but offers no directory sync.
Exact bounded count
A successful index count covers its whole interval. A count that would exceed its scan budget is rejected instead of truncated.
Typed IDs
The string "1", the number 1 and the bigint 1n identify three different documents. Positive and negative numeric zero are one ID.
Not covered: replication, failover, sharding, network file systems and any test that commits survive a power cut. On macOS, every flush asks the drive to empty its write cache, under Node.js and Bun. Validation scope and limits
Setup
The package includes ESM, CommonJS and TypeScript declarations. Use Node.js 26 or later, Bun 1.4.4 or later, or a browser worker with OPFS and Web Locks.