Git Merge and Merge Strategies Explained
Compare Git merge strategies by merge shape and version. Learn the current `ort` default, multi-head `octopus` merges, and how to inspect conflict behavior.
Git uses `ort` for a merge with one other head and `octopus` for multiple heads by default; older Git releases used `recursive` for two-head merges. The selected strategy affects how Git combines trees and handles conflicts. Check the behavior for the Git version you run.
Introduction
Merging is how Git combines divergent histories. When two branches have taken different paths, a merge reconciles those paths into a single coherent history. Git provides multiple merge strategies, each suited to different scenarios and team workflows.
Understanding merge strategies isn’t academic — it directly affects your project’s history readability, conflict frequency, and release stability. The wrong strategy can produce tangled histories or silently discard work. The right strategy keeps your history clean and your team confident.
Current Git uses ort for a merge with one other head and octopus when several heads are merged. recursive was the default for two-head merges through Git 2.33; in recent Git it is an alias for ort. Strategy names and defaults vary by version, so check git --version and the official merge strategies documentation. For choosing between merge and rebase, see the comparison guide.
When to Use / When Not to Use
When to Use Merge
- Integrating completed features — bring finished work into the main line
- Combining parallel development — reconcile work done by different team members
- Release integration — merge release candidates back into main after stabilization
- Preserving history — merge commits record when and how branches were combined
- Team collaboration — pull requests use merge under the hood
When Not to Use Merge
- Linear history preference — use rebase instead if you want a straight-line history
- When team policy keeps published commit IDs stable — use merge or coordinate a rewrite with everyone who may depend on the branch
- Trivial changes — cherry-pick individual commits instead of merging entire branches
- When branches have diverged significantly — consider interactive rebase for cleaner history
Core Concepts
Git uses different merge strategies depending on the relationship between branches. The strategy determines how Git computes the combined result.
graph TD
Merge["git merge"] --> FF{"Can fast-forward?"}
FF -->|Yes| FastForward["Fast-Forward Merge"]
FF -->|No| ThreeWay{"Common ancestor?"}
ThreeWay -->|Yes| Ort["ort Strategy (default for one head)"]
ThreeWay -->|No| Octopus["Octopus strategy (multiple heads)"]
Ort --> Conflict{"Conflicts?"}
Conflict -->|Yes| Resolve["Manual Resolution"]
Conflict -->|No| AutoMerge["Automatic Merge Commit"]
FastForward --> NoCommit["No merge commit created"]
Fast-Forward Merge
When the target branch hasn’t moved since the feature branch was created, Git simply moves the pointer forward. No merge commit is created.
Before:
main: A ── B
\
feature: C ── D
After (fast-forward):
main: A ── B ── C ── D
feature: └────── (same commits)
Three-Way Merge (ort)
When both branches have diverged, Git finds the common ancestor and creates a new merge commit that combines both lines of work.
Before:
main: A ── B ── E
\
feature: C ── D
After (three-way merge):
main: A ── B ── E ── M (merge commit)
\ /
feature: C ── D ─┘
Architecture or Flow Diagram
flowchart LR
A["main: A-B-E"] --> Check{"Feature branch\nexists?"}
Check -->|Feature is\nancestor of main| FF["Fast-Forward\nNo merge commit"]
Check -->|Both diverged| ThreeWay["Three-Way Merge\nFind merge base"]
ThreeWay --> Auto{"Auto-resolvable?"}
Auto -->|Yes| MC["Create Merge Commit\n2 parents"]
Auto -->|No| Conflict["CONFLICT\nManual resolution required"]
Conflict --> MC
FF --> Done["Done"]
MC --> Done
Step-by-Step Guide / Deep Dive
Basic Merge
# Switch to the target branch
git switch main
# Merge the feature branch into main
git merge feature-x
# Merge with a custom message
git merge feature-x -m "Integrate feature-x: payment processing"
Controlling Merge Strategy
# Force a merge commit even if fast-forward is possible
git merge --no-ff feature-x
# Force fast-forward only (fail if not possible)
git merge --ff-only feature-x
# Use 'ours' strategy (keep current branch, discard other)
git merge -s ours feature-x
# Use ort with a specific conflict resolution preference
git merge -s ort -X ours feature-x
git merge -s ort -X theirs feature-x
Merge Strategies Explained
resolve — A simple three-way strategy that merges the current HEAD and one other head. It does not detect renames. This two-head limit applies to the resolve strategy; Git can merge multiple heads with the octopus strategy, which refuses merges that require manual conflict resolution.
git merge -s resolve feature-x
See the official merge strategy documentation for version-specific details.
ort — The current default strategy when merging one other head. It performs a three-way merge, handles rename detection, and also handles criss-cross merge bases. Git 2.34 and later use ort by default for a two-head merge. In Git 2.50 and later, recursive is an alias for ort; older releases used recursive as the default.
git merge -s ort feature-x
octopus — Merges more than two heads in one operation and is the default when git merge receives multiple heads. It refuses a merge that needs manual conflict resolution.
git merge feature-a feature-b feature-c # auto-uses octopus
ours — Records a merge but keeps all content from the current branch. Useful for deprecating branches.
git merge -s ours deprecated-branch
subtree — Merges a subproject with its own history into a subdirectory. Useful for vendoring dependencies.
git merge -s subtree --squash -m "Add vendor lib" vendor-lib
Merge Options
# Squash all commits into a single commit (no merge commit)
git merge --squash feature-x
git commit -m "Add feature-x"
# Abort a merge in progress
git merge --abort
# Continue a merge after resolving conflicts
git merge --continue
# Show what would be merged without actually merging
git merge --no-commit --no-ff feature-x
Production Failure Scenarios
| Scenario | Impact | Mitigation |
|---|---|---|
| Accidental fast-forward loses merge context | History doesn’t show feature integration | Use --no-ff for feature branches |
| Merge conflict in binary files | Unresolvable without manual intervention | Avoid committing binaries; use Git LFS |
| Wrong merge strategy discards work | Data loss from ours strategy |
Always review before using -s ours |
| Criss-cross merge confusion | Git picks wrong merge base | Use the current ort strategy; it combines multiple merge bases |
| Merge during CI failure | Broken main branch | Require CI to pass before merge |
Recovering from a Bad Merge
Not every merge goes smoothly. The recovery path depends on where you are in the process when you realize something went wrong, and picking the wrong approach can make things worse. The three scenarios below cover every stage of a merge lifecycle.
If the merge is still in progress and you have not yet committed, git merge --abort is your safest option. It restores your working tree and index to their state before the merge started. Git only modifies the repository permanently when you create a commit, so until that point you can always walk away clean.
If the merge was already committed but you have not yet pushed, use git reset --hard HEAD~1 to step back one commit. The merge commit disappears completely. Only do this when you are certain nobody else has pulled from the branch — rewriting shared history causes problems for your whole team.
If the merge has already been pushed to a remote, rewriting history is not an option. Use git revert -m 1 <merge-commit-sha> instead, which creates a new commit that applies the inverse of the merge. The -m 1 flag tells Git that the first parent is the mainline, so the revert undoes only what the merged branch contributed. One caveat: subsequent commits from the merged branch are not reverted by this command.
# If merge is still in progress
git merge --abort
# If merge was already committed
git reset --hard HEAD~1 # removes the merge commit
# If already pushed, create a revert
git revert -m 1 <merge-commit-sha>
Trade-off Analysis
| Strategy | Pros | Cons |
|---|---|---|
| Fast-forward | Clean linear history | Loses context about when feature was integrated |
--no-ff merge |
Preserves feature branch context in history | Creates extra merge commits, busier history |
--squash |
Single clean commit on target | Loses individual commit history of the feature |
ours |
Clean way to deprecate branches | Discards all changes from merged branch |
subtree |
Keeps subproject history | Complex to manage updates |
ort -X theirs |
Auto-resolves conflicting hunks in favor of the other side | May silently overwrite important changes |
Implementation Snippets
# Standard feature branch merge (preserves context)
git switch main
git pull origin main
git merge --no-ff feature-x
git push origin main
# Squash merge for small features
git switch main
git merge --squash feature-x
git commit -m "feat: add user profile validation"
# Merge with conflict preference (use carefully)
git merge -s ort -X ours experimental
# Subtree merge for vendored library
git remote add -f lib-vendor https://github.com/vendor/lib.git
git merge -s subtree --no-commit lib-vendor/main
git commit -m "Add vendor/lib at v2.3.0"
Observability Checklist
- Logs: Record merge commits with descriptive messages linking to issue IDs
- Metrics: Track merge frequency and conflict rate per team
- Alerts: Alert on merge conflicts in protected branches
- Traces: Link merge commits to PR numbers for audit trails
- Dashboards: Display merge-to-deploy lead time in CI/CD dashboards
Security & Compliance Considerations
- Merge commits should reference issue/PR numbers for audit compliance
- Protected branches should require approved PRs before merging
- Review merge diffs carefully —
--squashcan hide problematic individual commits - Use signed merge commits (
git merge -S) for supply chain security - Audit
oursstrategy usage — it can silently discard security fixes
Common Pitfalls / Anti-Patterns
- Merging without pulling first — creates unnecessary merge commits; always pull before merging
- Using
--squashfor large features — loses valuable commit history and makes bisecting harder - Ignoring merge conflicts — resolving conflicts by accepting everything from one side can break functionality
- Merging into the wrong branch — double-check your current branch before running
git merge - Forgetting
--no-ff— fast-forward merges lose the visual grouping of feature commits in history - Merge commit spam — merging tiny branches creates noise; batch small changes together
Quick Recap Checklist
- Fast-forward merges move the pointer without a merge commit
- Three-way merges create a merge commit with two parents
- Use
--no-ffto preserve feature branch context - Use
--squashfor combining many commits into one - Use
-s oursto record a merge while keeping current content - Use
-s subtreefor vendoring external projects - Always pull before merging to avoid unnecessary conflicts
- Use
git merge --abortto cancel a merge in progress
Merge Strategy Visualization
graph TD
subgraph "Fast-Forward Merge"
A1["A"] --> B1["B"]
B1 --> C1["C"]
C1 --> D1["D"]
D1 -. "main moves here" .-> D1
end
subgraph "Three-Way Merge (ort)"
A2["A"] --> B2["B"]
B2 --> E2["E"]
A2 --> C2["C"]
C2 --> D2["D"]
E2 --> M2["M (merge commit, 2 parents)"]
D2 --> M2
end
subgraph "Squash Merge"
A3["A"] --> B3["B"]
B3 --> C3["C"]
A3 --> D3["D"]
D3 --> E3["E"]
E3 --> S3["S (single commit, no parents)"]
end
classDef ff color:#00fff9
class A1,B1,C1,D1,A2,B2,C2,D2,E2,M2,A3,B3,C3,D3,E3,S3 ff
Production Failure: Squashed History Prevents Efficient Bisect
Scenario: A team lead merges a feature branch with 15 carefully crafted commits using git merge --squash. The squash creates a single commit with all changes combined. Two weeks later, a bug is traced to one specific change within that feature. git bisect can’t isolate the problematic commit because individual commit history was destroyed.
Impact: Lost ability to bisect, audit individual changes, or revert specific parts of the feature. The entire feature must be reverted as a unit.
Mitigation:
- Reserve
--squashfor small, atomic features (1-3 commits) - Use
--no-fffor features with meaningful commit history - Document squash merges in PR descriptions with commit summaries
- Configure branch protection to require merge commits for regulated code
# Check if a merge was squashed (single commit with multiple file changes)
git log --oneline --since="2 weeks ago" | head -20
git show <commit> --stat # if too many files, likely a squash
Trade-offs: Merge Strategies
| Strategy | How It Works | Best For | Risks |
|---|---|---|---|
| Fast-forward | Moves pointer forward, no merge commit | Linear feature branches, solo development | Loses integration context, can’t identify when feature was merged |
| ort (default for one head) | Three-way merge with merge commit | Most two-head merges | Resolve conflicts where needed |
| Ours | Keeps current branch content, discards other | Deprecating branches, resolving deprecation | Silently discards all incoming changes — dangerous |
| Subtree | Merges subproject into subdirectory | Vendoring dependencies, subproject management | Complex to update, requires subtree-specific knowledge |
| Octopus | Merges 3+ branches simultaneously | Combining multiple independent features | Can’t resolve conflicts, auto-aborts on conflict |
| resolve | Two-head three-way merge | Simple merges without rename detection | Does not detect renames |
Security/Compliance: Merge Commit Signatures
In regulated environments, merge commits should be cryptographically signed to verify who authorized the integration:
# Sign a merge commit
git merge -S feature-x
# Verify merge commit signatures
git log --show-signature --merges
# Configure automatic signing for all merges
git config --global commit.gpgSign true
git config --global merge.gpgSign true
# Verify the entire merge chain
git verify-commit <merge-commit-sha>
Compliance notes:
- Signed merge commits create an auditable chain of who approved each integration
- Required for SOC 2, HIPAA, and financial industry compliance
- Platform-level merge (GitHub/GitLab UI) may not preserve GPG signatures — use CLI for signed merges
- Document merge signature verification in your security policy
- Audit unsigned merge commits in protected branches
Case Study: Squash Merge Gone Wrong
The team had a release branch with 23 commits — two weeks of QA-certified work. A senior engineer merged it into main using git merge --squash to keep history clean. The squash produced a single commit with 847 file changes across authentication, payment processing, and notification systems. Three days after release, a payment flow regression caused $14,000 in failed transactions before the on-call engineer could identify and revert the whole thing.
Reverting took four hours because nobody could pinpoint which change broke things. git bisect landed on the squash commit with no granularity to offer. The actual culprit turned out to be a one-line change in a payment validation function that worked fine locally but failed under concurrent load in production — something that would have been obvious if the original commits were still traceable.
After this, the team’s policy changed: feature branches with more than five commits now require --no-ff merges. The incident also surfaced that squash merges had been the default for eight months because one engineer decided clean history mattered more than traceable history. That decision — made once, by one person — had accumulated into risk across the entire deployment pipeline.
The cost of clean history shows up at incident time, and it is usually paid by someone who wasn’t in the room when the trade-off was made.
git merge --squash and git merge --no-ff?--squash combines all changes into a single commit with no merge commit and no parent references — the individual commit history is lost. --no-ff creates a merge commit with two parents, preserving both the feature branch history and the integration point in the graph.
ours merge strategy do, and when would you use it?The ours strategy creates a merge commit that keeps all content from the current branch and discards all changes from the merged branch. Use it to deprecate a branch — for example, when retiring an old release branch and recording that it was intentionally superseded.
The ort strategy tracks file renames by comparing content similarity (not just filenames). If one branch renames a file and the other modifies it, Git detects the rename and applies the modifications to the new filename. If both branches rename the same file differently, it creates a rename/rename conflict requiring manual resolution.
A criss-cross merge occurs when two branches have been merged into each other multiple times, creating multiple common ancestors. The current ort strategy handles multiple merge bases by combining them into a virtual base before the final merge. Older Git versions used the recursive strategy for this behavior.
Prefer rebase for local cleanup when team policy permits it. If a branch has been published, first check whether anyone has based work on its commits; coordinate before rewriting shared history.
git merge --abort vs git merge --continue?--abort cancels the merge and restores the pre-merge state — your working tree and index return to how they were before the merge started. --continue resumes a merge after you have resolved conflicts in your working files and staged the results with git add.
The octopus strategy merges multiple heads in one operation and is Git's default when more than one head is supplied. It can create a commit with several parents, but refuses a merge that needs manual conflict resolution. For a single other head, current Git uses ort by default.
git merge -s ort -X ours and git merge -s ours?-s ours (ours strategy) completely ignores all changes from the merged branch — the resulting merge contains only the current branch content. -s ort -X ours uses the ort strategy and prefers our version for conflicting hunks, while still including non-conflicting changes from the other head. The latter is a "smart ours" that takes the best of both.
A merge commit is a commit with two or more parent commits. The first parent is the branch you merged into; additional parents are the tips of the branches being merged. This parent linkage is what makes git log --merges find merge commits and what enables tools to visualize branching history.
git pull behave when merging, and how does it differ from fetch + merge?git pull is equivalent to git fetch followed by git merge (or git rebase with --rebase flag). By default it performs a merge, which means it can create a merge commit if the remote has diverged. Use git pull --rebase to rebase your local commits onto the updated remote tip instead.
Git classifies conflicts as: (1) content conflicts — same lines modified differently in each branch, (2) rename conflicts — both branches renamed the same file differently, (3) delete vs modify — one branch deleted a file another modified, (4) submodule conflicts — submodule references changed in both branches. Content conflicts are most common and are resolved by choosing or combining the competing changes.
Use git revert -m 1 <merge-commit-sha>. The -m 1 flag specifies that the first parent (typically main) is the mainline. This creates a new commit that applies the inverse of the merge, effectively undoing the merged changes while preserving history. Note: subsequent commits from the merged branch are not reverted, only the merge itself.
--squash merge for large feature branches?Risks include: (1) Loss of granular history — cannot use git bisect to isolate specific commits within the feature, (2) Auditing difficulty — individual change attribution is lost, (3) Revert is all-or-nothing — you cannot selectively revert a single bad commit within the squashed changes, (4) Code review harder — reviewers see a large diff instead of incremental changes.
Git cannot merge binary files — if two branches modify the same binary file, a conflict cannot be auto-resolved. Git will mark it as a conflict and require manual intervention (typically choosing one version entirely). Mitigation: use Git LFS for large binaries, store binaries outside version control, or use content-addressable storage with references in Git.
rerere function in Git and how does it help with merge conflicts?rerere (Reuse Recorded Resolution) caches how you resolved a conflict and replays that resolution when the same conflict appears again. Enable it with git config rerere.enabled true. It is useful when merging the same branch repeatedly (e.g., a long-running feature branch being updated from main) — previously resolved conflicts are automatically applied.
In CI/CD: (1) Require status checks to pass before merging (branch protection), (2) Use merge commits (not squash) for audit trails linking PR numbers to deploys, (3) Configure fast-forward only on protected branches to maintain clean history, (4) Use merge queues (GitHub, GitLab) to batch multiple PRs and run CI once before a combined merge, (5) Reject unsigned merge commits in regulated environments.
A regular commit has one parent — it records changes built on top of the previous commit. A merge commit has two or more parents — it represents the point where separate lines of development were combined. The first parent is the branch you were on when merging; additional parents are the tips of the merged branches. This parent structure is what git log --merges uses to identify merge commits.
Use subtree merge when you need to include an external repository as a subdirectory of your project while preserving its history. Unlike a simple subdirectory copy, subtree merge tracks the relationship and allows you to update from the upstream repository using git pull -s subtree. Common use cases: vendoring dependencies, including a library project within an application repository, or embedding documentation from a separate repo. The alternative (submodule) is better when you want strict version pinning; subtree is better when you want to treat the subproject as part of your own codebase.
Git first detects conflicts at the file level: if both branches modified the same file, a conflict is flagged. Within a conflicted file, Git then detects line-level conflicts: regions where both branches modified the same lines are marked with conflict markers. Git cannot auto-resolve file-level conflicts (one branch deleted a file the other modified, or both renamed differently). Line-level conflicts can sometimes be auto-resolved if the changes are on different lines.
merge.conflictstyle configuration option?merge.conflictstyle controls how Git formats conflict markers in conflicted files. merge.conflictstyle diff3 adds a third section showing the common ancestor content between the conflict markers, giving you three-way context: original (ancestor), ours, and theirs. The default only shows ours and theirs. Use diff3 when conflicts are complex and you need to understand what the original code looked like to make better resolution decisions.
Further Reading
- Undoing changes in Git — review recovery steps before resetting or reverting a merge
- Rebase vs merge — compare how each workflow shapes shared history
- Git Merge Documentation — Official Git merge reference
- Git Branching - Rebasing — Pro Git book chapter on rebase vs merge
- Atlassian Git Merge Strategies — Comparison of merge strategies with visuals
- Git Tools - Advanced Merging — Advanced merge techniques, includes rerere
- Git Merge Resolution — Full list of merge strategies and their options
Conclusion
Merge strategies matter because they determine how history looks. Fast-forward keeps it linear, three-way preserves topology — the right choice depends on whether you want a record of parallel work or a clean narrative. Understanding these trade-offs lets you shape your project history intentionally rather than by accident.
Category
Related Posts
Rebase vs Merge: When to Use Each in Git
Decision framework for choosing between git rebase and git merge. Understand trade-offs, team conventions, history implications, and production best practices.
Git Remote Management: Adding, Removing, and Configuring Remotes
Master git remote operations — adding, removing, renaming remotes, managing multiple remotes, and configuring remote URLs for effective collaboration.
Pull Requests and Code Review: Git Collaboration Best Practices
Master pull request workflows and code review — writing effective PR descriptions, review best practices, collaboration patterns, and team workflows.