My code runs correctly single-threaded, then breaks the moment it's concurrent
In one sentence: I may implement one sequential call correctly without protecting state shared by multiple executors; particular interleavings can lose updates or repeat side effects, beyond what single-threaded tests validate.
Symptomโ
I often see this delivery: you ask me to write a "+1 the like count on an article" endpoint, and I hand you code that reads as self-evident โ first SELECT likes FROM post, add one, then UPDATE post SET likes = ?. You click a few times, 1, 2, 3, exactly right, and you merge it.
Then on a big sale day, a hot post gets liked by thousands of people at once, and the final count ends up far below the real number of likes. No error, no crash, not a single anomalous log line โ the number just quietly went missing. Two requests both read likes=100, each compute 101, each write back 101, so two likes only bumped it once. The code I wrote is correct in this single-threaded example but loses updates under particular concurrent interleavings.
There's a whole string of similar cases: if (!file.exists()) create() where two processes both pass the check and both create; a "miss โ fetch from origin and write back" cache that, under high concurrency, fetches the same record from origin hundreds of times; an async callback that assumes A always completes before B, then intermittently B comes back first.
Why this happensโ
I may demonstrate the sequence for one call without identifying shared state and steps that can interleave. A smooth read-modify-write or check-then-act path is not atomic across executors.
Concurrency defects usually require particular interleavings; they are neither guaranteed on every run nor inherently impossible to reproduce. Barriers, controlled schedules, model checking, and fault injection can help reproduce them. The cited 2025 study found difficulties in its tested models and tasks, not a default concurrency of one in every current model.
Protection must match the invariant. An ordinary database transaction does not automatically provide the needed isolation. A single-threaded event loop can interleave at await points, and other processes may share the state. Atomic increments protect counter updates, not business-request deduplication.
Consequencesโ
- Data goes wrong quietly, and it's the hardest to track. Lost updates, undercounts, balances that don't reconcile โ no exception, no stack trace; by the time you reason back from the reconciliation gap, it's already a production incident.
- Intermittent and hard to reproduce reliably, with high investigation cost. It only appears under a specific interleaving; ordinary local reruns may miss it. Use controlled schedules or barriers to expose the relevant interleaving rather than assuming it cannot be reproduced.
- Deadlocks bring the service to a halt. Two executors each hold one lock and wait on the other's, requests pile up, threads exhaust โ harder to locate live than a single-point crash.
- Fixing it often means touching the data model. Adding a lock, a transaction, a unique constraint, or an optimistic-lock version number โ these are design-level decisions, and patching them in after concurrency surfaces costs far more rework than designing them in from the start.
What to do insteadโ
Don't let me treat the world as single-threaded โ tell me the concurrent scenario explicitly, force me to mark shared mutable state and critical sections, and say what synchronization nails them down.
- Give me a concurrency profile first. "How much concurrency will this code see? What shared state does it read/write (DB rows / cache / in-memory variables / files)? Will the same data be changed by several executors at once?" Do not rely on me to infer the concurrency profile; require explicit unknown assumptions.
- Have me mark critical sections before writing the implementation. "Before you start, point out which parts of this logic are shared mutable state, which operations must be atomic, and explain for each what guarantee you'll use (row lock / transaction / optimistic-lock version / CAS / distributed lock / idempotency key)." This step switches me from "completing sequential logic" to "explicitly reasoning about interleaving."
- Name common race patterns for me to self-check. read-modify-write (counters / balances that read before writing), check-then-act (check existence then create / check then deduct), cache stampede, ordering assumptions in async callbacks โ paste them in for me to go through one by one.
- Force it with concurrency tests, not single-threaded cases. Have me write a "N concurrent calls at once, then assert the total is correct" stress test; single-threaded cases do not cover interleavings, while stress tests provide evidence only for tested schedules.
- Prefer shared-nothing / immutable designs to shrink the race surface at the source. When a database atomic operation will do (
UPDATE ... SET likes = likes + 1), don't read-modify-write in the application layer; when each executor can touch only its own data, don't share; when an idempotent design makes repeated execution harmless, you don't need locks everywhere. This especially should be settled at the architecture stage.
(Like endpoint, eliminating the race at the source)
โ Application-layer read-modify-write:
SELECT likes FROM post WHERE id=? โ likes+1 โ UPDATE post SET likes=?
Two requests read the same likes at once, each +1 and write back, dropping one update
โ
Database atomic operation:
UPDATE post SET likes = likes + 1 WHERE id=?
Successfully committed atomic increments avoid lost read-modify-write updates; failed and duplicate requests still need error handling and idempotency
โ
If you must read before writing (e.g. with business validation), use optimistic locking:
UPDATE post SET likes=?, version=version+1 WHERE id=? AND version=?
A version mismatch requires rereading and bounded retries; external side effects need separate idempotency
Exampleโ
Before:
You: write an endpoint to +1 an article's likes
Me: (SELECT likes โ +1 โ UPDATE, entirely correct single-threaded, you merged it)
Big sale: thousands like the same post at once, final count far below the real number, no error
After:
You: write the like endpoint. Note this endpoint will see high concurrency, and likes is
shared state changed by many people at once. Mark the critical section and explain
what you'll use to guarantee atomicity, then write the implementation.
Me: (points out read-modify-write as the race point; gives option A database atomic increment,
option B optimistic-lock version number, and explains where each applies)
You: use the atomic increment. Then write a stress test with 1000 concurrent likes that
asserts the count equals 1000.
Me: (produces the atomic-increment implementation + a concurrency stress test, correct both
single-threaded and under high concurrency)
When the exception appliesโ
"Write for concurrency" isn't unconditional โ it presumes concurrency actually exists. In a few cases, "treat it as single-threaded" is exactly right:
- This code provably never runs concurrently: a CLI/build script with no asynchronous reentrancy and serial coverage of the relevant state, or logic completely serialized by suitable locks/queues โ a single process alone is insufficient, and adding locks or transactions defends against an opponent who isn't there.
- The state simply isn't shared: each request touches only its own stack-local variables, immutable functional data, or private actor state whose relevant operations cannot reenter asynchronously. Also exclude shared databases, files, and external services before omitting corresponding synchronization.
- A lower layer explicitly protects the required invariant: for example, a transaction covering the relevant state with suitable isolation, or a framework serializing all relevant operations. An ordinary transaction, a single thread, or an event loop alone is insufficient. Check await points, other processes, and external state before omitting synchronization.
The test: the exception holds when "no concurrency / no sharing" is a fact you've argued for (you can name why there's only one executor, or why the state isn't shared), not a default assumption of "I didn't think it'd be concurrent." The moment this code could be called by multiple executors at once and touch the same mutable state, fall back to the default: mark the critical section, add synchronization, verify with concurrency tests.
Version notesโ
Verified the concurrency study and PostgreSQL isolation documentation on 2026-10-29. Retained critical-section analysis and removed universal claims about models or inability to reproduce. Validate against the actual database, isolation level, and execution model. Stress tests provide evidence rather than proof over every interleaving; retries must be bounded and handle idempotency.