When to Use Git Merge vs Rebase: A Practical Comparison
This article walks through a common development scenario where two feature branches diverge from master, demonstrating how merge and rebase handle integration, conflict resolution, and commit history, and provides guidance on when each strategy is appropriate.
The author wrote this article after a team tech sharing session that raised the question of when to use git merge versus git rebase. Both commands integrate a feature branch into master, but they produce different histories: rebase creates a linear history, while merge preserves the branch tree.
Scenario Setup
Two developers, A and B, start from the same master commit and create separate feature branches ( feature/A and feature/B). Each branch adds three commits that modify the same file, guaranteeing conflicts when the branches are later merged.
Merge Workflow
Developer A merges first:
git checkout master
git merge feature/AAfter the merge, master and feature/A point to the same commit.
When B attempts to merge:
git checkout master
git merge feature/BThe merge creates a merge commit (mr node) that preserves both branch histories and requires a single conflict resolution step.
Fast‑Forward vs. Non‑Fast‑Forward Merge
Fast‑forward merge : If master has not advanced since the branch was created, the merge simply moves the master pointer forward—no merge commit is created.
Non fast‑forward merge : When master contains new commits, Git creates a new merge commit to combine the histories.
Rebase Workflow
After undoing B’s merge, the author rebases B onto the updated master:
git checkout feature/B
git rebase masterBecause each commit touches the same file, the rebase stops at every conflicting commit. After fixing a conflict, the developer runs git add followed by git rebase --continue to replay the next commit.
The final history is a straight line; no merge commit appears, but the original commit hashes are rewritten.
Conclusions
Merge retains the full, non‑linear history and may generate merge‑commit nodes; all conflicts are resolved in a single step at the point of integration.
Rebase rewrites the branch’s commits onto the tip of master, producing a linear history without extra merge commits, but requires conflict resolution for each individual commit.
Use rebase only on private, unpushed branches where you want a clean history; for shared branches or when you are unsure, stick with merge. Interactive rebase ( git rebase -i) can be used to reorder or squash commits, but never on a public branch because it changes commit hashes and can cause further conflicts.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
