# Gc Mechanism


![left](./student-guide/diagram/02-GC-01-01.png)
------------------------------------------------------------
The transaction implement of TiDB uses the MVCC (Multi-Version Concurrency Control) mechanism. When newly written data overwrites the old data, the old data is not replaced, but is kept at the same time as the newly written data, and the version is distinguished by a timestamp. The task of the GC is to clean up old data that is no longer needed. We will introduce the principle and implement of MVCC in the TiKV course and explain the GC process in detail.
Overall process:

A TiDB instance in a TiDB cluster is elect as the GC leader, and the GC leader controls the operation of the GC.

The GC is triggered periodically. At each GC, TiDB first calculates a timestamp called a safe point, and then TiDB deletes the earlier expired data on the premise that all snapshots after the safe point have the correct data. Each round of GC is divided into the following three steps:

- Resolve Locks: Scans all regions to find out the data that has expired (before the safe point) and cleans up the lock data above.

- Delete Ranges: This stage quickly deletes the entire range of discarded data generated by operations such as DROP TABLE/DROP INDEX. Note that the delete operation is before the safe point.

- Do GC: At this stage, each TiKV node will scan the data on that node individually and delete the old version for each key that it no longer needs.

- In the default configuration, the GC is triggered every 10 minutes, and each GC retains the data for the last 10 minutes (i.e. the default GC life time is 10 minutes, the safe point is calculated as the current time minus the GC life time). If one round of GC runs for too long, the next round of GC will not start until the GC is complete, even if it is time for the next GC to be triggered. Also, in order for a transaction with a longer duration to continue to function properly after the GC life time, the safe point does not exceed the start time (start_ts) of the executing transaction.