A race condition occurs when two or more threads, processes or requests access shared data at the same time and the outcome depends on which one gets there first. The code is correct in each ordering you tested but wrong in another.
Why it matters
Race conditions are hard to reproduce because they appear only under particular timing, often under load in production. They cause lost updates, duplicate orders, double charges and corrupted data. Fixes include locks, atomic operations, database transactions and unique constraints.
Example
Two requests buy the last item at the same time:
Request A: read stock = 1
Request B: read stock = 1
Request A: write stock = 0 (order OK)
Request B: write stock = 0 (order OK)
Both succeeded, so one item was sold twice. An atomic statement such as UPDATE items SET stock = stock - 1 WHERE id = 7 AND stock > 0 avoids it.
Common mistakes
- Testing only one request at a time, so the bug never shows up.
- Using a check-then-act sequence, such as "if no row exists, insert one", without a lock or unique constraint.
- Adding sleeps to hide the problem instead of fixing the shared-state access.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.