# Writes via Rocksdb (Continue...)


![left](./student-guide/diagram/03-RocksDB-Input-02-01.png)
------------------------------------------------------------
Next, we will focus on how to organize files after RocksDB's data is dropped.
Files on disk are organized in multiple layers. Let's call them Level-1, Level-2... Wait, or simple L1, L2... and so on. A special layer, Level-0 (L0), will contain the data just dropped from the memory MemTable, reaching 4 will trigger compaction to the next layer, and if the backlog reaches 20, it will trigger a write stall. Each level (except Level0) is an independent sorted result.

At each layer (except Level-0), the data is split into multiple SST files.

The keys in each SST file are in good order. If we need to locate a key, we first find the start and end keys of all files in two parts, locate which file has this key, and then find the specific file in two to locate the key. In general, it's a binary search for all keys in that layer.

All non-0 layers have a target size. The goal of compression is to limit the data size of these layers, which is usually an exponential increase.

Finally, for WAL logs, the WAL serializes the MemTable operations and stores them in the form of log files on persistent media. In the event of a crash, the WAL log (log) file can be used to rebuild the MemTable to help the database recover to a consistent state. When a MemTable is safely placed on persistent media, the associated WAL log (log) becomes stale and then archived. The final archived logs are deleted from the hard drive after a certain period of time.

At this point, the data has been persistently written. We can see that the WAL guarantees that the writes are not lost at the beginning. Next, let's summarize RocksDB's CRUD process:

Write operations

The write operation first needs to write the data to the disk log (Log) through the WAL to prevent data loss, and then the data is written to the MemTable in memory, so that one write operation is completed, only 1 disk IO plus 1 memory operation is required. Significant efficiency gains compared to multiple random disk IOs for B+ trees. Subsequently, the data in the MemTable is batched batch merged into the SSTable on disk, and the random writes are changed to sequential sequential write.

Delete operation

When there is a delete operation, it is not necessary to delete the corresponding data after finding the corresponding data in the disk like the B+ tree. You only need to insert a data into the MemTable as a flag, such as delete key: 1233. When the read operation reads this flag in MemTable, you will know that the key has been deleted. Then in the log merge, this deleted data will be deleted along with the merge process.

Update actions

The update operation is similar to the delete operation, in that it only operates on the MemTable, writes a flag, and then the actual update operation is deferred to complete at merge time.

















