Most developers learn Git merge and rebase through hand-wavy whiteboard diagrams. In those drawings, a merge creates a diamond shape, while a rebase turns a messy tree into a neat, straight line. Senior engineers usually summarize the difference with a tidy rule of thumb: "Rebase moves your branch to the tip of main."
That explanation is easy to remember, but it misrepresents how Git works. Git never moves a commit. In Git's object store, commits are cryptographically immutable. You cannot edit, shift, or transplant a node in a directed acyclic graph (DAG).
When you run git rebase, Git does not move anything. It creates brand-new commit objects with different hashes, leaves the old commits abandoned in your object database, and quietly repoints a text file under .git/refs/.
Understanding what Git actually does with blobs, trees, commit pointers, and the merge engine makes the entire "merge vs rebase" debate straightforward.
1. The Git Object Store: Commits Are Immutable
To understand merging and rebasing, you have to look at what Git stores on disk inside .git/objects/.
Git is fundamentally a content-addressable key-value store with four primitive object types:
- Blob: Raw file contents, indexed by the hash of their payload. Blobs have no file names and no timestamps.
- Tree: A directory listing that maps file names and Unix permissions to blob hashes or sub-tree hashes.
- Commit: A small text block containing a pointer to a root tree object, one or more parent commit hashes, author metadata, committer metadata, and a log message.
- Annotated Tag: A permanent pointer to a specific commit object with a tagger signature.
You can inspect any commit directly with git cat-file:
$ git cat-file -p HEAD tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904 parent a1b2c3d4e5f678901234567890abcdef12345678 author Sarah Chen <sarah@example.com> 1732512000 +0000 committer Sarah Chen <sarah@example.com> 1732512000 +0000 Fix connection pool exhaustion in database client A commit hash is the SHA-1 (or SHA-256 in newer repos) of those exact lines.
Because the hash includes the parent hash, every commit forms a cryptographically linked chain back to the root commit of the repository. If you change a single comma in a file, the blob hash changes. That changes the tree hash, which changes the commit hash.
More importantly, if you change a commit's parent, its author timestamp, or its committer timestamp, its hash changes completely.
A branch in Git is not a container of commits. A branch is just a 41-byte text file inside .git/refs/heads/ that stores the 40-character hex hash of a single commit, plus a newline. When you "switch branches," Git merely updates the HEAD pointer to point to a different text file.
2. What git merge Actually Does
Suppose you branch feature off main. Both branches have accumulated new commits:
B --- C [feature] / A --- D --- E [main, HEAD] When you run git checkout main && git merge feature, Git executes a three-stage pipeline.
Step A: Finding the Merge Base
Before Git compares any files, it finds the Lowest Common Ancestor (LCA) of the two branch tips in the DAG. Git calls this commit the merge base.
Git traverses the DAG backwards from both branch tips using commit generation numbers. In our graph, the merge base is commit A. You can check this manually at any time:
$ git merge-base main feature a1b2c3d... (Commit A) Step B: Fast-Forward vs Three-Way Merge
Git checks whether a new commit is even necessary:
- Fast-forward merge: If the merge base between two branches is identical to the current
HEAD(meaningmainnever moved while you worked onfeature), there is no divergent history. Git skips the merge engine entirely. It opens.git/refs/heads/mainand overwrites its hash with the hash of commitC. No new commit object is minted. - Three-way merge: If
mainandfeaturehave both advanced since commitA, Git cannot fast-forward. It must run a full three-way merge.
Step C: The Three-Way Merge Engine
A naive two-way diff between E and C cannot determine intent. If line 42 in E says timeout = 5 and line 42 in C says timeout = 10, which one is right? Did main change it from 10 to 5, or did feature change it from 5 to 10?
A two-way diff cannot tell. That is why Git requires the merge base A.
Git compares:
- Diff 1: Base
A-> CurrentE(Ours) - Diff 2: Base
A-> IncomingC(Theirs)
| In Merge Base A | In Ours (E) | In Theirs (C) | Resolution |
|---|---|---|---|
timeout = 30 | timeout = 5 | timeout = 30 | timeout = 5 (We changed it; take Ours) |
timeout = 30 | timeout = 30 | timeout = 10 | timeout = 10 (They changed it; take Theirs) |
timeout = 30 | timeout = 5 | timeout = 10 | CONFLICT (Both changed it; prompt user) |
timeout = 30 | timeout = 5 | timeout = 5 | timeout = 5 (Both made identical edit) |
Git applies this comparison at two distinct levels:
- Tree level: Resolves additions, deletions, and file renames.
- Content level: For files modified on both sides, Git runs a line-by-line diff algorithm (by default,
histogramdiff via theortmerge backend) on individual hunks.
Step D: The Special Case: Criss-Cross Merges and Virtual Bases
When two branches repeatedly merge each other back and forth, the DAG can produce a criss-cross pattern. In this scenario, there is no single lowest common ancestor. There are two equally valid merge bases.
A --- B --- M1 --- X [ours] \ / / \ / / C --- M2 [theirs] Here, both B and C are common ancestors of X and M2, and neither is an ancestor of the other.
Historically, picking one base arbitrarily could silently drop changes that the other side had deliberately reverted. Modern Git uses the ort strategy ("Ostensibly Recursive's Twin", the default since Git 2.34).
When ort encounters multiple common ancestors, it recursively merges the merge bases together in memory first. This creates a synthetic virtual merge base commit (a temporary in-memory tree that never gets written to your repository history). Git then uses that virtual merge base as the reference ancestor to merge X and M2.
Step E: Creating the Merge Commit
Once all files are resolved, Git writes the merged working directory into new blob and tree objects. Then it creates a new commit object:
B --- C -------- / \ A --- D --- E -------- M [main, HEAD] If you run git cat-file -p M, you will see two parent fields:
tree f1e2d3c... parent e5f6789... (Commit E: main prior to merge) parent c9b8a7f... (Commit C: feature branch tip) author Alex Rivera <alex@example.com> 1732512600 +0000 committer Alex Rivera <alex@example.com> 1732512600 +0000 Merge branch 'feature' into main The merge commit preserves history exactly as it occurred in physical time.
3. What git rebase Actually Does
Now consider the exact same starting point:
B --- C [feature, HEAD] / A --- D --- E [main] You are on feature and run:
$ git rebase main Git does not drag commits B and C across the graph. Here is the mechanical sequence that actually runs:
B' --- C' [feature, HEAD] / A --- D --- E [main] \ B --- C [orphaned / dangling in object store] Step 1: Discovering the Replay Set
Git calculates the merge base between feature and main (commit A).
It runs the equivalent of:
$ git rev-list --reverse A..feature This returns the list of commits unique to your feature branch: [B, C].
Step 2: Detached HEAD State
Git moves the repository into a detached HEAD state pointing directly at commit E (the tip of main). At this moment, your feature branch name is detached while Git sets up an internal workspace in .git/rebase-merge/.
Inside that directory, Git writes:
-
git-rebase-todo: The list of operations to execute. -
head-name: The ref being rebased (refs/heads/feature). -
onto: The target commit hash (E).
Step 3: Sequential Cherry-Pick Replay
Git loops through the commit list one by one. For commit B:
- Git computes the diff between
Band its original parentA:git diff A B. - Git applies that diff on top of the current
HEAD(commitE). - If conflicts occur, Git pauses and leaves conflict markers in your working tree.
- Once clean, Git commits the new tree as
B'.
Look at the metadata for B':
- Parent:
E(wasA). - Tree: New hash (includes changes from
DandE). - Author: Original author preserved.
- Author Date: Original timestamp preserved.
- Committer: You (the person running the rebase).
- Committer Date: Current timestamp right now.
Because the parent hash, committer date, and tree hash have all changed, the resulting commit hash is completely different. Commit B' is an entirely new object.
Git repeats this exact process for commit C, applying its diff on top of B' to create C'.
Step 4: Repointing the Ref
Once commit C' is written, Git updates .git/refs/heads/feature to point to the hash of C'. Then it attaches HEAD back to feature.
What Happened to the Old Commits B and C?
They were not deleted. They still exist on disk inside .git/objects/.
However, no branch reference points to them anymore. In graph theory terms, they are unreachable nodes (often called orphaned or dangling commits).
They will remain on your drive until Git runs garbage collection (git gc), which typically waits 30 to 90 days before pruning objects that are unreachable from the reflog.
4. The Golden Rule: Why Rebasing Shared Branches Breaks Collaboration
The rule is drilled into every developer: Never rebase a branch that has been pushed to a shared remote.
Here is the exact mechanism of why it breaks other people's repositories.
The Breakdown Sequence
- You create
featurewith commitsBandC. You push it to GitHub:
origin/feature: A --- B --- C - Your teammate Bob pulls
featureto collaborate with you. Bob writes commitDon top ofC:
Bob's local: A --- B --- C --- D [feature] - Meanwhile,
mainhas moved forward. You decide to tidy up your branch. You rungit rebase mainon your machine:
Your local: A --- ... --- E --- B' --- C' [feature] - You try to push, but Git rejects it because your history has diverged. You force-push:
$ git push --force-with-lease origin feature Now GitHub's origin/feature points to C'. Commits B and C are gone from GitHub's branch ref.
- Bob finishes his feature work and runs a standard pull:
$ git pull origin feature What Git Does to Bob
git pull runs git fetch followed by git merge.
Git looks at Bob's local branch (which has B, C, D) and the incoming remote tracking branch (which has B', C').
Git searches for the common ancestor between Bob's local branch and remote. The common ancestor is commit A.
Because B' has a different hash than B, Git treats B and C as unique commits authored by Bob that do not exist on the remote server. Git attempts to merge C' with D.
The result is a complete mess:
- Bob's commit history now contains duplicate commits:
B,B',C,C', andD. - Bob gets hit with merge conflicts on code that was already reviewed and resolved days ago, because Git is trying to replay the same code changes against each other under different hashes.
If Bob panics and resolves the merge, he pushes a merge commit back to GitHub that resurrects the old B and C commits. Your clean rebased history is destroyed.
5. Emergency Recovery: Rescuing a Botched Rebase
Because rebase leaves old commits in the object database, you can almost always undo a botched rebase.
Git records every movement of HEAD in the reflog (.git/logs/HEAD).
If you finish a rebase and realize half your changes disappeared or the branch is corrupted:
$ git reflog You will see an audit trail:
7c2a104 HEAD@{0}: rebase (finish): returning to refs/heads/feature 7c2a104 HEAD@{1}: rebase (pick): Add user authentication 3e9b110 HEAD@{2}: rebase (pick): Initial endpoint skeleton 4a82b99 HEAD@{3}: rebase (start): checkout main a1b2c3d HEAD@{4}: commit: Add user authentication <-- This was your old commit C! Find the entry right before rebase (start). Here, it is HEAD@{4}.
Run a hard reset to that reflog entry:
$ git reset --hard HEAD@{4} Git immediately repoints .git/refs/heads/feature back to your original commit C. The entire rebase is undone, and your repository is back to its exact state prior to the operation.
6. Git RERERE: Taming Repeated Conflicts
One annoying aspect of rebasing long-lived branches is resolving the exact same merge conflict across multiple commits.
If commit 1 of 5 conflicts on a dependency file, and commit 3 touches the same file, Git pauses on commit 1, asks you to fix it, and may pause again on commit 3 to ask for the same fix.
You can fix this permanently by enabling Git's rerere engine (REuse REcorded REsolution):
$ git config --global rerere.enabled true When rerere is active:
- When a merge conflict happens, Git saves a pre-image fingerprint of the conflicted hunks in
.git/rr-cache/. - Once you resolve the conflict and commit, Git records the post-image resolution.
- If the same conflict signature occurs anywhere else during a rebase, merge, or cherry-pick, Git automatically applies your previous resolution and notifies you:
Resolved 'src/config.ts' using previous resolution.
7. The Architectural Trade-Off: Merge vs Rebase
The debate between merge and rebase is not about which command is superior. It is a trade-off between two different values:
| Dimension | git merge | git rebase |
|---|---|---|
| Commit Graph | Non-linear DAG with branching forks and join commits | Linear chain with no forks |
| Commit Identity | Preserves original commit hashes and timestamps | Creates new commit hashes with updated committer times |
| Historical Truth | True chronological record of what happened and when | Curated story of how the feature should be read |
| Bisecting | git bisect can land on noisy merge commits | git bisect is clean and isolates bad commits quickly |
| Reverting | Reverting a merge commit requires -m 1 parent selection | Reverting is a simple single-commit patch |
| Collaboration Safety | Always safe to push to shared branches | Dangerous on shared branches; requires force-pushing |
Practical Rule of Thumb
Use rebase locally to polish your private branch before submitting a pull request. Squash messy "wip" and "fix typo" commits so your teammates can review clean, atomic units of work.
Use merge when combining integrated branches (such as merging a pull request into main), or when multiple engineers need to work against the same shared branch simultaneously.
Git gives you both tools because software development requires both: a clean narrative for code review, and an immutable historical record for production audits. Knowing what happens to the DAG underneath makes choosing between them easy.



