Skip to content
ADevGuide Logo ADevGuide
Go back

Race Conditions: Detection and Prevention in Backend Systems

By Pratik Bhuite | 7 min read

Hub: Java / Interview Fundamentals

Series: Backend Interview Mastery

Last verified: Sep 19, 2026

Part 55 of 88 in the Backend Interview Mastery

Key Takeaways

On this page
Reading Comfort:

Two concurrent backend requests racing to update shared state

Two customers click Buy at the same moment. Both requests read stock = 1, both decide the item is available, and both create an order. This is a race condition: correctness depends on timing between concurrent operations. Continue from database transactions, isolation levels, and distributed locks.

Table of Contents

Open Table of Contents

What a Race Condition Is

A race exists when two operations access shared state, at least one writes, and the result changes with execution order. It can happen inside one process, across application replicas, or between a service and a retrying client. A single-threaded event loop does not remove races because asynchronous callbacks can interleave between reads and writes.

flowchart TD
    A[Request A reads stock 1] --> C[Both requests see stock available]
    B[Request B reads stock 1] --> C
    C --> D[A decrements to 0]
    C --> E[B decrements to 0]
    D --> F[Two orders created]
    E --> F

The Check-Then-Act Failure

Code that checks a condition and later acts on it has a gap. An application-level mutex only protects one process; two replicas can still enter the gap. A distributed lock can narrow the gap but introduces lease expiry, fencing, and availability concerns.

Prefer one atomic database statement when the invariant belongs to the database. UPDATE inventory SET stock = stock - 1 WHERE sku = ? AND stock > 0 lets the storage engine serialize the write and tells the caller whether a row changed. Add a unique constraint for “only one” invariants such as idempotency keys.

Prevention Patterns

PatternBest forTrade-off
Atomic conditional writeCounters and inventoryTied to one storage system
Optimistic version checkConflicting editsCaller must retry
Serializable transactionMultiple related rowsLower throughput and possible aborts
Lease plus fencing tokenCross-process ownershipRequires clock/expiry-safe design
Idempotency keyRetries and duplicate requestsNeeds durable result storage

Use pessimistic locks when contention is high and waiting is safer than retrying. Use optimistic concurrency when conflicts are rare and the operation can recompute from a fresh version.

Testing and Detection

Write a stress test that launches concurrent operations against the same key and asserts an invariant, not just a response status. Force delays after reads to widen the race window. In production, monitor invariant violations, duplicate idempotency keys, optimistic-conflict rates, and lock wait time.

UPDATE inventory
SET stock = stock - 1, version = version + 1
WHERE sku = :sku AND stock > 0 AND version = :version;

The affected-row count is the decision. Never read a row, calculate in application memory, and assume the later write is still valid.

Interview Questions

1. Why does a transaction alone not always solve a race?

The isolation level controls which interleavings are allowed. At read committed, two transactions can both read the same value before either writes. You need a locking read, serializable isolation, an atomic predicate update, or a version condition that rejects the loser.

2. Is a mutex enough in a horizontally scaled service?

An in-process mutex only coordinates requests on one instance. Other instances can still modify the same record. Use a database invariant, a correctly designed distributed lock, or route all ownership of a key to one partition.

3. How do retries create races?

A timeout does not tell the client whether the server committed. Retrying can repeat a charge or create a duplicate job. An idempotency key lets the server return the original result instead of performing the side effect twice.

4. When is serializable isolation appropriate?

Use it for a small, critical invariant when retrying aborted transactions is acceptable. It can reduce throughput under contention, so measure aborts and lock waits. For hot counters, an atomic update or partitioned design is often cheaper.

5. How would you prove the fix?

State the invariant, create a concurrent test that tries to violate it, and assert the final state after all retries. Run it repeatedly with injected delays and multiple application instances. Then instrument production conflict and duplicate metrics to catch regressions.

Conclusion

Race conditions are failures of an invariant under an unsafe interleaving. Move the invariant to an atomic database operation when possible, use version checks or serializable transactions when needed, and make retries idempotent. Test with adversarial concurrency and observe conflict rates in production.

References

  1. PostgreSQL: Transaction isolation
  2. Martin Kleppmann: Designing Data-Intensive Applications
  3. Redis: Distributed locks

YouTube Videos

  1. “Race Conditions in Distributed Systems” - Hussein Nasser [https://www.youtube.com/watch?v=Ibf7wKf8MqU]

Share this post on:

Next in Series

Continue through the [object Object] with the next recommended article.

Related Posts

Keep Learning with New Posts

Subscribe through RSS and follow the project to get new series updates.

Was this guide helpful?

Share detailed feedback

Previous Post
Quorum Reads and Writes in Distributed Systems
Next Post
Saga Pattern: Orchestration, Choreography and Compensation