# RocksDB: Write

![`smart`](RocksDBWrite01_aa_002_20220511.png)

------------------------------------------------------------------------------
RocksDB is a key-value storage engine that uses the log-structured merge (LSM) tree data structure to store data. The LSM tree allows RocksDB to efficiently handle data insertion, modification, and deletion operations by storing them in memory and writing them to disk in batches. The LSM tree structure spans both memory and disk, and consists of several components such as the MemTable, immutable MemTable, and SSTable.

When a write operation is performed, RocksDB first writes the data to a `write-ahead logging` (WAL) file to ensure durability in case of memory loss. The data is then written to the MemTable, which is a memory data structure that holds the data for the Flush operation. The MemTable organizes the data using a data structure such as a skip list or search tree to keep it organized. The MemTable is used for both reading and writing; a new write operation always inserts data into the MemTable, and a read operation always queries the MemTable before querying the SSTable on disk because the data in the MemTable is always up-to-date.

When the MemTable reaches a certain size (controlled by the write_buffer_size parameter), it is transformed into an immutable MemTable to prepare it for writing to disk. This is done so that write operations can continue without being blocked during the transform process. A new MemTable is then created to process new incoming data, while a background thread writes the contents of the previous immutable MemTable to an SSTable file on disk. Once the data has been written, the MemTable and its associated WAL file can be deleted. By default, one immutable MemTable triggers a disk write operation, and five immutable MemTables trigger a write stall.

sync-log = true indicates that writing will call fsync and persist the WAL log file to disk instead of the operating system cache.


