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 can store objects loose or in pack files with indexes and, when useful, delta compression. Object IDs and pack checksums follow the repository's hash format. Use Git's inspection commands and format documentation to understand pack data; avoid deleting or rewriting pack files by hand.
Introduction
Git stores objects in a repository object database, commonly under .git/objects/; linked worktrees and alternates can place or supply that data elsewhere. A shallow or partial clone may intentionally omit some history or objects. In a loose-object layout, each stored object is individually compressed and named by its object ID.
But as your project grows to thousands of commits and millions of files, storing each object as a separate file becomes inefficient. Filesystem overhead, disk space waste, and slow enumeration become real problems. Git solves this with pack files — a binary format that stores multiple objects together with delta compression between similar objects.
Understanding the object database and pack file system is essential for managing large repositories, optimizing CI/CD clone times, and debugging storage issues. This article explains how Git stores objects, how pack files work, and how to optimize your repository’s storage.
When to Use / When Not to Use
When to understand pack files:
- Managing large repositories with long histories
- Optimizing clone and fetch times in CI/CD pipelines
- Debugging repository size issues
- Understanding
git gcandgit repackbehavior - Building Git server infrastructure
When not to manipulate pack files directly:
- Daily development — Git manages packs automatically
- Small repositories — loose objects are fine
- When unsure — use
git gcinstead of manual repacking
Core Concepts
Git’s object database has two storage modes:
graph TD
OBJ[".git/objects/"] --> LOOSE["Loose Objects\none file per object"]
OBJ --> PACK["Pack Files\nmultiple objects per file"]
LOOSE --> L1["zlib-compressed\nindividual files"]
LOOSE --> L2["path: object-ID-prefix/remainder\n(prefix length follows hash format)"]
PACK --> P1[".git/objects/pack/\npack-<hash>.pack\npack-<hash>.idx"]
PACK --> P2["delta-compressed\nbetween similar objects"]
PACK --> P3["reverse-index for\nfast lookup"]
Loose objects are individually compressed and named using the repository’s object ID format. The leading ID characters form a directory prefix.
Pack files store multiple objects in one binary file, often using delta compression between similar objects, with index files for lookup. The exact binary layout is versioned; see Git’s pack format documentation.
Git uses SHA-1 by default. SHA-256 is a newer, optional repository format with longer object IDs; Git’s documentation says SHA-1 and SHA-256 repositories do not interoperate directly. Check the formats supported by every client and server before adopting SHA-256. See the hash function transition notes and git init --object-format.
Architecture or Flow Diagram
flowchart LR
COMMIT["New Commit"] -->|creates| NEW_OBJ["New Objects\n(blobs, trees, commit)"]
NEW_OBJ -->|stored as| LOOSE["Loose Objects\n.git/objects/XX/"]
GC["git gc / git repack"] -->|collects| MANY["Many Loose Objects"]
MANY -->|delta compression| DELTA["Delta Chains\nbase → delta → delta"]
DELTA -->|writes| PACK["Pack File\n.pack + .idx"]
PACK -->|replaces| OLD["Old Loose Objects\n(deleted)"]
FETCH["git fetch"] -->|receives| THIN["Thin Pack\n(deltas against missing bases)"]
THIN -->|resolves| COMPLETE["Complete Pack\n(all bases present)"]
The flow shows how objects start as loose files, get packed during garbage collection, and how fetch operations use thin packs for efficient network transfer.
Step-by-Step Guide / Deep Dive
Loose Object Format
Each loose object is stored as:
zlib(<object type> <size>\0<object content>)
# Create a loose object
echo "hello" | git hash-object -w --stdin
# Output: ce013625030ba8dba906f756967f9e9ca394464a
# The file is at .git/objects/ce/013625030ba8dba906f756967f9e9ca394464a
ls -la .git/objects/ce/
# Inspect the raw compressed content
python3 -c "
import zlib, sys
with open('.git/objects/ce/013625030ba8dba906f756967f9e9ca394464a', 'rb') as f:
data = zlib.decompress(f.read())
print(repr(data))
"
# Output: b'blob 6\x00hello\n'
Pack File Format
A pack file (.pack) contains the following components. Git’s pack format specification documents their versioned binary layout; use it when you need exact field details.
- Header:
PACKsignature, version number, object count - Objects: Each object is either:
- A full (base) object: type + size + zlib-compressed data
- A delta object: type + size + base object reference + delta instructions
- Trailer: checksum of the entire pack using the repository’s hash format
The index file (.idx) provides:
- Sorted list of object IDs with their offsets in the pack
- Fan-out table for binary search
- Pack checksum
# List pack files
ls -lh .git/objects/pack/
# Output:
# pack-abc123.idx (index - fast lookup)
# pack-abc123.pack (data - compressed objects)
# pack-abc123.rev (reverse index - offset to object ID)
# Inspect pack contents
git verify-pack -v .git/objects/pack/pack-abc123.idx
# Output per object:
# <object-ID> <type> <size> <packed-size> <offset> <depth>
# abc123... commit 234 230 12 0
# def456... tree 120 115 242 1
# 789ghi... blob 5432 128 357 2 (delta, depth 2)
Delta Compression
Delta compression is Git’s key storage optimization. Instead of storing full copies of similar objects, Git stores:
- Base object: A full copy (usually the oldest version)
- Delta objects: Instructions to transform the base into the target
graph LR
BASE["Base Object\nv1 of file.py\n(full copy, 5KB)"] -->|delta| D1["Delta 1\nv1 → v2\n(changes only, 200B)"]
D1 -->|delta| D2["Delta 2\nv2 → v3\n(changes only, 150B)"]
D2 -->|delta| D3["Delta 3\nv3 → v4\n(changes only, 180B)"]
This can reduce storage by 90%+ for text files that change incrementally. The delta depth matters — deep chains require more decompression work to reconstruct an object.
Thin Packs
When fetching from a remote, Git sends “thin packs” that contain deltas against objects the receiver already has. This minimizes network transfer:
# The server sends deltas against objects it knows you have
git fetch origin
# Output: remote: Compressing objects: 100% (15/15), done.
# Your Git resolves the deltas against local objects
# and creates a complete pack file
Pack Bitmaps
For very large repositories, Git can generate bitmap indexes that accelerate git rev-list operations. Bitmap indexes work by precomputing reachability information — instead of traversing commit parent chains at query time, Git can jump directly to commits that are reachable from a given ref using bitmap lookup tables.
Bitmap generation happens during git repack when bitmaps are enabled. Git builds two bitmap structures: one mapping commits to the objects they contain, and another mapping refs to the commits they can reach. When you run git log --all or git rev-list HEAD, Git checks the bitmap first and skips entire object subgraphs that are known to be unreachable.
The tradeoff is disk space and repack time. A .bitmap file adds roughly 1 bit per object in the repository, so a repo with 10 million objects needs about 1.25 MB for the bitmap. Repack times increase because Git must compute reachability for every object. However, for repositories where git log or clone operations are frequent (CI/CD runners, code hosting servers), the speedup justifies the cost.
Bitmap indexes also enable fascinating optimizations during clone. Git can send a precomputed bitmap along with the pack file, allowing the client to skip objects that are already reachable locally without doing full reachability analysis.
# Enable bitmaps in config
git config repack.writeBitmaps true
# Repack with bitmaps
git repack -adb
# The .bitmap file speeds up history queries
ls .git/objects/pack/*.bitmap
Production Failure Scenarios
| Scenario | Symptoms | Mitigation |
|---|---|---|
| Corrupted pack file | git fsck or git verify-pack reports an error |
Preserve a full backup, then restore from a verified backup or trusted remote; do not delete pack files manually |
| Deep delta chains | Slow git log or checkout |
Repack with git repack -f to reset delta depth |
| Missing base object | “fatal: bad object” during unpack | Fetch from remote; the base may exist only in another pack |
| Pack file too large | Memory issues during repack | Use git repack --window-memory=1g to limit memory |
| Incomplete fetch | git fsck reports missing or corrupt objects |
Preserve a backup and inspect with Git; restore the repository from a verified backup or trusted remote. Do not delete pack files manually. |
Trade-off Analysis
| Aspect | Advantage | Disadvantage |
|---|---|---|
| Loose objects | Simple, fast individual access | Wasteful for many similar objects |
| Pack files | Excellent compression, fast enumeration | Slower individual object access |
| Delta compression | 90%+ space savings for text | CPU cost for delta creation and resolution |
| Thin packs | Minimal network transfer | Requires receiver to have base objects |
| Pack bitmaps | Fast history queries | Additional disk space, repack time |
Optional Advanced Maintenance and Inspection
These commands are for deliberate storage inspection or maintenance. They do not repair corruption; preserve a backup before rewriting packs, and let Git manage ordinary repacking.
# Check object database statistics
git count-objects -vH
# Output:
# count: 1234 (loose objects)
# size: 5.6M (loose object size)
# in-pack: 56789 (packed objects)
# packs: 3 (number of pack files)
# size-pack: 45.2M (pack file size)
# Verify pack integrity
git verify-pack -v .git/objects/pack/pack-*.idx
# List objects in a pack, sorted by size
git verify-pack -v .git/objects/pack/pack-*.idx | sort -k3 -n -r | head -20
# Repack with maximum compression
git repack -a -d -f --depth=250 --window=250
# Repack with delta compression disabled (for speed)
git repack -a -d -f --no-reuse-delta
# Create a pack with bitmaps
git repack -a -d -b
# Run aggressive maintenance only when you have a specific reason
git gc --aggressive
# Find largest objects in the repository
git rev-list --objects --all | \
git cat-file --batch-check | \
sort -k3 -n -r | head -20
# Check delta chain depth
git verify-pack -v .git/objects/pack/pack-*.idx | \
awk '{print $6}' | sort -n | uniq -c | sort -n
Observability Checklist
- Monitor: Loose object count (
git count-objects -v) - Track: Pack file sizes and count over time
- Alert: Delta chain depth exceeding 50 (causes slow access)
- Verify: Pack integrity with
git verify-packafter repacking - Audit: Largest objects in repository (may need Git LFS migration)
Security & Compliance Considerations
- Pack files contain all historical data — deleted files may still exist in packs
- Running
git gc --prune=nowremoves unreachable objects but doesn’t overwrite disk blocks - For true secret removal, see Removing Sensitive Data from History
- Pack files are not encrypted — anyone with filesystem access can extract objects
Common Pitfalls / Anti-Patterns
- Running
git gctoo frequently — wastes CPU; Git auto-gc is usually sufficient - Ignoring large objects in packs — they bloat every clone; migrate to Git LFS
- Disabling auto-gc — leads to excessive loose objects and slow operations
- Not pruning after history rewrite — old objects remain in packs until pruned
- Assuming
git rmdeletes data — it only removes from the working tree; objects persist
Quick Recap Checklist
- Loose objects are individual zlib-compressed files
- Pack files store multiple objects with delta compression
- Delta chains save space but add decompression cost
- Thin packs minimize network transfer during fetch
- Pack bitmaps accelerate history queries
-
git gcconverts loose objects to packs automatically -
git repackgives fine-grained control over packing - Deleted files may still exist in pack files
Multi-Pack Index (MIDX) for Large Repositories
For repositories with hundreds of pack files, Git supports Multi-Pack Index (MIDX) to accelerate object lookups:
# Generate MIDX to accelerate multi-pack repos
git multi-pack-index write
# Verify MIDX integrity
git multi-pack-index verify
# Check MIDX statistics
git multi-pack-index statistics
# Enable MIDX generation automatically
git config core.multiPackIndex true
How MIDX works:
- Creates a single
.midxfile containing combined index across multiple packs - Maintains a reachability bitmap for fast history traversal
- Uses a tiered approach: pack files are grouped by access frequency
- Bitmap generation (
--write-midx-bitmaps) dramatically speeds upgit log,git blame, and clone operations
When to use MIDX:
- Repositories with more than 50 pack files
- CI/CD environments doing frequent partial clones
- Monorepos with large object counts (>5 million objects)
- Server-side Git with heavy read traffic
Benchmark comparison:
| Operation | Without MIDX | With MIDX |
|---|---|---|
git log --all |
120s | 25s |
git clone |
45s | 18s |
git rev-list |
80s | 15s |
Object Storage Architecture (Clean)
graph TD
DB[".git/objects/"] --> LOOSE["Loose Objects"]
DB --> PACK_DIR["pack/"]
DB --> MIDX_DIR[".midx/"]
LOOSE --> L_FORMAT["zlib-compressed files"]
LOOSE --> L_PATH["Path: .git/objects/XX/YYYY..."]
LOOSE --> L_ACCESS["Fast individual access"]
PACK_DIR --> IDX[".idx (index file)"]
PACK_DIR --> PACK[".pack (object data)"]
PACK_DIR --> REV[".rev (reverse index)"]
MIDX_DIR --> MIDX[".midx (multi-pack index)"]
MIDX --> BITMAP[".bitmap (reachability bitmap)"]
PACK --> DELTA_CHAIN["Delta Chain"]
DELTA_CHAIN --> BASE["Base object (full copy)"]
BASE --> D1["Delta 1 (changes)"]
D1 --> D2["Delta 2 (changes)"]
Production Failure: Pack File Corruption
Scenario: Incomplete clone with missing deltas
Network interruptions during clone or fetch operations leave pack files in a broken state. The symptoms appear later when Git tries to traverse commit parent chains and finds that delta objects reference base objects that were never written to disk. The error messages are cryptic — “Could not read abc123…” — because Git doesn’t know at that moment whether the object is missing due to corruption or an incomplete transfer.
The root cause is almost always external: a network timeout, a disk full condition during write, or a process that was killed mid-write. Thin packs are especially vulnerable because their delta objects make sense only in the context of base objects that should have been received earlier. If the write was interrupted before all base objects arrived, the pack file contains dangling references.
Do not delete .pack, .idx, or reverse-index files by hand. Start with read-only checks and preserve the repository before any repair: save uncommitted work, stop concurrent Git processes, and make a full backup of both the working tree and the actual Git/common directory. A linked worktree may store object data outside its local .git file.
git count-objects -v
git fsck --full
git rev-parse --git-common-dir
git rev-parse --git-path objects/pack
git verify-pack -v <path-to-pack.idx>
If a trusted remote has the missing objects, use Git’s documented fetch or clone recovery after preserving the damaged copy. A remote cannot restore local-only commits. If it is the only source, restore from a known-good backup or another clone. For routine maintenance, see Git garbage collection and maintenance.
Prevention is straightforward: use complete clone operations, verify repository integrity after large fetches, and avoid shallow clones when full history is needed.
# Symptoms
$ git log --oneline
error: Could not read abc123...
fatal: Failed to traverse parents of commit def456...
$ git fsck --full
error: packfile .git/objects/pack/pack-abc.pack does not match index
error: def456...: object missing
# Root cause: Network interruption during clone/fetch left pack file
# incomplete, or disk corruption damaged pack data
# Recovery checks: keep pack files intact while you diagnose.
# Stop concurrent Git processes, save uncommitted work, and make a
# full backup of the working tree and actual Git/common directory.
git rev-parse --git-common-dir
git rev-parse --git-path objects/pack
git count-objects -v
git fsck --full
git verify-pack -v <path-to-pack.idx>
# Restore a verified backup or recover into a fresh clone using Git's
# documented commands. A remote may not contain local-only objects.
# Prevention:
# - Use git clone --recurse-submodules for complete clones
# - Verify after large fetches: git fsck --connectivity-only
# - Use shallow clones only when full history isn't needed
Trade-offs: Loose vs Packed Storage
| Aspect | Loose Objects | Packed Objects |
|---|---|---|
| Performance (read) | Fast for individual objects | Slower per-object (must unpack) |
| Performance (enumerate) | Slow (many filesystem calls) | Fast (single file scan) |
| Disk space | High (no delta compression) | Low (delta compression saves 90%+) |
| Transfer efficiency | Poor (many small files) | Excellent (single pack file) |
| Creation cost | None (created on each commit) | High (CPU-intensive repacking) |
| Network transfer | Inefficient for fetch/clone | Optimized with thin packs |
| Corruption impact | Single object lost | Entire pack may be unreadable |
| Best for | Active repos with few objects | Large repos, archives, servers |
Rule of thumb: Let Git manage packing during normal work. Manual repacking is an advanced, optional step for specific maintenance or inspection needs, such as preparing a very large repository for archiving.
Advanced, Optional: Manual Pack Creation and Inspection
# === Create a pack from loose objects ===
# Repack all objects into a single pack
git repack -a -d
# -a: pack everything (not just unreachable)
# -d: delete loose objects after packing
# === Create pack with maximum compression ===
git repack -a -d -f --depth=250 --window=250
# -f: ignore existing delta info, recompute
# --depth: max delta chain length
# --window: objects to consider for delta
# === Inspect pack contents ===
PACK_FILE=$(ls .git/objects/pack/pack-*.idx | head -1)
git verify-pack -v "$PACK_FILE" | head -20
# Output format:
# <object-ID> <type> <size> <packed-size> <offset> <delta-depth>
# === Find largest objects in pack ===
git verify-pack -v "$PACK_FILE" | \
grep -v "^$" | \
grep -v "chain" | \
sort -k3 -n -r | \
head -10
# === Check delta chain depths ===
git verify-pack -v "$PACK_FILE" | \
awk 'NF==6 {print $6}' | \
sort -n | uniq -c | sort -rn
# Shows distribution: how many objects at each delta depth
# === Create a custom pack with specific objects ===
# Pack only objects reachable from main
git pack-objects my-pack <<EOF
$(git rev-list main)
EOF
# Creates: my-pack-<pack-checksum>.pack and my-pack-<pack-checksum>.idx
# === Create thin pack for network transfer ===
# Pack objects missing from remote's known commits
git pack-objects --thin --stdout <<EOF | ssh remote "git unpack-objects"
$(git rev-list origin/main..main)
EOF
Interview Questions
Git finds similar objects (usually different versions of the same file) and stores one as a full base object. Subsequent versions are stored as delta instructions — byte-level copy/insert commands that transform the base into the target. This is similar to xdelta or bsdiff. Delta chains can be deep (A → B → C → D), but Git limits depth to balance compression ratio with access speed.
git repack only creates new pack files from loose objects and/or existing packs. git gc is a higher-level command that runs repack, prunes unreachable objects, expires reflogs, and runs other maintenance tasks. Think of repack as a tool and gc as a maintenance workflow that uses repack.
The server creates a thin pack — a pack file containing deltas against objects it believes the client already has. This minimizes network transfer. The client then "thickens" the pack by resolving deltas against its local objects. If the server's assumption is wrong, the fetch fails and retries with a complete pack.
Use git rev-list --objects --all | git cat-file --batch-check | sort -k3 -n -r | head -20. This lists all objects reachable from any ref, shows their sizes, and sorts by size descending. For objects inside pack files, use git verify-pack -v .git/objects/pack/*.idx | sort -k3 -n -r | head -20.
A thin pack contains delta objects that reference base objects the sender believes the receiver already has. Git creates thin packs during git push and git fetch to minimize network transfer. The receiving side "thickens" the pack by resolving deltas against its existing objects. If the receiver is missing the base objects, the operation fails and falls back to a full pack.
Run git fsck --full and git verify-pack -v to locate a problem. Before any repair, save uncommitted work and make a full backup of the working tree and Git/common directory. Do not delete pack files manually. Restore from a verified backup or recover in a fresh clone from a trusted remote; the remote may not contain local-only objects.
Pack bitmaps accelerate git rev-list operations by precomputing reachability information. Enable with git config repack.writeBitmaps true or git repack -adb. Best for large repositories with many objects where history queries are frequent (CI/CD, code hosting servers). Trade-off: additional disk space and longer repack times.
MIDX creates a combined index across multiple pack files, dramatically speeding up object lookups in repos with many packs (50+). Use git multi-pack-index write to generate it. Combined with bitmaps, it can reduce git log time by 80%+ in large monorepos. Enable automatically with git config core.multiPackIndex true.
Pack files store all objects ever added to the repository, including unreachable ones. git rm removes files from the working tree but not from history — objects persist until unreachable and then still may remain until git gc --prune=now runs. For true secret removal, use git filter-repo or BFG Repo-Cleaner to rewrite history and expire reflogs.
Deep delta chains (depth > 50) cause slow git log, checkout, and fetch operations because Git must reconstruct objects by applying many deltas sequentially. Use git repack -f --depth=250 to recompute deltas with controlled depth. Shallower chains (depth ~10-20) trade disk space for faster access.
.pack contains the actual compressed objects and delta instructions. .idx is the forward index (object ID → offset) for fast object lookup using binary search. .rev is the reverse index (offset → object ID) for operations needing offset-to-object-ID mapping. Git creates all three when generating a pack.
Avoid manual repacking for: (1) Daily development — Git's auto-gc is sufficient, (2) Small repositories — loose objects work fine, (3) During active development — repacking creates brief lock contention, (4) When unsure — git gc handles most cases safely. Only repack manually for optimization before archiving or when debugging specific storage issues.
A shallow clone limits the history available at a recorded boundary; it is not the same thing as a thin pack. A thin pack is a transfer format whose deltas may refer to objects the receiver already has; Git resolves those references before storing the resulting pack. To fetch more history from a shallow clone, use git fetch --unshallow when the remote can provide it.
Possible causes include an interrupted write, disk corruption, or a pack/index mismatch. Inspect with git fsck --full and git verify-pack -v. Preserve a full backup before repair. Do not delete files from .git/objects/pack by hand; recover from a verified backup or use Git's documented fetch or clone process in a fresh copy.
Large binary files stored in pack files bloat every clone. Migrate to Git LFS with git lfs migrate to replace large blobs with pointer files. After verifying the rewritten history and preserving a backup, run git gc to let Git prune unreachable objects according to its configured retention rules. Check large objects before migration with git rev-list --objects --all | git cat-file --batch-check | sort -k3 -n -r | head -20.
git repack -a -d packs everything and deletes loose objects after. git repack -a -d -f adds -f to force recomputation of deltas from scratch, ignoring existing delta information. Use -f when delta chains are too deep, when you suspect delta corruption, or when you want maximum compression at the cost of longer repack time.
A loose object is stored as zlib(<object type> <size>\0<object content>). The object type is one of the four core types: blob, tree, commit, or tag. The content varies by type — a blob contains file data, a tree lists names and object IDs, a commit references a tree and parent commits, and a tag references another object. In a loose-object layout, the path uses a short object-ID prefix and the remaining characters; the ID length depends on the repository's hash format. See the hash transition documentation.
Pack files can save space through delta compression: similar objects may be stored as differences from a base object. Git's packing heuristics also consider object similarity and access patterns. The compression ratio varies with repository content and pack settings, so a fixed percentage is not a useful expectation. See Git's pack format documentation.
The fan-out table in a .idx file narrows object lookups by the first byte of each object ID. It has 256 cumulative entries, one for each possible byte value; the object-ID size follows the repository's hash format. The pack format documentation specifies the index structure.
Start with read-only checks: run git fsck --full, then use git verify-pack -v on the index for the reported pack. Preserve the working tree and Git/common directory before any repair. Do not delete pack and index files manually; restore the affected repository from a verified backup or follow Git's documented recovery path using a known-good remote. A remote may not contain local-only objects. See Git's pack format documentation and the Git maintenance guide.
Further Reading
- Git Internals — Pro Git Book
- Git pack format specification
- Git hash-function transition notes
- Git objects overview
- Git garbage collection and maintenance
- Git Object Model — Atlassian
- Understanding Git Pack Files — GitHub Blog
- Git gc and Pack Files — GitHub Docs
- Packfile Compression — Git Source Code
Conclusion
Git’s object database stores every version of every file as individual objects until pack files compress them into efficient deltas. This design — loose objects for fresh work, packed storage for history — is why Git can hold years of project history in megabytes.
Category
Tags
Related Posts
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.
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.
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.