惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
MongoDB | Blog
MongoDB | Blog
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
O
OpenAI News
酷 壳 – CoolShell
酷 壳 – CoolShell
The GitHub Blog
The GitHub Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
W
WeLiveSecurity
Hacker News: Ask HN
Hacker News: Ask HN
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
D
Docker
F
Full Disclosure
AI
AI
罗磊的独立博客
博客园 - 【当耐特】
U
Unit 42
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Palo Alto Networks Blog
博客园_首页
H
Help Net Security
量子位
月光博客
月光博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 司徒正美
F
Fortinet All Blogs
D
DataBreaches.Net
B
Blog RSS Feed
Webroot Blog
Webroot Blog
TaoSecurity Blog
TaoSecurity Blog
S
Secure Thoughts
爱范儿
爱范儿
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
C
CERT Recently Published Vulnerability Notes
Martin Fowler
Martin Fowler
Blog — PlanetScale
Blog — PlanetScale
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Securelist

Show HN

GitHub - steveking-gh/firmion: Firmion is DSL and engine for firmware image generation. GitHub - villagesql/villagesql-skills: Agent skills for VillageSQL - gemini-cli-extension; claude-code-plugin GitHub - flightdeckhq/flightdeck: Observability and control plane for AI agents. CSP Radar GitHub - Light-Heart-Labs/DreamServer: Turn your PC, Mac, or Linux box into an AI server. LLM inference, chat UI, voice, agents, workflows, RAG, and image generation. GitHub - Diplomat-ai/diplomat-agent-ts: What can your TypeScript AI agent do to the real world? Scan your code. See which tool calls have zero checks Code Block Selector - Visual Studio Marketplace Prometheus dependency graph — interactive showcase | Riftmap Show HN: I made a vi-like modal keyboard plugin for Figma GitHub - run-llama/liteparse: A fast, helpful, and open-source document parser GitHub - dalemyers/Roar: A macOS CLI tool for notifications GitHub - district-solutions/open-agent-tools-coder: Enables small-to-large self-hosted ai models to use local source code when running tool-calling agentic workloads. We actively data mine 20,900+ (2+ TB) popular github repos using large and small ai models to create reuseable: json, markdown and parquet files for local-first tool-calling models. GitHub - progapandist/stripeek: A local TUI proxy for real-time Stripe API debugging, built for navigating complex payloads fast. GitHub - sir1st/hermes-desktop: All-in-one cross-platform desktop app for Hermes Agent — bundles Python + hermes-agent + hermes-web-ui GitHub - astefanutti/shaderbang: Shebang for Shaders Show HN: Generate Claude Code Workflows using Spec Driven Development approach GitHub - nixys/nxs-universal-chart: The Helm chart you can use to install any of your applications into Kubernetes/OpenShift Show HN: AI agents for UK GDAD PCF roles and their skills The Two Pillars: Mixer Mode and Meta-Software in the Reorganization of Software Work After AI GitHub - JaiCode08/teleport-env What 1,000+ Harness Experiments Taught Me About Self-Improving Agents Show HN: Liiists, a Markdown-first, iOS and CLI list app SwiperTab – Get this Extension for 🦊 Firefox (en-US) GitHub - kouhxp/fftext: Summarize, explain, fact-check, or translate any text, URL, or file. No GPU. No cloud. One command GitHub - sweetpad-dev/sweetpad: Develop Swift/iOS projects using VSCode GitHub - dogmaticdev/IRON: IRON a.k.a. Intermediate Representation Object Notation is a Interpreter/Database that is used to create Programming Languages. GitHub - sjhalani7/vaen: Package your AI coding harness into a portable .agent file, and share it across repos, teams, & the community without ever having to copy-paste instructions, skills, MCP config, or secrets. Show HN: Gandalf the Grader Show HN: Citadeld – replay any CI failure locally from a single file GitHub - tdortman/cuSBF: High-Performance GPU Super Bloom Filter coral-ai/claude-code-token-xray at main · Coral-Bricks-AI/coral-ai GitHub - ulyssestenn/funes: Funes is a Git-based framework for LLM-managed knowledge work: an AI Librarian ingests raw sources, builds an interlinked Markdown knowledge base, and uses it to produce cited reports, analyses, and other outputs. GitHub - ThatXliner/gah: Git Add Hunk, built for agents to use GitHub - harmont-dev/harmont-cli: Command-line client for the Harmont CI platform GitHub - brooksmcmillin/mcp-authflow: OAuth 2.0 Authorization Server framework for MCP servers GitHub - javaid-codes/audit-supply-chain-agents GitHub - amorey/gochan: A small library of common channel architectures for Go, inspired by Rust GitHub - arifozgun/OpenGem: Free, Open-Source AI API Gateway with Gemini, OpenAI & Anthropic Compatibility in 1 file GitHub - Pranesh950/BioPetals: 🌸 Run BIOxAI models at home, BitTorrent-style. Fine-tuning and inference up to 10x faster than offloading GitHub - cnguyen14/bounty-doctor: Diagnose a GitHub bounty issue before you waste hours: detects honeypot scam repos, AI-bot attempt swarms, and stale contests. Show HN: CoreMCP – MCP Server for On-Prem DBs Show HN: KittyHTML – Render HTML/CSS as an inline image in your terminal GitHub - bingud/filemat: Web-based file manager Show HN: TruthLens – Free multi-signal deepfake image detector GitHub - apexlocal-jz/claude-usage-tray: Windows system-tray app showing your Claude Code rate-limit usage at a glance. Zero deps, ~300 lines of PowerShell. Cross-IDE (works regardless of VS Code, Cursor, plain terminal). Release v0.1.2.1 · kouhxp/yapsnap GitHub - noopolis/moltnet: Self-hostable chat network for AI agents. Pre-built bridges for Claude Code, Codex, and the Claws. Rooms, DMs, history. No Slack bots, no Matrix, no glue code. GitHub - tamerh/enju: Coordinating Humans, AI Agents, and Compute as Peers on a Shared Workflow Graph Show HN: Continuity-auth – Respect-weighted rate limits for the open web GitHub - luml-ai/luml: AI lifecycle platform where engineers and agents track experiments, train models, and ship to production. GitHub - mrdanielcasper/CoreTex: A UNIX-inspired, biomimetic, flat-file AI harness and knowledge engine. GitHub - clemg/pierre-github: Pierre's diffs.com and trees.software for Github GitHub - lyriks-io/unspaghettit: Behavior-driven AI development without prompt spaghetti. GitHub - sofumel/claude-handoff-revive: Resume Claude Code work after rate/usage/context limits without replaying the prior transcript. Auto-saves at 90%/95% usage. Plugin-installable, 10 languages. GitHub - dotexorg/saferpc: Typed, end-to-end encrypted RPC over any bidirectional channel. GitHub - BeeZeeAgent/beezee: Agent harness orchestration Legato Next.js Boilerplate for Internal Tools · CoreUI GitHub - clark-labs-inc/clark-hash: Clark Hash, 32x smaller searchable sketches for embeddings GitHub - ZeroPointRepo/youtube-mcp: The fastest YouTube transcript + YouTube search MCP for AI agents. Try for free. Typing Mastery — climb toward 100+ WPM, deliberately GitHub - Andebugulin/Awareen GitHub - fayzan123/claude-workflow-composer: Visual desktop app for composing multi-agent coding workflows. Drag agents, attach skills and MCPs, wire handoffs, export to .claude/ GitHub - harshaneel/humanize: Best static AI text humanizer. Two research-grounded skills that work in any LLM (Claude, ChatGPT, Gemini, Codex): humanize beats perplexity-based detectors, ai-check produces forensic scoring with evidence-quoted flags. Nine levers, 50+ peer-reviewed sources, 2024-2026 detection literature. GitHub - StackOneHQ/stack-nudge GitHub - nodes-app/swift-markdown-engine: A native AppKit Markdown editor for macOS, built on TextKit 2 and bridged to SwiftUI. We hardened an LLM agent. Each defense we added made it more exploitable. GitHub - alkait/WhatsKept: Agent-queryable WhatsApp history from an iOS backup — a single Go binary. GitHub - octelium/cordium: Open-source, general-purpose sandbox platform for devs and AI agents that provides identity-based secure access to infrastructure without credentials. WAR.GOV/UFO Microfilm5 GitHub - scosman/videowright: Build animated explainer videos with your coding agent GitHub - dipankar/dscode: The code editor you can take apart. GitHub - zoharbabin/web-researcher-mcp: MCP server (Go) for AI assistants: web search, content extraction, academic/patent/news research. Multi-provider routing, 4-tier scraping, search lenses. Works with Claude, Cursor, and any MCP client. GitHub - ruvnet/RuView: π RuView turns commodity WiFi signals into real-time spatial intelligence, vital sign monitoring, and presence detection — all without a single pixel of video. GitHub - scanaislop/aislop: Catch the slop AI coding agents leave in your code: narrative comments, swallowed exceptions, as-any casts, dead code, oversized functions. 50+ rules across 7 languages (TypeScript, JavaScript, Python, Go, Rust, Ruby, PHP). Sub-second, deterministic, no LLM at runtime. MIT-licensed. GitHub - kouhxp/cheap-im: CPU-only voice agent approximating Thinking Machines' Interaction Models demo GitHub - unprovable/OrchidMantis: Orchid Mantis — standalone framework for Zero-Knowledge Proofs of eXploit (ZKPoX). GitHub - MarcellM01/TinySearch: Shrink the web for your local LLMs! GitHub - TangibleResearch/Halgorithem: A Algo designed to detect AI Hallucitions GitHub - DO-SAY-GO/freelang: I love freelang GitHub - CarpseDeam/Aura-IDE: An AI coding harness that shaped itself - Planner/Worker agents, repo awareness, surgical edits, validation, recovery, and safe diff approvals. GitHub - chojs23/concord: A feature-rich TUI client for Discord GitHub - tommyjepsen/awesome-ux-skills: UX & AI Product designs skills you can use today in Claude Code GitHub - aerf-spec/aerf: Agent Evidence Receipt Format (AERF) — an open specification for tamper-evident, independently verifiable records of AI agent actions. GitHub - kklimuk/docx-cli: CLI for AI agents (Claude, Codex) to read, edit, and comment on .docx files with full format fidelity. GitHub - Jwrede/tokentoll: Catch LLM cost changes in code review. Infracost for LLM spend. GitHub - samchon/ttsc: A `typescript-go` toolchain for compiler-powered plugins and type-safe execution + 500x faster lint integrated into compiler GitHub - Higangssh/homebutler: 🏠 Manage your homelab from chat. Single binary, zero dependencies. GitHub - olalie/tapmap: See where your computer connects and what stands out on a live world map. GitHub - Diplomat-ai/diplomat-agent: What can your AI agent do to the real world? Scan your code. See which tool calls have zero checks GitHub - Bajusz15/beacon: Open-source agent for secure remote access, monitoring, and deploys across home-lab and self-hosted machines like Raspberry Pi, N100, or any Linux server. Open web based TTY or tunnel Home Assistant and other local services securely without opening ports. BigTech AI News - Chrome 应用商店 GitHub - vinhnx/VTCode: VT Code is an open-source coding agent with LLM-native code understanding and robust shell safety. Supports multiple LLM providers with automatic failover and efficient context management. GitHub - michaelaz774/decision-engine: A decision operating system for startup founders, powered by Claude Code. Synthesizes wisdom from 25+ legendary founders and investors into interactive AI-driven decision frameworks. GitHub - Chrilleweb/dotenv-diff: Validate environment variable usage in your codebase GitHub - Lumen-Labs/brainapi2: BrainAPI is a knowledge graph–powered AI memory layer that transforms unstructured data into structured knowledge, enabling intelligent search, recommendations, and contextual memory for AI agents and applications. GitHub - familiar-software/familiar: Let AI watch you work. Familiar lets your AI update its memory, skills, and knowledge by watching your screen. GitHub - skorotkiewicz/rudo: A small, elegant dock for Wayland GitHub - muxshed/shed: One stream in, or many. Every destination, simultaneously. No cloud middleman, no per-channel fees, no limits. make sidebar/address bar rounded corner toggleable
GitHub - AxFab/pocket-db: The local database for Electron, desktop & CLI apps — one file, zero native bindings, a MongoDB-style API.
axfab · 2026-06-17 · via Show HN

pocket-db

Pocket DB — the local database for Electron, desktop and CLI apps. One file, zero native dependencies, a familiar MongoDB-style API.

npm version MIT License Node ≥ 18 npm downloads


Add persistent local storage to a Node.js or Electron app — no server, no daemon, and no native bindings. No node-gyp, no rebuilding against every Electron version, none of the better-sqlite3 recompile dance. Run npm install and you have a working document store backed by a single file.

import { pocketDb } from "@axfab/pocket-db";

const db = pocketDb("./data.pdb");
const users = db.collection("users");

users.insertOne({ name: "Ada", role: "admin" });
const admins = users.find({ role: "admin" }).toArray();

db.close();

That's the whole setup — open a file, work with collections of JSON documents, close.

  • 🪶 Zero native dependencies — pure TypeScript, no node-gyp, no per-Electron rebuilds
  • 📄 Single file — back up your whole database by copying one .pdb file
  • 🍃 MongoDB-style APIfind / insert / update with the operators you already know
  • Append-only writes — every mutation is a fast sequential append, with crash-safe batches
  • 🛡️ Safe reads — every query returns an independent copy, so mutating a result never corrupts your stored data

Inspired by SQLite (one embedded file) and MongoDB (document model), but intentionally small. The core rule — never reserialise the whole database on a write — makes every insert, update and delete a fast append, and reads seek straight to a document's offset.

Good fit: Electron & desktop apps, CLI tools, local servers, plugins, structured caches, offline-first prototypes. Not a fit: multiple processes writing the same file at once, complex aggregation pipelines, or anything that really wants a server database.


Install

npm install @axfab/pocket-db

No native binaries. No optional dependencies. Pure TypeScript compiled to ESM.


Quick start

import { pocketDb } from "@axfab/pocket-db";

const db = pocketDb("./data.pdb");
const users = db.collection("users");

// Insert
const { insertedId } = users.insertOne({ name: "Ada", role: "admin", age: 37 });

// Find
const ada = users.findOne({ name: "Ada" });
console.log(ada); // { _id: "...", name: "Ada", role: "admin", age: 37 }

// Query with operators
const admins = users.find({ role: "admin", age: { $gte: 18 } }).toArray();

// Update
users.updateOne(insertedId, { $set: { age: 38 }, $inc: { loginCount: 1 } });

// Delete
users.deleteOne(insertedId);

db.close();

Core concepts

Single file, append-only

All writes are appended to the end of the file. Reads go directly to the byte offset of the document — no full-file scan. The in-memory state is rebuilt by replaying the log when open() is called. Deleted and updated documents leave dead records behind; db.compact() reclaims that space in a single forward pass.

Collections

A database holds any number of named collections. Collections are created implicitly on first access and persisted to the log. Each collection has its own primary index (keyed by _id) and optional secondary indexes.

Document IDs

Every document gets a _id: a 24-character lowercase hex string (12-byte ObjectId layout — 4-byte timestamp, 5-byte random, 3-byte counter). You can supply your own _id on insert as long as it matches that format.

Safe reads

Every document returned by findOne, find, or a cursor is a fresh, independent object that you fully own. Mutating a query result never affects what is stored — exactly what you'd expect from a real database. This holds whether the read came from disk or from the hot-document cache (cached reads are deep-cloned on the way out).

This is a deliberate guarantee: some in-memory stores return references to their internal objects by default, which is faster but means modifying a query result silently corrupts the database. Pocket DB always isolates your results.


API

Opening a database

import { pocketDb } from "@axfab/pocket-db";
const db = pocketDb("./data.pdb");

You can also merge both arguments by setting the path property in the options object, or pass all options together:

const db = pocketDb({ path: "./data.pdb" });

pocketDb accepts an optional OpenOptions object as its second argument (or first, when using the object form):

const db = pocketDb("./data.pdb", {
  durability: "strict",      // default: "relaxed"
  serialization: "bson",     // default: "json" — only applies when creating a new file
});

durability

Controls whether fsync is called after every write.

  • "relaxed" (default) — skips fsync. Writes reach the OS page cache but may be lost on a power failure or OS crash before the cache is flushed. Faster; suitable when losing the last few writes on a hard crash is acceptable.
  • "strict" — calls fsync after every appendOperation, guaranteeing data is on durable storage before the call returns. Safest; incurs one extra syscall per write.

serialization

Selects the document encoding format when creating a new database file. Opening an existing file always uses the format recorded in the file header — this option is ignored.

  • "json" (default) — documents stored as UTF-8 JSON. Human-readable, universally compatible.
  • "bson" — documents stored as BSON (Binary JSON). Supports double, string, document, array, boolean, null, int32, int64. More compact than JSON for numeric-heavy documents.
  • "amf3" — documents stored as AMF3 (Action Message Format 3). A compact binary format supporting undefined, null, boolean, integer, double, string, array, and object.

Database

db.collection(name: string): Collection
db.getCollections(): string[]              // names of all registered collections
db.existsCollection(name: string): boolean
db.compact(): void                         // reclaim space from dead records
db.close(): void

Collection

collection.insertOne(doc): InsertOneResult
collection.insertMany(docs): InsertManyResult

collection.findOne(query?): Record | null
collection.find(query?): Cursor
collection.countDocuments(query?): number

collection.updateOne(id | query, update): UpdateResult
collection.updateMany(query, update): UpdateResult

collection.replaceOne(id, doc): ReplaceOneResult
collection.replaceOne(doc & { _id }): ReplaceOneResult

collection.deleteOne(id | query): DeleteOneResult
collection.deleteMany(query?): DeleteManyResult

collection.createIndex(field, { type: "string" | "number" }): CreateIndexResult
collection.dropIndex(field): DropIndexResult
collection.getIndexes(): { name: string; type: string }[]
collection.existsIndex(name: string): boolean
collection.drop(): DropResult

collection.enableCache(maxBytes: number): void   // hot-document cache (off by default)
collection.disableCache(): void
collection.cacheStats(): DocumentCacheStats | null

Cursor

cursor.next(): Record | null
cursor.toArray(): Record[]
cursor.count(): number

cursor.sort(spec: Record<string, 1 | -1>): Cursor   // up to 4 fields
cursor.limit(n: number): Cursor
cursor.skip(n: number): Cursor

Query operators

Queries are plain objects. A bare value is shorthand for $eq.

Operator Description
$eq Strict equality (no type coercion)
$ne Not equal
$gt / $gte Greater than / greater than or equal
$lt / $lte Less than / less than or equal
$in Field value is in the given array
$nin Field value is not in the given array
$exists Field is present (true) or absent (false)
$regex String matches a regular expression (flags via $options; g/y rejected)
$not Negates an operator expression
$and Logical AND of sub-queries
$or Logical OR of sub-queries
$nor Logical NOR of sub-queries
// Compound query
users.find({
  $and: [
    { role: { $in: ["admin", "editor"] } },
    { age: { $gte: 18, $lt: 65 } }
  ]
});

// Negation
users.find({ status: { $not: { $eq: "banned" } } });

// OR
users.find({ $or: [{ role: "admin" }, { role: "editor" }] });

// Regex (string pattern + $options, RegExp value, or bare RegExp shorthand)
users.find({ name: { $regex: "^ada", $options: "i" } });
users.find({ name: { $regex: /^ada/i } });
users.find({ name: /^Ada/ });

Update operators

Updates are expressed as operator objects applied to the current document.

Operator Description
$set Set one or more fields
$unset Remove one or more fields
$inc Increment a numeric field
$mul Multiply a numeric field by a factor
$min / $max Set field only if new value is lower / higher
$rename Rename a field (missing source is a no-op)
$currentDate Set field to the current date (true / { $type: "date" } → ISO string, { $type: "timestamp" } → epoch ms)
$push Append a value to an array field
$addToSet Append a value only if no equal element exists
$pop Remove the last (1) or first (-1) array element
$pull Remove array elements equal to a value or matching a condition
$pullAll Remove array elements equal to any listed value
users.updateOne(id, {
  $set: { role: "editor" },
  $inc: { loginCount: 1 },
  $mul: { score: 1.1 },
  $currentDate: { lastLogin: true },
  $addToSet: { tags: "active" },
  $pull: { scores: { $lt: 10 } }
});

_id is immutable and cannot be modified by any update operator.


Indexes

Secondary indexes speed up equality and range queries. They are rebuilt from the log at every open.

// Create
users.createIndex("role", { type: "string" });
users.createIndex("age",  { type: "number" });

// Drop
users.dropIndex("role");

StringIndex supports $eq and $in lookups. NumberIndex additionally supports $gt, $gte, $lt, $lte range scans. The query planner automatically picks the most selective available index for each query.


Hot-document cache

By default every read decodes its document from the file. For workloads that read the same documents repeatedly, you can opt into an in-memory cache that keeps parsed hot documents around, so repeated reads skip both the file read and the decode.

users.enableCache(16 * 1024 * 1024); // 16 MB budget; least-recently-used docs are evicted
users.cacheStats();                  // { hits, misses, evictions, bytes, documentCount, ... }
users.disableCache();                // free everything, back to zero overhead

The cache is off by default — when disabled it costs nothing (no object is even allocated). It is keyed by _id and versioned by file offset, so it stays correct across updates, deletes, compaction, and open cursors (snapshot reads are preserved).

The gain: on a 2,000-document JSON dataset, single-document reads get ~2.9× faster and even full scans ~1.8× faster, because skipping the read + JSON parse outweighs the cost of cloning the cached object.

The drawbacks: it trades memory for speed, so size the budget for your hot working set. It is rebuilt empty on every open() (in-memory only, never persisted). And large scans populate the cache as they read — if the budget is smaller than a scan's footprint, a one-off scan can evict genuinely hot documents.

See docs/cache.md for the full design, internals, and benchmark methodology.


Sorting and pagination

const page = users
  .find({ role: "admin" })
  .sort({ age: -1, name: 1 })   // up to 4 sort fields
  .skip(20)
  .limit(10)
  .toArray();

Sort accepts 1 (ascending) and -1 (descending). Missing values sort first in ascending order and last in descending order. Sorting is always eager — narrow the candidate set with an indexed query before sorting over large collections.


Compaction

Dead records accumulate as documents are updated or deleted. compact() rewrites the file in a single forward pass, keeping only live data:

After compaction, all in-memory indexes are refreshed automatically.


Batch atomicity

insertMany, updateMany, and deleteMany are crash-safe: if the process is killed mid-batch, the partial batch is silently discarded on the next open. Either all operations are visible or none are.


File locking

pocketDb() creates a .lock file next to the database file. A second pocketDb() on the same path from a different process will throw. Stale locks left by crashed processes are detected via PID check and cleared automatically.

Pocket DB is designed for single-process use. Multiple concurrent writers on the same file are not supported.


TypeScript

Pocket DB is written in TypeScript and ships its own type declarations. All public types are exported from the package root:

import { pocketDb } from "@axfab/pocket-db";
import type {
  Database, Collection, Cursor,
  InsertOneResult, InsertManyResult,
  UpdateResult, ReplaceOneResult,
  DeleteOneResult, DeleteManyResult,
  CreateIndexResult, DropIndexResult, DropResult,
  IndexInfo, OpenOptions, SortDirection,
  DocumentCacheStats
} from "@axfab/pocket-db";

Documentation

The docs/ folder contains in-depth documentation available as a wiki:


Performance

Pocket DB is built for fast, durable writes. Benchmarked against other embedded stores on 1,000 documents across the operations in our benchmark suite — ops/sec, higher is better.

The headline: for durable writes, pocket-db is 40–700× faster than every other file-backed store here, and lands within ~12% of in-memory SQLite — which isn't even durable.

📊 Full results table → benchmarks/RESULTS.md — all adapters and operations side by side. Regenerate anytime with npm run bench, which prints a width-aware ranked view to the console and refreshes RESULTS.md and results.json.

Reading the results

Writes — where pocket-db shines. Every mutation is a single sequential append: no B-tree rebalancing, no page allocation, no full-file reserialisation. That's why insertOne, updateOne and deleteOne leave every other persistent store far behind and sit right next to in-memory SQLite. For a desktop or Electron app writing to disk on every user action, this is exactly the path that matters — and it stays durable.

Single-document reads are fast too. findById runs at ~140k ops/sec — more than enough for typical app workloads, even though it reads from disk rather than RAM.

Full scans and sorts — the current tradeoff, by design. json-file, lowdb and LokiJS win on findAll and sortByScore because they hold the entire dataset in memory and serve reads from there. That speed has a hard ceiling: your database can never grow larger than available RAM. Pocket DB keeps only its indexes in memory and reads each document from its file offset on demand — so it can back a database far larger than RAM would ever allow. The price today is slower full scans.

A hot-document cache now closes most of that read gap without touching the append-only write model. Opt in with collection.enableCache(maxBytes) and hot documents stay parsed in memory: single-document reads get ~2.9× faster and full scans ~1.8× faster on the 2,000-document JSON benchmark. It is off by default and trades memory for speed — see docs/cache.md.

Reading the read numbers fairly. pocket-db returns an independent copy of every document, so mutating a result never touches stored data. Some in-memory stores in this table return references to their internal objects by default — fast, but modifying a query result silently corrupts the database. Part of their read-throughput lead is simply the defensive copy pocket-db makes and they skip; it buys a correctness guarantee we keep on purpose.

In short: if your workload is write-heavy, needs durability, or outgrows memory, pocket-db is the right tool. If you need pure in-memory read throughput on a dataset that comfortably fits in RAM, an in-memory store still wins today.

Run the benchmarks yourself:

npm install
npm run bench

License

MIT © Fabien Bavent