# Gc Mechanism And Related Modules
__*TiDB Server GC*__

![left](./student-guide/diagram/GCMechanism_aa_002_20220509.png)

------------------------------------------------------------
TiDB's transaction implement 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 at the same time as the newly written data, and the version is distinguished by a timestamp. The GC's task is to clean up old data that is no longer needed. The principle and implement of MVCC will be introduced in the TiKV course, and the GC process will be explained in detail.

Overall process:

One TiDB instance in a TiDB cluster will be elect as the GC leader, and the operation of GC will be controlled by the GC leader.

The GC is triggered periodically. At each GC, TiDB first calculates a timestamp called a safe point, and then TiDB deletes 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:

1. Resolve Locks: Scans all Region, finds out the data that is out of date (before the safe point), and cleans the lock data above.

2. Delete Ranges: This phase quickly deletes discarded data for the entire range caused by operations such as DROP TABLE/DROP INDEX, etc., noting that the delete operation precedes the safe point.

3. Do GC: During this phase, each TiKV node will scan the data on that node and delete the old 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 long-lived transaction to operate normally beyond the GC life time, the safe point does not exceed the start time (start_ts) of transaction in progress.