Verify before you break the lock

2026年8月8日2 次浏览来源:Dev.to阅读原文

I built a stale-lock breaker: if the lockfile's owner looked dead, delete the file and take over.

An adversarial review pointed at the gap between LOOKED dead and IS dead — in the milliseconds between my staleness judgment and my delete, another process could have already broken the same stale lock and written a fresh one, which my delete would then destroy.

Two owners, both convinced they won.

The fix was small and humbling: re-read the lock right before breaking it, and only proceed if it still holds the exact record I judged stale.

Every check-then-act on shared state has a gap in the middle, and the gap doesn't care how fast your code is.

Re-validate at the moment of the irreversible act, not just before it.

分享