Keeping Repositories Fast

Updated · 12 min read
hardGit 2.53gitgcmaintenancecommit-graphfsmonitorscalarperformance

Repository maintenance is the housekeeping Git does to keep a repository small and its commands fast: packing loose objects into packfiles, deleting unreachable objects, and writing extra index files that speed up history and status commands. Git does some of it automatically. For large repositories, you can schedule it in the background with git maintenance and turn on features such as the file system monitor. It is used so that commands like git log, git status and git fetch stay quick as a project grows.

A kitchen is a fair comparison. Cooking leaves dishes everywhere. Washing up once a day, and keeping a list of where everything is, means that the next meal starts quickly.

Syntax

Terminal
git gc
git maintenance run [--task=<task>]
git maintenance start
git count-objects -vH
CommandDescription
git count-objects -vHIt is used to show how many loose objects and packs a repository has, and their size.
git gcIt is used to pack loose objects, remove unreachable old objects and tidy references.
git maintenance run --task=<task>It is used to run one maintenance task now, such as gc, commit-graph, prefetch, loose-objects or incremental-repack.
git maintenance startIt is used to register the repository and schedule maintenance in the background (hourly, daily and weekly).
git maintenance stopIt is used to stop the scheduled maintenance.
git commit-graph write --reachableIt is used to write the commit-graph file, which speeds up history commands.
git multi-pack-index writeIt is used to write one index across all packfiles.
git repack -a -d -bIt is used to repack everything into one pack with a reachability bitmap.

The Starting Point

Navika's Fee Tracker has had many small commits:

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
git config gc.auto 0
for month in 1 2 3 4 5 6 7 8 9 10 11 12; do
  echo "Month $month fees collected" >> fees.txt
  git add fees.txt
  git commit --quiet -m "Record month $month"
done
git count-objects -v
Output
count: 36
size: 144
in-pack: 0
packs: 0
size-pack: 0
prune-packable: 0
garbage: 0
size-garbage: 0

Explanation: each commit wrote three new objects (a commit, a tree and a blob), all as separate loose files under .git/objects/. count is the number of loose objects, size their total in KiB, and in-pack is 0 because nothing is packed yet. The line git config gc.auto 0 turns off automatic housekeeping for this example, so that we can see the state before it runs. Leave it at its default (6700 loose objects) in real projects.

Example 1: git gc

Terminal
git gc --quiet
git count-objects -v
ls .git/objects/pack
Output
count: 0
size: 0
in-pack: 36
packs: 1
size-pack: 4
prune-packable: 0
garbage: 0
size-garbage: 0
pack-ce76c53381c7ca9435f6c72deff1ca9396c34566.idx
pack-ce76c53381c7ca9435f6c72deff1ca9396c34566.pack
pack-ce76c53381c7ca9435f6c72deff1ca9396c34566.rev

Explanation: git gc (garbage collection) moved all 36 objects into one packfile (in-pack: 36, count: 0) with its .idx index and a .rev file, which maps positions in the pack back to objects. Inside the pack, Git stored most versions of fees.txt as small deltas, as described in "Packfiles and Garbage Collection". It also packed the branch references into .git/packed-refs and deleted unreachable objects older than two weeks.

Git runs git gc --auto after commands like commit, merge and fetch, which does nothing until there are too many loose objects or packs. That is why most people never need to run git gc by hand.

Example 2: The Commit-Graph

History commands such as git log --graph, git merge-base and the ahead/behind counts in git status must walk through commits. Normally, Git opens and decompresses each commit object to find its parents. The commit-graph file stores every commit's parents, tree and date in one compact table, so the walk is much faster. git gc has already written one:

Terminal
ls .git/objects/info
git commit-graph verify
git maintenance run --task=commit-graph
ls .git/objects/info
Output
commit-graph
packs
commit-graph
packs

Explanation: the file .git/objects/info/commit-graph was written by git gc (the setting gc.writeCommitGraph is on by default), and git commit-graph verify checked it and printed nothing, which means it is correct. git maintenance run --task=commit-graph is the task that keeps it up to date between garbage collections; here it found no new commits and changed nothing. Git reads the file automatically, because core.commitGraph is on by default.

Example 3: Background Maintenance

git maintenance start registers the current repository in your global config and creates a schedule with your operating system's scheduler (launchd on macOS, Task Scheduler on Windows, systemd timers or cron on Linux). It is shown without output here, because it changes system settings on the computer that checks this page:

Terminal
git maintenance start
git config --global --get-all maintenance.repo
git maintenance stop

Explanation: once started, Git runs these tasks in the background, without blocking your work:

TaskScheduleWhat it does
prefetchHourlyFetches from remotes into hidden refs, so your next git fetch has little to download
commit-graphHourlyAdds new commits to the commit-graph
loose-objectsDailyPacks loose objects
incremental-repackDailyCombines small packs, using the multi-pack index
pack-refsWeeklyPacks loose references into packed-refs

git maintenance stop removes the schedule, and git maintenance unregister removes the repository from the list.

What git maintenance start schedules

Example 4: The Multi-Pack Index and Bitmaps

A repository that fetches often ends up with many packfiles, and looking up an object means checking each pack's index. A multi-pack index (MIDX) is one index across all packs. A reachability bitmap records, for chosen commits, exactly which objects they need, so a git clone or git fetch from this repository can count objects almost instantly. Servers rely on bitmaps.

Terminal
git repack --quiet -a -d -b
git multi-pack-index write
git multi-pack-index verify
ls .git/objects/pack | sed -E "s/pack-[0-9a-f]{40}/pack-<id>/"
Output
multi-pack-index
pack-<id>.bitmap
pack-<id>.idx
pack-<id>.pack
pack-<id>.rev

Explanation: git repack -a -d -b packed everything into one new pack (-a), deleted the old one (-d) and wrote a .bitmap file next to it (-b). multi-pack-index write then created .git/objects/pack/multi-pack-index, and verify checked it, printing nothing because it found no problems. With a single pack, the multi-pack index adds little; it pays off when there are dozens of packs. The sed only replaces the long pack ID with <id> to keep the listing short.

The File System Monitor and Untracked Cache

git status must check every file in the working folder for changes. In a repository with hundreds of thousands of files, that can take seconds. Two settings help:

Terminal
git config core.fsmonitor true
git config core.untrackedCache true
git config --get-regexp "core\.(fsmonitor|untrackedcache)"
Output
core.fsmonitor true
core.untrackedcache true

Explanation: core.fsmonitor true starts Git's built-in file system monitor daemon on macOS and Windows the next time a command needs it. The daemon listens to the operating system's change notifications, so git status asks it "what changed?" instead of looking at every file. core.untrackedCache true lets Git remember the contents of folders that didn't change, which speeds up the search for untracked files. On Linux, the built-in monitor isn't available, and a hook such as Watchman can fill the role. git fsmonitor--daemon status shows whether the daemon is running.

scalar for Very Large Repositories

scalar is a command that comes with Git and turns on all the recommended settings for a very large repository in one step: a blobless partial clone, sparse checkout in cone mode, the file system monitor, the commit-graph, and background maintenance. It is shown without output here, because it schedules background tasks:

Terminal
scalar clone https://github.com/navika-anamaneni/fee-tracker.git
scalar register
scalar list

Explanation: scalar clone makes a new clone set up this way (the repository goes in a src folder inside the folder it creates), and scalar register applies the settings to an existing clone. Microsoft built it for repositories like Windows and Office, and it became part of Git in version 2.38.

Measuring

Before tuning anything, measure. Git can report what it does and how long each step takes:

Terminal
time git status
GIT_TRACE=1 git status
GIT_TRACE_PERFORMANCE=1 git status
GIT_TRACE2_PERF=1 git status
VariableIt is used to
GIT_TRACE=1Show every command and program Git runs
GIT_TRACE_PERFORMANCE=1Show how long each step took
GIT_TRACE2_PERF=1Show a detailed table of timings for each region of work
GIT_TRACE_PACKET=1Show the conversation with a server during fetch and push

These print timestamps and timings that differ on every run, so they are shown without output. Set the variable to a file path instead of 1 to write the trace to that file.

Common Mistakes

Running git gc --aggressive regularly. It recomputes every delta from scratch and can take hours on a big repository. A plain git gc is enough; use --aggressive once, if ever, after a large import.

Expecting git gc to remove a committed large file. It only deletes unreachable objects. A file in history is reachable. Remove it with git filter-repo (see "Removing Files from History").

Deleting files in .git/objects by hand. This corrupts the repository. Let git gc and git prune decide what is safe.

Tuning before measuring. Use time and GIT_TRACE_PERFORMANCE first, to find which step is slow.

Under the Hood

git gc is a bundle of smaller commands: git pack-refs (references into packed-refs), git reflog expire (old reflog entries, after 90 days by default), git repack -d -l (objects into packs), git prune (unreachable loose objects older than gc.pruneExpire, two weeks by default), and git worktree prune. The two-week grace period protects objects that another command is just writing. git maintenance splits this work into smaller tasks that run in the background, and uses a lock file so that two runs never overlap. The commit-graph file stores, for each commit, its tree, parents, date and a generation number (how far it is from the root commits). With generation numbers, Git can stop walking history early, for example when it knows a commit is too old to be an ancestor of another.

Interview Corner

What does git gc do?

It packs loose objects into packfiles, packs references, expires old reflog entries and deletes unreachable objects older than two weeks. Git runs git gc --auto by itself when there are too many loose objects.

What is the commit-graph?

A file that stores every commit's parents, tree, date and generation number in a compact table, so history commands like git log --graph and git merge-base don't have to open each commit object. git maintenance and git gc keep it up to date.

How do you speed up git status in a huge repository?

Turn on the file system monitor (core.fsmonitor true) and the untracked cache (core.untrackedCache true), and use sparse checkout to have fewer files on disk. scalar turns all of these on.

What is git maintenance start?

It schedules background maintenance (prefetch and commit-graph hourly, loose objects and incremental repack daily, pack-refs weekly) with the operating system's scheduler, so the repository stays fast without blocking your commands.

Practice

Challenge: pack again after more work. Make three more commits in Navika's repository, check how many loose objects there are, then run git gc --quiet and check again.

What does Git print? Before you open the solution, work out count before and after, and in-pack after.

Show solution
Terminal
for extra in 1 2 3; do
  echo "Bonus entry $extra" >> fees.txt
  git commit --quiet -am "Record bonus entry $extra"
done
git count-objects -v | grep -E "^(count|in-pack)"
git gc --quiet
git count-objects -v | grep -E "^(count|in-pack)"
Output
count: 9
in-pack: 36
count: 0
in-pack: 45

Three commits wrote 9 loose objects (three each), next to the 36 already packed. After git gc, all 45 are in the pack and none are loose.

Checkpoint. In one of your own repositories, run git count-objects -vH, then git maintenance run --task=gc and git maintenance run --task=commit-graph, and compare the numbers before and after.

Quick check: keeping repositories fast

4 questions
1Which command shows loose and packed object counts?
2What does the commit-graph speed up?
3Does git gc remove a large file that is in a commit's history?
4What does core.fsmonitor true do?

Key Takeaways

Quick reference

CommandIt is used to
git count-objects -vHCheck loose objects and pack size
git gcPack and tidy the repository
git maintenance start / stopSchedule or stop background maintenance
git maintenance run --task=<task>Run one maintenance task now
git commit-graph write --reachableWrite the commit-graph
git config core.fsmonitor trueTurn on the file system monitor
scalar registerApply large-repository settings

Was this tutorial helpful?

Lesson 87 of 106