# TiKV Data Writing Process

![`smart`](WritingData_aa_003_2022051.png)

------------------------------------------------------------
The data write process of TiKV is as follows:

Assuming we want to write key = 100, value = Jack

1. The client (usually TiDB server) asks PD about the Region where key = 100 is located.

2. PD informs the Leader of the Region location (TiKV node).

3. The client (usually a TiDB server) sends the write operation instructions to the TiKV node where the leader is located.

4. After the leader node receives the write instruction, it starts to initiate the write process of TiKV.
- Here, we use two components, one called raftstore pool, the other called apply pool, which are both mechanisms for writing to the persistent storage engine (RocksDB).
- As for the storage engine, i.e. RocksDB instances, in a TiKV we have two RocksDB instances, one of which is responsible for persisting the Raft Log, which we call RocksDB Raft, and the other is responsible for persisting the actual key-value data, which we call RocksDB KV.
- When the Leader node receives a write command, the raftstore pool will serialize it into a Raft Log and submit it to RocksDB Raft for persistence (`Append`). At the same time, the raftstore pool is also responsible for distributing the Raft Log to the TiKV nodes where the followers are located (`Replicate`). When the majority of the followers in the cluster have received this Raft Log, we consider it to be committed.

Next, Apply Pool will parse the committed log (Raft Log) and apply it to RocksDB KV.

5. Leader applies key = 100, value = Jack to KV RocksDB and then returns write success to the client.

6. Afterwards, the client's commit is considered successful, and other sessions can read the data.

Above is the data writing process in TiKV.


