Race Conditions, Locks and Atomics
An online store runs a flash sale: 100 headphones at half price. Ten thousand people click "Buy" in the same second. When the dust settles, 104 orders were confirmed. The inventory code was tested, reviewed and correct for one buyer at a time. With many buyers at once, it sold four headphones that don't exist.
This is a race condition: the result depends on the timing of threads, and some timings give the wrong answer. It is the most common concurrency bug in LLD interviews, and it is the first thing your interviewer checks when they ask "what if two users do this at once?" This post looks at the two shapes races take, the two tools that fix them (locks and atomics), and a repeatable recipe for making any class in your design thread safe.
💡 Why this matters in an interview: almost every "make it thread safe" follow-up is a race in one of two shapes. If you can name the shape, point at the exact lines, and fix it with the smallest correct lock, you have answered the question.
What Makes a Race
A race needs three things at once:
- Shared state: two threads can reach the same object (an inventory map, an account, a counter).
- Mutation: at least one of them writes it.
- A multi-step operation: the code reads, decides and writes in several steps, and assumes nothing changes between them.
Remove any one and the race is gone. Each thread gets its own copy (no sharing), the object is immutable (no mutation), or the steps are made indivisible (atomic). Locks and atomics are tools for the third option, but keep the first two in mind: often the best fix is not to share.
Races are nasty because they are non-deterministic. The bad interleaving might happen once in a million calls. Unit tests with one thread never see it, and a test with many threads might pass a hundred times and fail on the hundred-and-first. That's why you reason about races on paper, line by line, rather than hope to catch them in testing.
Races come in two shapes. Learn to spot both.