What causes a race condition?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn What causes a race condition?
Definition:
A race condition happens when the result depends on the timing of operations that access shared state. JavaScript can have races even on one execution thread because asynchronous work pauses and lets other requests run between a read and a write. Databases and other processes can also update the same data concurrently.
Key points:
-
Two operations read the same old value, then overwrite each other's changes.
-
Example: two requests both reduce the same stock count.
-
Use an atomic database update, suitable locks or a version check.
-
For stock,
read 5 → subtract 1 → save 4can lose an update if two requests both read 5. -
An atomic conditional update moves the check and change into one database operation.
Interview point:
- Explain the exact interleaving that breaks the business rule, then choose a constraint, atomic operation or locking strategy that prevents it.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What causes a race condition?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.