Concurrency questions in a technical test rarely ask for definitions. They describe a system that misbehaves under load, such as a double-charged customer, an oversold event or a hung worker, and expect you to name the mechanism and the fix. To answer well, you need a precise vocabulary: which operations are atomic, what a lock actually guarantees, when a write becomes visible to another thread, and why a database row can still be overwritten inside a transaction. This guide covers the concepts behind strong answers. Each one comes with an invented scenario, a short runnable example and the traps that separate a mid-level answer from a senior one. The examples use Go, Java, TypeScript, Python and SQL because interviewers move between threads, event loops and databases, and the same race shows up in all of them.
Study order
If time is short, go in this order.
- Race conditions: check-then-act and read-modify-write
Every other topic is a fix for check-then-act or read-modify-write. Naming the race precisely is the first thing interviewers listen for.
- Database isolation levels, lost updates and row locks
Most production races in web backends happen in the database, and many engineers wrongly assume a transaction alone prevents them.
- Locks, critical sections and lock granularity
Locks are the default tool. You need to explain scope, granularity and what must stay out of a critical section.
- Idempotency keys and distributed locks
Senior roles expect you to handle retries and multiple instances, where in-process locks no longer help.
- Races in single-threaded async code
Node and asyncio questions are common, and the trap that single-threaded code still races catches many candidates.
- Optimistic concurrency with versions and ETags
Version checks and ETags come up in API and data-modelling questions as the alternative to holding locks.
- Deadlocks, livelocks and lock ordering
A classic follow-up once you introduce multiple locks. Lock ordering and retry with jitter are the expected answers.
- Memory visibility, volatile and happens-before
Separates mid from senior on JVM and Go roles. Know why volatile helps visibility but not atomicity.
- Atomic variables and compare-and-swap loops
Useful for counters and lock-free updates. Know CAS loops and where atomics stop composing.
Race conditions: check-then-act and read-modify-write
A race condition happens when the correctness of a result depends on the timing of operations that run concurrently. Most production races follow one of two shapes. Check-then-act: you read a condition, such as "seats available > 0", and then act on it, but another thread changes the state between the check and the act. Read-modify-write: you read a value, compute a new one and write it back, as in count++, and a concurrent writer's update is lost.
The fix is to make the whole compound operation atomic: no other thread can observe or modify the state halfway through. You can do that with a lock around both steps, with a single atomic instruction, or by pushing the operation into a store that executes it atomically, such as one conditional SQL UPDATE.
In an interview, name the shape of the race explicitly. Saying "this is a check-then-act on the seat count, so the check and the decrement must run under the same lock" is far stronger than saying "add synchronization". Note also that a data race (unsynchronized access to the same memory where at least one access is a write) is a narrower, language-level concept. You can have race conditions with no data race at all, for example across two database transactions.
Go
package main
import (
"fmt"
"sync"
"sync/atomic"
)
// SeatPool for the 120-seat Harbor Cinema screening room.
type SeatPool struct {
mu sync.Mutex
free int
}
// Reserve performs check-then-act under one lock, so it cannot oversell.
func (p *SeatPool) Reserve(n int) bool {
p.mu.Lock()
defer p.mu.Unlock()
if p.free < n {
return false
}
p.free -= n
return true
}
func main() {
pool := &SeatPool{free: 120}
var booked atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 200; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if pool.Reserve(1) {
booked.Add(1)
}
}()
}
wg.Wait()
fmt.Println(booked.Load(), pool.free) // 120 0
}200 concurrent buyers compete for 120 seats. Because the check and the decrement share a lock, exactly 120 succeed.
Traps
- Locking the check and the act separately. Two short critical sections are not one atomic operation, and the gap between them is exactly where the race lives.
- Assuming a race is fixed because it no longer reproduces locally. Races depend on timing, so use tools such as
go test -raceor stress tests instead of trusting one passing run. - Treating
x++ormap[key] = map[key] + 1as atomic. In most languages these compile to separate read, compute and write steps. - Protecting a field in one method but reading or writing it unguarded in another. Every access to shared mutable state needs the same synchronization.
Locks, critical sections and lock granularity
A mutex guarantees mutual exclusion: only one thread at a time runs the critical section it guards. In most memory models, releasing a lock also publishes your writes to the next thread that acquires it, so a lock gives you both atomicity and visibility. A read-write lock allows many concurrent readers but only one writer. It pays off only when reads clearly dominate and the critical sections are long enough to outweigh its extra bookkeeping.
Granularity is the main design decision. A single coarse lock is simple and easy to reason about, but it serialises all work. Fine-grained locks, such as one per shard or per key, increase throughput but bring more ways to deadlock and harder invariants that span several locks. A good default is to start coarse, measure contention, and only then split.
Keep critical sections short and never do slow, unbounded work inside them: no network calls, no disk I/O, no callbacks into unknown code. A lock held across a 300 ms HTTP request turns a CPU-bound service into one that processes about three requests per second per lock.
Java
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;
// Feature-flag cache for the Lumen dashboard: read thousands of times per second,
// refreshed once a minute.
public class FlagCache {
private final ReentrantReadWriteLock rw = new ReentrantReadWriteLock();
private Map<String, Boolean> flags = new HashMap<>();
public boolean isEnabled(String name) {
rw.readLock().lock();
try {
return flags.getOrDefault(name, false);
} finally {
rw.readLock().unlock();
}
}
// Build the new map outside the lock; hold the write lock only for the swap.
public void refresh(Map<String, Boolean> fresh) {
Map<String, Boolean> copy = new HashMap<>(fresh);
rw.writeLock().lock();
try {
flags = copy;
} finally {
rw.writeLock().unlock();
}
}
public static void main(String[] args) {
FlagCache cache = new FlagCache();
cache.refresh(Map.of("new-billing-page", true));
System.out.println(cache.isEnabled("new-billing-page")); // true
System.out.println(cache.isEnabled("dark-mode")); // false
}
}Expensive work happens outside the lock, and the critical section is a single reference swap. Unlock always sits in a finally block.
Traps
- Forgetting to release a lock on an exception path. Use try/finally, defer or a scoped guard every time.
- Holding a lock while calling external services, logging to a slow sink or invoking user-supplied callbacks.
- Upgrading a read lock to a write lock. With
ReentrantReadWriteLockthis deadlocks, so release the read lock first and recheck the condition after taking the write lock. - Returning a reference to internal mutable state from inside a lock. The caller then mutates it with no lock held.
Atomic variables and compare-and-swap loops
Atomic types such as AtomicLong, Go's sync/atomic or C++ std::atomic perform single-variable operations like increment, exchange and compare-and-swap (CAS) as one indivisible step, usually through a CPU instruction. CAS means: set the value to B only if it is currently A, and report whether it succeeded. Retrying CAS in a loop lets you build lock-free updates of arbitrary logic on one variable.
Atomics are excellent for counters, flags, sequence generators and "keep the maximum" style updates. They do not compose. Two atomic variables updated one after the other do not form an atomic pair, so an invariant that spans both fields needs a lock or a single atomic reference to an immutable object holding both values.
Under heavy contention a CAS loop can spin and burn CPU. Specialised structures such as Java's LongAdder spread updates across cells and sum them on read. They trade exact point-in-time reads for much higher write throughput.
Java
import java.util.concurrent.atomic.AtomicLong;
// Tracks the peak number of open sockets seen by the Quarry chat gateway.
public class PeakTracker {
private final AtomicLong peak = new AtomicLong();
public void record(long observed) {
long current;
do {
current = peak.get();
if (observed <= current) {
return; // nothing to do, no write needed
}
} while (!peak.compareAndSet(current, observed));
}
public long get() {
return peak.get();
}
public static void main(String[] args) throws InterruptedException {
PeakTracker tracker = new PeakTracker();
Thread[] workers = new Thread[4];
for (int i = 0; i < workers.length; i++) {
final int base = i * 1000;
workers[i] = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
tracker.record(base + j);
}
});
workers[i].start();
}
for (Thread w : workers) {
w.join();
}
System.out.println(tracker.get()); // 3999
}
}A CAS loop: read, decide, and write only if nobody changed the value in between, otherwise retry. accumulateAndGet(observed, Math::max) does the same thing in one call.
Traps
- Updating two atomics in sequence and assuming the pair is consistent. Readers can see one updated and the other not.
- Ignoring the ABA problem in lock-free structures that reuse nodes: the value goes from A to B and back to A, and CAS succeeds even though the state changed in between.
- Using a CAS loop with a side effect inside the loop body. The body can run many times, so keep it pure.
- Choosing atomics for complex invariants to avoid locks. A correct lock is better than a clever, subtly broken lock-free design.
Memory visibility, volatile and happens-before
Atomicity is not the only problem. Compilers and CPUs reorder instructions and cache values, so a write made by one thread may never become visible to another, or may become visible in a different order than it was written. The language memory model defines when visibility is guaranteed through a happens-before relation: if action A happens-before action B, then B sees A's effects.
In Java, happens-before edges come from unlocking and later locking the same monitor, from writing and later reading the same volatile field, from Thread.start and Thread.join, and from the concurrent collections and executors. Go has equivalent rules for channels, mutexes and sync/atomic. Without such an edge, a loop polling a plain boolean flag can legally spin forever, because the JIT may hoist the read out of the loop.
The classic interview follow-up is double-checked locking for lazy initialisation. It only works in Java when the field is volatile. Otherwise another thread can see a non-null reference to a partially constructed object.
Java
// Background poller for the Driftwood inventory sync job.
public class InventoryPoller implements Runnable {
// volatile: the stop() write happens-before the next read in run().
private volatile boolean running = true;
private long cycles = 0; // only touched by the poller thread
@Override
public void run() {
while (running) {
cycles++;
Thread.onSpinWait();
}
System.out.println("stopped after " + (cycles > 0 ? "some" : "no") + " cycles");
}
public void stop() {
running = false;
}
public static void main(String[] args) throws InterruptedException {
InventoryPoller poller = new InventoryPoller();
Thread t = new Thread(poller);
t.start();
Thread.sleep(100);
poller.stop();
t.join(); // terminates reliably; without volatile it might never return
}
}volatile guarantees visibility and ordering for this flag. It does not make cycles++ atomic, which is safe here only because a single thread writes it.
Traps
- Believing
volatilemakes compound operations atomic.volatileCounter++still loses updates under concurrent writers. - Writing double-checked locking without
volatile, or reaching for it when a static holder class or an enum gives thread-safe lazy initialisation for free. - Letting
thisescape from a constructor, for example by registering a listener there. Other threads can then observe a half-initialised object. - Assuming x86 behaviour is the contract. Code that happens to work on strongly ordered hardware can break on ARM or after JIT optimisation.
Deadlocks, livelocks and lock ordering
A deadlock needs four conditions at once: mutual exclusion, hold-and-wait, no preemption, and a circular wait. The circular wait is the one you can usually break. Thread 1 holds lock A and waits for B, while thread 2 holds B and waits for A. The standard fix is a global lock order: always acquire locks in a consistent order, such as ascending id, whichever direction the business operation goes.
When a global order is impossible, use timed acquisition (tryLock with a timeout), release everything and retry with jittered backoff. Avoid symmetric retry with fixed delays, because two threads that keep backing off and retrying in lockstep produce a livelock: both are busy and neither makes progress. Starvation is the related case where one thread never gets the lock because others keep winning it.
In production you diagnose deadlocks from thread dumps (jstack shows "Found one Java-level deadlock"), goroutine dumps, or in databases from deadlock errors, where the engine picks a victim transaction and aborts it. Your code must be ready to retry that transaction.
Java
// Pebble wallet app: peer-to-peer transfers between wallets.
public class Transfers {
static final class Wallet {
final long id;
long balanceCents;
Wallet(long id, long balanceCents) {
this.id = id;
this.balanceCents = balanceCents;
}
}
// Always lock the lower id first, so A->B and B->A cannot form a cycle.
static void transfer(Wallet from, Wallet to, long cents) {
Wallet first = from.id < to.id ? from : to;
Wallet second = first == from ? to : from;
synchronized (first) {
synchronized (second) {
if (from.balanceCents < cents) {
throw new IllegalStateException("insufficient funds");
}
from.balanceCents -= cents;
to.balanceCents += cents;
}
}
}
public static void main(String[] args) throws InterruptedException {
Wallet ana = new Wallet(1, 50_000);
Wallet ben = new Wallet(2, 50_000);
Thread t1 = new Thread(() -> { for (int i = 0; i < 10_000; i++) transfer(ana, ben, 1); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 10_000; i++) transfer(ben, ana, 1); });
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(ana.balanceCents + ben.balanceCents); // 100000
}
}Opposite-direction transfers would deadlock with naive synchronized(from) { synchronized(to) { ... } }. Ordering by id removes the circular wait.
Traps
- Ordering locks by
hashCodeorSystem.identityHashCodewithout a tie-breaker. Collisions are possible, so equal hashes need an extra global lock. - Calling into another component while holding a lock. That component can take its own locks and create an ordering cycle you cannot see locally.
- Treating a database deadlock error as a bug to log and drop. The engine aborts one transaction by design, and the caller should retry it.
- Fixing a deadlock by adding timeouts everywhere without retry jitter, which often converts it into a livelock.
Races in single-threaded async code
Node.js, browser JavaScript and Python asyncio run your code on one thread, so there are no data races on plain variables. Race conditions still happen, because every await is a point where other tasks run. A check before an await and an act after it is a check-then-act with a gap, exactly as with threads.
Typical bugs include two concurrent requests both seeing an empty cache and both calling the slow upstream (a cache stampede), a user double-clicking "Pay" and creating two orders, or a stale response arriving after a newer one and overwriting fresher UI state. Fixes include sharing the in-flight promise per key, serialising work per key with a small async mutex or queue, and tagging requests with a sequence number so stale results are discarded.
Remember that one Node process is not the whole system. With four replicas behind a load balancer, an in-memory guard only deduplicates within one process. Cross-process races need the database, a distributed lock or idempotency keys.
TypeScript
// Price lookup for the Copperleaf store. The upstream call is slow, so
// concurrent requests for the same SKU share one in-flight promise.
let upstreamCalls = 0;
async function fetchPriceFromUpstream(sku: string): Promise<number> {
upstreamCalls++;
await new Promise((resolve) => setTimeout(resolve, 50));
return sku === "MUG-42" ? 1999 : 999;
}
const inflight = new Map<string, Promise<number>>();
function getPrice(sku: string): Promise<number> {
const existing = inflight.get(sku);
if (existing) return existing;
// Check and set happen synchronously, with no await in between.
const p = fetchPriceFromUpstream(sku).finally(() => inflight.delete(sku));
inflight.set(sku, p);
return p;
}
async function main(): Promise<void> {
const prices = await Promise.all(
Array.from({ length: 10 }, () => getPrice("MUG-42")),
);
console.log(prices[0], upstreamCalls); // 1999 1
}
main();Ten concurrent callers trigger one upstream call. Putting an await between inflight.get and inflight.set would reintroduce the race.
Traps
- Assuming single-threaded means race-free. Any
awaitbetween reading and writing shared state opens a window. - Caching a rejected promise forever. Remove it on failure, as
finallydoes here, or every later caller gets the same error. - Using an in-process lock to protect state that lives in a shared database or cache used by several instances.
- Ignoring out-of-order responses in clients. Searching as the user types can display results for an older query unless you discard stale responses.
Database isolation levels, lost updates and row locks
Wrapping code in a transaction does not make it race-free. PostgreSQL and many other databases default to READ COMMITTED, where two transactions can both read stock = 1, both decide to sell, and both write stock = 0, a lost update that oversells by one. Isolation levels define which anomalies are allowed: dirty reads, non-repeatable reads, phantoms, lost updates and write skew. SERIALIZABLE prevents all of them but aborts conflicting transactions, so you must retry on serialization errors.
There are three practical tools. First, make the update itself conditional and atomic: UPDATE ... SET stock = stock - 1 WHERE id = ? AND stock > 0, then check the affected row count. Second, lock the rows you are about to change with SELECT ... FOR UPDATE so concurrent transactions wait. Third, enforce invariants with constraints such as UNIQUE or CHECK, so the database rejects the losing write even when application logic races.
Write skew is the senior-level case. Two on-call engineers each check that at least one other person is on call and each removes themselves, and neither touched the other's row. Row locks on the rows you update do not catch this. You need SERIALIZABLE, explicit locks on the rows you read, or a constraint that encodes the rule.
SQL
-- Coupon SPRING25 for the Fernway bakery chain allows 500 redemptions.
CREATE TABLE coupons (
code TEXT PRIMARY KEY,
max_redemptions INTEGER NOT NULL,
redeemed INTEGER NOT NULL DEFAULT 0,
CHECK (redeemed <= max_redemptions)
);
INSERT INTO coupons (code, max_redemptions) VALUES ('SPRING25', 500);
-- Atomic check-and-increment: affects 1 row on success, 0 when exhausted.
UPDATE coupons
SET redeemed = redeemed + 1
WHERE code = 'SPRING25'
AND redeemed < max_redemptions;
-- Alternative when you need to read, decide in code, then write:
BEGIN;
SELECT redeemed, max_redemptions
FROM coupons
WHERE code = 'SPRING25'
FOR UPDATE; -- concurrent transactions block here until COMMIT
-- application checks the values, then:
UPDATE coupons SET redeemed = redeemed + 1 WHERE code = 'SPRING25';
COMMIT;Prefer the single conditional UPDATE. Use FOR UPDATE when the decision needs application logic. The CHECK constraint is a final safety net.
Traps
- Reading a value in one statement and writing a computed value in another under READ COMMITTED, then believing the transaction protects you.
- Switching to SERIALIZABLE or REPEATABLE READ without adding retry logic for serialization failures.
- Holding
FOR UPDATElocks while calling a payment provider or other slow external system, which turns a hot row into a queue. - Forgetting that isolation behaviour differs between engines. MySQL InnoDB REPEATABLE READ and PostgreSQL REPEATABLE READ do not handle the same anomalies in the same way.
Optimistic concurrency with versions and ETags
Pessimistic locking makes conflicting writers wait. Optimistic concurrency lets everyone proceed and detects conflicts at write time. Each record carries a version number or timestamp. A writer sends the version it read, and the update succeeds only if the stored version still matches. If zero rows are affected, someone else won and the caller must reload, merge or report a conflict.
This fits long user-facing edits well, such as two people editing the same record in a browser for minutes. Holding a database lock across think time is impossible there. Over HTTP the same idea appears as ETags: the client sends If-Match with the ETag it read, and the server responds 412 Precondition Failed when the resource has changed. ORMs expose it as version attributes, for example JPA's @Version.
The trade-off is about contention. When conflicts are rare, optimistic control has almost no overhead. When many writers hit the same row, they keep failing and retrying, and a pessimistic lock or an atomic in-place update performs better.
Python
import sqlite3
# Recipe editor for the Saltmarsh cooking app.
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT NOT NULL, version INTEGER NOT NULL)"
)
conn.execute("INSERT INTO recipes (id, title, version) VALUES (7, 'Lemon tart', 1)")
def save_title(conn: sqlite3.Connection, recipe_id: int, title: str, expected_version: int) -> bool:
cur = conn.execute(
"UPDATE recipes SET title = ?, version = version + 1 WHERE id = ? AND version = ?",
(title, recipe_id, expected_version),
)
conn.commit()
return cur.rowcount == 1
# Two editors both loaded version 1.
print(save_title(conn, 7, "Lemon tart with thyme", 1)) # True, now version 2
print(save_title(conn, 7, "Lemon meringue tart", 1)) # False, conflict detected
print(conn.execute("SELECT title, version FROM recipes WHERE id = 7").fetchone())
# ('Lemon tart with thyme', 2)The version check and the write happen in one statement, so the second editor gets a conflict instead of silently overwriting the first.
Traps
- Checking the version in a SELECT and then running an unconditional UPDATE. That reintroduces the race the version was meant to stop.
- Ignoring the affected row count. Without it, a conflict looks exactly like success.
- Retrying automatically by reapplying the user's full stale payload. That is still a lost update, so reload and merge, or surface the conflict.
- Using wall-clock timestamps as versions. Two writes in the same millisecond or clock skew between servers can break the check.
Idempotency keys and distributed locks
Across services, retries are unavoidable. A client times out and resends, a message broker redelivers, a load balancer replays a request. Since you cannot prevent duplicates, make operations idempotent: processing the same request twice has the same effect as processing it once. The usual mechanism is an idempotency key generated by the client and stored under a unique constraint. The first insert wins, and duplicates return the stored result.
Distributed locks, for example built on Redis or ZooKeeper, coordinate work across processes, but they are leases rather than true mutexes. A process can pause for a garbage collection or a network stall longer than the lease TTL, lose the lock without knowing it, and then write anyway. The robust pattern is a fencing token: a number that increases each time the lock is granted, which the protected resource checks and rejects if it has already seen a larger one.
Whenever possible, push correctness into the system of record: unique constraints, conditional writes, and transactional outbox tables. Use distributed locks for efficiency, such as avoiding duplicate work, rather than as the only line of defence for correctness.
SQL
-- Tollgate payments API: clients send an Idempotency-Key header with each charge.
CREATE TABLE charge_requests (
idempotency_key TEXT PRIMARY KEY,
customer_id BIGINT NOT NULL,
amount_cents BIGINT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Claim the key. Returns a row only for the first request with this key.
INSERT INTO charge_requests (idempotency_key, customer_id, amount_cents)
VALUES ('c9f1e2a4-7b3d-4e8a-9f10-2d6b5c8e1a77', 4182, 2599)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key;
-- If no row came back, this is a duplicate: return the stored outcome instead.
SELECT status, amount_cents
FROM charge_requests
WHERE idempotency_key = 'c9f1e2a4-7b3d-4e8a-9f10-2d6b5c8e1a77';PostgreSQL syntax. The primary key turns a concurrent duplicate into a no-op, even when two retries arrive at two different API instances at the same moment.
Traps
- Checking for an existing key with SELECT and then inserting. Without the unique constraint, two concurrent retries both pass the check.
- Not binding the key to the request body. A reused key with a different amount should be rejected, not silently served the old result.
- Assuming a Redis lock with a TTL guarantees mutual exclusion. Process pauses can outlast the lease, and you need fencing tokens or conditional writes downstream.
- Marking a message as processed before the side effect commits, or after it without atomicity. Crashes in between cause either lost or duplicated work.
Common questions
Short answers to the usual doubts.
What is the difference between a data race and a race condition?
A data race is a memory-level event: two threads access the same memory location without synchronization, and at least one access is a write. Many language memory models make that undefined or unpredictable. A race condition is a logic-level bug where the outcome depends on timing. You can have a race condition with no data race, for example two properly synchronized steps with a gap between them, or two database transactions. You can also have a data race that happens not to cause a visible bug yet.
Should I reach for a lock or an atomic variable?
Use an atomic when the invariant involves a single variable and the update is simple: counters, flags, maximums, sequence numbers. Use a lock when the invariant spans several fields or several steps, or when the logic would make a CAS loop hard to read. A correct, short critical section beats a clever lock-free design that only you can verify.
Does running a service with one thread per request make races impossible?
No. Requests still share state such as caches, singletons, connection pools, files and above all the database. Two requests on different threads, processes or machines can read and write the same row concurrently. Thread-per-request removes sharing of stack variables only.
How do I explain a fix convincingly in an interview?
State the shape of the race, the interleaving that breaks it, and the mechanism that removes the window. For example: two requests both read stock = 1 before either writes, so I replace read-then-write with one conditional UPDATE and check the affected row count. Then mention the trade-off, such as contention, retries or lock duration, and how you would verify the fix with a stress test or race detector.
When is optimistic locking a bad choice?
When many writers update the same record frequently, such as a global counter or a popular item's stock. Most attempts then fail and retry, wasting work and adding latency. An atomic in-place update or a short pessimistic lock performs better in that case, while optimistic control suits low-contention edits with long think time.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Concurrency and race conditionsTake the test
- Promises with a concurrency limitSolve the exercise