Q28 of 40 · Git
A bad commit was merged to `main` and CI is broken. What are your options for undoing it, and which is safest?
Short answer
Short answer: Safest: `git revert <sha>` (or `git revert -m 1 <merge-sha>`) to create an undo commit — no history rewrite, safe for shared branches. Nuclear option: `git reset --hard` + force-push — only if the team is notified and no one else has pulled.
Detail
When a bad commit lands on main, you have two broad strategies: additive undo (revert) and destructive undo (reset + force-push). The safest choice is almost always revert.
git revert <sha>: creates a new commit that is the exact inverse of the bad commit. History is preserved, collaborators' clones are unaffected, and CI re-runs on the clean revert commit. If the bad change was merged as a merge commit, use git revert -m 1 <merge-sha> where -m 1 means "keep parent 1" (the main branch before the merge).
git reset --hard + force-push: moves main back to before the bad commit and force-pushes. Anyone who has already pulled the bad commit will have diverged history and will need to run git reset --hard origin/main to recover — data loss risk if they had local work. Only viable if the team is tiny, everyone is warned, and the commit was pushed seconds ago.
Revert of a revert: if you later want the feature back, you revert the revert commit. This is a well-known Git workflow.
Hotfix deploy cycle: after reverting, tag the revert commit, trigger a new CI/CD run, and deploy. Then open a new PR to re-introduce the feature with the bug fixed — don't just un-revert without fixing the root cause.
// EXAMPLE
# --- Option 1: Revert (safe for shared main) ---
# Revert a single bad commit
git switch main
git pull --rebase
git revert a1b2c3d4
git push origin main
# Revert a merge commit ('-m 1' keeps the main-branch parent)
git revert -m 1 badMergeCommitSha
git push origin main
# --- Option 2: Reset + force-push (team must be warned!) ---
# Find the last good commit
git log --oneline -10
# Move main back (local)
git reset --hard lastGoodCommitSha
# Verify
git log --oneline -3
# Force-push (DESTRUCTIVE — coordinate with team first)
git push --force-with-lease origin main
# Teammates recover with:
git fetch origin
git reset --hard origin/main// WHAT INTERVIEWERS LOOK FOR
// COMMON PITFALL
// Related questions
What is the difference between `git revert` and `git reset`, and when should you use each?
Git
A teammate accidentally force-pushed to `main` and lost 3 commits that were never backed up. How do you recover them?
Git
Explain `git reflog` — what it records, for how long, and walk through a scenario where it saves a QA engineer's work.
Git