Skip to content
JZLeetCode
Go back

TiKV Source Walkthrough - How Raft Log Garbage Collection Works

Table of contents

Open Table of contents

The log is history, not the data itself

Each TiKV Region has a Raft group. Its Raft log is the ordered history of commands that the group replicates and applies to the Region’s state machine. That history lets followers catch up when they miss messages. Once commands have been applied and the group has enough progress to move forward, keeping every old entry forever would waste disk space.

This walkthrough follows the normal leader-driven log garbage-collection path in tikv/tikv. It focuses on four pieces: the peer state machine’s periodic check, the CompactLog Raft command, the RaftlogGcTask, and the background worker that removes entries from the Raft Engine. The source links are pinned to upstream commit fefc79afb04d, current on December 1, 2026. Region destruction has a related cleanup path, but it is outside this walkthrough.

                 TiKV leader peer state machine
                 on_raft_gc_log_tick()
                           |
             inspect applied and replication progress
             choose an old log index to compact
                           |
                           v
             propose AdminCmdType::CompactLog
                           |
                  Raft commits and applies it
                           |
                           v
                 on_ready_compact_log()
                 schedule RaftlogGcTask
                           |
                           v
             background RaftlogGc worker
              sync KV engine, then delete
              the region's old Raft entries

Why the leader checks more than the log size

The Raft log has several indexes that answer different questions:

TiKV’s PeerFsm::on_raft_gc_log_tick runs only while the peer is the leader. It samples these indexes and the replication progress tracked by Raft. It also avoids compacting past log data that has not been persisted by Raft Engine. The leader can then decide whether to wait for a little more replication progress or propose a compaction.

There is a good reason to wait sometimes. If the leader removes the log prefix too eagerly, a follower that is just slightly behind may need a snapshot instead of replaying a few missing entries. The soft raft-log-gc-threshold setting retains a cushion of recent entries. When replication progress has advanced at least this far beyond the first available index, normal GC can compact. If progress stays below the threshold, the leader can defer compaction on periodic ticks; a separate reserve-tick limit prevents that cushion from keeping old entries forever.

Count and size limits provide a backstop. If the applied log range or approximate Raft log size crosses a hard limit, the leader can advance compaction even when the soft threshold would normally make it wait. The source computes a candidate from the available range and replication progress, then proposes the compact index through Raft.

Why compaction is a Raft command

The leader does not simply erase entries from its local disk and hope its followers agree. It proposes an administrative CompactLog command to the Region’s Raft group. The command carries a compact index and term, plus replication progress information used by the group. Raft replication makes the decision part of the Region’s ordered history.

When the command is applied, on_ready_compact_log reads the resulting truncated state. It records the next first index and schedules a RaftlogGcTask for the old index range. The new truncation point is therefore tied to an applied Raft command, rather than an uncoordinated local deletion.

 Leader PeerFsm       Raft group       Apply result       GC worker
      |                   |                  |                 |
      | CompactLog(index) |                  |                 |
      |------------------>|                  |                 |
      |                   | replicate/commit |                 |
      |                   |----------------->|                 |
      |                   |                  | schedule task   |
      |                   |                  |---------------->|
      |                   |                  |                 | KV sync
      |                   |                  |                 | RaftEngine.gc

The worker preserves the write order

RaftlogGcTask identifies a Region and an index range. The worker batches tasks for multiple Regions so one flush can handle many small cleanup requests. Before it asks Raft Engine to delete those log ranges, it calls kv.sync() on the KV engine.

That sync is a durability boundary: commands through the applied index must be safely persisted in the Region’s state before the old Raft history needed to produce that state is removed. The worker then builds a Raft log batch, asks the Raft Engine to GC each range, and consumes the batch. This separates the peer’s decision about what may be discarded from the background I/O that performs the deletion.

There are two layers to disk reclamation. Raftstore’s GC removes entries from a Region’s logical Raft log. Raft Engine stores logs in a log-structured format, so reclaiming a Region’s entries and reclaiming space in its underlying files are related but distinct operations. The Raft Engine design article below explains why this storage layer uses sequential log files and its own cleanup work.

The settings that control when GC runs

These are TiKV configuration file parameters under the raftstore section, not SQL session variables:

SettingDocumented defaultWhat it controls
raft-log-gc-tick-interval3sHow often a peer schedules the log-GC check. 0 disables the periodic feature.
raft-log-gc-threshold50 entriesSoft limit that leaves a recent-log cushion before normal compaction.
raft-log-gc-count-limitAbout three-fourths of the configured Region split size, estimating 1 KiB per entryHard count limit that can force a compaction attempt.
raft-log-gc-size-limitThree-fourths of the configured Region split sizeHard approximate-size limit that can force a compaction attempt.

The two hard-limit defaults depend on Region size. The tick interval controls how quickly TiKV notices that a limit has been crossed; it does not mean the worker deletes every Region’s logs exactly on that schedule. The leader still needs an eligible compact index, and the cleanup work runs asynchronously.

Raising the retention threshold generally keeps more history available for follower catch-up, at the cost of disk space. Lowering it can make lagging peers rely on snapshots sooner. For most clusters, start with the documented defaults and use TiKV’s Raft log GC metrics and disk behavior to guide tuning.

The mental model

Think of Raft log GC as a coordinated archive trim. A leader checks how much history the Region has applied and how far its peers have progressed. It asks the Raft group to agree on a truncation point. After the resulting state is applied, a worker waits for the KV state to reach durable storage and removes the obsolete Raft entries.

The important distinction is that Raftstore decides when old entries are no longer needed, while its background worker asks Raft Engine to delete them. The thresholds balance disk use against the amount of history available to help a lagging peer catch up.

References

  1. TiKV Configuration File: Raft log GC parameters — documented purpose and defaults for the GC settings.
  2. TiKV PeerFsm::on_raft_gc_log_tick at fefc79afb04d — leader checks, thresholds, and CompactLog proposal.
  3. TiKV PeerFsm::on_ready_compact_log at fefc79afb04d — schedules the asynchronous task after applying the compact result.
  4. TiKV Peer::schedule_raftlog_gc at fefc79afb04d — creates and schedules a region cleanup task.
  5. TiKV Raft log GC worker at fefc79afb04d — syncs the KV engine before deleting Raft log ranges.
  6. TiKV Raftstore configuration at fefc79afb04d — configuration fields and their source comments.
  7. Raft Engine: a Log-Structured Embedded Storage Engine for Multi-Raft Logs in TiKV — background on how TiKV stores and cleans up Raft logs.
Share this post on:

Previous Post
System Design - How Kubernetes StatefulSets Keep Pod Identity and Storage
Next Post
LeetCode 1291 Sequential Digits