# Writes via Rocksdb

![left](./student-guide/diagram/03-RocksDB-Input-01-01.png)
------------------------------------------------------------
Let's take a look at how RocksDB writes are performed, so as to understand how the TiDB database persists data through RocksDB. RocksDB uses the data structure of the LSM tree to store key value data, and LSM treee inserts, modify, and deletes all the 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, it is merged with the previous data. During the merging process, the original data is not modify in place like the B+ tree, but the new data is inserted directly, thus avoiding random writing.

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

- Back up to disk via WAL to prevent data loss due to memory loss (write-ahead logging (WAL for short) is a set of techniques used in relational database systems to provide atomicity and persistence (two of the ACID properties)). On systems using WAL, all modify are written to the log file before committing), sync-log = true indicates that the write invokes fsync to persist the WAL log file to disk instead of to the operating system cache.

- When the WAL is completed, data is written to MemTable, which is an in-memory data structure that holds the data before the disk is dropped. MemTables can be used to organize data using data structures such as jump tables or search trees to maintain data order.

MemTable serves both read and writes—new writes always insert data into the MemTable, and reads always query the MemTable before querying the SST file, because the data in the MemTable is always up to date.

- When the MemTable reaches a certain amount of data (write_buffer_size size), the MemTable is converted to an immutable MemTable (an immutable MemTable is an unmodifiable data structure in memory, it converts the MemTable to An intermediate state for SSTable. The purpose is to not block writes during the staging process. Writes can be handled by the new MemTable instead of waiting because the MemTable is locked), and a new MemTable is created to process the new data. A background thread will put the contents of this MemTable into an SST file (Sorted String Table), which is an ordered set of key-value pairs, which is the structure of the data in the LSM tree on disk. The data in the MemTable will eventually be converted to an SSTable and saved on disk. ), then the MemTable can be destroyed, and the WAL file carrying the data associated with this MemTable can also be deleted. By default, 1 immutable MemTable will be dropped, and 5 will trigger a write stall.