Skip to content

Research notes / Storage engines

LMDB readers: a stable snapshot can exhaust a fixed map

/ Controlled synthetic experiment

An LMDB reader can leave the writer mutex available while preventing old pages from being reused. In our fixed-map workload, a live snapshot exhausted the map; ending that snapshot restored write progress without increasing capacity. A stalled backup can cause the same pressure, even when its output is compacted. A terminated reader can leave abandoned entries that still need cleanup before writes resume. A readable copy also needs the original key-comparison semantics to support the application's lookups.

On this page9 sections

The same 128 KiB of values, different space pressure

Each environment contained eight keys with 16 KiB values. We repeatedly overwrote one key per committed transaction, keeping the key count and value lengths fixed. The only treatment was the lifetime of a read transaction opened after seeding: end it, keep it active, or reset it while retaining its handle.

Committed high-water extent with a 1 MiB map
Reader ended252 KiB
Reader active1012 KiB
Reader reset252 KiB

0 KiB Map limit: 1,024 KiB

Extent = (last committed page number + 1) x page size. It includes reusable and retained pages, not just live values. Bars share a zero baseline; they are not allocated filesystem-block or resident-memory measurements.

Three repetitions per row; counts were identical. Target: 256 committed overwrites. KiB = 1,024 bytes; MiB = 1,048,576 bytes.
Reader stateMap MiBCommittedExtent KiBNext result
Reader ended1256252Target completed
Reader active1301012MDB_MAP_FULL
Reader reset1256252Target completed
Reader ended2256252Target completed
Reader active2642028MDB_MAP_FULL
Reader reset2256252Target completed

The active-reader cases stopped after 30 and 64 commits at map sizes of 1 and 2 MiB respectively. The original reader still returned every original byte. A fresh reader saw every successfully committed change, with no partial failed update. After ending the active reader, all 64 further overwrites succeeded at the unchanged map size.

The committed high-water extent did not decrease after release. Progress came from reuse, not file shrinking. Both controls completed all 256 initial updates and 64 follow-up updates. These constructed cases are not independent samples of production incidents; no failure probability follows.

Not blocking the writer is not the same as releasing space

Chu's 2011 paper describes copy-on-write B+ trees and a separate tree of retired pages, grouped by transaction. A writer can reuse a group only when its retirement predates every active reader. Thus an old snapshot can hold back reclamation even though reads do not take the writer mutex. We examine this mechanism, not the paper's LDAP throughput results. [1, section 4.2]

In the pinned implementation, mdb_find_oldest() scans reader transaction IDs and mdb_page_alloc() excludes free-list records that are too recent. If suitable reusable pages are unavailable, allocation seeks new pages within the map bound. This is a source-code inference for LMDB 0.9.33, not a universal MVCC rule. [3]

The boundary is a transaction ID, not a list of pages explicitly fetched by the reader. Our byte checks establish snapshot consistency for this workload, not a per-page liveness census. Compare the different SQLite WAL checkpoint boundary: both retain historical views, but their reclamation mechanisms differ.

A live old reader is not a stale dead-process slot

At map exhaustion, mdb_reader_check() returned success and cleared zero slots. Another write still returned MDB_MAP_FULL. The reader was alive and intentionally holding a snapshot. That original experiment did not kill a process; the separate lifecycle test below now covers abandoned-slot cleanup.

The reviewed implementation checks process liveness for stale reader entries; it is not a transaction-age timeout. Separately, mdb_txn_reset() ends a read transaction but retains a renewable handle. Our reset control kept that handle without retaining the old snapshot. Reading through it again requires mdb_txn_renew(). [2] [3]

Python LMDB warns that cleanup of an abandoned transaction reference can depend on the interpreter's garbage collector. Explicit lifetime management is easier to audit. Our experiment uses the C API and does not measure a binding's cleanup behavior. [4]

Process exit is not reader-table cleanup

Killing the reader did not immediately restore writes. In a follow-up with a separate reader process, a fresh write still returned MDB_MAP_FULL after termination. Explicit mdb_reader_check() removed its abandoned entries; the next write succeeded at the unchanged map size. This reproduces a documented mechanism, not a newly discovered LMDB defect. [2]

The five lifecycle controls below started with an exhausted map and old snapshots of eight 16 KiB values. The parent kept its environment open throughout, so last-close/first-open lock-file initialization was not the cleanup mechanism. Each case used LMDB 0.9.33 and MDB_NOTLS, allowing one child to own several read handles in one thread.

One child, three read handles, 1 MiB map. Both repetitions matched; the 2 MiB cases had the same status outcomes. The one-handle cases cleared one slot after death instead of three.
Reader lifecycleWrite before checkSlots clearedWrite after check
Alive, snapshots retainedMap full0Map full
Alive, handles resetSuccess0Success
Closed cleanly, child reapedSuccess0Success
Killed, child reapedMap full3Success
Killed, not yet reapedMap full3Success

Across five lifecycles, two capacities, two handle counts and two repetitions, all 40 constructed cases passed. A successful cleanup call was not sufficient evidence of recovered capacity: it also returned success in the live-reader control, where it cleared zero entries and the next write still failed. Ending or resetting a live snapshot is a different operation.

A PID can remain present after its lock disappears

In all eight unreaped cases, waitid() confirmed termination by SIGKILL with WNOWAIT, leaving the child waitable. kill(pid, 0) still succeeded, yet reader checking cleared the slots before the parent collected the exit status. [7]

The pinned POSIX implementation queries a byte-range lock at the reader PID's offset in the lock file, then rechecks under the reader-table mutex. It does not use kill(pid, 0) for this decision. Linux releases process-associated record locks at process exit. Together these explain the observation; they do not establish behavior on Windows or under PID reuse. [3, mdb_reader_pid and mdb_reader_check0] [6]

Slots cleared, current occupancy and high-water use differ

One killed process with three handles produced a cleared count of three. After cleanup its reader list was empty, but me_numreaders remained three. That field is a historical high-water measure, not the current active-reader count. After closing the live controls, all cases completed 64 further writes; complete key, length and byte checks also passed after reopening. The map was neither resized nor shrunk.

Chu's paper explains the reclamation boundary through reader transaction IDs. That design argument does not by itself specify when an abandoned slot is cleared; the versioned implementation and lifecycle controls answer that narrower question. No throughput result from the paper is reproduced here. [1, section 4.2]

For diagnosis, distinguish the current entries and their transaction ages, the cleanup return code, the number of slots removed, and a fresh write result. A persistent high-water number is not evidence of failed cleanup. Use the library's supported mechanism; do not edit its lock file or substitute a PID scan.

Termination occurred at command-wait barriers, outside library mutex operations. We did not test writer death, robust-mutex recovery, PID reuse, filesystem exhaustion or power loss. Two repeats on one Linux host are not independent production incidents; the exact write counts are not sizing guidance.

The canonical replay instructions, 40-case observations, runner, validator and tests preserve the pinned source hashes and full-byte oracles. Validation checks internal consistency, not independent authenticity.

Reproduce the observation

We compiled LMDB 0.9.33 at commit 3a29a24777c82a0165de813ae696a5068b5add30, verifying source SHA-256 hashes first. The runtime reported 4,096-byte pages. All 18 environments used private temporary directories, removed after use. No existing database was opened.

Calls were sequential on one thread with overlapping transaction lifetimes. MDB_NOTLS permits the read handle and writer in that arrangement. We did not enable MDB_NOSYNC, MDB_NOMETASYNC, MDB_WRITEMAP or MDB_NOLOCK. Payloads were deterministic.

The harness checks key count, value lengths and all bytes, records extent after each commit, checks the old snapshot, aborts failed put transactions, retries after reader checking, and checks values after release. The runner requires identical outcomes across three repetitions per configuration.

Download the JSON observations, C harness and Python runner. Obtain LMDB at the pinned commit, keep the harness files together, then run:

python3 run-lmdb-readers.py --lmdb /path/to/lmdb --output observations.json

Requires a C compiler, pthreads, Python 3 and a Unix-like temporary filesystem. The JSON records the platform and compiler. Exact counts depend on page size, map geometry, build and workload. This is not a benchmark, crash-consistency test, hardware-fault experiment or field failure-rate estimate.

A stalled backup can retain the pages the writer needs

Include backup jobs when looking for old readers. LMDB's copy API uses a read transaction, and its own manual warns about source-file growth during concurrent updates. Compact copying omits free pages from the output; it does not compact the live source in place. [5]

We tested that operational consequence with the same pinned LMDB 0.9.33 build. Eight 16 KiB values and 64 warm-up overwrites produced a 252 KiB source extent. A separate thread called mdb_env_copyfd2() into a pipe with 4 KiB capacity. We read the first 12 KiB, then either finished the copy before writing or stopped draining the pipe while attempting 256 one-key overwrites.

1 MiB source map; 128 KiB of live values. Three runs per row gave identical counts. Extent is the committed page high-water mark, not physical disk allocation.
Copy / receiverWrites / source extentFinal backup
Plain
Copy completed first
256 writes
252 KiB
252 KiB
Plain
Receiver paused
29 writes
1016 KiB
252 KiB
Compact
Copy completed first
256 writes
252 KiB
172 KiB
Compact
Receiver paused
29 writes
1016 KiB
172 KiB

Both paused copies reached MDB_MAP_FULL after 29 successful overwrites. With a 2 MiB map they reached 63. Checking for dead readers cleared zero slots, and retrying still failed. After draining and joining the copy thread, all 64 further writes succeeded without changing map size. The source extent stayed high: progress resumed through reuse, not shrinking.

The compact backup was smaller, but retained the same source history. Its output was 172 KiB rather than 252 KiB. Every backup reopened successfully and contained all eight pre-copy values, byte for byte; the source contained every committed update. Thus snapshot correctness and write availability were different outcomes in this test.

The handshake matters. In this version, plain copying holds the writer mutex while emitting two metadata pages. Reading into the third page ensures our paused receiver tests page-retention pressure after that phase, not a writer waiting for the initial mutex. Compact copying keeps its read transaction until its output thread finishes. These are version-specific source-code observations. [3, mdb_env_copyfd0 and mdb_env_copyfd1]

Across two map sizes, two copy formats, two receiver schedules and three repetitions, all 24 cases passed the full-byte checks. Linux, 4 KiB pages and RAM-backed temporary files were used; normal LMDB commit settings remained enabled. The pipe is a controlled stall, not a network-speed model. Reopening checks a readable snapshot, not survival of a crash or power loss; the harness does not explicitly synchronize the backup output to durable storage.

Operationally, inspect the age and progress of copying readers alongside source-map headroom. A compact destination is not evidence that the source has reclaimed pages. A larger map can provide headroom; it does not end a stalled copy. These small-run counts are not production sizing thresholds.

Reproduce using the instructions, C probe, runner and validation tests. The 24-case receipt includes source and harness hashes. This extends the experiment above; it does not reproduce the 2011 paper's performance measurements.

A copied tree still needs its comparison semantics

Every record can survive while indexed lookups miss those records. In a separate, synthetic LMDB 0.9.33 fixture, a complete cursor scan returned all 257 expected keys and their values. Reopening that descending-order tree with the default ascending comparator made all 257 existing-key lookups return MDB_NOTFOUND. The read-only probes left the data file byte-identical.

Snapshot consistency settles which committed pages are copied; it does not supply the application's ordering rules. The API requires compatible comparison behavior to be registered before data access. In the pinned implementation, mdb_set_compare() installs a runtime callback, not a tree rebuild. Persisted key flags and application callbacks are different state. [2, mdb_set_compare] [3, mdb_default_cmp and mdb_node_search]

Descending source, 257 synthetic keys. Successful existing-key lookups / keys tested; every row retained all 257 key/value pairs in a full scan. The two same-host builds agreed.
ArtifactDefault readerDescending reader
Original0 / 257257 / 257
Native copy0 / 257257 / 257
Compact copy0 / 257257 / 257
Normal dump/load257 / 2570 / 257
Dump/load with -a0 / 257257 / 257

Plain and compact native copies retained the ordering dependency. Normal dump/load instead rebuilt an ascending tree: it supported the default reader, but not the original descending reader. In these unique-key fixtures this was not irreversible data loss. Loading with -a retained the supplied order, without supplying the callback to later processes.

The pinned dump manual warns about restoring custom-comparator databases, while the load manual provides -a for this case. Its precondition matters: input must already be correctly ordered, and sorting and redundant-value checks are skipped. The loader uses temporary always-greater comparison behavior with append operations; it does not reconstruct the original comparator. Do not treat a successful append import as proof that an arbitrary or reordered dump is valid. [8] [9] [10]

The experiment covered 9 and 257 keys, ascending and descending writers, five artifacts and three reader policies. Default and separately registered, equivalent ascending callbacks both found every key in ascending controls. A callback's presence was not the problem: its ordering had to match the tree. In the smaller descending fixture the default reader found 1 of 9 keys, so zero matches is an observation, not a universal consequence of mismatch.

All 120 observations came from one pinned release on one Linux host, built with -O2 and -O0. Each probe checked full traversal, all existing keys, two absent keys, values and data-file hashes. Successful lookups returned the expected values; the observed mismatch was omission. No incompatible-comparator writes, duplicate-key databases, concurrent copy writes, power failures or throughput were tested. These exhaustive fixture counts are not incident rates or independent laboratory replications. Database statistics are not an integrity checker.

A full scan and an indexed query test different paths

Chu's original evaluation explicitly notes that its whole-database LDAP scan did not use attribute indexes, so those index pages were not mapped into the process. That is a workload detail, not a comparator-mismatch experiment. The practical connection is query coverage: enumerating records does not exercise every access path an application will need after restoration. Our separate fixture tests point lookup as well as traversal; it does not reproduce or extend the paper's throughput measurements. [1, section 5, Table 2]

Restore acceptance must exercise the intended application

Retain the key encoding and comparator implementation/version with a backup. On an isolated restore, install compatible behavior before reading, then check expected lookups as well as inventory. For larger systems, state the coverage and limitations of any sample. If ordering changes intentionally, migrate into a new tree under the target semantics instead of changing a callback in place. This demonstrates a documented caller obligation, not a newly discovered LMDB defect.

The related SQLite runtime-dependency experiment tests a different database and checking interface. Both illustrate why stored bytes alone need not preserve query meaning; LMDB statistics and SQLite integrity checks are not equivalent.

Inspect the method and limits, generated table data and source provenance. The public package includes the runner, C probe, exact-input replay verifier and mutation tests. The integration replay receipt records 120 matching retained-input replays; that is verification on the same host, not an independent replication.

Capacity, reclamation and compaction are different questions

MDB_MAP_FULL concerns the environment's map-capacity bound, not necessarily exhausted filesystem space. The transaction API separately lists disk-space and I/O errors. [2]

Our recommendation: record map size, committed extent, oldest active transaction and the owning request before changing capacity. Avoid keeping a snapshot across unrelated network waits or unbounded report generation. End or reset it only when its view is no longer needed; renewal obtains a new view.

A bigger map provides headroom but does not remove a retained reader. Ending a reader permits later reuse; it promises neither immediate file shrinking nor secure erasure. None of these experiments resized the map or tested a system crash; compact copying in the backup test rewrote only its destination.

Corpus: LMDB and LMDB reader table. The SQLite experiment separately examines stale values and transaction retries.

Primary sources

  1. Howard Chu. MDB: A Memory-Mapped Database and Backend for OpenLDAP. LDAPCon 2011, sections 3.2 and 4.2.
  2. LMDB 0.9.33 API: transaction lifetime, reset/renew, map capacity and reader checks
  3. LMDB 0.9.33 implementation: mdb_find_oldest, mdb_page_alloc and mdb_reader_check0
  4. Python LMDB documentation: transaction management and long-lived readers
  5. LMDB 0.9.33 mdb_copy manual: compact output and source-growth caveat
  6. Linux fcntl record locks: process-associated lock release
  7. Linux waitid: WNOWAIT and termination status before reaping
  8. LMDB 0.9.33 mdb_dump manual: custom-comparator restore warning
  9. LMDB 0.9.33 mdb_load manual: -a ordering precondition and skipped checks
  10. LMDB 0.9.33 loader implementation: greater callback and append loading

Published by Hesela team · Published · Updated

Report a correction · Editorial standards · Reuse guidance

Change history

: first published.

: latest recorded update. A detailed change note is not available for this revision.

New-publication RSS · Correction RSS

Cite this page
Hesela team. LMDB readers: a stable snapshot can exhaust a fixed map. Hesela. 2026-10-25. https://hesela.com/analyses/lmdb-readers-page-reuse-map-full/