Git Performance Engineering: Measuring Before Optimising

Writer, my software system for producing books and managing AI-assisted publication workflows, was becoming slow to commit and push. With thousands of files, years of development history and a growing collection of experiments and generated assets, I suspected that the repository had simply become too large.
The numbers told a different story. Git had compressed hundreds of MiB of historical file content into approximately 49 MiB. The entire initial pack store occupied only 71.48 MiB. Removing source history, my first instinct, would have addressed a problem I had not established existed.
This article examines that investigation and develops a practical diagnostic workflow for slow repositories. It assumes familiarity with Git, branches and the index. The examples primarily use PowerShell 7, with Python for portable diagnostic utilities.
TL;DR: Writer had 9,282 tracked files, 3,468 commits and 36,303 historical blobs analysed. Historical blob storage was reduced by packing to roughly one-fifteenth of its unpacked size. Animation assets dominated the packed blob report, but that does not make them the cause of slow pushes. Profile the operation itself before altering history.
Scope of the case study: I measured repository storage and completed maintenance and index configuration changes. I did not capture operation latency before those changes, and I do not yet have post-maintenance storage measurements or a confirmed cause of the slow commits and pushes. The diagnostic procedures below are a way to complete that investigation, not a report of a demonstrated speed-up in Writer.
1. Start with the operation, not the repository size
A Git repository can be slow in several independent ways. The index, working tree, object database and remote transport have different costs. Even a small repository can have a slow hook or expensive filesystem traversal.
| Symptom | First measurement | Possible bottleneck |
|---|---|---|
| Slow status | Compare normal status with -uno |
Filesystem and untracked discovery |
| Slow staging | Stage a controlled change | Hashing, clean filters, index writes |
| Slow commit | Trace a real commit | Hooks, signing, tree creation, maintenance |
| Slow push | Compare remote lookup, dry run and real push | Authentication, packing, upload, remote processing |
| Slow clone | Measure transfer and checkout separately | Historical objects, working tree size |
| Intermittent delay | Trace multiple operations | Resource contention, background maintenance |
The aim is to isolate the expensive stage. Repository size is a useful diagnostic variable, not a diagnosis.
2. Establish a repeatable latency baseline
Start with simple measurements, recording the Git version and relevant configuration alongside the results:
git --version
git config --show-origin --get-regexp '^(core|index|feature|gc|maintenance|pack|filter|lfs|push)\.'
(Measure-Command { git status --porcelain }).TotalMilliseconds
(Measure-Command { git status --porcelain -uno }).TotalMilliseconds
(Measure-Command { git ls-remote origin }).TotalMilliseconds
(Measure-Command { git push --dry-run }).TotalMilliseconds
A dry run does not upload a pack. It is useful for diagnosing connection and negotiation, but cannot substitute for a real push. It may also execute a pre-push hook; inspect your hooks before treating the operation as free of side effects. Remote commands assume a configured origin and appropriate push configuration.
On Linux or macOS, use time git status --porcelain or the platform’s timing tools. On Linux, /usr/bin/time -v can also expose resource usage.
A portable benchmark script
The following Python utility measures wall-clock time, includes process-launch overhead as a control, records the first observed run separately from subsequent runs and writes results outside the repository. It does not stage or commit files. Save it as measure_git.py and run it from the repository root.
import argparse
import csv
import statistics
import subprocess
import time
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("output", type=Path)
parser.add_argument("--runs", type=int, default=10)
parser.add_argument("--remote", action="store_true")
args = parser.parse_args()
if args.runs < 2:
parser.error("--runs must be at least 2")
version = subprocess.check_output(["git", "--version"], text=True).strip()
operations = {
"version": ["--version"],
"status": ["status", "--porcelain"],
"tracked-only": ["status", "--porcelain", "-uno"],
"ls-files": ["ls-files"],
"history": ["rev-list", "--all", "--count"],
}
if args.remote:
operations.update({
"remote": ["ls-remote", "origin"],
"push-dry-run": ["push", "--dry-run"],
})
rows = []
for name, command in operations.items():
warm = []
for i in range(args.runs):
start = time.perf_counter()
result = subprocess.run(["git", *command], stdout=subprocess.DEVNULL)
ms = (time.perf_counter() - start) * 1000
rows.append((version, name, i + 1, round(ms, 3), result.returncode))
if result.returncode:
print(f"{name}: run {i + 1} failed ({result.returncode})")
elif i == 0:
print(f"{name}: first observed run {ms:.2f} ms")
else:
warm.append(ms)
if warm:
print(f"{name}: subsequent median {statistics.median(warm):.2f} ms; "
f"range {min(warm):.2f}–{max(warm):.2f} ms")
with args.output.open("w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["git_version", "operation", "run", "ms", "exit_code"])
writer.writerows(rows)
python measure_git.py "$env:TEMP\writer-before.csv" --runs 10 --remote
The first observed run is not necessarily a genuinely cold-cache run. Previous commands and other processes may already have warmed the filesystem. The version row provides a rough process-startup reference, not a number to mechanically subtract from every measurement. Record the machine, Git configuration, branch, filesystem and concurrent workload separately; the CSV records the Git version and timings.
For staging and commit benchmarks, use a disposable clone with a fixed set of representative changes. Restore the same starting index and working-tree state between trials. Repeating git add -A without resetting the changes measures a different workload after the first run. For push tests, use equivalent outgoing objects and equivalent remote starting states; once a push succeeds, repeating it measures an up-to-date push rather than the original upload.
3. Profile Git with Trace2
This is the most useful diagnostic facility in Git that many developers never use. Trace2 records internal regions, child processes and other events, allowing you to distinguish work performed by Git from work delegated to hooks or transport processes.
The older GIT_TRACE_PERFORMANCE variable provides basic performance tracing. Trace2 offers two particularly useful targets: GIT_TRACE2_PERF for human-readable performance output and GIT_TRACE2_EVENT for structured JSON events.
Capture a status operation using a fresh trace file:
$trace = Join-Path $env:TEMP "git-status-$([guid]::NewGuid()).jsonl"
$env:GIT_TRACE2_EVENT = $trace
$env:GIT_TRACE2_EVENT_NESTING = "5"
try {
git status --porcelain
} finally {
Remove-Item Env:GIT_TRACE2_EVENT, Env:GIT_TRACE2_EVENT_NESTING
}
The nesting limit controls how deeply nested regions are recorded (the usual default is two). Increasing it can reveal expensive operations inside broader regions, at the cost of more instrumentation. Run this in a diagnostic shell without existing trace settings.
For human-readable profiling, set GIT_TRACE2_PERF to a separate absolute filename and run the operation under investigation. Capture a real commit or push only when you intend to perform that operation, or in a controlled test repository.
Ranking expensive Trace2 regions
The following analyser consumes the JSON event target, not the text performance target. In a region_leave event, t_rel is the elapsed duration of that region in seconds. In a child_exit event it is the child’s elapsed duration. The field is event-specific; t_abs describes time relative to process start. There is no need to subtract two t_abs values for an ordinary completed region. See the Trace2 specification.
Save as analyze_git_trace.py:
import argparse
import json
from pathlib import Path
def load_events(path):
rows = []
malformed = 0
children = {}
with Path(path).open(encoding="utf-8") as handle:
for line in handle:
try:
event = json.loads(line)
except json.JSONDecodeError:
malformed += 1
continue
kind = event.get("event")
key = (event.get("sid"), event.get("child_id"))
if kind == "child_start":
children[key] = event
if kind not in ("region_leave", "child_exit"):
continue
duration = event.get("t_rel")
if not isinstance(duration, (int, float)):
continue
if kind == "child_exit":
start = children.pop(key, {})
label = start.get("hook_name") or start.get("child_class") or "child"
category = "child process"
else:
label = event.get("label", "")
category = event.get("category", "")
rows.append((duration, category, label, event.get("thread", ""),
event.get("nesting", 0), event.get("sid", "")))
return rows, malformed
def main():
parser = argparse.ArgumentParser()
parser.add_argument("trace_file")
parser.add_argument("--top", type=int, default=30)
args = parser.parse_args()
if args.top < 1:
parser.error("--top must be positive")
rows, malformed = load_events(args.trace_file)
print(f"Completed events: {len(rows)}; malformed lines: {malformed}")
if not rows:
return 1
print(f"{'Seconds':>10} {'Depth':>5} {'Category':20} {'Region':35} Thread / session")
for seconds, category, label, thread, depth, sid in sorted(rows, reverse=True)[:args.top]:
print(f"{seconds:10.4f} {depth:5} {category:20} {label:35} {thread} / {sid}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
python analyze_git_trace.py $trace --top 20
These are inclusive durations. Nested regions, parent processes and child processes can overlap; summing the ranked rows will double-count work. Instead, follow the thread and session identifiers to investigate the critical path. A long child process labelled as a hook is a different problem from a long index refresh or pack-objects region.
Trace files may expose paths, URLs, arguments or other sensitive information. Inspect them before sharing.
4. The Writer case study: measure object storage
My initial storage measurements were collected with:
cd C:\Projects\writer
git count-objects -vH
git ls-files | Measure-Object -Line
git status
The working tree was clean and the branch was up to date with its upstream. The object database reported:
count: 761
size: 1.96 MiB
in-pack: 98215
packs: 29
size-pack: 71.48 MiB
prune-packable: 0
garbage: 0
size-garbage: 0 bytes
| Metric | Initial measurement |
|---|---|
| Tracked files | 9,282 |
| Loose objects | 761 |
| Loose object storage | 1.96 MiB |
| Packed object entries | 98,215 |
| Pack files | 29 |
| Pack storage | 71.48 MiB |
These figures are modest enough that storage alone is not a compelling explanation for the reported latency. For orientation, hundreds of MiB and multiple GiB of packed history warrant progressively closer inspection, but there is no universal repository-size threshold at which Git becomes slow. Object count, tree shape, working set and hardware matter as much as bytes. All sizes here use binary units (1 MiB = 1,048,576 bytes).
Maintenance and the missing after-measurement
I ran git gc, which enumerated 74,557 objects and separately processed 43 cruft objects. I subsequently ran git maintenance run and git commit-graph write --reachable. Both maintenance commands performed repacking in this case.
The difference between 98,215 initial packed entries and 74,557 enumerated objects is 23,658. Duplicate objects across packs and differences in reachability and maintenance selection can contribute to this discrepancy. It is a useful clue, but not a measured count of duplicate or unreachable objects. That would require inspecting the original packs and object reachability separately.
Crucially, I did not capture latency before maintenance. Nor did I capture git count-objects -vH again afterwards. I cannot honestly quantify how much storage or time was saved. A fresh clone can provide a new comparison baseline, but cannot recreate the original pack layout, caches or all local state.
5. Analyse historical files rather than guessing
Install git-filter-repo and use its analysis mode:
python -m pip install git-filter-repo
git filter-repo --analyze
Analysis does not rewrite history. The fresh-clone safety check applies to destructive filtering, not ordinary analysis. Use a stable checkout for comparable results. Locate the reports with:
$report = git rev-parse --git-path filter-repo/analysis
Get-Content (Join-Path $report README)
Get-Content (Join-Path $report extensions-all-sizes.txt)
Get-Content (Join-Path $report path-all-sizes.txt) | Select-Object -First 30
Get-Content (Join-Path $report path-deleted-sizes.txt) | Select-Object -First 30
The reports include historical paths, extensions, directories, blob identities, rename information and deletion estimates. The README explains attribution caveats: repeated content may be attributed to multiple paths, deletion status can depend on branch history, and removing a delta base may increase the size of other objects.
Writer’s analysis, performed after maintenance, reported:
| Metric | Result |
|---|---|
| Commits | 3,468 |
| Blobs processed | 36,303 |
| Historical filenames | 13,024 |
| Historical directories | 1,674 |
| Unpacked blob size | 756.05 MiB |
| Packed blob size | 49.31 MiB |
The unpacked-to-packed blob ratio is approximately 15.3:1, or a 93.5% reduction in represented blob bytes. This is not a compression ratio for the entire .git directory. Git deduplicates identical content and can delta-compress similar objects; it does not store a separate physical copy of every file for every commit.
The initial 71.48 MiB pack-store measurement and later 49.31 MiB blob report differ by about 22 MiB. They cover different object populations and were collected before and after maintenance respectively. Trees, commits, tags, duplicate entries and pack overhead can contribute; the residual cannot be assigned entirely to structural objects without a comparable post-maintenance inventory.
The surprising concentration of binary storage
| Extension | Unpacked MiB | Packed MiB |
|---|---|---|
| FBX | 282.99 | 19.82 |
| Python | 361.12 | 19.14 |
| Markdown | 45.06 | 6.05 |
| JSONL | 16.93 | 1.85 |
| SQL | 24.09 | 0.20 |
Python history represents more than 361 MiB of unpacked content but only about 19 MiB packed. Deleting source history would be difficult to justify on that evidence.
The path report revealed a more interesting pattern:
| Historical path (abbreviated where appropriate) | Packed attribution |
|---|---|
assets/animations/Standard Walk.fbx |
18.20 MiB |
SceneDefinitionAggregateDTO.context.md |
1.25 MiB |
pi-budget-events.jsonl |
793 KiB |
trip.jsonl |
727 KiB |
repo_last_24h.md |
669 KiB |
Sitting Cross Legs.fbx |
362 KiB |
repo_last_48h.md |
292 KiB |
pi-followup-events.jsonl |
251 KiB |
repo_last_24h.diff |
236 KiB |
test_db/test_database.db |
208 KiB |
The Standard Walk path alone represents approximately 37% of the overall reported packed blob bytes. Other animation files have comparable unpacked sizes but much smaller packed representations. One plausible explanation is that they are encoded as deltas against a shared base, perhaps Standard Walk itself. The reports do not prove that relationship; git verify-pack -v can be used to inspect delta chains. Removing the apparent largest asset could cause other assets to expand on repacking.
The largest file in Git history is not necessarily the cause of the slowest Git operation.
If a binary object is unchanged and already exists on the remote, an ordinary incremental push does not usually send it again. Removing it might help future clones, but the effect on routine pushes could be negligible.
The generated-looking JSONL, diff and context paths are also worth attention. Their names suggest a potential storage-growth policy problem. Before moving or ignoring them, establish whether they are disposable outputs, required fixtures or durable research evidence. Check whether any hook regenerates those files on commit; that is a testable latency hypothesis, not a finding from the storage report.
Inspect object storage directly
For an inventory independent of git-filter-repo, use Git’s batch interface:
git cat-file --batch-all-objects --unordered '--batch-check=%(objecttype) %(objectname) %(objectsize) %(objectsize:disk)' |
ForEach-Object {
$type, $oid, $logical, $disk = $_ -split ' '
[pscustomobject]@{
Type = $type; OID = $oid
LogicalBytes = [long]$logical; DiskBytes = [long]$disk
}
} | Where-Object Type -eq blob |
Sort-Object DiskBytes -Descending | Select-Object -First 20
This enumerates available objects, including unreachable ones and objects in alternate stores. It does not include paths, and when multiple copies exist, the selected disk representation is not a complete accounting of every physical copy. Use git rev-list --objects --all to associate reachable object IDs with paths, and git verify-pack -v <pack-index> to inspect a particular pack. git-sizer is useful for investigating structural extremes such as large trees and excessive references.
6. Apply maintenance and index optimisations selectively
For repositories accumulating fragmented packs, ordinary garbage collection is a reasonable intervention after collecting a baseline:
git count-objects -vH
git gc
git count-objects -vH
Standard garbage collection preserves reachable commit identities. It can expire reflogs and prune older unreachable objects, however, so preserve dangling work or dropped stashes you may need. Avoid git gc --prune=now, particularly while other processes are writing objects. Aggressive garbage collection increases delta-search effort and is not a routine performance fix.
git maintenance run without a configured task set normally runs garbage collection. Running it immediately after git gc may therefore repeat work. Garbage collection also normally updates the commit graph (gc.writeCommitGraph defaults to true). For regular incremental maintenance, investigate git maintenance start, which registers scheduled tasks on supported platforms. Use git commit-graph write --reachable when a separate commit-graph refresh is warranted.
Working-tree and index optimisations
If status or staging traces show repeated index refreshes and directory scans, test these settings individually:
git update-index --test-untracked-cache
git config --local core.untrackedCache true
git config --local core.fsmonitor true
git config --local index.version 4
git update-index --index-version 4
Use the untracked cache only on compatible filesystems. Built-in FSMonitor is available on supported Windows and macOS Git builds, with boolean configuration available in the Git 2.37 era. Check every Git implementation that accesses the repository, including IDE integrations and WSL. Older clients may interpret the boolean as a hook path. Verify the daemon with git fsmonitor--daemon status where supported; Windows monitoring is not a shared monitoring service for WSL Git.
Index version 4 compresses path prefixes. Modern Git also exposes feature.manyFiles, which sets defaults for index version, untracked caching and, on newer releases, index.skipHash. The latter skips writing the index checksum and has compatibility and integrity implications, so I prefer explicit settings unless all clients have been qualified. See the Git configuration reference.
Writer had around nine thousand tracked paths, not hundreds of thousands. These changes might help, but their effect has not been measured. Capture a new baseline, then change one variable at a time. Restore the previous setting if it does not improve the target operation. Remember that removing the configuration for index version does not itself convert the existing index format; use git update-index --index-version 2 if version 2 is the intended comparison.
7. Investigate filesystem overhead, hooks and concurrency
Untracked directories
The object database can be small while the working directory contains millions of dependency, cache or generated files. Compare:
git status --porcelain
git status --porcelain -uno
git ls-files --others --exclude-standard
git check-ignore -v path/to/file
If the tracked-only status is significantly faster, inspect untracked discovery. Keep virtual environments, dependency caches and generated outputs outside the repository or correctly ignored. A file already tracked is not made untracked by adding it to .gitignore; git rm --cached removes it from the next index snapshot, not from historical commits. Review the resulting diff before committing.
Windows and WSL
Writer lives at C:\Projects\writer, accessible from WSL as /mnt/c/Projects/writer. Linux Git traversing a Windows-hosted repository can incur substantial cross-filesystem overhead. Switching Git implementations on one checkout may also invalidate cached stat information or expose file-mode and line-ending configuration differences.
Compare native Windows Git and WSL Git from their respective shells, rather than counting WSL startup as Git execution time:
# Windows PowerShell
cd C:\Projects\writer
(Measure-Command { git status --porcelain }).TotalMilliseconds
# Already running WSL shell
cd /mnt/c/Projects/writer
time git status --porcelain
For a third comparison, clone the same commit into WSL’s native Linux filesystem and benchmark there. Use comparable configuration and working-tree contents. Prefer native filesystem access for the tools doing most of the work; migrating a Windows-centric application to Linux solely because of an assumed performance advantage may create more problems than it solves.
Antivirus scanning
On Windows, Git creates and reads many small files. Defender scanning can contribute to latency. Observe the actual operation with Task Manager or use Defender’s performance analyser from an elevated PowerShell session on supported systems:
New-MpPerformanceRecording -RecordTo "$env:TEMP\defender-git.etl"
Run the problematic Git operation while recording, stop the capture as instructed, then inspect it:
Get-MpPerformanceReport -Path "$env:TEMP\defender-git.etl" -TopFiles 20 -TopProcesses 10
On supported Windows 11 installations, Dev Drive provides a development-oriented ReFS volume and Defender performance mode. It is not a Windows 10 feature and Microsoft does not promise a corresponding improvement for WSL access to Windows files. Writer’s environment is Windows 10, so this is an option for other readers or a future platform change, not an applied fix.
Do not disable endpoint protection or broadly exclude repositories containing downloaded dependencies and generated executable code. First demonstrate that scanning is responsible for a meaningful portion of the latency.
Hooks and signing
A slow commit may spend almost all its time outside Git’s object database. Find the configured hook location:
git config --show-origin --get core.hooksPath
git rev-parse --git-path hooks
git config --show-origin --get commit.gpgSign
An unset configuration key may return exit status 1; that is not itself an error in the repository. If core.hooksPath is set, inspect the effective hook directory rather than only .git/hooks. Trace child processes from a real commit. Pay particular attention to pre-commit, commit-msg, post-commit, signing and automatic maintenance. On a push, examine pre-push and LFS activity.
If the hook runs an entire test suite for every documentation edit, consider targeted deterministic checks and broader validation in CI, while preserving the original guarantees. Do not make bypassing hooks the permanent performance solution.
Concurrent automation
Build systems, CI processes and AI coding agents increasingly initiate Git activity. Several agents sharing one checkout can contend over the index, locks and working-tree changes. To investigate:
git worktree list
Get-Process git*, python*, node* -ErrorAction SilentlyContinue |
Select-Object Name, Id, CPU, WorkingSet
CPU is accumulated processor time, not current utilisation. Correlate active processes with actual latency measurements. Do not delete an index lock without establishing whether a live process owns it.
Separate worktrees give each agent its own checkout and index while sharing the object database:
git worktree add -b agent/task-a C:\Projects\writer-agent-a
git worktree add -b agent/task-b C:\Projects\writer-agent-b
Shared references and object storage still require coordination. Schedule repository-wide maintenance centrally instead of letting every agent repack independently.
8. Diagnose slow pushes separately
A push involves authentication, reference discovery, determining which objects the server needs, pack construction, transfer and server-side validation. A pre-push hook or Git LFS may introduce additional work.
Start with the inexpensive probes:
git ls-remote origin
git push --dry-run
If both are slow, investigate connectivity, credentials and server response. If both are fast but an actual push is slow, capture Trace2 during the actual push and look for pack-objects, LFS transfers and transport-related child processes. If the delay occurs after upload, remote processing may be responsible.
Inspect the outgoing history, after refreshing remote-tracking references with git fetch if appropriate:
git rev-list --objects HEAD --not --remotes=origin
git log '@{upstream}..HEAD' --oneline
git diff --stat '@{upstream}' HEAD
The latter two commands require an upstream branch. The object enumeration approximates objects not reachable from locally known remote references; it is not an exact prediction of the pack or upload size. The server may have additional objects, and a diff between endpoints will not reveal a large file added and deleted in intermediate outgoing commits.
Transport diagnostics
For HTTPS transport, Git provides cURL and packet tracing. For SSH, verbose SSH logging can help identify connection or authentication stalls.
$env:GIT_TRACE_CURL = '1'
$env:GIT_TRACE_CURL_NO_DATA = '1'
$env:GIT_TRACE_PACKET = '1'
try {
git push --dry-run 2> "$env:TEMP\git-transport.log"
} finally {
Remove-Item Env:GIT_TRACE_CURL, Env:GIT_TRACE_CURL_NO_DATA, Env:GIT_TRACE_PACKET
}
For an SSH remote, in a separate diagnostic shell:
$env:GIT_SSH_COMMAND = 'ssh -v'
try {
git ls-remote origin
} finally {
Remove-Item Env:GIT_SSH_COMMAND
}
Use the SSH override only if it is compatible with your normal SSH configuration. These logs can still contain sensitive metadata even with HTTP body logging disabled. Do not publish raw diagnostic logs without reviewing them.
If Trace2 identifies pack construction as the bottleneck, investigate pack.threads, pack.window, pack.depth, pack.windowMemory and pack.compression. These settings trade CPU, memory, compression efficiency and network bytes against each other. Benchmark changes with equivalent outgoing object sets. Increasing http.postBuffer is not a general-purpose performance optimisation: its primary effect is on HTTP request buffering and when chunked transfer encoding is used, not on Git’s object selection or compression.
9. Reduce the working set without rewriting history
For very large repositories, especially monorepos, a developer or agent may only require a small part of the tree. Modern Git provides two complementary mechanisms: partial clone and sparse checkout.
git clone --filter=blob:none --sparse <repository-url> writer-small
cd writer-small
git sparse-checkout set --cone src tests
git sparse-checkout reapply --sparse-index
Replace src and tests with directories appropriate to the repository. Partial clone avoids initially downloading many file-content objects; the promisor remote supplies missing objects when needed. Sparse checkout limits the paths materialised in the working tree. A sparse index can reduce index overhead further where tools support it.
These techniques preserve history and commit identities. They are particularly useful when initial clones, checkouts or agent-specific working sets are the problem. They do not automatically improve routine pushes from an existing full clone. Some operations trigger lazy downloads, so offline access and tooling compatibility must be considered. Partial clone also depends on server support. For very large repositories, Scalar provides a more opinionated collection of large-repository optimisations.
10. When historical cleanup really is justified
History rewriting becomes worth considering when large historical objects cause measurable clone, fetch, storage or maintenance costs, or when prohibited content must be removed. Deleting a file in a later commit does not remove its earlier versions.
The following is an experimental procedure, not something I executed on Writer. Preserve the production repository and suspend conflicting automation before beginning. Create the backup directory first, save uncommitted and untracked work separately, and back up external LFS objects if applicable.
git bundle create C:\Backups\writer-backup.bundle --all
git bundle verify C:\Backups\writer-backup.bundle
git clone --mirror --no-local C:\Projects\writer C:\Projects\writer-history-experiment.git
cd C:\Projects\writer-history-experiment.git
A bundle preserves included references and their reachable Git objects, not every local configuration, reflog entry or unreferenced object. Verify that you can restore the required branches and tags before relying on it.
To test the removal of one historical path in the disposable mirror:
git filter-repo --path 'assets/animations/Standard Walk.fbx' --invert-paths
git fsck --full
git count-objects -vH
git filter-repo --analyze
Use separate fresh clones for alternative experiments. Historical renames may require additional path arguments. A blanket --strip-blobs-bigger-than 50M can destroy important evidence and should not be used without a specific retention decision.
By default, destructive git-filter-repo operations require a fresh clone and remove the origin remote to reduce the chance of accidentally pushing rewritten history. Do not bypass these safeguards with --force as a matter of routine. The metadata and analysis location is relative to the Git directory, not necessarily a .git subdirectory:
git rev-parse --git-path filter-repo
Retain the generated commit-map, ref-map and other migration records. Verify that required files and references survive, compare storage against an equivalent unfiltered mirror and test applications and build workflows from the rewritten history.
Publishing rewritten history
A history rewrite changes affected commit identities and may invalidate commit signatures, tags, pull requests, CI caches and reproducibility records. Treat publishing it as a migration: freeze writes, record expected remote ref IDs, coordinate collaborators, verify backups, update only approved references and validate fresh clones afterwards.
For an explicitly approved single-branch migration, a command of the following form protects against overwriting a branch whose tip has changed since the recorded expectation:
git push --force-with-lease=refs/heads/main:<recorded-old-oid> origin refs/heads/main:refs/heads/main
The remote must have been deliberately configured to point to the intended destination. Replace the placeholder with the independently recorded old tip. This is not a complete multi-branch or tag migration procedure, nor does the lease prove that the rewritten history is correct. Prefer fresh clones for collaborators after migration; preserve unpublished work and port it deliberately rather than instructing everyone to hard-reset indiscriminately. Avoid merging old history back into the new repository.
For Writer, the observed storage footprint does not currently justify this disruption as a solution to slow commits or pushes.
11. Git LFS versus artifact storage
Git LFS stores pointer blobs in Git and large content in a separate LFS store. It is appropriate for binaries that genuinely require version control, such as frequently revised design files, 3D assets or datasets.
git lfs install
git lfs track '*.fbx'
git add .gitattributes
Review and commit the attributes, and deliberately renormalise the intended existing files if converting them in the current snapshot. git lfs track does not retroactively replace historical Git blobs. git lfs migrate info --everything helps assess the existing history; git lfs migrate import --include='*.fbx' --everything performs a history rewrite and requires the same migration discipline as other rewriting tools. A --no-rewrite migration can convert selected current files in a new commit instead. Ensure migrated LFS objects are available on the intended server (for example via git lfs push --all origin in an approved migration), and validate a fresh checkout.
LFS introduces storage quotas, network dependencies and filter overhead. Writer’s roughly 20 MiB of packed FBX data is not, on its own, a strong reason to adopt it. The choice should reflect future asset growth, update patterns and actual clone costs.
Generated PDFs, EPUBs, build products, caches and experiment outputs often belong outside version control altogether. The important distinction is between reproducible artifacts and irreplaceable evidence. Keep source, configuration, prompts and manifests in Git; store large outputs in a durable artifact or evidence store with appropriate retention. A manifest can record the source commit, generator version, content digest and storage URI. A digest verifies content but cannot recover a missing artifact.
12. Prevent the next storage problem
The most useful preventive rule is to reject inappropriate large blobs before they enter the history. Existing tooling such as the pre-commit framework and its check-added-large-files hook may already meet your requirements. A custom staged-object policy is useful when you want explicit thresholds, warnings and control over which changes are evaluated.
A naive implementation launches multiple Git processes for every staged file. That makes the policy itself a possible commit bottleneck. Use Git’s NUL-delimited raw diff to obtain staged object IDs and a single batch query to inspect their sizes. The following example uses at most two Git processes regardless of the number of changed files. It checks added, copied, modified, renamed and type-changed entries, rather than rescanning the entire index on every commit.
Save as check_staged_files.py:
import subprocess
import sys
MIB = 1024 * 1024
WARNING_SIZE = 10 * MIB
MAXIMUM_SIZE = 50 * MIB
def staged_blobs():
raw = subprocess.check_output([
"git", "diff", "--cached", "--raw", "-z", "--no-abbrev",
"--diff-filter=ACMRT", "--no-ext-diff", "--",
])
fields = raw.split(b"\0")
i = 0
while i < len(fields) - 1:
_, mode, _, oid, status = fields[i].decode("ascii").lstrip(":").split()
renamed = status.startswith(("R", "C"))
path = fields[i + (2 if renamed else 1)]
i += 3 if renamed else 2
if mode == "160000": # Submodule reference, not a blob
continue
yield oid, path.decode("utf-8", errors="replace")
def main():
entries = list(staged_blobs())
if not entries:
return 0
payload = "".join(f"{oid}\n" for oid, _ in entries).encode("ascii")
output = subprocess.run(
["git", "cat-file", "--batch-check=%(objecttype) %(objectsize)"],
input=payload, capture_output=True, check=True,
).stdout.decode("ascii").splitlines()
if len(output) != len(entries):
raise ValueError("Incomplete Git object response")
rejected = False
for (_, path), result in zip(entries, output):
kind, _, size_text = result.partition(" ")
if kind != "blob":
raise ValueError(f"Expected a staged blob for {path!r}: {result}")
size = int(size_text)
if size > MAXIMUM_SIZE:
rejected = True
print(f"ERROR: {path!r}: {size / MIB:.2f} MiB")
elif size > WARNING_SIZE:
print(f"WARNING: {path!r}: {size / MIB:.2f} MiB")
return int(rejected)
if __name__ == "__main__":
try:
sys.exit(main())
except (subprocess.CalledProcessError, OSError, ValueError, IndexError) as error:
print(f"Cannot validate staged objects: {error}", file=sys.stderr)
sys.exit(1)
The example rejects blobs strictly larger than 50 MiB and warns above 10 MiB. It examines the actual staged contents, not a potentially different working-tree version. NUL-delimited records handle filenames containing spaces or newlines; a renamed or copied entry has two path fields. Missing or unexpected objects cause validation to fail rather than being silently skipped. LFS pointer blobs remain small, as intended for a policy protecting the ordinary Git object store.
Integrate this into an existing pre-commit configuration as a local hook, without replacing unrelated validation:
repos:
- repo: local
hooks:
- id: staged-blob-size
name: Check staged Git blob sizes
entry: python check_staged_files.py
language: python
pass_filenames: false
always_run: true
Install pre-commit using your project’s normal dependency management and run pre-commit install if appropriate. Local hooks can be bypassed, so enforce important storage requirements in CI or on the server as well. A production policy may need explicit reviewed exceptions and checks covering all incoming commits, not just the current staged snapshot.
13. Finish the investigation with evidence
The Writer case established that the initial pack store was relatively small, that historical source content compressed effectively and that the packed blob report was concentrated in animation assets. It did not establish which Git operation or external process caused the observed slowdown.
The next useful experiment is to capture a latency baseline under the current configuration, record the current object store, trace a representative real commit and push, and compare native Windows and WSL execution. Then change one relevant variable at a time and repeat the measurements. The original pre-maintenance latency cannot be recovered simply by reversing settings; the original object layout and cache state have changed.
| Measurement | Before maintenance | After maintenance |
|---|---|---|
| Pack files | 29 | Not captured |
| Packed storage | 71.48 MiB | Not captured |
| Status latency | Not captured | Not captured |
| Staging latency | Not captured | Not captured |
| Commit latency | Not captured | Not captured |
| Push latency | Not captured | Not captured |
For automated development environments, this diagnostic process can become a recurring repository-health check. Track object-store growth, tracked file counts, pack fragmentation and operation latency, and investigate changes rather than enforcing arbitrary repository-size targets. Keep the measurements deterministic; use AI to help interpret the results and propose experiments.
The key lesson is not that Git repositories should be small. It is that successful execution of an optimisation is not evidence that the optimisation improved the operation we were concerned about. Git can retain a substantial history at surprisingly low cost, and removing that history may sacrifice useful knowledge without fixing the actual bottleneck.
References
- Git Trace2 specification
- Git configuration reference
- Git garbage collection and maintenance
- Git cat-file and verify-pack
- Git-filter-repo manual
- Git partial clone and sparse checkout
- Git push and worktrees
- Microsoft: WSL filesystem guidance
- Microsoft: Dev Drive
- Microsoft: Defender performance analyser