Git Garbage Collection and Maintenance

Learn how Git GC, pruning, fsck, and scheduled maintenance work, and how to inspect recovery paths before removing unreachable objects.

published: reading time: 21 min read author: Geek Workbench updated: November 12, 2026
Quick Summary

Git maintenance packs objects and can expire unreachable data according to repository settings. Automatic and manual runs may prune objects past the configured grace period, so a two-week default is not a recovery guarantee. This guide explains how Git versions and settings affect cruft packs and maintenance, and how to inspect and back up a repository before intentionally pruning data.

Introduction

Git repositories grow over time. A commit, branch deletion, or force push can leave objects unreachable from current refs. Maintenance may repack objects, expire reflog entries, and eventually remove unreachable data. The exact work depends on the Git version and repository configuration.

Git can run maintenance automatically, but the thresholds and tasks vary by version and configuration. Knowing what a command will do matters most before changing prune or reflog settings, where an unexpected cleanup can remove recovery paths.

This guide covers automatic maintenance, manual cleanup, prune policies, and ways to inspect repository health before removing unreachable objects.

When to Use / When Not to Use

When to manage Git garbage collection:

  • Repository size is growing unexpectedly
  • CI/CD clone times are increasing
  • After history rewriting (rebase, filter-branch)
  • Before archiving or backing up repositories
  • Troubleshooting “bad object” errors

When not to intervene:

  • Small, active repositories — inspect the configured automatic maintenance before changing it
  • During active development — let Git manage itself
  • When unsure about pruning — unreachable objects may be needed

Core Concepts

Git maintenance can repack objects, expire reflog entries, and prune unreachable objects. Which tasks run depends on the command, Git version, and configuration:


graph TD
    REPO["Repository"] -->|accumulates| UNREACH["Unreachable Objects\n(commits, blobs, trees)"]
    REPO -->|accumulates| LOOSE["Loose Objects\nindividual files"]
    REPO -->|accumulates| STALE["Stale Reflogs\nexpired entries"]

    AUTO["Automatic maintenance\n(trigger depends on configuration)"] -->|may check| THRESHOLD["Configured thresholds\nand tasks"]
    THRESHOLD -->|exceeded| PACK["Repack Objects\ninto pack files"]
    THRESHOLD -->|not exceeded| SKIP["Skip GC\ncontinue normally"]

    GC["git gc"] -->|may expire| PRUNE["Unreachable objects\nafter configured grace period"]
    GC -->|may expire| REFLOG["Reflog entries\nafter configured age"]
    GC -->|repackages| PACK

git gc --auto may run after Git commands when configured thresholds are met. The documented default for gc.auto is 6700 loose objects, but gc.auto, maintenance settings, and other thresholds can change that behavior. git gc can also expire unreachable objects; it is not limited to packing. See the current git-gc documentation and git-maintenance documentation.

Architecture or Flow Diagram


flowchart LR
    COMMITS["New Commits"] -->|create| OBJECTS["New Objects\nloose files"]
    OBJECTS -->|count exceeds| TRIGGER["gc.auto threshold\n(default: 6700)"]
    TRIGGER -->|may trigger| AUTO_GC["Automatic maintenance\n(git gc --auto)"]

    AUTO_GC -->|packs| PACKS["Pack Files\ncompressed objects"]
    AUTO_GC -->|removes| LOOSE_DEL["Deleted Loose Objects"]

    REBASE["git rebase"] -->|creates| ORPHAN["Orphaned Objects\nunreachable commits"]
    ORPHAN -->|after configured grace period| EXPIRY["gc.pruneExpire\n(default: 2 weeks in current docs)"]
    EXPIRY -->|pruned| GONE["Permanently Deleted"]

    FSCK["git fsck"] -->|finds| DANGLING["Dangling Objects\nreachable via reflog"]
    DANGLING -->|reflog expires| PRUNED["Pruned by gc"]

Step-by-Step Guide / Deep Dive

Automatic Garbage Collection

Some Git commands may trigger git gc --auto or git maintenance run --auto after they update the repository. Whether maintenance runs and which tasks it performs depends on the Git version and configuration. The gc.auto default is 6700 loose objects, but inspect the repository’s effective settings rather than assuming that value is active:


# Show explicitly configured gc settings (unset values may print nothing)
git config --get gc.auto

git config --get gc.autoPackLimit

# Check if auto-gc will trigger
git count-objects -v
# Output:
# count: 1234        (loose objects)
# in-pack: 56789     (packed objects)
# packs: 3           (number of packs)

An automatic run can expire unreachable data that is older than the configured grace period. Current Git documentation describes a two-week default for gc.pruneExpire, with cruft-pack behavior controlled by gc.cruftPacks; older Git versions and local settings can differ. A grace period is not a guaranteed recovery window. See the current git-gc documentation and cruft-packs documentation.

Manual Garbage Collection

Before running these commands, inspect the repository’s refs, reflogs, and unreachable objects. A standard git gc may remove objects past the configured expiry. Save a verified backup or rescue refs outside the repository before opting into any shorter prune window.


# Standard garbage collection
git gc
# Output:
# Enumerating objects: 12345, done.
# Counting objects: 100% (12345/12345), done.
# Delta compression using up to 8 threads
# Compressing objects: 100% (5678/5678), done.
# Writing objects: 100% (12345/12345), done.
# Total 12345 (delta 8901), reused 12345 (delta 8901)

# Aggressive repacking (slower; normal expiry rules still apply)
git gc --aggressive

# Keep unreachable objects from expiring during this run
git gc --prune=never

Pruning Unreachable Objects

Unreachable objects are commits, trees, or blobs that cannot be reached from the refs Git considers. A reflog may still provide a path to an object. Inspect before pruning:


# Find unreachable objects
git fsck --unreachable
# Output:
# unreachable commit abc123...
# unreachable blob def456...

# Show dangling objects reported by Git's current reachability check
git fsck --dangling

# Preview objects that would be pruned
git prune --dry-run --verbose --expire=7.days.ago

# Preview reflog entries that would expire
git reflog expire --dry-run --verbose --expire=30.days.ago --all

git prune and git reflog expire remove recovery data when run without --dry-run. Before intentionally pruning, inspect git status, review git reflog --all and git fsck --unreachable, and save a verified backup or rescue refs outside the repository. Confirm that no needed object exists only in the data you plan to expire. Then, and only then, run an explicit prune or reflog-expiration command with a deliberate expiry date. Avoid --expire=now while another Git process may be writing to the repository. See the git-prune and git-reflog documentation.

Repository Health Checks


# Full integrity check
git fsck --full
# Output:
# Checking object directories: 100% (256/256)
# Checking objects: 100% (12345/12345)
# dangling commit abc123...

# Check for missing objects
git fsck --no-dangling --no-reflogs

# Verify pack files
git verify-pack -v .git/objects/pack/*.idx

# Check repository size
git count-objects -vH

Git Maintenance Command

git maintenance can run repository tasks on a schedule. Supported tasks and their default schedule depend on the Git version and configuration; review the current git-maintenance documentation before enabling it:


# Register for automatic maintenance
git maintenance register

# Run all maintenance tasks
git maintenance run --auto

# Run specific tasks
git maintenance run --task=gc
git maintenance run --task=loose-objects
git maintenance run --task=incremental-repack

# Start the configured maintenance scheduler
git maintenance start

# Stop maintenance
git maintenance unregister

Production Failure Scenarios

Scenario Symptoms Mitigation
Accidental prune A needed object is missing after cleanup Check reflogs, other refs, remotes, and backups. Do not prune until you have saved a verified backup and checked recovery paths.
GC during CI A maintenance task adds latency Inspect the runner’s Git version and configuration. Disable auto maintenance only when measurements justify it.
Pack corruption “bad packed object” errors Preserve a copy of the repository before repair. Verify the pack and compare with a trusted remote or backup before replacing anything.
Disk space exhaustion Repository fills disk Check object and pack sizes first. Plan maintenance with enough temporary disk space; do not use aggressive repacking as a blind fix.
Reflog bloat .git/logs/ consumes substantial space Preview expiry with git reflog expire --dry-run --verbose; use destructive expiry only after the backup and recovery preflight.

Trade-off Analysis

Aspect Advantage Disadvantage
Automatic maintenance Handles routine work without a manual schedule Tasks and thresholds depend on version and configuration.
Aggressive repacking May find smaller packs Can take longer and use more resources; it is not a routine cleanup shortcut.
Immediate expiry Can reclaim eligible unreachable objects sooner Removes recovery data and should only follow an explicit backup and recovery check.
Default prune grace period Delays removal of some unreachable objects The current two-week default is configurable and is not a recovery guarantee.
Git maintenance Can spread configured tasks over a schedule The selected strategy, tasks, and scheduler affect what actually runs.

Implementation Snippets


# Preview cleanup candidates; these commands do not remove objects or reflog entries
git fsck --unreachable --no-reflogs
git reflog expire --dry-run --verbose --expire=30.days.ago --all
git prune --dry-run --verbose --expire=30.days.ago

# Only after inspecting status, confirming recovery refs, and saving a verified
# backup outside this repository, explicitly opt into the planned cleanup:
# git reflog expire --verbose --expire=30.days.ago --all
# git gc --prune=30.days.ago

# CI/CD optimization: disable auto-gc
git config gc.auto 0
git config gc.autoDetach false

# Check what would be pruned (dry run)
git fsck --unreachable --no-reflogs

# Monitor repository health
git count-objects -vH
git fsck --full 2>&1 | grep -E "error|warning"

# Check maintenance strategy and task settings before changing them
git config --get maintenance.strategy
git config --get-regexp '^maintenance\.'

Observability Checklist

  • Monitor: Loose object count (git count-objects -v)
  • Track: Repository size growth over time
  • Alert: Pack file count relative to the configured gc.autoPackLimit
  • Verify: Integrity with periodic git fsck --full
  • Audit: Reflog size per branch

Security Considerations

Git pruning is repository cleanup, not secure erasure. It cannot guarantee removal from filesystem snapshots, storage media, backups, clones, caches, build artifacts, logs, or remote hosting. Secure-delete utilities also cannot make that guarantee across every filesystem or storage layer.

If a credential was committed, revoke or rotate it first, then scope the incident and notify the provider when needed. Clean the credential from history only after rotation, and check forks, clones, caches, artifacts, and logs for copies. See Removing Sensitive Data from Git History for the response sequence. Git GC does not clean remote repositories or other clones.

Common Pitfalls / Anti-Patterns

  • Running prune or reflog expiry without a recovery preflight — can discard the only local recovery path
  • Disabling auto-gc permanently — leads to excessive loose objects
  • Assuming history rewriting erases data — old objects and copies can remain until their separate retention or cleanup paths run
  • Assuming git gc removes secrets — it only removes unreachable objects, not specific content

Quick Recap Checklist

  • Automatic maintenance behavior checked against this repository’s Git version and configuration
  • git gc understood as repacking that may also expire unreachable objects
  • Backup and recovery paths checked before any destructive prune or reflog expiry
  • gc.pruneExpire and cruft-pack settings reviewed; defaults are not recovery guarantees
  • git fsck verifies repository integrity
  • git maintenance tasks and schedule checked against the active version and configuration
  • Always check reflog before pruning

GC Process Flow (Clean Architecture)


graph TD
    REPO["Repository Operations"] -->|generate| LOOSE["Loose Objects"]
    REPO -->|generate| REFLOG["Reflog Entries"]
    REPO -->|generate| UNREACH["Unreachable Objects"]

    AUTO_GC["Automatic maintenance\n(trigger and tasks vary)"] -->|may check| COUNT["Configured thresholds\nand tasks"]
    COUNT -->|yes| PACK["Repack objects\ninto pack files"]
    COUNT -->|no| SKIP["Skip — no action"]

    GC["git gc"] --> PACK
    GC --> EXPIRE_REFLOG["May expire reflog entries\nunder configured policy"]
    GC --> PRUNE["May expire unreachable objects\nunder configured policy"]
    PACK --> CLEAN["Clean repository\noptimized storage"]
    PRUNE --> CLEAN

Production Failure: Aggressive GC Data Loss

Scenario: Reflog data loss after aggressive pruning

This is a failure example. Do not run the destructive commands shown here unless you have completed the backup and recovery preflight above and intend to remove those recovery paths.


# What happened (example only; do not copy as a cleanup command):
# git gc --prune=now
$ # Later: need to recover a commit from 3 days ago
$ git reflog
# Empty — reflog entries were expired too!

# Symptoms
$ git log --oneline
# Missing commits that were on deleted branches
$ git fsck --unreachable
# No unreachable objects — they're all gone

# Recovery (limited options):

# 1. Check if remote still has the commits
git fetch origin
git log origin/old-branch --oneline

# 2. Check other clones (colleagues' machines)
# Ask teammates if they have the commits locally

# 3. Check CI/CD logs for commit SHAs
# Some CI systems log commit hashes before building

# 4. If truly lost — the commits are unrecoverable
# This is why --prune=now is dangerous

# Prevention: inspect first and preserve a verified backup outside the repository.
# Preview candidates; this does not remove them:
git fsck --unreachable --no-reflogs
git reflog --all
# Create rescue refs for any commits you need, then review the preview output.
# Only after the recovery check, explicitly opt into pruning with a chosen date:
# git gc --prune=90.days.ago

Trade-offs: Auto GC vs Manual GC

Aspect Auto GC Manual GC
Trigger Depends on version, thresholds, and task config Explicit command
Safety Depends on configured thresholds and tasks Explicit runs may expire objects under the selected settings
Performance Runs during operations (may slow commit/fetch) Runs on your schedule
Disk recovery May expire objects under configured rules Can expire objects under selected settings
Configuration gc.auto, gc.autoPackLimit, maintenance settings Explicit flags and repository config
CI/CD impact Can trigger unexpectedly Can be disabled or scheduled
Best for Daily development Maintenance windows, large repos
Risk level Low Medium to high (depends on flags)

Keep the configured automatic maintenance unless you have measured a problem. Before a manual cleanup after a history rewrite, inspect the unreachable objects, preserve recovery refs and a verified backup, then choose a deliberate expiry policy. There is no need to schedule manual GC by calendar alone.

Implementation: GC Configuration Tuning

These settings change later maintenance behavior. In particular, a shorter prune expiry can remove recoverable objects on a later GC run. Confirm the current configuration and back up needed objects before changing expiry values.


# === Threshold tuning ===
# When auto-gc triggers (default: 6700 loose objects)
git config gc.auto 10000

# Maximum number of eligible pack files before consolidating (current docs: 50)
git config gc.autoPackLimit 10

# === Pruning windows ===
# Grace period for unreachable objects (current docs: 2 weeks; configurable)
git config gc.pruneExpire 30.days.ago

# Default expiry for reachable reflog entries (current docs: 90 days)
git config gc.reflogExpire 180.days.ago

# Default expiry for unreachable reflog entries (current docs: 30 days)
git config gc.reflogExpireUnreachable 90.days.ago

# === Pack optimization ===
# Delta search window size (default: 10)
git config pack.window 50

# Maximum delta chain depth (default: 50)
git config pack.depth 250

# Memory limit for delta search
git config pack.windowMemory 512m

# Compression level (0-9, default: -1 = zlib default)
git config pack.compression 6

# === Pack bitmaps (for large repos) ===
# Speeds up git rev-list operations
git config repack.writeBitmaps true

# === CI/CD optimization ===
# Disable auto-gc in CI environments
git config gc.auto 0
git config gc.autodetach false

# === Verify current configuration ===
git config --get-regexp 'gc\.'
git config --get-regexp 'pack\.'
git config --get-regexp 'repack\.'

# === Scheduled maintenance (availability and defaults vary by Git version) ===
# Register for automatic background maintenance
git maintenance register

# Run maintenance tasks
git maintenance run --auto

# Available tasks: gc, commit-graph, loose-objects, incremental-repack
git maintenance run --task=gc
git maintenance run --task=commit-graph

Interview Questions

1. What's the difference between `git gc` and `git gc --aggressive`?

Both commands repack objects. --aggressive uses separate aggressive window and depth settings, which can make repacking slower and more resource-intensive. The result depends on the repository's objects and configuration; it is not guaranteed to produce a smaller pack. See the git-gc documentation before tuning those settings.

2. How long does Git keep unreachable objects before pruning them?

Current Git documentation gives gc.pruneExpire a two-week default, but the value can be configured and behavior differs across versions and cruft-pack settings. Reflog expiry has separate defaults: 90 days for reachable entries and 30 days for unreachable entries. These are grace periods, not recovery guarantees. See the [git-gc](https://git-scm.com/docs/git-gc), [git-reflog](https://git-scm.com/docs/git-reflog), and [cruft-packs](https://git-scm.com/docs/cruft-packs) documentation.

3. Why should you disable auto-gc in CI/CD pipelines?

Automatic maintenance can run after repository updates, depending on Git version, configuration, and thresholds. CI jobs sometimes use short-lived clones, but don't disable maintenance by default. Measure the delay first; if you choose to disable a task, scope that setting to the disposable CI repository and document why. The [git-maintenance documentation](https://git-scm.com/docs/git-maintenance) describes the available strategies and tasks.

4. Can `git gc` remove commits that were force-pushed away?

A force-push can make commits unreachable from a particular remote ref, but local refs, reflogs, other remote refs, and other clones may still retain them. A later GC can expire objects only after they are no longer protected by refs and their configured expiry conditions are met. This depends on version and configuration; check the [git-gc](https://git-scm.com/docs/git-gc) and [git-reflog](https://git-scm.com/docs/git-reflog) documentation.

5. What is the difference between loose objects and pack files in Git?

Loose objects are individual files under .git/objects/. Pack files bundle objects and can use delta compression. Git may repack loose objects when configured GC thresholds are met. The current documented default for gc.auto is 6700, but local settings and maintenance strategy can change when work runs.

6. What does `git count-objects -vH` tell you about repository health?

git count-objects -vH reports loose object counts and sizes, packed object counts and sizes, and pack-file count. Treat the numbers as clues, not an instruction to run GC: thresholds such as gc.autoPackLimit and maintenance tasks can be configured or version-dependent. Inspect the repository settings and maintenance history before changing them.

7. What happens when `gc.autoPackLimit` is reached?

The current documentation names this setting gc.autoPackLimit and gives it a default of 50 eligible pack files. Git may consolidate packs when the threshold is exceeded, subject to the repository's other GC settings. Check git-gc documentation before tuning it.

8. How does `git maintenance` differ from `git gc --auto`?

git gc --auto checks GC thresholds when invoked; it can perform normal GC work, including expiring objects under configured rules. git maintenance can schedule selected tasks, but the strategy and task schedule depend on configuration and Git version. Scheduled or incremental maintenance can spread work out, but it does not guarantee that every run is free of latency. See the [git-maintenance documentation](https://git-scm.com/docs/git-maintenance).

9. What is a dangling commit and how does Git handle it?

A dangling commit is an unreferenced object reported by git fsck; it may still be found through a reflog or another ref. Use git fsck --unreachable and git reflog --all to inspect recovery options, then create a rescue ref for any commit you need. Do not treat the configured expiry period as a guarantee that an object can still be recovered.

10. Why does `git gc --prune=now` pose a data loss risk?

--prune=now removes the grace period for objects that are eligible for pruning; it does not mean every unreachable object is deleted regardless of other references. It can still destroy the only local recovery copy. Do not use it as routine cleanup. Before any prune, inspect status, refs, reflogs, and unreachable objects, then save a verified backup or rescue refs outside the repository. The [git-gc documentation](https://git-scm.com/docs/git-gc) also warns against pruning while another process is writing to the repository.

11. What is the purpose of `git fsck --full` and when should you run it?

It performs a full integrity check on all objects in the repository, verifying SHA-1 checksums, directory structure validity, and referential integrity. It detects corrupted or missing objects, broken refs, and dangling objects. Run it periodically (monthly or after any filesystem issue) and always check the output for errors or warnings.

12. How do `gc.reflogExpire` and `gc.reflogExpireUnreachable` differ?

gc.reflogExpire controls the age limit for ordinary reflog entries and currently defaults to 90 days. gc.reflogExpireUnreachable controls entries unreachable from the current tip and currently defaults to 30 days. Settings may be overridden, and expiry removes recovery information. Review the effective configuration before changing either value; see the [git-reflog documentation](https://git-scm.com/docs/git-reflog).

13. What does `pack.depth` configuration control in Git gc?

pack.depth sets the maximum delta chain depth for repacking; the current documented default is 50. git gc --aggressive uses separate aggressive window and depth settings, so it is not accurate to describe it as always making chains deeper. Tuning can trade storage against CPU and lookup work. See the [git-gc documentation](https://git-scm.com/docs/git-gc).

14. When should you use `git verify-pack` instead of `git fsck`?

Use git verify-pack when you suspect pack file corruption specifically. It verifies the .idx index file matches the .pack file and lists all objects in the pack. git fsck checks object integrity across both loose objects and packs, resolving refs and checking object connectivity. Run git verify-pack -v .git/objects/pack/*.idx to see all objects in all packs and spot-check for issues.

15. What is the commit-graph file and how does gc maintain it?

The commit-graph is a binary index that accelerates commit lookups, especially git log and reachability queries. git maintenance updates it incrementally. While gc itself does not directly update commit-graph, running git maintenance run --task=commit-graph alongside gc keeps it current. Without it, repos with many commits see significantly slower log operations.

16. What happens to the reflog when a branch is deleted and then recreated?

Deleting a branch also deletes that branch's reflog when one exists. The HEAD reflog may still record switching away from the branch, and other refs or remotes may retain the commit. Check git reflog --all and git fsck --unreachable, then create a rescue ref if needed. The [git-branch documentation](https://git-scm.com/docs/git-branch) describes the branch deletion behavior.

17. How does Git LFS interact with garbage collection?

Git LFS stores file content outside Git's ordinary object database, so Git GC does not prune those LFS objects. LFS has its own prune command and retention rules. Review the installed Git LFS documentation and use its dry-run option before intentionally removing local LFS objects; keep any backup or copy you still need.

18. What is the difference between `git reflog expire` and `git gc --prune`?

git reflog expire removes eligible reflog entries; git gc --prune may remove objects no longer reachable through refs or remaining reflogs and past the configured expiry. Expiring reflogs first can remove a recovery path, so that sequence is not automatically safe. Preview both operations, inspect the objects and refs, and make a verified backup before explicitly opting into cleanup.

19. Why might running `git gc` on a very large repository cause problems?

A large repository can make repacking CPU-, memory-, and disk-intensive. The time and temporary space depend on its object graph, storage, configuration, and concurrent work. Measure on a copy or during a planned maintenance window. Incremental maintenance may help, but its task schedule and resource use are configuration-dependent; use --aggressive only when a measured need justifies it.

20. What are the best practices for scheduling and automating Git repository maintenance in a production environment?

Use the strategy and task schedule documented for the Git version in use. The git maintenance start command sets up a scheduler, but tasks depend on configuration; inspect the effective strategy before enabling it. Monitor object counts and maintenance duration, and keep full integrity checks for troubleshooting or planned audits. In CI, measure first and scope any disabled maintenance to disposable clones. See the [git-maintenance documentation](https://git-scm.com/docs/git-maintenance).

Further Reading

Conclusion

Git maintenance can repack objects and expire unreachable data under the repository’s configured rules. Check those settings before cleanup, and preserve a verified backup and recovery refs before pruning. For exposed credentials, revoke or rotate them first; Git GC cannot remove copies from hosts, clones, caches, or artifacts.

Category

Related Posts

Git Object Database and Pack Files

Learn how Git stores loose objects and pack files, how repository hash formats affect object IDs, and how to inspect or recover storage safely.

#git #version-control #pack-files

Centralized vs Distributed VCS: Team Trade-offs

Compare centralized and distributed version control by offline work, repository size, access control, branching, review, and migration effort.

#git #version-control #svn

Automated Changelog Generation

Generate release notes from structured commits, choose a release policy, and add changelog generation to CI without treating every merge as a release.

#git #version-control #changelog