Memtables work by keeping recent database changes in a searchable memory structure before those changes are transferred into immutable sorted files. They help the storage engine turn many small incoming operations into larger, ordered outputs without making readers wait for every batch to reach its final file representation.
The difficult part is the handoff. A memtable can stop accepting writes while readers still need it. A flush can finish writing bytes before its output becomes an installed part of the database. A buffer can become replaceable for new readers while an older reader still holds a reference to it. These are different transitions.
This guide explains how memtables work in the common logged LSM design, then uses a fictional equipment catalogue to test each transition. The examples are a teaching model, not production database code or performance measurements. Start with How LSM Trees Work for the complete storage lifecycle.
Continue the LSM series: the complete LSM mechanism · the sorted files created by flushing · how compaction maintains those files.
The Direct Answer: A Memtable Holds Searchable Recent State
The name combines memory and table, but its job is more specific than storing arbitrary data in RAM. In the common design, recent puts, deletes and other supported update records enter a memory-resident structure that participates in reads. Eventually a flush creates sorted-table storage from a selected generation.
RocksDB’s MemTable documentation describes both its read/write role and the switch from an active buffer to an immutable one. It also documents multiple implementations. A memtable is a responsibility in the storage pipeline, not one mandatory class or data structure.
The simplest mental model is a working desk that is searchable while new forms arrive. Once a batch is sealed, another desk accepts new forms and the sealed batch is archived. The archive handoff must be reliable because a reader may ask about any accepted form during the transition.
Why a Memtable Is Not Just a Read Cache
A read cache usually stores copies that can be fetched again from an established backing store. Evicting a cached block changes performance, not the logical database. A memtable can contain a recent version that no installed SSTable holds yet.
That difference determines what memory pressure is allowed to do. The engine cannot simply discard an active memtable and treat every missing entry as a future cache miss. It must retain an adequate live-read and recovery path until the handoff is complete.
There may be a write-ahead log from which recent changes could be reconstructed after a crash. However, having a recovery log is not the same as providing normal low-latency reads without the memtable. Recovery machinery and serving machinery answer different questions. The RocksDB block-cache reference describes a separate component whose purpose is caching table blocks rather than receiving new writes.
What an Entry Must Remember
For the teaching model, an entry contains a user key, a version sequence, an operation type and, for a put, a value. The sequence distinguishes two changes to the same key. The operation type distinguishes a stored value from a deletion marker.
Consider camera-2 at sequence 41 with value available and again at sequence 47 with value reserved. A latest-read-only map could keep just reserved if nothing else needed the older state. A versioned database with an active snapshot at sequence 45 still needs a way to return available to that snapshot.
Therefore, “the same key was updated” is not sufficient permission to overwrite all earlier evidence in memory. The representation and pruning rules must match the visibility contract. RocksDB’s snapshot documentation explains the broader requirement to preserve data visible to active snapshots through flush and compaction.
User-Key Order and Internal-Version Order
A memtable that supports ordered scans needs a coherent ordering of its entries. In a versioned teaching model, sort first by user key and then by descending sequence. Entries for camera-2 appear together, with the newest version examined first within that group.
The sequence is not a wall-clock file timestamp. A flush can happen later without changing the logical order of the operations it contains. Giving an old entry a fresh version merely because it moved to another file would change the database rather than preserve it.
The comparator also has to agree across memory, file construction and file lookup. If memory treats two byte strings as equal but storage treats them as distinct, the handoff changes key identity. If one component sorts case-insensitively and another sorts raw bytes, range boundaries can fail even when every component looks locally organised.
Why Implementations Use Different Memory Structures
A skip list offers ordered insertion and traversal. A tree can also maintain order. A prefix-oriented hash structure can favour queries inside a known key prefix. A vector-like representation can favour cheap accumulation and perform sorting when an ordered view is required.
These choices trade insertion cost, comparison count, pointer overhead, concurrent access and scan behaviour. RocksDB’s MemTable reference makes those differences explicit; they should not be converted into the claim that all memtables are skiplists or all are automatically sorted in the same physical way.
For reasoning, ask what operations the structure must serve before flush. A batch-only importer and a database interleaving writes with arbitrary range scans have different requirements. The best representation is the one that supports the promised workload, not the one whose name sounds most sophisticated.
Write-Ahead Log and Memtable: Two Views of the Same Updates
The recovery log and memtable are not redundant copies maintained for no reason. The log is designed around recording and replaying accepted operations. The memtable is designed around serving recent state efficiently. They can contain related information in different physical orders and encodings.
In a logged design, a successful durable-write contract must ensure that the acknowledged operation has an adequate recovery record before the system relies on volatile memory alone. The exact batching and ordering implementation belongs to the engine. RocksDB documents the relationship in its write-ahead log guide.
Do not confuse that recovery log with a diagnostic text log. A message saying “write completed” is not the data required to replay the write. The names can be similar, but the correctness responsibility is entirely different.
When May the Application Be Told the Write Succeeded?
That answer depends on the requested guarantee. A response can promise accepted in memory, written to a log buffer, synchronised to local storage, committed within a transaction, or replicated under a distributed protocol. These are not interchangeable milestones.
RocksDB’s Basic Operations distinguishes synchronous writes and options that change logging behaviour. Rather than copying a default into an evergreen rule, inspect the application configuration and the deployed engine version.
For a teaching exercise, write the acknowledgement promise before drawing the write path. Suppose the promise is survival of a supported local crash. Then ask which durable representation exists at the instant the response is sent. If the only answer is “the value is in the memtable,” the promised failure protection has not been established.
Batching Changes Cost, Not the Need for Atomic Semantics
An engine may group several updates to reduce repeated logging or coordination work. That can amortise a fixed cost across more operations, but it does not automatically turn arbitrary application updates into one transaction.
Imagine reserving a camera and decrementing an available-item counter. If the application requires those two changes to be atomic, a reader must not observe only one half. The memory insertion procedure, publication of read-visible state and recovery procedure must all respect that requirement.
The general lesson is to separate physical batching from logical atomicity. Several writes sharing one disk synchronisation can remain separate logical operations. Conversely, one logical transaction can span several physical structures. A memtable explains where recent records live; it does not by itself define the transaction model.
The Lifecycle: Active, Sealed, Flushing, Installed, Retired
These labels describe a useful teaching state machine rather than a universal set of engine enum names. An active generation accepts new records. A sealed generation no longer accepts them. A flushing generation is being converted to table output. Installed means the replacement is recognised by the live-file metadata. Retired means the old memory generation can be released under reader-lifetime rules.
Each transition answers a different question. Can a writer still modify the generation? Can a reader still access it? Have replacement bytes been completed? Can recovery discover those bytes? Does any active reader still hold the old representation?
Collapsing these questions into a single “flushed” flag encourages errors. A correct lifecycle can have temporary overlap, with the old memory representation and new table both available. The dangerous state is a gap in which neither is available to a reader that is entitled to see the data.
Freezing Requires a Clear Writer Boundary
Suppose generation A is being sealed while another writer is inserting into it. The system needs a protocol that determines whether that write belongs to A or the replacement generation B. The flush must not copy A while a late mutation slips into an already-scanned part of it.
Locks, sequence allocation, reference ownership and publication mechanisms vary across engines. What must remain true is straightforward: every accepted write belongs to a well-defined generation and is included in a representation the live read and recovery paths can reach.
A useful failure test pauses a writer exactly at the switch. Resume the switch and writer in different orders. After each run, check that the operation appears once logically, receives the correct sequence relationship and survives the promised failure. Testing only an uncontended fill-and-flush cycle misses this boundary.
Immutable Memtables Remain Part of Reads
When A becomes immutable and B becomes active, A does not instantly become irrelevant. It can contain camera-2’s latest value while B contains unrelated newer writes. Until A’s installed replacement can serve those records, readers still need A.
Consider A containing camera-2 reserved at 47 and B containing lamp-9 checked-out at 54. A latest read of camera-2 must still return reserved. Searching only B and then the older SSTables would miss the current version in A.
This is a small example with a broad lesson: the newest generation is not necessarily the only generation containing recent relevant state. A handoff does not grant permission to ignore the source before the destination is authoritative. The same principle appears in caches, deployment transitions and versioned documents, although their exact protocols differ.
Why a Flush Can Start Before a Buffer Is Full
Capacity is one possible trigger, not the only one. Shared memory limits, accumulated log retention and explicit administrative requests can also make flushing useful. RocksDB’s documented memtable triggers include per-buffer pressure, total-buffer pressure and WAL-size pressure.
That matters when interpreting small SSTables. A small output does not automatically prove that the configured buffer size was ignored or broken. The generation may have been selected for another reason, or the output may be compressed and pruned.
In our catalogue, one rarely updated namespace might contain an old record that prevents retiring a shared log. Flushing that small amount of state could permit useful recovery-log reclamation. The right diagnosis follows the trigger and retained dependencies rather than assuming every flush is a full-buffer event.
Building the Replacement File Is Not the Same as Publishing It
A flush worker can write an output file that is not yet part of the live database. The output may need completion checks, storage synchronisation and an installation step recorded in the engine’s file catalogue.
RocksDB uses a MANIFEST to describe file-set changes. The educational invariant is independent of one format: do not retire the only recoverable source merely because replacement bytes have started appearing in a directory.
Picture a librarian printing a new catalogue volume. Half a printed volume is not a published replacement. A complete volume not yet entered in the catalogue can also remain undiscoverable. Completion, publication and source retirement are separate responsibilities. In storage software, the failure consequences are sharper, so those stages need explicit durability and recovery rules.
Crash Windows Reveal Whether the Handoff Is Sound
Before and during file construction
Before a flush finishes, recovery must still obtain acknowledged durable operations from the appropriate existing tables and logs. An incomplete output must not be mistaken for a complete replacement. Detecting and rejecting partial output is part of the implementation, not an optional cleanup detail.
After installation but before cleanup
Old recovery material may still exist temporarily. Recovery must recognise which sources are authoritative and avoid treating every retained file as a new logical update. Extra physical copies can be safe when their identities and versions are understood; an unrecorded replacement with no surviving recovery source is not.
Test these windows with controlled fault injection rather than inventing a universal file-operation order. Filesystem and engine protocols vary. The acceptance criterion is that every operation promised durable before the fault is represented correctly after recovery, with no partially published batch exposed as complete.
WAL Retirement Depends on Coverage, Not Age Alone
A log segment can contain operations for more than one memory generation or namespace. Retiring it safely requires knowing that the engine’s recovery obligations no longer need its records. “This file is old” is not an adequate criterion.
RocksDB’s Column Families documentation describes independently managed memtables and table files within a database, alongside shared facilities. This creates dependencies that a simplistic one-buffer-one-log diagram can hide.
Suppose a shared log includes frequently updated equipment entries and one old location entry. Flushing only the equipment buffer may leave the location record dependent on that log. Coverage must be established for every relevant record before reclamation. The general reasoning resembles reference tracking: remove an object only after every obligation that requires it has been discharged.
Snapshots Limit Which Versions a Flush May Discard
A flush can sometimes avoid writing versions that are already provably obsolete, but “superseded for the latest reader” is not the same as “unneeded by every reader.” Consider a snapshot at 45, camera-2 available at 41 and reserved at 47. The older snapshot still needs 41.
The output of a flush must therefore satisfy the relevant version-retention rules. It is not enough to run a last-value-per-key dictionary reduction over the buffer. That reduction produces a latest-state map, which is a different product from a representation supporting older snapshots.
This distinction is useful beyond databases. Compression is safe only relative to the questions the compressed representation must still answer. A summary can remove detail that a current reader does not need and still be inadequate for a later audit. The same logic applies here with precise version and visibility rules.
Deletion Markers Must Survive the Handoff When Needed
Suppose memory contains a deletion of camera-2 at 52, while an old table still contains available at 41. Removing the tombstone merely because it has no value payload would expose the old value again.
The flush may need to write the deletion marker into the output so later reads can suppress that older entry. An empty string, a null-like application value and an actual database deletion are different states. Using one ambiguous marker for all three breaks the read contract.
A strong test flushes a deletion while deliberately leaving the old value in another file. The latest read must remain absent before flush, during the handoff and after memory retirement. This test catches a bug that a standalone new-key write-and-read exercise cannot reveal.
Reader Lifetimes Can Outlast Replacement Publication
A new reader may use the installed SSTable while an existing iterator still holds a reference to the old memory generation. Publication makes the replacement available; it does not necessarily make every reference to the source disappear.
Memory reclamation must respect that lifetime. The engine may use reference counts, epochs or another ownership protocol. The exact mechanism varies, but the requirement is the same: do not free a representation while a permitted reader can still dereference it.
RocksDB’s Iterator documentation describes the resource implications of live iterators. For diagnosis, separate a buffer that is waiting to flush from one retained because something still references it. Both consume memory, but adding flush throughput addresses only the first cause.
Memory Accounting Needs More Than the Active-Buffer Size
Process memory can include active buffers, immutable buffers, retained history, indexes, filters, block caches, allocator overhead and application objects. A configured memtable target is not the same as a limit on the entire process.
RocksDB documents these categories in Memory Usage in RocksDB. Its Write Buffer Manager provides controls across participating column families or database instances. Scope matters: a limit controls the components actually attached to it, not every allocation on the machine.
A useful accounting exercise lists each owner of memory and the event that releases it. An active buffer releases through a flush lifecycle; a cached block through eviction; a pinned read resource through reader release. Combining all of them under “the cache is too large” hides the mechanism needed to reduce usage safely.
Larger Buffers Can Help Bursts but Cannot Cure an Endless Deficit
For a simple illustrative queue, suppose records arrive at 12 MB per second while the handoff can sustainably drain 8 MB per second. The difference is 4 MB per second. An additional 80 MB of available buffering postpones exhaustion by about 20 seconds, ignoring overhead and rate variation.
That is useful for a short burst. It is not a solution to continuous overload. Once the extra buffer fills, the same mismatch reappears. Raising the limit repeatedly converts throughput pressure into memory pressure without changing the long-run balance.
These are queue arithmetic assumptions, not RocksDB benchmark numbers. Real flush work includes compression, encoding, storage writes and installation. Still, the model is valuable because it distinguishes temporary shock absorption from sustainable service capacity. Ask whether the queue drains after the burst, not only whether the first response becomes faster.
Small Buffers Also Have Costs
A smaller buffer can limit one generation’s size, but it can also create more frequent flushes and more small table outputs. Those outputs may increase downstream file-management and compaction work. The write path is a pipeline: optimising one stage in isolation can burden the next.
For example, changing the catalogue buffer from a thousand records to ten makes individual batches easy to clear. But a million incoming records now create many more batch boundaries. If each flush has fixed overhead, the smaller setting can spend more time on setup and metadata rather than useful bytes.
The correct experiment holds the workload and durability guarantee constant, then measures memory, flush frequency, output sizes, downstream backlog and latency together. “Smaller is safer” and “larger is faster” are both incomplete without the rest of the pipeline.
Write Stalls Are Backpressure
A system that always accepts writes regardless of maintenance progress can eventually exhaust memory or storage. Throttling or stopping admission can be a deliberate protective response rather than an arbitrary defect.
RocksDB’s Write Stalls reference distinguishes pressure from pending memtable flushes, accumulated level-zero files and estimated compaction work. Those are different bottlenecks. Diagnose the reported trigger before changing limits.
Application behaviour matters too. A retry loop that immediately resubmits rejected writes can increase contention. A client that ignores timeout ambiguity can duplicate a logical action. The storage layer and caller need an explicit admission, retry and idempotency contract. A memtable’s bounded capacity makes these system-level questions visible; it does not answer them automatically.
Flush Capacity and Compaction Capacity Are Different
A fast flush can free memory by turning buffers into SSTables while leaving the storage engine with too many overlapping files. The memory queue improves, but the compaction queue grows.
Conversely, ample compaction capacity does not help if all available resources are occupied and a sealed memory generation cannot obtain service. Resource scheduling needs to preserve progress through both stages, subject to the engine’s actual thread and I/O design.
Think of a warehouse with an intake desk and a shelving team. Moving parcels off the desk into the corridor is not the same as shelving them. It can be the right intermediate step, but a corridor that fills forever is not a healthy warehouse. Measure completed handoffs and downstream debt together.
Multiple Namespaces Create Shared-Resource Questions
Several column families or database instances can each have their own memory structures while sharing a process, a write-buffer manager or an underlying device. A generous per-buffer setting can become a large aggregate commitment.
The diagnostic question is therefore “How many independently growing generations can exist?” rather than “How large is one buffer?” Include simultaneously active, sealed and reader-retained generations, and distinguish logical configured capacity from actual allocated bytes.
Cross-namespace consistency also needs its own mechanism. RocksDB’s Atomic Flush documentation describes coordinated flush publication for specified uses. It should not be mistaken for a general substitute for transactions. Sharing a storage engine does not make every pair of independently published structures atomic by default.
An Empty Latest Buffer Does Not Prove an Empty Database
After a successful switch, the new active generation can be empty while the previous immutable generation contains every recent change. After that generation flushes, the installed SSTable can hold those changes even if no memtable contains them.
This sounds obvious when stated slowly, but it exposes a recurring debugging error: inspecting one representation and treating its contents as the entire logical state. A database is a coordinated view over several representations.
For our catalogue, search camera-2 immediately after switching generations and again after flush. The answer should remain the same at the same read sequence. The correct test follows the key through the handoff; it does not require the key to remain at one physical address.
A Worked Handoff With Two Generations
Generation A contains camera-2 available at 41 and reserved at 47. It is sealed. Generation B becomes active and receives camera-2 deleted at 52. A is now flushing, while B remains writable.
At snapshot 45, a read must return available. At snapshot 49, it must return reserved. At snapshot 55, it must return absence. These answers do not change when A’s output becomes installed. They also do not change when A’s memory is finally released.
Now inject a bug: the reader examines only B and the installed files before A’s flush is installed. At snapshot 49, B’s deletion is too new and the earlier versions exist only in A. The reader can incorrectly return absence. This is a visibility gap, not a sorting failure. Its repair is to maintain a coherent read view across generations throughout the handoff.
A Verification Plan That Tests the Transitions
Begin with an independent version-history model for a small set of keys. Record each put and delete with its sequence. At selected snapshots, compute the expected latest eligible operation per key. Compare that reference with point reads and complete range scans.
Repeat while forcing generation switches, delaying flush workers, retaining iterators and injecting failures during output construction and publication. Include repeated updates to one key, empty values, deletions hiding older SSTable values and writes arriving exactly during a switch.
For durability tests, retain only the operations the configured acknowledgement contract promises to survive the chosen failure. Test error returns and ambiguous client timeouts separately. A random test that ignores the contract can label correct behaviour as failure or, worse, accept data loss that the application was promised could not occur.
Diagnose by the First Missing Postcondition
If a write is absent immediately, verify admission and read publication. If it disappears only during a switch, inspect generation ownership and the reader’s source set. If it disappears only after restart, inspect logging, synchronisation and recovery. If memory never falls after output installation, inspect retained references and history policies.
If memory falls but table count rises without bound, the memtable handoff may be working and compaction may be the bottleneck. If only scans fail, check comparator and iterator behaviour rather than assuming exact-key reads prove the whole structure correct.
This diagnostic sequence prevents broad, risky fixes. Increasing every limit is not a causal repair. Identify the missing transition, establish which condition blocks it, then change the smallest responsible part while measuring both the original symptom and the downstream consequences.
Frequently Asked Questions
Is a memtable always a sorted tree?
No. The implementation can vary. What matters is that it supports the engine’s write, read and flush requirements. Some structures maintain global order continuously; others organise prefixes or sort when an ordered view is required.
Does immutable mean the buffer is already on disk?
No. It means that generation no longer accepts ordinary new writes under the lifecycle. Its bytes can still be in volatile memory while a worker constructs and installs its persistent replacement.
Why can a database have several memtables?
A new active generation can accept writes while older immutable generations wait for or complete flush. Multiple namespaces and retained reader history can add more memory structures. Limits and ownership rules keep this overlap bounded.
Can a full buffer simply be cleared after a file appears?
No. The output must be complete and installed under the engine’s protocol, required recovery coverage must remain valid, and readers must no longer need the old allocation before it can be reclaimed. File existence alone is not the acceptance test.
Is flush the same as compaction?
No. Flush transfers selected memory state into table storage. Compaction reorganises existing table state. They can share some algorithms or pruning rules, but they occupy different positions in the lifecycle and create different queues.
Does more memory always make writes faster?
No. It may absorb bursts or reduce flush frequency, but it can also increase resource use and change maintenance behaviour. It does not remove a sustained throughput deficit. Benchmark the whole pipeline under the same durability contract.
Sources and Further Reading
The linked RocksDB references cover memtable representations, WAL behaviour, memory accounting, shared buffer management, snapshots, iterators, atomic flush and write stalls. They document one engine and its evolving implementation. The lifecycle labels, catalogue examples and queue calculation here are explanatory models intended to make the invariants visible.
Return to How LSM Trees Work to reconnect the memory handoff with sorted files and compaction, or explore the How X Works library.
Final Synthesis: A Memtable Is a Carefully Managed Handoff
The memtable makes recent updates easy to accumulate and search. Its real achievement is not simply using fast memory. It is allowing writers, readers, flush workers and recovery machinery to agree about the same evolving logical state while that state moves between representations.
Accept writes into a defined generation. Freeze without losing late arrivals. Keep sealed state readable. Build a complete output. Publish it through the correct metadata. Retire old recovery material and memory only when their obligations are satisfied. That sequence turns a write buffer into a reliable part of an LSM storage engine.
