๐ฅ๐ฎ๐ฐ๐ฒ ๐๐ผ๐ป๐ฑ๐ถ๐๐ถ๐ผ๐ป๐: ๐ง๐ต๐ฒ ๐๐ฎ๐๐ ๐๐ผ๐ผ๐ธ๐ถ๐ฒ
One cookie sits on a plate. You and your sibling see it. You both grab it at once.
Computers do this too. It is a race condition.
This bug happens when two tasks run at the same time. The result depends on who wins the race.
Example: Two people buy the last item in stock.
- Person A reads stock. It is 1.
- Person B reads stock. It is 1.
- Person A buys it. Stock becomes 0.
- Person B buys it. Stock becomes 0.
You shipped two items. You only had one.
The pattern is always the same. Read. Decide. Write.
There is a gap in the middle. Someone sneaks in.
Fix it by making the check and change one locked step. Let the database handle the subtraction.
Race conditions happen here:
- Selling the last ticket.
- Creating two accounts with one email.
- Like counters losing numbers.
Avoid these mistakes:
- Saying it works on your machine.
- Adding a sleep timer to fix it.
- Trusting a read from a moment ago.
Look for "read, check, write" in your code. Think about two users acting at the same millisecond. Do both win?
If yes, you found a race.
Source: https://dev.to/edriso/race-condition-when-two-things-reach-for-the-same-cookie-36do