Core system concepts · Concept lesson
Concurrency
Understand overlapping work, shared mutable state, race conditions, coordination primitives, and the difference between concurrency and parallelism.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Distinguish concurrency from parallel execution.
- Identify race conditions and define invariants that synchronization must preserve.
- Choose coordination mechanisms and test behavior under contention.
How concurrent work behaves
Concurrency exists whenever operations overlap in time. A single processor can interleave them by switching tasks; multiple cores can execute them in parallel. Network services face concurrency even when application code is single-threaded, because requests, callbacks, database operations, and timers remain in flight together. The central challenge is shared state: two operations may read the same old value and both make a decision that was only safe if they ran alone. First define the invariant, such as “inventory never falls below zero” or “a counter includes every accepted event.” Then identify which reads and writes participate. A mutex can serialize access inside one process, an atomic operation can combine a narrow read-modify-write, and a database transaction can coordinate durable rows across processes. These tools have different scopes and failure behavior. Adding synchronization without stating the invariant often makes code slower while leaving the actual correctness gap untouched.
Reads shared state and attempts a state transition.
May overlap with Worker A and observe the same prior value.
Atomic update, constraint, lock, or transaction protects an invariant.
Durable value whose invariant must hold after both operations.
- Worker A → Coordination boundary: conditional operation
- Worker B → Coordination boundary: competing operation
- Coordination boundary → Shared state: valid state change
- Shared state → Worker A: success or conflict
- Shared state → Worker B: success or conflict
Worked example: competing reservations
Suppose inventory starts at 1 item. Two workers each read stock = 1, each check that stock is positive, and each writes stock = 0 while creating a reservation. The final counter says zero, but two reservations exist: the invariant is broken even though no arithmetic overflow occurred. If workers take 40 ms to read, decide, and write, a rough 50 operations/second per worker can overlap when requests arrive faster than 25 ms apart. A process-local mutex can protect a single in-memory map but does not coordinate two application instances. A database conditional update such as “decrement only where stock > 0” can make the test and mutation one atomic database operation; its affected-row count decides whether reservation succeeded. The unit is one item, the condition is stock ≥ 1, and the state change is −1. A transaction can then ensure the reservation record and decrement commit together. Load and contention tests must verify both the invariant and the latency cost.
Coordination alternatives
A mutex is straightforward for short in-process critical sections, but holding it across network I/O blocks unrelated work and a process crash loses its coordination. Read-copy-update or immutable snapshots can make read-heavy access cheaper, at the cost of copy or publication work. Atomic compare-and-swap is useful for simple state transitions but becomes difficult when several fields must change together. Database constraints and conditional writes are often the clearest option for durable shared state. Optimistic concurrency uses a version: read version 7, update only if it remains 7, and retry or report a conflict otherwise. Pessimistic row locks can serialize high-contention updates, but may increase waits and deadlock risk. Actor or single-writer designs reduce shared mutation by routing a key to one owner, yet require routing and failover semantics. Pick the narrowest coordination scope that protects the invariant and has an explicit behavior when the owner, lock holder, or store fails.
Failure and recovery
Concurrency bugs often appear as duplicate work, lost updates, deadlocks, starvation, or queues that grow under contention. A process crash releases an ordinary memory mutex, but it does not automatically repair a partially completed business operation. A distributed lock may expire while its holder is paused; the old holder can resume after a new holder acquired the lock. A lease is therefore not proof that stale work is harmless. Use fencing tokens or storage-side version checks so the resource rejects writes from older owners. For deadlocks, database systems may abort one transaction; the caller must retry the whole transaction only if it is safe and bounded. Avoid retry loops that hold scarce resources while waiting. Instrument lock wait time, transaction retries, queue age, and conflict rates. Recovery means restoring the invariant, reconciling any partial external effects, and proving that stale actors cannot overwrite newer state—not merely restarting a process.
When coordination is unnecessary
Do not add locks around immutable values, thread-confined state, or operations already isolated by a reliable atomic database constraint. Redundant coordination adds latency and can create deadlocks. Conversely, do not remove synchronization because a race has not appeared in a few tests; the schedule space is much larger than observed execution. A lock-free algorithm is rarely the right first choice for application business state: it can be harder to review and may still need memory-order reasoning. For naturally independent keys, partition ownership or per-key coordination may be preferable to one global mutex. If a value can be recomputed and stale results are acceptable for a defined interval, a lock may be avoidable. The decision depends on the consequence of violating the invariant, contention, and the boundary where shared state lives. Never assume a process-local primitive protects data accessed by another process or host.
Senior followups
Ask whether the correctness argument covers every operation interleaving, crashes, cancellation, and retries. Is the protected state local, database-backed, or shared across regions? Does lock acquisition have a bounded timeout, and what does a timeout mean to the caller? If an owner can pause past lease expiration, does a monotonically increasing fencing value reach the resource that accepts writes? Are lock scopes ordered consistently to reduce deadlocks? Could a queue or partitioned single-writer model remove contention while changing latency or availability? Review database isolation level and indexes, since a lock may cover more rows or last longer than expected. Examine tail wait time rather than only average lock time. Also check observability: race outcomes can be rare and destructive, so invariant checks, conflict metrics, audit trails, and deterministic concurrency tests have distinct roles. Senior decisions explain not just the chosen primitive but the scope and failure assumptions under which it is correct.
Operational practice
Write concurrency tests around invariants, not sleeps. Launch many workers behind a start barrier, have them compete for a small known quantity, then assert the final state and number of successful operations. Repeat with process boundaries when the shared store is distributed. Introduce controlled pauses between read and write to expose stale-read windows, and test cancellation and duplicate delivery where applicable. In production, track active operations, lock acquisition delay, conflict or serialization-abort rate, and queue depth by bounded labels. Protect diagnostic logs from leaking values while preserving transaction or trace identifiers. A rising wait metric may reveal a hot key or overly broad transaction. On-call action should reduce contention safely or route traffic away from a degraded dependency; manually deleting locks or resetting counters can violate invariants. After remediation, reconcile affected business records from authoritative state and retain evidence of the correction.
Terms in plain language
- Concurrency
- Multiple operations whose lifetimes overlap, whether or not they execute at the exact same instant.
- Race condition
- Behavior whose correctness depends on the timing or interleaving of concurrent operations.
- Critical section
- A region accessing shared state that requires coordination to preserve an invariant.
- Linearizability
- A correctness condition under which each operation appears to take effect at one instant between invocation and response.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Primary database documentation on multi-version concurrency control.
Primary language documentation explaining synchronization and visibility guarantees.