Skip to content
defuss-db

defuss-db

EmbeddedAn alternative to MongoDB on one machine

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.

Storage: OPFS in the browser, a data directory on the server, memory in both · TypeScript, ESM and CommonJS · MIT license

import { openOPFS } from 'defuss-db/browser'
interface Order {
  id: string; customer: string
  total: bigint; placedAt: Date
}
interface Stock { id: string; reserved: number }
const db = await openOPFS({ namespace: 'shop' })
const orders = db.collection<Order>('orders')
await orders.createIndex({
  name: 'byCustomer',
  fields: ['customer', 'placedAt'],
  order: ['asc', 'desc'],
})
await db.transaction(async (tx) => {
  await tx.collection<Order>('orders').insert({
    customer: 'ada', total: 120n, placedAt: new Date(),
  })
  await tx.collection<Stock>('stock')
    .put({ id: 'sku-7', reserved: 1 })
})
const page = await orders.pageByIndex('byCustomer', {
  prefix: ['ada'], limit: 20,
})
await db.close()
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.

Server example

With persistence

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.

Try browser persistence

Transactions across collections

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.

Try a pinned snapshot and a rollback

Indexes that seek, page and count

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.

See index and scan timings

Efficient compaction

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.

Read how compaction runs

Search by words or meaning

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.

Read the search guide

Read a past price

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.

See a price correction

Native values between runtimes

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.

Read the API guide

Backup and restore

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.

Read the archive guide

Database Explorer

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.

defuss-db or MongoDB?

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.

Run your MongoDB queries

import { openMemory } from 'defuss-db'
import { aggregateMongo, findMongo } from 'defuss-db/mongo'
type Order = { id: number; status: string; amount: number; items: { sku: string }[]; at: Date }
const db = await openMemory()
const orders = db.collection<Order>('orders')
await orders.createIndex({ name: 'byStatus', fields: ['status'] })
await orders.insertMany([
  { id: 1, status: 'paid', amount: 120, items: [{ sku: 'kb' }], at: new Date('2026-11-16') },
  { id: 2, status: 'paid', amount: 80, items: [{ sku: 'ms' }, { sku: 'kb' }], at: new Date('2026-11-18') },
  { id: 3, status: 'open', amount: 45, items: [{ sku: 'ms' }], at: new Date('2026-11-24') },
])
await findMongo(orders, "{ status: 'paid', 'items.sku': 'kb' }", { sort: { amount: -1 } })
// → ids 1, 2: status from the index; items.sku matches any item
await aggregateMongo(orders, [
  { $group: { _id: { $dateTrunc: { date: '$at', unit: 'week' } }, revenue: { $sum: '$amount' } } },
  { $sort: { _id: 1 } },
])
// → [{ _id: 2026-11-15, revenue: 200 }, { _id: 2026-11-22, revenue: 45 }]
MongoDB 9.0.8 returns the same.
Matching
166 of 166 filters return MongoDB 9.0.8's documents: arrays, dot paths, null, types.
Indexes
Equality and ranges on indexed fields use the index.
Pipelines
$match $unwind $group $sort $limit $count become one aggregate.
Calendar
$dateTrunc with timezone, binSize, startOfWeek.
Schemas
analyzeSchema() returns a JSON Schema (2020-12) of a sample.
Refused by name
$lookup, $expr, $where and other untranslatable parts.

Operators, stages and schemas

Benchmarks

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.

Runtime
Documents
Speed relative to MongoDB
Median per operation, each on its own scale

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 search0.107 msBM25 on indexed terms
Vector search0.081 msExact cosine similarity
Hybrid search0.217 msCombine 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.

Median milliseconds per operation
OperationPathNode memoryNode directoryBun memoryBun directory
Tenant feed, 20 complete eventsCompound index0.3400.3250.5580.384
Tenant feed, 20 complete eventsCollection scan3.783.994.854.28
Commit 64 eventsWith the compound index0.6414.210.6684.15
Commit 64 eventsPrimary keys only0.3233.890.3234.01
Current documentUntracked collection0.0150.0150.0160.021
Current documentTracked collection0.0120.0140.0170.018
Historical documentEffective date0.0380.0660.0340.053
Historical documentEffective date and recorded cutoff0.0560.0550.0510.082
Commit one updateUntracked collection0.1134.040.1184.26
Commit one updateTracked collection0.1954.040.1554.01
Correct a closed intervalOne document0.1664.020.3654.02
Delete a closed intervalOne document0.1254.040.2914.04
Count historical documentsFull scan2.2212.253.5710.36
Count historical documentsWarm result cache0.0640.1320.1710.145
Historical page of 32 IDsBuild postings and read page2.118.812.629.67
Historical page of 32 IDsRead retained postings0.0390.0490.0560.056
Ordered page of 20 IDsLive index0.0360.0470.0630.079
Ordered page of 20 documentsLive index and document lookup0.1150.1200.1650.171
Count 64 index entriesLive index0.0450.0760.1870.109
Search for five documentsWarm lexical engine0.1070.0740.2530.097
Search for five documentsWarm vector engine0.0810.1060.2540.107
Search for five documentsWarm hybrid engine0.2170.3080.2050.367

Method and results · Node.js samples · Bun samples

Already hold the rows in RAM? Compare the in-memory database and a resident DataView array.

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.

import { openMemory } from 'defuss-db'
interface Price { id: string; eur: number }
const utc = (month: number, day: number) =>
  new Date(Date.UTC(2026, month - 1, day))
const db = await openMemory()
const prices = await db.ensureCollection<Price>('prices', {
  $trackHistory: true,
})
await prices.at(utc(1, 1)).put({ id: 'plan', eur: 100 })
await prices.at(utc(2, 1)).put({ id: 'plan', eur: 120 })
const before = (await db.stats()).revision
await prices.update('plan', { eur: 110 }, { $historic: utc(1, 15) })
const past = prices.at(utc(1, 20), { $asOfRevision: before })
const price = (await past.get('plan'))?.eur // 100
await db.close()
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.

Six parts of a read

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.

  1. PinOpen one read revision.
  2. ValidateCheck cursor scope and version.
  3. SeekRead from the previous full key.
  4. ReturnDecode 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.

Validation scope and limits

Safety guarantees

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.

bun add defuss-db
# or
npm install defuss-db

A MongoDB alternative for the web

The API reference covers queries, indexes, search, transactions, history, archives and the storage options of each runtime.