Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
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.
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.
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:
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.
Four object types, one graph
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.
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.
A: Because a branch never copies anything. It's a 41-byte name for a node in a graph that already exists.
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:
| Command | What it syncs |
|---|---|
git add | working directory → index (stage this version) |
git commit | index → new commit; branch pointer advances |
git reset --soft | moves 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 / switch | all 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.
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.
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).
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.
good position
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).
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.
The model in one breath
| Concept | What it actually is |
|---|---|
| Object store | immutable, content-addressed blobs/trees/commits |
| History | commits pointing at parents — a DAG of snapshots |
| Branch | a 41-byte file naming one commit |
| HEAD | a pointer to a branch (or, detached, to a commit) |
| add / commit / reset | syncs between working dir, index, HEAD |
| Merge | a two-parent commit joining histories truthfully |
| Rebase | replayed copies under new hashes; old ones abandoned |
| Reflog | Everywhere HEAD has been (90 days if reachable, 30 if not; local only) — the undo of last resort |
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.
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.
| Step | Command | Objects written | What moves |
|---|---|---|---|
| 1 | echo hello > README | none | working directory only |
| 2 | git add README | blob ce01362: header blob 6\0 + 6 bytes | index: README → ce01362 |
| 3 | git commit -m one | tree 7d4a466 (one 34-byte entry) + commit C1 | refs/heads/main ← C1; reflog +1 line |
| 4 | echo "hello world" > README, git add README | blob 3b18e51 | index: README → 3b18e51 |
| 5 | git commit -m two | a new tree + commit C2 (parent C1) | main ← C2; reflog +1 line |
| 6 | git reset --hard HEAD~1 | none | main ← C1; index and README ← tree 7d4a466 |
| 7 | git reflog | none | lists HEAD@{1} = C2, “commit: two” |
| 8 | git reset --hard HEAD@{1} | none | main ← 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.
Cost and trade-offs of everyday commands
| Case | Time | Space | Why |
|---|---|---|---|
git commit | Hash each changed file, then each tree on its path up to the root | One blob per changed file, one tree per changed directory, one commit | Unchanged subtrees keep their ids, so they are reused, not rewritten. |
| Create a branch | O(1): write one file | 41 bytes | Nothing is copied; the commits already exist. |
git switch | Proportional to the paths that differ between two trees | No new objects | Subtrees with equal ids are skipped without reading their contents. |
git merge | Walk the DAG to the merge base, then three-way merge the differing paths | One commit with two parents, plus changed trees and blobs | If your branch is an ancestor, it is a fast-forward: a ref move, no new commit. |
git rebase of n commits | n replays, each able to stop on a conflict | n new commits; the originals stay until gc prunes them | New parents mean new ids for every replayed commit. |
git gc / repack | CPU-heavy delta search | Packfiles far smaller than loose objects | Snapshots in the model, deltas on disk, as section 07 says. |
git clone | Downloads every reachable object | The 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.
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 addalready wrote a blob. If you staged a file and then ranreset --hard, the blob still sits in the object store, unreferenced.git fsck --lost-foundlists 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/mainis 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. Rungit fetchbefore deciding anything from it. - Rebasing away merge commits
A plain
git rebasereplays the commits in a straight line and drops merge commits, flattening history you may have wanted to keep. Use--rebase-mergesto preserve them, or merge instead.
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 andgit branch name <hash>. Both questions test whether you hold the model or only the commands.
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.
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.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The System Design Fundamentals HandbookThe load-bearing ideas behind every distributed system — the CAP theorem and consistency models, concurrency and locking, partitioning and replication, and consensus and coordination — each tied to a real worked design you can study interactively.Read →
- CAP Theorem & Consistency ModelsWhat a distributed system can promise when the network splits — CP vs AP, why "CA" is a myth, PACELC, and the full spectrum from linearizable to eventual consistency. Part of System Design Fundamentals.Read →
- Partitioning, Sharding & ReplicationHow one dataset becomes many — range vs hash partitioning, consistent hashing and virtual nodes, hot partitions, replication topologies, replication lag, and quorums. Part of System Design Fundamentals.Read →
- Consensus, Transactions & CoordinationHow nodes that can crash still agree on one truth — majority quorums, Raft and Paxos, leader election, two-phase commit vs the saga pattern, and idempotency for exactly-once effects. Part of System Design Fundamentals.Read →
- The Kubernetes HandbookThe one idea under all the YAML — declare desired state, and a control loop makes reality match. Covers the orchestration problem, pods, deployments and replicasets, services and networking, the reconciliation loop and self-healing, the scheduler, config/secrets and health probes, autoscaling, and when you actually need Kubernetes.Read →
- The Observability HandbookSeeing inside production — monitoring vs observability, the three pillars (metrics, logs, traces) and what each answers, structured logging, metric types and the cardinality trap, distributed tracing, the golden signals and SLIs/SLOs/error budgets, alerting on symptoms not causes, and correlating all three during an incident.Read →