# Rocksdb: Write
__*MemTable*__
__*immutable MemTable*__
__*SST*__
__*RocksDB Writing Process*__

![left](./student-guide/diagram/RocksDBWrite01_aa_001_20220511.png)

------------------------------------------------------------
Let's take a look at how RocksDB writes are performed, so as to understand how the TiDB database persistes data through RocksDB. RocksDB uses the data structure of the LSM tree to store key value data, and LSM treee will insert, modify, and delete all data It is stored in memory, and when such operations reach a certain amount of data, it is written to disk in batch. When writing to disk, the previous data will be merged. During the merging process, the original data is not modify like a B+ tree, but new data is inserted directly, thus avoiding random writes.

The structure of the LSM tree spans memory and disk, and contains several parts such as memTable, immutable MemTable, and SSTable. We explain the workflow of the LSM tree and its related components with a single write operation in the figure.

1. First back up to disk via WAL to prevent data loss due to memory loss (write-ahead logging (WAL) is a series of techniques used in relational database systems to provide atomicity and persistence (two of the ACID properties). On systems that use WAL, all modify must be written to the log file before committing). sync-log = true indicates that writing will call fsync to persist the WAL log file to the disk instead of the operating system cache.

2. After the WAL is completed, data is written to MemTable. MemTable is an in-memory data structure that stores the data before it is placed. MemTable can use data structures such as skip list or search trees to organize data to maintain data order.
MemTable serves both read and writes — new writes always insert data into MemTable, and read operations always query MemTable before querying the SST file, because the data in MemTable is always up to date.

3. When MemTable reaches a certain amount of data (write_buffer_size size), MemTable is converted to an immutable MemTable (immutable memTable is a data structure that cannot be modify in memory, it transforms MemTable into An intermediate state of SSTable. The goal is not to block writes during the staging process. Writes can be processed by the new MemTable without waiting for locking the MemTable), and a new MemTable is created to handle the new data. A background thread will drop the contents of this MemTable into an SST file (SSTable (Sorted String Table) is a collection of ordered key-value pairs, which is the structure of the data in the LSM tree on disk. The data in MemTable will eventually be converted to SSTABLE and saved on disk ), then the MemTable can be destroyed, and the WAL file containing data related to this MemTable can also be deleted. By default, 1 immutable MemTable will fail, and 5 will trigger a write stall.