The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • Others
          • Indexing
      • Vendor-Specific Concepts
        • Oracle Specific
          • Rownum vs Rowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism and Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Distributed Tracing
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Low-Level Design (LLD)
      • Programming Paradigms
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Enhancements
        • Fluent API Design
          • Examples
    • High-Level Design (HLD)
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Architecture
        • Event Driven Architecture
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 1 - Maths theory & Pattern
          • Set 2 - Arrays
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • General Interview Preparation Tips - TBU
      • Flowchart - How to Solve Coding Problem?
  • Personal Projects
    • Hackathon
Powered by GitBook
On this page
  • About
  • How Rebase Works Internally ?
  • Practical Use Cases
  • 1. Keeping a Feature Branch Up to Date Without Polluting History
  • 2. Preparing Clean Commits Before a Pull Request or Merge Request
  • 3. Avoiding Merge Conflicts Later by Resolving Them Early
  • 4. Linear History for Bisecting and Debugging
  • 5. Integrating Upstream Changes in Forked Repositories
  • 6. Reordering Commits for Logical Clarity
  • 7. Dropping or Fixing Broken or Temporary Commits

Was this helpful?

  1. Git
  2. Workflows
  3. Merge Strategies

Rebase

About

Git rebase is a mechanism that reapplies commits on top of another base tip, allowing us to relocate changes in history as if they had been made at a different point in time.

It does not merge histories. Instead, it transplants the work we have done onto a new base — as if our changes were made starting from that point.

In other words, rebasing is a history-rewriting operation. It reconstructs our branch from a new point in the project’s timeline.

Git is a distributed version control system. Every commit has a pointer to its parent(s), forming a directed acyclic graph (DAG). When branches diverge and change, they can be brought together by:

  • Merging: Preserves both histories as-is, introducing a new “merge commit” that connects the timelines.

  • Rebasing: Discards the old base and replays changes from one branch onto a new one, making it look like they always began from there.

Imagine two people, Alice and Bob, working on a document.

  • Alice starts writing a new section based on version 1.

  • Bob, meanwhile, updates the document to version 2.

  • Now Alice’s section is “based on the old version.”

If Alice merges, the document shows two authors' efforts coming together — but with side notes of when and how they diverged.

If Alice rebases, she takes her section and rewrites it as if she had started writing on version 2 all along.

No history of divergence remains — just a smooth narrative.

How Rebase Works Internally ?

Rebase is a sequence of three steps:

  1. Identify the Fork Point Find the last common commit between the current branch and the target branch.

  2. Extract our Commits Take all commits after the fork point in our branch and treat them as patches.

  3. Replay on Top of New Base Apply each patch on top of the tip of the target branch in order.

This results in:

  • A new set of commits (with new hashes).

  • A linearized history with no merge commits.

This is fundamentally a history rewrite operation — not a content merge.

Never rebase a branch others have pulled from. Because rebasing changes commit hashes, it invalidates the original timeline. Everyone else’s branch becomes incompatible — they now refer to commits that “don’t exist.”

Force pushing a rebased branch can overwrite collaborators’ work unless coordinated properly.

Use rebase for private or feature branches where we control the timeline.

We are working in a Git repository with two branches:

A---B---C         (main)
     \
      D---E---F   (feature)
  • main branch: contains commits A → B → C

  • feature branch: was created from commit B, and has commits D → E → F

  • feature has diverged because new commits (C) have been added to main after feature was created.

What Happens During a Rebase ?

The command:

git checkout feature
git rebase main

tells Git:

"Take the commits from the feature branch that are not in main (i.e., D, E, F), and replay them on top of the latest commit in main (i.e., C)."

Step-by-Step Breakdown

  1. Git finds the common ancestor of main and feature, which is commit B.

  2. Git creates patches (internal changes) for each of the commits on feature after B: → patches for D, E, and F.

  3. Git checks out main (commit C), and applies those patches one by one on top of it.

  4. New commit hashes are generated for the rebased commits — Git doesn't reuse D, E, F; it creates new ones (let's say D', E', F').

Resulting History

After rebasing:

A---B---C---D'---E'---F'   (feature)
            ^
           (rebased)
  • feature now appears as if it was developed on top of the latest main.

  • History is linear — no merge commits.

  • Old commits D, E, F are no longer part of the branch history.

Equivalent Merge (for contrast)

Had we used:

git checkout feature
git merge main

We'd get:

A---B---------C              (main)
     \          \
      D---E---F---M      (feature)
  • M is a merge commit with two parents: C and F

  • We retain full context of both branches’ histories

  • History is non-linear, with more branching complexity

Practical Use Cases

1. Keeping a Feature Branch Up to Date Without Polluting History

Problem: We are working on a feature branch for several days or weeks. In the meantime, our main branch (usually main or develop) continues to evolve with other features or bug fixes from the team. We want to bring in those updates to avoid conflicts later, but we don’t want merge commits cluttering our history every time we sync.

Why Rebase Works Well: Rebasing allows us to replay our work on top of the latest state of main, as if our work had started from the current version of the codebase. This produces a clean, linear history.

Effect: Instead of introducing merge commits and branching noise, rebasing keeps our branch’s commit history aligned with the project’s ongoing state — as if we were always up-to-date.

## Use Case: Sync our feature branch (feature/login) with develop, keeping a linear history.

# Make sure we are on our feature branch
git checkout feature/login

# Rebase our branch on top of latest develop
git fetch origin
git rebase origin/develop

# If conflicts occur, Git will stop and ask us to resolve them. After resolving:
git add <conflicted-files>
git rebase --continue

# If we want to abort the rebase:
git rebase --abort

2. Preparing Clean Commits Before a Pull Request or Merge Request

Problem: During development, we often make multiple small, messy commits (fix typo, oops, refactor, add test, etc.). When preparing our branch for review, we want the commit history to be meaningful, concise, and structured.

Why Rebase Works Well: Using interactive rebase (git rebase -i), we can rewrite our history before it is pushed or shared. This allows us to:

  • Combine several commits into one (squash)

  • Edit commit messages to reflect real purpose

  • Drop irrelevant or temporary commits

Effect: A reviewer sees a clean sequence of commits, each with a clear purpose. It makes our work easier to review, audit, and understand. The history appears deliberate, not accidental.

## Use Case: Squash, reorder, or edit multiple commits for clarity before code review.

# Rebase interactively the last N commits (e.g., last 5 commits)
git rebase -i HEAD~5

# We will get an editor showing a list like:
pick 123abc Add user login form
pick 456def Fix typo
pick 789ghi Add validation

We can change pick to:

  • squash: combine commits

  • edit: modify commit contents

  • reword: change commit message

  • drop: remove commit

After saving, Git will apply changes step-by-step.

3. Avoiding Merge Conflicts Later by Resolving Them Early

Problem: When multiple branches change the same code, merge conflicts are inevitable. If we wait until the end of development to merge, conflicts might be large and hard to resolve because of accumulated differences.

Why Rebase Works Well: Rebasing early and often helps we resolve conflicts in small increments. By frequently rebasing onto the latest base branch, we continuously align with our team’s changes.

Effect: We deal with smaller, more understandable conflicts along the way, instead of a large, stressful merge crisis at the end of the development cycle.

## Use Case: Regularly pull in updates from base branch (e.g., main) to avoid big conflicts at the end.

git checkout feature/api-refactor
git fetch origin
git rebase origin/main

4. Linear History for Bisecting and Debugging

Problem: When bugs are found in production, using git bisect helps locate the exact commit where the bug was introduced. This tool relies on a clean commit history.

Why Rebase Works Well: With a linear history, each commit only introduces a specific logical change. This makes it easy to test each step and pinpoint the problematic one.

Effect: Debugging becomes much faster. Each commit becomes a reliable checkpoint in the evolution of our project.

## Use Case: A clean, sequential history makes git bisect easier and more effective.

# Keep rebasing our feature branch on top of main to maintain linearity
git checkout feature/data-cleanup
git fetch origin
git rebase origin/main

5. Integrating Upstream Changes in Forked Repositories

Problem: In open-source or team workflows, we may fork a repository and develop a feature over time. Meanwhile, the upstream repository continues to evolve. Eventually, we want to sync our work with upstream without introducing complex merge paths.

Why Rebase Works Well: Rebasing our fork or branch onto the updated upstream branch makes it look as if our changes were always made against the latest code — no unnecessary merge bubbles are introduced.

Effect: When we submit a pull request or merge request, our code appears naturally integrated into the project, and maintainers don't need to wade through unnecessary merge conflicts or unrelated commits.

## Use Case: We are contributing to an open-source repo. We forked it and want to rebase our changes on top of the latest upstream master.

# Add upstream repo if not done
git remote add upstream https://github.com/original/project.git

# Fetch updates from upstream
git fetch upstream

# Rebase our feature branch on top of upstream/main
git checkout feature/my-contribution
git rebase upstream/main

6. Reordering Commits for Logical Clarity

Problem: Sometimes the order of our commits doesn't match the logical flow of the code. We might have added a test before the implementation, or fixed a bug before writing the code that introduced it.

Why Rebase Works Well: With interactive rebase, we can reorder commits to match a logical, cause-and-effect sequence. This improves not just history readability, but also consistency in the project's timeline.

Effect: The commit history becomes a story: it can be read from top to bottom, and each change builds upon the previous one. This is invaluable for onboarding, documentation, and future debugging.

## Use Case: Reorder commits for clarity or to group similar changes together.
git rebase -i HEAD~6

In the editor, simply move lines up or down to reorder the commits. Git will replay them in that order.

7. Dropping or Fixing Broken or Temporary Commits

Problem: We committed something temporary (e.g., debug logs, experiment, forgotten print statements) and don’t want that in the final project history.

Why Rebase Works Well: Interactive rebase allows we to remove these commits (drop) or edit them in-place (edit) to fix issues without creating additional commits.

Effect: The history appears intentional and clean. There are no embarrassing or confusing commits left behind that need to be explained later.

## Use Case: We added a commit like Added console.log() or debug version — now we want to remove it.
git rebase -i HEAD~5

Then in editor:

pick 123abc Added feature
drop 456def Added debug logs
pick 789ghi Final cleanup

Save and Git will remove the dropped commit.

PreviousMergeNextSquash

Last updated 7 hours ago

Was this helpful?