Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Git Internals
Engineering~13 min readIntermediate
Deep Dive

Git internals: learn the model, and the commands become obvious.

Most people use Git the way medieval sailors used stars — memorized incantations, deep superstition, occasional disaster. But under .git sits one of the most elegant data structures in software: a content-addressed, immutable graph with a few movable pointers on top. Learn that model once and every scary command — reset, rebase, detached HEAD — turns out to be a one-line pointer operation.

01

Everything is content-addressed

Git's foundation is one decision: every piece of data is named by the hash of its content. Store a file, and its bytes are hashed; that hash IS the file's identity, forever. Two consequences do enormous work. Deduplication is automatic — a thousand commits containing the same unchanged file store its blob exactly once. And nothing can be silently corrupted or edited — change a single byte anywhere and every hash above it changes, which is why Git can verify an entire repository's integrity by checking one hash.

→ The mental model

Git is not a version-control system that happens to use hashes. It is a content-addressed database (objects in, hashes out) with a thin version-control UI on top. Every mystery below dissolves against this fact.

Concretely, the "address" of any object is the SHA-1 of a short header plus the bytes — the same recipe git hash-object runs:

id(o) = SHA1( "<kind> <len>\0" + bytes )  →  equal bytes ⇒ equal id (stored once)  ·  one byte differs ⇒ different id

Because a tree's bytes are the names and ids of its children, and a commit's bytes include its tree's id, a single changed byte ripples up into a brand-new commit id — while every unchanged file keeps its old id and is never re-stored. The runnable version below hashes real objects (its README hash matches git's own) and watches both effects happen.

02

Four object types, one graph

The whole database schema
BlobFile contents. Just bytes — no filename, no permissions, no history. The name lives one level up.
TreeA directory: a list of (name, mode, hash) entries pointing at blobs and other trees. One tree hash captures an entire directory snapshot.
CommitA tree hash (the snapshot) + parent commit hash(es) + author + timestamp + message. History is commits pointing at parents — a DAG.
TagA named, optionally signed pointer at a commit. The only object type most people can ignore.

Note what a commit is not: a diff. Every commit is a full snapshot — a pointer to a complete tree. Diffs are computed on demand by comparing two trees. This is why checkout of any ancient commit is instant (follow one pointer), and why Git needs packfiles (section 07) to keep full-snapshot storage cheap.

03

Branches are 41-byte files

Run cat .git/refs/heads/main. You'll see one commit hash and a newline — 41 bytes. That file is the branch. There is nothing else. "Creating a branch" writes this file. "Committing" appends an object and rewrites this file with the new hash. "Deleting a branch" deletes the file — the commits remain, merely unlabeled.

HEAD is one more level of indirection: a file usually containing ref: refs/heads/main — a pointer to a pointer, marking "where you are." The infamous detached HEAD is simply HEAD containing a raw commit hash instead of a ref name. Nothing is broken; you're just standing on a commit rather than riding a branch — and any commits you make there are reachable only via the reflog until you name them.

Q: Why is branching in Git "free" when it was expensive in older systems?
A: Because a branch never copies anything. It's a 41-byte name for a node in a graph that already exists.
04

The three trees: what add, commit and reset really move

Git juggles three snapshots at all times: HEAD (last commit), the index (staging area — the next commit, prebuilt), and the working directory (your actual files). Every day-to-day command is a synchronization between them:

CommandWhat it syncs
git addworking directory → index (stage this version)
git commitindex → new commit; branch pointer advances
git reset --softmoves branch pointer only — index & files untouched
git reset --mixed…also index ← HEAD (unstages)
git reset --hard…also working directory ← HEAD (destroys local edits)
git checkout / switchall three ← the target commit (with safety checks)

This table is the entire mystery of reset: the three flags are just how far the sync propagates. And add -p stops feeling exotic — you're editing the index, a real, inspectable snapshot (git diff --staged shows it) that exists so you can compose a commit deliberately instead of committing your whole messy desk.

05

Merge and rebase: two ways to join histories

Merge is honest arithmetic on the DAG: find the common ancestor (merge base), three-way compare both sides against it, combine, and record a commit with two parents. History stays true — the fork happened, the join happened, the graph says so.

Rebase is rewriting: take your commits since the fork, and replay them one at a time on top of the new base. Each replayed commit has a different parent and timestamp — so it hashes to a new commit. The old ones aren't modified (nothing ever is); they're abandoned, and your branch file now points at the copies.

→ Why "never rebase shared branches" is a law

Rebase replaces commits with lookalikes under new hashes. Anyone who built work on the originals now holds orphaned parents — and Git will try to "helpfully" merge the duplicates back. Rewrite what only you have seen; merge what others have.

Same logic explains --force-with-lease: a rewritten branch no longer fast-forwards, so pushing needs force — and the lease makes force safe by refusing if the remote moved since you last looked (i.e., a teammate pushed).

06

The reflog: why nothing is ever lost

Here's the fact that turns Git panic into Git calm: objects are never edited and almost never deleted. Reset "back" in history? The commits ahead still exist — unlabeled. Botch a rebase? The originals still exist. Git additionally keeps a private, local journal — the reflog — of every position HEAD has occupied: ~90 days for entries still reachable from a branch (gc.reflogExpire), 30 days for unreachable ones (gc.reflogExpireUnreachable). It is never pushed or cloned.

The universal recovery recipe
git reflog
→
find the last
good position
→
git reset --hard <hash>
or branch/cherry-pick it

Garbage collection eventually prunes objects nothing references — but "eventually" is weeks away by default. The honest statement of Git safety: anything you ever committed is recoverable for months; only never-committed working-directory changes can truly vanish (reset --hard and restore are the two genuinely dangerous commands).

07

Remotes and packfiles: the wire and the disk

A remote is just someone else's object database plus their refs. fetch downloads their new objects and updates your remote-tracking refs (origin/main — your read-only bookmark of their state); pull is fetch + merge (or rebase) into your branch; push uploads your objects and asks the remote to move its ref — refused unless it's a fast-forward, hence the force flags. All the sync commands are pointer diplomacy between two object stores.

And the storage trick that makes full-snapshot commits affordable: loose objects are periodically compressed into packfiles, where similar objects are stored as deltas against each other. Snapshots in the model, diffs on the disk — each layer choosing the representation that serves it best. It's the same play databases run with WALs and B-trees, and it's why a 15-year repo with 100K commits fits in a coat pocket.

08

The model in one breath

ConceptWhat it actually is
Object storeimmutable, content-addressed blobs/trees/commits
Historycommits pointing at parents — a DAG of snapshots
Brancha 41-byte file naming one commit
HEADa pointer to a branch (or, detached, to a commit)
add / commit / resetsyncs between working dir, index, HEAD
Mergea two-parent commit joining histories truthfully
Rebasereplayed copies under new hashes; old ones abandoned
ReflogEverywhere HEAD has been (90 days if reachable, 30 if not; local only) — the undo of last resort
RUN IT YOURSELF

Build git's object store, for real

This is git's content-addressing in ~20 lines. hash_object uses git's exact recipe — "blob <len>\0" + bytes, SHA-1'd — so the README's hash below is byte-identical to what git hash-object prints on your machine. Three "commits" snapshot the same README plus a changing app.py: six blob writes collapse to three stored objects (dedup), the first two trees hash equal (nothing changed), and flipping one byte of app.py gives the third tree a different hash. Edit the snapshots and watch the counts move.

CPython · WebAssembly
By the numbers

Worked example: what .git gains, command by command

Start from an empty repository, make two commits to one file, throw the second away with reset --hard, then get it back. Watch the two columns separately: objects are only ever added, while refs and the index are the only things that move.

StepCommandObjects writtenWhat moves
1echo hello > READMEnoneworking directory only
2git add READMEblob ce01362: header blob 6\0 + 6 bytesindex: README → ce01362
3git commit -m onetree 7d4a466 (one 34-byte entry) + commit C1refs/heads/main ← C1; reflog +1 line
4echo "hello world" > README, git add READMEblob 3b18e51index: README → 3b18e51
5git commit -m twoa new tree + commit C2 (parent C1)main ← C2; reflog +1 line
6git reset --hard HEAD~1nonemain ← C1; index and README ← tree 7d4a466
7git reflognonelists HEAD@{1} = C2, “commit: two”
8git reset --hard HEAD@{1}nonemain ← C2; README says “hello world” again

Six objects exist after step 5 (two blobs, two trees, two commits), and the reset in step 6 deletes none of them. It rewrites one 41-byte file and resyncs the index and working directory from C1’s tree. That is why step 8 is a full recovery. Try step 2 yourself: git hash-object README prints ce013625030ba8dba906f756967f9e9ca394464a on any machine, because the id depends only on the bytes.

Trade-offs

Cost and trade-offs of everyday commands

CaseTimeSpaceWhy
git commitHash each changed file, then each tree on its path up to the rootOne blob per changed file, one tree per changed directory, one commitUnchanged subtrees keep their ids, so they are reused, not rewritten.
Create a branchO(1): write one file41 bytesNothing is copied; the commits already exist.
git switchProportional to the paths that differ between two treesNo new objectsSubtrees with equal ids are skipped without reading their contents.
git mergeWalk the DAG to the merge base, then three-way merge the differing pathsOne commit with two parents, plus changed trees and blobsIf your branch is an ancestor, it is a fast-forward: a ref move, no new commit.
git rebase of n commitsn replays, each able to stop on a conflictn new commits; the originals stay until gc prunes themNew parents mean new ids for every replayed commit.
git gc / repackCPU-heavy delta searchPackfiles far smaller than loose objectsSnapshots in the model, deltas on disk, as section 07 says.
git cloneDownloads every reachable objectThe full history--depth 1 or --filter=blob:none trade history for speed.

The pattern: commands that move refs are constant-time, commands that compare snapshots cost as much as the difference between them, and only gc and clone scale with the whole history.

Watch for

Common mistakes

  • Trusting the reflog for 90 days

    The ~90 days is git’s default for reflog entries still reachable from the branch. Entries for commits that are no longer reachable, which are exactly the ones a reset or a bad rebase leaves behind, expire after 30 days by default (gc.reflogExpireUnreachable). The reflog is also local: it is never pushed or cloned, so a fresh clone has no undo history.

  • Thinking staged work is gone after reset --hard

    git add already wrote a blob. If you staged a file and then ran reset --hard, the blob still sits in the object store, unreferenced. git fsck --lost-found lists the dangling blobs and copies them into .git/lost-found/. Only changes never added are truly lost.

  • Deleting a secret or a huge file with a new commit

    The old blob is still in history and in every clone. For a leaked key, rotate the key; rewriting history does not reach copies already made. For a large binary, every future clone keeps downloading it until history is rewritten (for example with git filter-repo) and everyone re-clones.

  • Reading origin/main as the live remote

    origin/main is a bookmark updated only when you fetch. “Your branch is up to date with origin/main” means up to date with your last fetch, which may be hours old. Run git fetch before deciding anything from it.

  • Rebasing away merge commits

    A plain git rebase replays the commits in a straight line and drops merge commits, flattening history you may have wanted to keep. Use --rebase-merges to preserve them, or merge instead.

In the wild

Where this shows up beyond git, and in interviews

  • Container images

    Docker and OCI images use the same idea: each layer is named by the SHA-256 digest of its contents. Two images built on the same base share those layers on disk and over the network, just as a thousand commits share one unchanged blob.

  • CI checkouts

    A CI job rarely needs history. A shallow clone (--depth 1) fetches one commit and its tree; a partial clone (--filter=blob:none) fetches the commits and trees and only downloads blobs when a checkout needs them. Both are direct uses of the object graph.

  • Moving off SHA-1

    After the 2017 SHAttered collision, git switched to a SHA-1 implementation that detects that class of attack. It can also create repositories with SHA-256 ids (git init --object-format=sha256). There, the page’s 41-byte branch file is 65 bytes: 64 hex characters and a newline.

  • The interview version

    “What happens when you run git commit?” Walk the example above: blob, tree, commit, ref. “How would you recover a branch deleted by mistake?” The reflog and git branch name <hash>. Both questions test whether you hold the model or only the commands.

Self-check

Check yourself

You change only the message with git commit --amend. Which objects are new?

Just one commit. The files did not change, so the blobs and the tree keep their ids and are reused. The message is part of the commit’s bytes, so the commit gets a new id and the branch moves to it. The old commit still exists and is in the reflog.

You edit src/app/main.py and commit. How many new objects does that commit write?

Five. One blob for the new main.py, then one tree each for src/app, src and the root, because each tree’s bytes include its child’s id, and one commit. Every other file and directory keeps its old id.

You ran git branch -D feature with unmerged commits. The branch is gone. How do you get it back?

Deleting a branch also deletes its reflog, but HEAD’s reflog remains. If you ever had feature checked out, git reflog shows its last commit; git branch feature <hash> recreates it. The commits were never deleted, only unlabelled.

Your editor fetches in the background. A teammate pushes, the editor fetches, then you push your rebased branch with --force-with-lease. What happens?

Your push overwrites theirs. The lease compares the remote branch with your origin/ bookmark, and the background fetch already updated that bookmark to include their commit. The check passes even though you never looked at their work. Name the expected commit explicitly with --force-with-lease=main:<hash> if that matters.

Frequently asked

Quick answers

What are Git's object types?

Blob (file bytes), tree (directory listing), commit (tree + parents + metadata), tag. All immutable, all named by content hash.

What is a branch?

A 41-byte file containing one commit hash. HEAD points at the branch; committing rewrites the file.

Soft vs mixed vs hard reset?

How far the sync goes: pointer only → +index → +working directory. Only --hard touches your files.

Is a lost commit recoverable?

Almost always, if you act within 30 days on the same clone: git reflog shows past HEAD positions (unreachable entries kept 30 days by default, reachable ones 90) — reset or branch to the good hash.

Git Internals · Engineering · Vibe Engines · 2026
Finished this one? 0 / 209 Handbooks done
NextThe System Design Fundamentals Handbook Closest handbook to this one

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks