Q22 of 40 · Git

How does `--force-with-lease` protect against overwriting a colleague's work, and when can it still fail?

GitMidgitforce-with-leaseforce-pushsafetyremote

Short answer

Short answer: `--force-with-lease` compares your local remote-tracking ref (origin/branch) against the actual remote tip before pushing. If they differ (someone pushed since your last fetch), the push is rejected. It can still fail if you fetched recently without noticing new commits.

Detail

A plain git push --force tells the remote "replace whatever is there with what I have" — no questions asked. If a teammate pushed commits since you last fetched, those commits are silently overwritten.

--force-with-lease adds a precondition: "only force-push if the remote tip matches what my local remote-tracking ref (origin/branch) remembers it being." If someone pushed commits in between, the remote tip will be ahead of your remote-tracking ref, and Git rejects the push with an error.

The gap: the protection relies on your remote-tracking ref being current. If you ran git fetch (or git pull --rebase) just before the push, your remote-tracking ref is fresh. But if your CI or IDE auto-fetched in the background and updated the remote-tracking ref, your local cache now reflects the new tip — and --force-with-lease will no longer protect you against those commits (you "know" about them even if you haven't integrated them). This is the documented caveat.

--force-if-includes (Git 2.30+) was introduced to close this gap: it verifies that the commits on the remote tip are actually reachable from your local history, not just that the ref pointer matches. Combining --force-with-lease --force-if-includes gives the strongest safety guarantee.

// EXAMPLE

# Safe force-push after interactive rebase
git rebase -i HEAD~3
git push --force-with-lease origin feature/order-tests

# Rejected output (teammate pushed after your last fetch):
# ! [rejected]  feature/order-tests -> feature/order-tests
#   (stale info)

# Fetch first, inspect, then re-rebase and retry
git fetch origin
git log HEAD..origin/feature/order-tests  # see what they pushed
git rebase origin/feature/order-tests     # incorporate their work
git push --force-with-lease origin feature/order-tests

# Strongest safety: lease + force-if-includes (Git 2.30+)
git push --force-with-lease --force-if-includes origin feature/order-tests

// WHAT INTERVIEWERS LOOK FOR

The mechanism: comparing local remote-tracking ref against actual remote tip. The gap when background fetch updates the ref. Knowing --force-if-includes closes that gap. This is a depth signal that separates mid from junior.

// COMMON PITFALL

Assuming --force-with-lease is completely safe and skipping the fetch-inspect-rebase cycle. The protection only works when your remote-tracking ref is stale, not when it's been silently updated.