# GC Mechanism and Related Modules

![`smart`](GCMechanism_aa_002_20220509.png)

------------------------------------------------------------
TiDB transaction implementation uses the MVCC (Multi-Version Concurrency Control) mechanism. When the newly written data overwrites the old data, the old data is not replaced, but is kept and the version is distinguished by a timestamp on the key of the key-value in TiKV. The GC task is to clean up old data that is no longer needed. The principle and implementation of MVCC will be introduced in the TiKV unit.

GC overall process:
- One TiDB instance in a TiDB cluster will be elected as the GC leader, and the operation of GC will be controlled by the GC leader.

The GC is triggered periodically. At each GC point, TiDB server first calculates a timestamp called a safe-point, all previous versions generated before the safe-point are deemed obsoleted and need to be removed by GC. Each round of GC is divided into the following three steps:
- `Resolve Locks:` Scans all Region, finds out the data that is obsoleted (before the safe-point), and cleans the lock data if any.
- `Delete Ranges:` This phase quickly deletes obsoleted data for the entire Range caused by operations such as `DROP TABLE` and `DROP INDEX`, etc., noting that the delete operation precedes the safe-point.
- `Execute GC:` During this phase, each TiKV instance will scan the data on that store and delete the obsoleted version that is no longer needed for each key.

By default, the GC is triggered every 10 minutes, and each GC retains data for the last 10 minutes (that is, the default GC life time is 10 minutes, and the safe-point is calculated as the current time minus GC life time). If one round of GC runs for too long, the next round of GC will not start until the next GC is triggered, even if it is time for the next GC to be triggered. In addition, in order for ensuring the long-lived transaction to operate normally beyond the GC life time, the safe-point will not exceed the start time (start_ts) of an active transaction.