How Git Works Under the Hood
An interactive systems engineering guide, visual state machine simulator, and intuitive mental models demystifying Git's Directed Acyclic Graph (DAG), storage engine, 3-way merges, and disaster recovery.
The 4 Git Architecture Zones
Git does not work directly between your code editor and GitHub. It coordinates transitions between four distinct, decoupled rooms. Click the buttons below to simulate file movements and observe internal state changes in real time.
Changes not staged for commit: modified: server.go
Untracked files: auth.go
Think of Git as a photography studio with four separate rooms. Code walks through them one door at a time:
- Room 1: Your Messy Desk (Working Directory): Where you type code, break things, and experiment. Git watches through a window, but doesn't touch your desk.
- Room 2: The Photo Stage (Staging Area / Index): When you run
git add, you invite specific files onto the stage to strike a pose. Any file you didn't add stays on your desk. - Room 3: The Fireproof Safe (Local Repository): When you run
git commit, the camera shutter snaps a permanent photo, stamps the date, and locks it inside your safe in.git/. Even if your laptop battery dies, this snapshot is permanent. - Room 4: The Cloud Warehouse (GitHub / Remote): When you run
git push, you photocopy all the photos in your safe and mail them to GitHub for your team to see.
Live Merge Conflict Resolution Lab
A merge conflict is not an error—it is Git safely pausing when two branches diverge and edit the same line since their Lowest Common Ancestor (Base).
Imagine you and your teammate both download a restaurant menu file where Burger Price = $10.
• You decide: "Burgers should be $12", edit line 3, and commit.
• Your teammate decides: "Burgers should be $15", edits line 3, and commits.
When you type git merge, Git looks at the original $10 base and compares both changes. Git is smart, but Git is not psychic. Git says: "You both changed line 3 from $10 to different prices! I refuse to guess who is right because I might crash your restaurant. You human, look at this and choose!"
4 | log_level: "info"
6 | log_level: "debug"
Once you stage and commit the resolution above, Git generates a Merge Commit with two parents. This new merge commit permanently becomes the Lowest Common Ancestor (Base) for any future merges between these two branches. Because the base now contains your resolved code, the diff between the base and either branch tip is zero—preventing Git from ever prompting on that line again!
The Content-Addressable Object Database & DAG
Under the hood, Git is not a file tree—it is a key-value database (like a giant warehouse with numbered lockers). The key is a 40-character SHA-1 hash, and the value is compressed data. Everything in .git/objects/ is one of four primitive types:
• Directed: Arrows point in one direction only. (Children point backward to their parent commits).
• Acyclic (NO LOOPS): You can never loop in a circle. You can't be your own grandfather.
• Graph: Dots (commits) connected by lines.
Why is it unbreakable? Each commit's fingerprint includes its parent's fingerprint. If someone tampers with an old commit from 3 months ago, every single commit after it breaks instantly, alerting Git to tampering!
Blob (Binary Large Object)
Stores pure file contents compressed via zlib. A blob does not know its own filename, folder, or permissions! It is just nameless raw content.
Tree Object (A Folder)
Represents a directory node. It is a checklist that maps filenames and file permissions (e.g. 100644 for normal files, 040000 for subdirectories) to Blob hashes.
Commit Object
The snapshot envelope. Contains a pointer to the root Tree object, author/committer identities, ISO timestamps, commit message, and a pointer to the parent commit(s).
Branches & HEAD (41 Bytes)
A branch is not a copy of your files. It is a 5-cent yellow sticky note in .git/refs/heads/ containing a 40-character commit hash! HEAD is just a red sticker saying "You Are Here".
10 Core Git Engineering Topics & Systems Scenarios
Deep technical breakdowns paired with plain-English mental models covering Git topology, merge theory, disaster recovery, and DevSecOps integrity controls. Click each topic to expand.
The Photo Album vs 500 Transparent Tracing Papers: Older systems (SVN/CVS) store revisions as diff deltas (transparent tracing papers layered on top of each other). To see version 500, SVN has to stack 500 tracing papers, making it slower and slower over time. Git stores full Polaroid snapshots. Checking out any past commit is a constant-time \(O(1)\) lookup.
Automatic File Deduplication
If a file is unchanged between commits, the new tree simply references the pre-existing Blob's SHA-1 hash. Even in a 50,000-file project, changing 1 file only creates 1 new blob. The other 49,999 files are shared references!
The Common Grandparent: Git never compares Branch A directly against Branch B alone—that would cause chaos because Git wouldn't know who changed what. Git finds the Lowest Common Ancestor (Base) in the DAG using git merge-base branchA branchB.
| Base (LCA) | HEAD (Current) | Incoming (Feature) | Git Automatic Resolution Decision |
|---|---|---|---|
port: 8000 |
port: 8080 (Modified) |
port: 8000 (Untouched) |
Take HEAD (Only current branch changed it) |
port: 8000 |
port: 8000 (Untouched) |
port: 9090 (Modified) |
Take Incoming (Only incoming branch changed it) |
port: 8000 |
port: 8080 (Modified) |
port: 9090 (Modified) |
CONFLICT! Both branches changed the same lines divergently. |
The New Master Copy: When you resolve a merge conflict today, the resulting Merge Commit has two parents (main & feature). In all future merges, that merge commit becomes the new Common Ancestor (Base). Because both branches already share that resolved state from the new base, the difference is 0 and no conflict is ever triggered again!
Tying Ropes Together (Merge) vs Time-Traveling to Replay Commits (Rebase):
- `git merge`: Tying two ropes together with a knot. Preserves the exact truth of when work was branched. Perfect for release branches and shared mainlines.
- `git rebase`: Time travel. Pretentiously pretends you only started your work today on top of the latest code. Produces a single, beautiful straight line in
git log.
Never rebase commits that have been pushed to a public/shared branch! Rebasing rewrites history and changes commit SHA hashes. If teammates have built work on the old hashes, force-pushing creates duplicate commit loops and broken topologies for the team.
The CCTV Security Camera: Did you accidentally run git reset --hard HEAD~1 and think your unpushed commit is gone forever? In Git, almost nothing is ever lost! Git has an append-only journal in .git/logs/HEAD recording every move your HEAD pointer ever made.
Floating in Space Without a Tether: Normally, HEAD points to a branch sticky note (ref: refs/heads/main). When you checkout a commit hash directly (git checkout 4b2e8d), HEAD points directly to the commit, detached from any branch name. Any new commits made here are "dangling" (untethered). If you switch branches, Git GC will eventually delete them unless you give them a sticky note: git branch saved-work HEAD.
The 3 Levels of Undo:
• `--soft`: Gentle Undo. Takes down the photo, but leaves everyone standing on the stage (staged in green).
• `--mixed` (Default): Normal Undo. Takes down the photo and tells everyone to step off the stage (unstaged in red).
• `--hard`: Nuclear Undo. Takes down the photo and wipes the files completely from your disk!
| Command | HEAD Pointer | Staging Index (.git/index) | Working Directory | Primary Production Use Case |
|---|---|---|---|---|
git reset --soft HEAD~1 |
Moves to target | Preserved (Staged) | Preserved (Unchanged) | Squash commits or reword commit message. |
git reset --mixed HEAD~1 (Default) |
Moves to target | Reset to target | Preserved (Unchanged) | Unstage files and selectively re-add chunks. |
git reset --hard HEAD~1 |
Moves to target | Reset to target | Wiped to target | Completely discard broken local experiments. |
The 10-Track Music Album and the Tweezers: Your teammate recorded a 10-song album on their branch. 9 songs are buggy experiments, but Track #4 is an urgent security patch. Instead of merging their whole branch, you reach in with tweezers and pluck only Track #4 onto your branch using git cherry-pick <hash>.
Architecture Nuance: The cherry-picked commit applies the exact same patch, but gets a new timestamp, new parent, and new SHA-1 hash.
Sherlock Holmes & The "Guess My Number" Game: If a regression bug appeared somewhere across 1,000 commits, testing each commit manually takes days. git bisect cuts the commit history in half on every test iteration (\(O(\log_2 N)\)). Across 1,000 commits, you isolate the exact breaking commit in at most 10 test steps!
The Honor System vs Central Airport Security:
• Client-side hooks (.git/hooks/pre-commit) run on the developer's laptop. They are helpful for code formatting, but are not secure because any engineer can bypass them with git commit --no-verify.
• Server-side hooks (pre-receive) run centrally on GitHub/GitLab. They cannot be bypassed by clients and enforce strict compliance: cryptographically verified GPG signatures, secret key scanning (blocking leaked AWS/API keys), and branch policies.
Systems Self-Assessment & Knowledge Check
Test your mastery of Git internals, recovery protocols, and merge algorithms. Select an answer to reveal the underlying architectural explanation.
git reset --hard HEAD~1 and loses an unpushed commit. What is the most reliable way to recover it?git reset --soft HEAD~1?git rebase on commits that have already been pushed to a shared public branch?