Try it
Thirty requests each add one to a counter, all at the same moment. See how many the counter keeps.
POST /api/lab/raceReal serverNaive
Reads the number, waits a moment, then writes back that number plus one.
0
of 30 adds counted
Not run yet.
Atomic
Asks the database to add one, in a single step.
0
of 30 adds counted
Not run yet.
What just happened
The naive counter reads the number, adds one and writes it back. When thirty requests do that at the same moment, many of them read the same old number, say 4, and all write back 5. Every one of those adds but one is lost.
The atomic counter asks the database to add one in a single step. The database does the read and the write under a lock, so no add is lost.
The shared poke counter on the home page works the atomic way, which is why a crowd poking at once never loses a poke.
Where you've seen it
- Two people booking the last seat on a bus at the same moment
- Stock in an online sale that drops below zero