Skip to article content
FrontendXLesson 12 / 20

Concurrency and race conditions

Turn a vague failure report into a reproduction, isolate the cause, form and falsify hypotheses, instrument the code, fix async and state bugs, lock the fix behind a regression test and review changes for real trade-offs.

advanced · about 45 minutes · 2 exercises

  • Debug
  • Interview

What you will be able to do

#
  • Identify a read-modify-write race on shared state.
  • Guard a double submit and make a retry safe with an idempotency key.

Overview

#

A race condition happens when the result depends on the order in which two independent operations happen to run. The code is correct in every possible order except the one that actually occurs.

The classic shape is read-modify-write on shared state. Two operations read the same value, both add one, and both write back the same result, losing an update.

snippet.js
let balance = 100;
function withdraw(amount) {
  const current = balance;
  balance = current - amount;
}

If two withdrawals read 100 before either writes, the second overwrites the first and money is created. The fix is to make the operation atomic, either with a lock or with a single update that does not separate read from write.

snippet.js
function withdraw(amount) {
  balance = balance - amount; // single expression, no stale snapshot
}

In a browser the same problem appears with double submits. The user clicks twice before the first request returns, so two orders are created. Guard with a disabled state or an idempotency key.

snippet.js
async function submit(order) {
  if (pending) return;
  pending = true;
  try {
    await post('/orders', { ...order, idempotencyKey: order.id });
  } finally {
    pending = false;
  }
}

An idempotency key lets the server recognise a retry of the same logical request and return the original result instead of creating a duplicate. Retries should always be safe to repeat.

When you suspect a race, look for shared mutable state touched by more than one async path: a counter, a cache, a flag, a DOM node. Then ask what happens if the operations interleave in the worst possible order. If the answer is wrong, you have found the race.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Debug

    A double click creates two orders. Fix submit so a second call while the first is pending is ignored, and add an idempotency key so a retry does not duplicate the order.

    starter.javascript
    async function submit(order) {
      await post('/orders', order);
    }

    Reveal the reference answer
    reference.javascript
    let pending = false;
    async function submit(order) {
      if (pending) return;
      pending = true;
      try {
        await post('/orders', { ...order, idempotencyKey: order.id });
      } finally {
        pending = false;
      }
    }

    Authored expected output: A second call while the first is pending returns immediately without posting; the request carries an idempotency key so a server retry returns the original order.

    The pending flag serialises the client calls, and the finally block clears it even on failure. The idempotency key covers the case where a retry reaches the server after the first request already succeeded.

  2. Exercise 2Interview

    Describe how you would find and fix a race condition in a shared counter updated from two async paths.

    Reveal the reference answer
    reference.text
    First reproduce it: run both paths concurrently many times and check whether the final count is less than the number of increments. Then locate the read-modify-write: each path reads the counter, adds one and writes back, so an interleaving loses an update. Fix by making the update atomic, either with a single expression that does not separate read from write, a lock around the critical section, or a server-side atomic increment. Add a regression test that runs the concurrent update and asserts the final value.

    Authored expected output: A reproduce, locate, fix and regression-test procedure for a read-modify-write race.

    Reproducing under concurrency is what makes the race visible, because a single run usually passes. The read-modify-write is the shared pattern to fix, and the concurrent regression test stops it returning.

Common misconceptions

#
  • Two async operations never interfere if each one is correct on its own.
  • Retrying a request is always safe.

Follow-up practice

#
  • debugging-review-13-reproduce-the-environment

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.