Advanced 12 min

Concurrency and race conditions

Concurrency means multiple operations can be in progress at the same time.

How it works

Draw the two orders on separate lines and mark when each reads the remaining stock. If both reads happen first, neither sees the other order’s change. Protect the decision that checks and reserves stock as one operation, so someone arriving later can observe the reservation.

Walk through an example

Two operations can both read a value before either writes. If each calculates a new value from that same old version, one write may overwrite the other.

What to watch for

Identify the whole read–modify–write decision that must be protected. Synchronizing only the final write may still let both decisions use stale data.

Check your understanding

What risk does the program face?

See the example and explanation
Worked example
Given Stock is 1. Two orders independently read 1 before either decrements.
Answer Both orders may be accepted for the same item.

Both decisions were based on the same stock value. The check and update need a coordinated boundary.

Open practice problem
Next lessonBackground jobs and retries