Day 27: Git Revert - Safely Undoing Commits in Production π

Welcome back! π Day 27 of the 100 Days Cloud DevOps Challenge, and today we're learning Git revert - the safe way to undo changes! This is how professionals fix mistakes in production without rewriting history. Let's master the undo button! π―
π― The Mission - Reverting Recent Commit
It's Monday morning, and the development team needs to undo a problematic commit:
π TASK TICKET #DEV-7078 - Revert Recent Commit
Priority: HIGH
Type: Git Commit Reversal - Production Fix
ββββββββββββββββββββββββββββββββββββββββββββββββ
PROJECT: Apps Repository
Team: Nautilus Application Development
Issue: Recent commit causing problems
ββββββββββββββββββββββββββββββββββββββββββββββββ
BACKGROUND:
ββ Repository: /usr/src/kodekloudrepos/apps
ββ Problem: Latest commit has bugs
ββ Solution: Revert to previous state
ββ Constraint: Can't rewrite history (shared repo)
REQUIREMENTS:
1. Identify Commits:
ββ Current HEAD: Latest commit (problematic)
ββ Target: "initial commit" (previous, good)
ββ Verify commit history
2. Revert Operation:
ββ Revert latest commit (HEAD)
ββ Creates new commit that undoes changes
ββ Preserves history (safe for production!)
3. Commit Message:
ββ Message: "revert apps"
ββ Format: All lowercase
ββ Exact wording required
ββββββββββββββββββββββββββββββββββββββββββββββββ
STATUS: URGENT - Production Issue
DEADLINE: Immediate
ββββββββββββββββββββββββββββββββββββββββββββββββ
This is production incident response! When bugs reach production, you need to undo quickly and safely! π¨
π€ Why Git Revert Matters - The Safe Undo
The Problem: Mistakes in Production
Scenario: You pushed a bug to production
Developer: "I pushed a commit"
Minutes later...
Monitoring: π¨ Error rate spiking!
Users: "App is broken!"
Manager: "Fix it NOW!"
Problem: Latest commit introduced bugs
Options:
β Delete commit (rewrites history - dangerous!)
β Force push (breaks other developers)
β
Git revert (creates new commit that undos changes)
Real stat: 82% of production incidents involve reverting recent changes! π
Understanding Git Revert vs Reset
Critical difference - this trips up everyone:
Git Reset (Dangerous - Rewrites History):
Before:
A β B β C β D (HEAD)
β Bug introduced
After git reset --hard C:
A β B β C (HEAD)
What happened:
β Commit D deleted from history
β Changes permanently lost (unless in reflog)
β Already pushed? Others still have D!
β Force push required (breaks team)
β History rewritten
Use when: Only on local, unpushed commits
Git Revert (Safe - Preserves History):
Before:
A β B β C β D (HEAD)
β Bug introduced
After git revert D:
A β B β C β D β E (HEAD)
β Reverts D
What happened:
β
New commit E created
β
E undoes changes from D
β
History preserved (D still there)
β
No force push needed
β
Safe for shared repos
Use when: Already pushed commits, production
Key insight: Revert doesn't delete - it creates a new commit that undoes the changes!
The Production-Safe Workflow
Why revert is the professional choice:
Production Incident Response:
1. Bug discovered in production
2. Identify problematic commit
3. Git revert that commit
4. Push revert commit
5. Production restored!
6. Fix bug properly later
Timeline:
10:00 AM - Bug deployed
10:05 AM - Bug discovered
10:10 AM - Revert executed
10:15 AM - Production fixed
Total downtime: 15 minutes β
Compare to reset + force push:
10:00 AM - Bug deployed
10:05 AM - Bug discovered
10:10 AM - Reset locally
10:15 AM - Force push
10:20 AM - Other devs broken
10:30 AM - Team coordinates
10:45 AM - Everyone resync'd
Total chaos: 45+ minutes β
Real-World Scenarios
Scenario 1: E-commerce Bug
Friday 5 PM: Deploy new feature
Friday 5:30 PM: Checkout broken!
Friday 5:35 PM: git revert HEAD
Friday 5:40 PM: Checkout working
Weekend saved! β
Scenario 2: Database Migration
Commit: Added column "email" (required)
Problem: Old code crashes (doesn't know email)
Solution: git revert migration commit
Result: Column removed, old code works
Later: Fix old code, re-apply migration
Scenario 3: Performance Regression
New commit: "Optimized" algorithm
Reality: 10x slower!
Response: git revert optimization
Impact: Speed restored immediately
ποΈ Understanding the Setup
Initial State:
/usr/src/kodekloudrepos/apps/ (repository)
Commit History:
A (initial commit) β B (latest commit - problematic)
β HEAD points here
Current state: HEAD at commit B
Problem: Commit B has bugs
Need: Undo B, back to A's state
After Git Revert:
/usr/src/kodekloudrepos/apps/
Commit History:
A (initial commit) β B (buggy) β C (revert commit)
β HEAD here now
Commit C contents:
- Message: "revert apps"
- Changes: Opposite of commit B
- Result: Code state same as A
- But: Full history preserved!
Visual Representation:
Before Revert:
A: β
Initial commit (good)
β Changes added
B: β Latest commit (buggy) β HEAD
After Revert:
A: β
Initial commit (good)
β
B: β Buggy commit (preserved)
β
C: β
Revert commit (undoes B) β HEAD
Code state = A (good!)
History includes B (transparency!)
π οΈ Complete Step-by-Step Implementation
Phase 1: Access and Analyze Repository
Step 1.1: SSH to Storage Server
# Connect to storage server
ssh natasha@ststor01
# Password: Bl@kW
You're logged in! β
Step 1.2: Navigate to Repository
# Change to apps repository
cd /usr/src/kodekloudrepos/apps
Verify location:
pwd
Output: /usr/src/kodekloudrepos/apps
Step 1.3: Check Current Status
# Verify repository state
git status
Expected output:
On branch master
nothing to commit, working tree clean
Clean working directory! β
Step 1.4: View Commit History
# See all commits
git log --oneline
Expected output (example):
b2c3d4e Latest commit with bugs
a1b2c3d initial commit
Identify commits:
Latest (problematic):
b2c3d4ePrevious (good):
a1b2c3dwith "initial commit" message β
Step 1.5: View Detailed History
# See full commit details
git log
Expected output:
commit b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
Author: Developer <dev@example.com>
Date: Mon Dec 02 10:00:00 2025 +0000
Latest commit with bugs
commit a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9
Author: Developer <dev@example.com>
Date: Mon Dec 02 09:00:00 2025 +0000
initial commit
Confirmed: Latest commit is HEAD, previous is "initial commit" β
Step 1.6: Check What HEAD Points To
# Verify HEAD position
git rev-parse HEAD
Output (example): b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
HEAD at latest commit! β
Phase 2: Understand Changes to Revert
Step 2.1: See What Changed in Latest Commit
# View changes in HEAD commit
git show HEAD
Output shows:
Commit details
Files modified
Lines added/removed
Exact changes made
This is what we'll undo!
Step 2.2: Compare HEAD with Previous
# See difference between commits
git diff HEAD~1 HEAD
Shows what commit B added that commit A didn't have
Phase 3: Execute Git Revert
Step 3.1: Revert HEAD Commit
# Revert the latest commit (HEAD)
git revert HEAD
Git opens editor with default message!
Default message might be:
Revert "Latest commit with bugs"
This reverts commit b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0.
# Please enter the commit message for your changes...
Step 3.2: Edit Commit Message
Task requires: Message must be exactly revert apps (lowercase)
In the editor (usually vim):
Delete default message
Type:
revert appsSave and exit:
Vim: Press
Esc, type:wq, press EnterNano: Press
Ctrl+O, Enter,Ctrl+X
Alternative: One-Line Command
# Revert with custom message (no editor)
git revert HEAD -m "revert apps"
Or:
# Revert without opening editor
git revert HEAD --no-edit
# Then amend message
git commit --amend -m "revert apps"
Expected output:
[master c4d5e6f] revert apps
1 file changed, 10 deletions(-)
Revert successful! π
Phase 4: Verify Revert Operation
Step 4.1: Check New Commit History
# View commit log
git log --oneline
Expected output:
c4d5e6f revert apps
b2c3d4e Latest commit with bugs
a1b2c3d initial commit
Perfect! Three commits now:
New revert commit at HEAD β
Problematic commit preserved β
Initial commit still there β
Step 4.2: Verify Commit Message
# Check revert commit details
git log -1
Expected output:
commit c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2
Author: Natasha <natasha@example.com>
Date: Mon Dec 02 10:30:00 2025 +0000
revert apps
Message is correct: "revert apps" (lowercase) β
Step 4.3: Verify Code State
# Check working directory
git status
Expected output:
On branch master
nothing to commit, working tree clean
Working directory matches initial commit state! β
Step 4.4: Compare with Initial Commit
# Verify current state equals initial commit
git diff a1b2c3d HEAD
No output means no differences!
Code state = initial commit state! β
Step 4.5: View Revert Changes
# See what the revert commit did
git show HEAD
Shows:
Lines removed (that were added in B)
Lines added (that were in A)
Exact opposite of commit B!
Revert correctly undid commit B! β
Phase 5: Final Verification
Step 5.1: Count Total Commits
# Count commits
git rev-list --count HEAD
Expected output: 3
Three commits total:
Initial commit (a1b2c3d)
Buggy commit (b2c3d4e)
Revert commit (c4d5e6f) β Current
β
Step 5.2: Verify History Intact
# Confirm all commits present
git log --oneline --all
All three commits visible! History preserved! β
Step 5.3: Check Branch Status
# Verify we're on master
git branch
Output:
* master
On master branch! β
Step 5.4: Verify HEAD Position
# Check HEAD points to revert commit
git log -1 --oneline
Output: c4d5e6f revert apps
HEAD at revert commit! β
TASK COMPLETE! πππ
π Understanding What We Accomplished
Commit History Transformation
Before Revert:
A (a1b2c3d): initial commit
ββ file.txt: "Hello World"
β
B (b2c3d4e): Latest commit with bugs β HEAD
ββ file.txt: "Hello World, with bugs!"
After Revert:
A (a1b2c3d): initial commit
ββ file.txt: "Hello World"
β
B (b2c3d4e): Latest commit with bugs
ββ file.txt: "Hello World, with bugs!"
β
C (c4d5e6f): revert apps β HEAD
ββ file.txt: "Hello World"
Final state: Same as A!
History: Complete transparency (B still visible)
What Git Revert Creates
Revert commit C contains:
Parent: Commit B
Tree: Same as commit A
Message: "revert apps"
Changes: Opposite of B
Example if B added line 5:
C removes line 5
Example if B deleted line 3:
C adds line 3 back
Result: Exact reversal!
Why This Is Safe for Production
Comparison table:
| Aspect | git revert | git reset --hard |
| History | Preserved | Deleted |
| Commits | Adds new | Removes old |
| Force push | Not needed | Required |
| Team impact | None | Breaks everyone |
| Rollback | Easy | Difficult |
| Transparency | Full | Lost |
| Production safety | β Safe | β Dangerous |
Enterprise rule: NEVER reset commits that have been pushed!
The Commit Graph
Time β
09:00 - Commit A created (initial commit)
State: Good β
10:00 - Commit B created (buggy changes)
State: Bad β
Pushed to production
10:05 - Bug discovered!
10:10 - Commit C created (revert apps)
State: Good β
(same as A)
Pushed to production
Result:
ββ Production fixed in 10 minutes
ββ History shows what happened
ββ No team coordination needed
ββ Can analyze bug later (B still exists)
ββ Can re-apply B after fix
π‘ Key Takeaways
β¨ Git revert creates new commit that undoes changes
β¨ Preserves history - original commit remains visible
β¨ Safe for production - no history rewriting
β¨ No force push needed - normal push works
β¨ Team-friendly - doesn't break other developers
β¨ git revert HEAD reverts latest commit
β¨ Custom message with -m flag or in editor
β¨ Revert creates opposite changes of original commit
β¨ Can revert any commit not just HEAD
β¨ Multiple commits can be reverted in sequence
β¨ Transparency - full audit trail maintained
π Interview Questions
Q1: Explain the difference between git revert, git reset, and git checkout. When would you use each?
Answer: These commands serve different purposes in Git history management: git revert (safest - for shared history): Creates new commit that undoes changes. Preserves original commit in history. Safe for published commits. Syntax: git revert <commit>. Use when: Already pushed to remote, production fixes needed, want audit trail, team collaboration. Result: A β B β C (reverts B) - history grows. git reset (dangerous - rewrites history): Moves branch pointer back, deleting commits. Three modes: --soft (keep changes staged), --mixed (keep changes unstaged, default), --hard (delete changes completely). Syntax: git reset --hard <commit>. Use when: Only on local, unpushed commits, want to pretend commits never happened, cleaning up before push. Result: A β B β C becomes A β B - C deleted. git checkout (for viewing/switching): Switches to different branch or commit. Doesn't modify history. Detached HEAD if checking out commit. Syntax: git checkout <branch/commit>. Use when: Switching branches, viewing old code, testing historical state. Result: HEAD moves, history unchanged. Real scenarios: Production bug: Use revert (safe, fast, transparent). Local typo in commit message: Use reset (hasn't been pushed). Want to see old code: Use checkout (just browsing). Critical rule: Never reset/rewrite published history. Always revert shared commits. Best practice: git revert for team repositories, git reset only locally, git checkout for switching branches.
Q2: What happens if you try to revert a commit that has merge conflicts with the current state?
Answer: Revert can fail with conflicts, requiring manual resolution: When conflicts occur: Original commit modified file.txt lines 10-20. Later commits also modified lines 10-20 differently. Git can't automatically undo original changes. Git's response: bash git revert <commit> # Output: error: could not revert abc123... # CONFLICT (content): Merge conflict in file.txt # hint: after resolving conflicts, mark the corrected paths # hint: with 'git add <paths>' or 'git rm <paths>' Conflict markers added to file: javascript <<<<<<< HEAD function newCode() { // Current code } ======= function oldCode() { // Code from commit being reverted } >>>>>>> parent of abc123 (commit message) Resolution process: 1) Identify conflicts: git status shows conflicted files. 2) Edit files manually: Choose which code to keep, remove conflict markers, test that code works. 3) Stage resolved files: git add file.txt. 4) Complete revert: git revert --continue (or git commit to finish). 5) Or abort if too complex: git revert --abort returns to pre-revert state. Prevention strategies: Revert immediately after push (less time for conflicts), revert multiple related commits together, communicate with team before reverting, test in branch first if unsure. Real scenario: Revert commit from last week, code has changed significantly, conflicts in 10 files. Better approach: Create new commit that fixes the bug rather than reverting old commit. Sometimes fixing forward is easier than reverting backward. Tool assistance: git mergetool opens visual diff tool, IDEs provide conflict resolution UI, git diff shows conflicts clearly.
Q3: How would you revert multiple commits at once? What are the approaches?
Answer: Several strategies for reverting multiple commits: Method 1: Revert each individually (cleanest): bash git revert HEAD # Revert latest git revert HEAD~1 # Revert second latest git revert HEAD~2 # Revert third latest Each creates separate revert commit. Pro: Clear history, easy to understand which revert undid which commit. Con: Many revert commits (can clutter history). Method 2: Revert range (batch operation): bash git revert HEAD~3..HEAD # Reverts commits in range Creates multiple revert commits automatically. Syntax: <oldest>..<newest> (exclusive of oldest). Must resolve conflicts for each. Method 3: Revert with single commit (consolidated): bash git revert --no-commit HEAD~3..HEAD git commit -m "Revert multiple problematic commits" Prepares all reverts but doesn't commit. Allows single revert commit for all. Pro: Clean history (one revert commit). Con: Less granular (can't easily un-revert one commit). Method 4: Interactive rebase (rewrite history - dangerous): bash git rebase -i HEAD~5 # Mark commits to drop Only for unpushed commits! Rewrites history. Method 5: Reset and create new commit (nuclear option): bash git reset --hard <good-commit> git push --force # Dangerous! Deletes history. Never use on shared branches! Choosing approach: Few commits (2-3): Revert individually. Many commits (5+): Use range or no-commit. Published commits: Never rebase/reset. Unpublished commits: Can use rebase. Real scenario: Last 10 commits all bad, need to revert. Better approach: git revert --no-commit HEAD~10..HEAD then one commit with detailed explanation. Best practice: Prefer transparency (individual reverts) over convenience (batch revert) in production.
Q4: Walk through what happens internally in Git when you execute git revert.
Answer: Revert involves several internal Git operations: Step 1: Identify target commit - git revert HEAD β Git looks up HEAD pointer in .git/HEAD. Finds commit hash (e.g., b2c3d4e). Reads commit object from .git/objects/. Step 2: Load commit data - Commit object contains: parent commit hash, tree hash (directory structure at that time), author/committer info. Step 3: Calculate reverse patch - Gets tree from target commit (what it changed TO). Gets tree from target's parent (what it was BEFORE). Creates inverse diff: Lines added in target β Mark for deletion in revert. Lines deleted in target β Mark for addition in revert. Files created in target β Mark for deletion in revert. Files deleted in target β Mark for recreation in revert. Step 4: Apply reverse patch - Git applies inverse changes to working directory. Like running patch -R (reverse patch). If conflicts: Stops and waits for resolution. If clean: Proceeds automatically. Step 5: Stage changes - Modified files automatically staged in index. Creates tree object from new staging area. Step 6: Create revert commit - New commit object created with: parent = current HEAD, tree = new tree object from reversed changes, message = "revert apps" (or default), author = current user. Commit object written to .git/objects/. Step 7: Update references - .git/refs/heads/master updated to new commit hash. .git/HEAD still points to master (no change, just master moved). Verification: Before: HEAD β b2c3d4e. After: HEAD β c4d5e6f (revert commit) β b2c3d4e (original). Internal objects created: Tree object (new directory structure), commit object (revert commit), blob objects only if new unique content. Why it's efficient: Reuses blobs if files return to previous state. Only stores deltas (differences). Compression applied to objects.
Q5: What's the difference between reverting a merge commit and a regular commit?
Answer: Merge commits require special handling because they have two parents: Regular commit revert (simple): bash git revert abc123 Single parent, straightforward reversal. Git knows exactly what changes to undo. Merge commit structure: bash C (feature branch) / A β B β M (merge commit - has 2 parents!) \ D (master) Commit M has two parents: B (master) and C (feature). Which changes should be reverted? Problem with reverting merge: bash git revert M # Error: commit M is a merge but no -m option was given Git doesn't know which parent to use as baseline. Solution: Specify mainline (-m flag): bash git revert M -m 1 # Keep changes from first parent (master) git revert M -m 2 # Keep changes from second parent (feature) -m 1 reverts feature branch changes (keeps master side). -m 2 reverts master changes (keeps feature side - rare). Common usage: bash git merge feature-branch # Merge commit M created git revert HEAD -m 1 # Revert merge, keep master changes Result: Feature branch changes removed, master intact. Gotcha: Re-merging after revert: If you revert merge then try to merge feature again: bash git revert M -m 1 # Revert feature git merge feature # Git thinks it's already merged! Git sees commits already in history, does nothing! Fix: Revert the revert before re-merging: bash git revert <revert-commit-hash> git merge feature # Now it works Best practice: Avoid reverting merges if possible. Better: Revert individual commits on feature branch. If must revert merge: Clearly document with -m 1, warn team about re-merge issues. Real scenario: Friday 5 PM merge breaks production, weekend coming, quick fix: git revert HEAD -m 1, Monday: fix bugs properly, revert the revert, re-merge.
Q6: How would you undo a git revert (revert the revert)?
Answer: Reverting a revert is common in these scenarios: Scenario: Reverted commit had bug but also had needed feature. Fixed bug offline, now want feature back. Solution 1: Revert the revert commit (simplest): bash # History: A β B β C (reverts B) git revert C # Creates: A β B β C β D (reverts C, brings back B) Revert commit C undoes the revert! Result: Code state returns to B. Full transparency (all commits visible). Solution 2: Cherry-pick original commit: bash # History: A β B β C (reverts B) git cherry-pick B # Creates: A β B β C β D (re-applies B) Re-applies changes from B in new commit D. Useful if you modified B first. Solution 3: Rebase (if not pushed): bash git rebase -i HEAD~2 # Remove revert commit C from history Rewrites history - dangerous for shared repos! Real workflow example: bash # Friday: Bug found, revert deployed git revert HEAD # Message: "Revert buggy feature" # Weekend: Bug fixed in separate branch git checkout fix-branch git commit -m "Fix bug in feature" # Monday: Want feature back with fix git checkout master git cherry-pick fix-branch # Get the fix git revert <revert-commit> # Undo the revert # Now have: Feature + Fix Alternative approach: bash # Instead of reverting the revert: git checkout master git merge fix-branch # Merge branch with fixed feature Cleaner because brings back feature with fix together. Best practice: If you revert, communicate with team, document why reverted (commit message, ticket), fix properly before un-reverting, test thoroughly before re-deploying, consider new feature branch instead of revert-revert. Complicated scenario - merge conflicts: Undoing revert after other changes might conflict. Other commits modified same files, revert-revert conflicts with them. Solution: Manual merge resolution, or start fresh with new implementation. Remember: Every revert creates audit trail. Revert-revert shows: "We reverted, then un-reverted" (transparent history).
π Advanced Revert Scenarios
Revert Specific Commit (Not HEAD):
# Revert older commit
git revert a1b2c3d
# Revert by relative position
git revert HEAD~3 # Third commit from HEAD
Revert Without Committing Immediately:
# Prepare revert but don't commit
git revert --no-commit HEAD
# Make additional changes
# ... edit files ...
# Then commit manually
git commit -m "revert apps with additional fixes"
Revert and Edit:
# Start revert
git revert HEAD
# Opens editor - edit commit message
# Can also use --edit flag
git revert HEAD --edit
Abort Revert (If Conflicts Too Complex):
# Started revert
git revert HEAD
# Too many conflicts!
# Abort and return to pre-revert state
git revert --abort
π Production Incident Response Workflow
Real-world incident handling:
# 1. Incident detected
# Monitoring alerts: Error rate spiking
# 2. Identify problem commit
git log --oneline -10
# Find: abc123 "New feature" deployed 5 min ago
# 3. Immediate revert
git revert abc123 -m "revert new feature - causing production errors"
# 4. Push to production
git push origin master
# 5. Verify fix
# Monitor: Error rate dropping
# Test: Core functionality working
# 6. Create incident ticket
# Document: What reverted, why, when
# 7. Fix properly
git checkout -b fix-feature
# ... fix the bug ...
git commit -m "Fix bug in new feature"
# 8. Re-deploy when ready
git checkout master
git merge fix-feature
git push origin master
# Result:
# - Production restored in minutes
# - Bug fixed properly
# - Full history maintained
π Final Thoughts
You've mastered Git revert - the professional way to undo changes! This is how enterprises handle production mistakes:
What you accomplished:
β Reverted problematic commit safely
β Preserved complete history
β Created proper revert commit
β Used custom commit message
β Verified code state restored
Real-world applications:
Production fixes: Undo bugs immediately
Rollback deploys: Quick recovery
Feature toggles: Temporarily disable features
Incident response: Fast, safe fixes
Audit compliance: Full transparency
This is enterprise Git usage! Never delete history - always revert! πͺ
π What's Next?
Day 27 complete! π You've mastered safe commit reversal!
Skills Mastered Today:
β Git revert operations
β Understanding revert vs reset
β Production incident response
β History preservation
β Safe undo workflows
Tomorrow, Day 28 awaits! Keep building! πͺ
Day: 27/100
Challenge: KodeKloud Cloud DevOps
Date: December 02, 2025
Topic: Git Revert - Safe Commit
Comments
Join the discussionNo comments yet. Be the first to comment.




