GenClass is open source.Star on GitHub

Race condition simulator. Change the timing, watch the bug.

Change how long each request takes and watch three common bugs happen with no error: old search results, a double charge and a lost edit.

It runs in your browser, sends nothing of its own and needs no account.

The simulator needs JavaScript. The code below shows each bug and its fix.

How to use it

  1. Pick a scenario, then a fix. No fix shows the bug.
  2. Set each request's latency with a slider or a preset, then press Run.
  3. Explore 100 runs tries 100 random sets of latencies. Copy link shares your setup.

Three bugs that raise no error

Nothing throws; only the data is wrong. A fast machine hides all but the double tap, which a test that taps once misses.

Stale response: the search box

Each keystroke sends a request, and nothing keeps the answers in order. When "pa" is slow, its results land last and replace those for "paris". Debounce sends fewer requests but does not order them; ignoring stale responses or aborting the previous request fixes it. More in the guide to stale responses; for React effects that fetch, see race conditions in React data fetching.

Double submit: the pay button

A second tap sends a second payment. Disabling the button stops the tap but not a retry. If the first request is slow, the client sends it again, but the server already made the order. Choose "Disable the button while paying" to see it; untick the retry to see the second tap alone. An idempotency key with a unique index on the server makes every repeat return the same order. More in how to prevent duplicate form submissions.

Lost update: the autosave

Saves travel separately, so an older one can reach the server last and win. The editor says saved, but the server holds "Draft 2". A sequence number lets the server refuse an older save; one save at a time keeps them in order. More in the guide to lost edits and autosave.

Why you never see it on your machine

On localhost every request takes about the same time, so answers come back in order. Real networks are uneven: a cold cache or a weak signal can make one request many times slower than the next. DevTools throttling slows every request alike, so it rarely changes their order.

Check it yourself: choose No fix and press Explore 100 runs. It runs 100 real-network draws (80 to 400 ms, with a 15% chance of 800 to 2,000 ms) and 100 fast ones (20 to 60 ms). Compare the two lines.

The fixes in code

Broken code first, then each fix, which replaces the handler above it. renderResults, showReceipt and showError stand for your own code; the server uses Express 5 and node-postgres.

Search box

Broken. Every answer renders when it lands.
const box = document.querySelector("#search");

box.addEventListener("input", async () => {
  const q = box.value;
  const res = await fetch(`/search?q=${encodeURIComponent(q)}`);
  renderResults(q, await res.json()); // whichever answer lands last wins
});
Debounce: not enough alone. Two requests can still cross.
let timer;

box.addEventListener("input", () => {
  clearTimeout(timer);
  timer = setTimeout(async () => {
    const q = box.value;
    const res = await fetch(`/search?q=${encodeURIComponent(q)}`);
    // fewer requests, but a slow one can still land after a newer one
    renderResults(q, await res.json());
  }, 250);
});
Fixed: ignore stale responses.
let latest = 0;

box.addEventListener("input", async () => {
  const id = ++latest;
  const q = box.value;
  const res = await fetch(`/search?q=${encodeURIComponent(q)}`);
  const results = await res.json();
  if (id !== latest) return; // a newer request was sent: drop this answer
  renderResults(q, results);
});
Fixed: abort the previous request.
let controller;

box.addEventListener("input", async () => {
  controller?.abort(); // cancel the request still in flight
  controller = new AbortController();
  const q = box.value;
  try {
    const url = `/search?q=${encodeURIComponent(q)}`;
    const res = await fetch(url, { signal: controller.signal });
    renderResults(q, await res.json());
  } catch (err) {
    if (err.name !== "AbortError") throw err;
  }
});

Pay button

Broken. Every tap pays, and pay() sends again after 1 s. The simulator retries only the first tap's request.
// POST /pay. With no answer within 1 s, give up and send it again.
async function pay(headers = {}) {
  const send = async (signal) => {
    const res = await fetch("/pay", {
      method: "POST",
      headers: { "Content-Type": "application/json", ...headers },
      body: JSON.stringify({ cartId: "c_42" }),
      signal,
    });
    if (!res.ok) throw new Error(`Payment failed: ${res.status}`);
    return res.json();
  };
  try {
    return await send(AbortSignal.timeout(1000));
  } catch (err) {
    if (err.name !== "TimeoutError") throw err;
    return send(); // the server may already have taken the first one
  }
}

const button = document.querySelector("#pay");

button.addEventListener("click", async () => {
  try {
    showReceipt(await pay()); // every tap sends a payment
  } catch (err) {
    showError(err);
  }
});
Disable the button: not enough alone. The retry still runs.
button.addEventListener("click", async () => {
  button.disabled = true; // a second tap does nothing now
  try {
    showReceipt(await pay()); // but pay() still sends again after 1 s with no answer
  } catch (err) {
    button.disabled = false;
    showError(err);
  }
});
Fixed in the browser: an idempotency key.
// Made once, when the checkout opens, and sent with every request, retries included.
const idempotencyKey = crypto.randomUUID();

button.addEventListener("click", async () => {
  try {
    showReceipt(await pay({ "Idempotency-Key": idempotencyKey }));
  } catch (err) {
    showError(err);
  }
});
Fixed: both.
const idempotencyKey = crypto.randomUUID();

button.addEventListener("click", async () => {
  button.disabled = true; // stops a second tap
  try {
    // the key covers the retry inside pay()
    showReceipt(await pay({ "Idempotency-Key": idempotencyKey }));
  } catch (err) {
    button.disabled = false; // trying again sends the same key
    showError(err);
  }
});
Fixed on the server, part 1. A unique index on the key (PostgreSQL).
CREATE TABLE orders (
  id bigserial PRIMARY KEY,
  idempotency_key text NOT NULL,
  cart_id text NOT NULL
);

-- one order per key, enforced by the database
CREATE UNIQUE INDEX orders_idempotency_key ON orders (idempotency_key);
Fixed on the server, part 2. The insert the index guards.
import express from "express";
import pg from "pg";

const app = express();
const db = new pg.Pool(); // connection settings from the PG* environment variables
app.use(express.json());

app.post("/pay", async (req, res) => {
  const key = req.get("Idempotency-Key");
  if (!key) return res.status(400).json({ error: "Idempotency-Key header required" });
  // findOne-then-insert alone is racy: two requests can both find nothing and both insert.
  await db.query(
    `INSERT INTO orders (idempotency_key, cart_id) VALUES ($1, $2)
     ON CONFLICT (idempotency_key) DO NOTHING`,
    [key, req.body.cartId],
  );
  // the first request made the order; every repeat reads the same one
  const { rows } = await db.query(
    "SELECT id FROM orders WHERE idempotency_key = $1",
    [key],
  );
  res.json({ order: rows[0].id });
});

app.listen(3000);

Autosave

Broken, in the browser.
const note = document.querySelector("#note");

note.addEventListener("input", () => {
  // a save per change; waiting for a pause first only makes the saves rarer
  fetch("/notes/1", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text: note.value }),
  }).catch(showError);
});
Broken, on the server. The last save to arrive wins.
// app and db as in the payment server above
app.put("/notes/:id", async (req, res) => {
  // the last save to arrive wins, even when it is an older one
  await db.query("UPDATE notes SET text = $2 WHERE id = $1", [
    req.params.id,
    req.body.text,
  ]);
  res.sendStatus(204);
});
Fixed: a sequence number, in the browser.
// The page renders the stored number: <textarea id="note" data-seq="7">
let seq = Number(note.dataset.seq);

note.addEventListener("input", () => {
  seq += 1;
  fetch("/notes/1", {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ text: note.value, seq }),
  }).catch(showError);
});
Fixed: a sequence number, on the server.
// notes has a seq column: ALTER TABLE notes ADD COLUMN seq integer NOT NULL DEFAULT 0;
app.put("/notes/:id", async (req, res) => {
  const { text, seq } = req.body;
  // only a newer save replaces what is stored; an older one changes nothing
  const { rowCount } = await db.query(
    "UPDATE notes SET text = $3, seq = $2 WHERE id = $1 AND seq < $2",
    [req.params.id, seq, text],
  );
  res.json({ stored: rowCount === 1 });
});
Fixed: one save at a time.
let saving = false;
let pending = null; // the newest text that waits to be saved

note.addEventListener("input", () => {
  pending = note.value; // a newer edit replaces a waiting one
  if (!saving) saveNext();
});

async function saveNext() {
  saving = true;
  while (pending !== null) {
    const text = pending;
    pending = null;
    try {
      const res = await fetch("/notes/1", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ text }),
      });
      if (!res.ok) throw new Error(`Save failed: ${res.status}`);
    } catch (err) {
      showError(err);
      if (pending !== null) continue; // a newer edit waits: send that one now
      pending = text; // keep it for the next save
      break;
    }
  }
  saving = false;
}

Test for it

Hold one answer back in a test and the stale response happens on any machine. This Playwright test holds the answer for "pa" until the results for "paris" are on screen, then lets it land. It fails with no fix or debounce alone, and passes once stale answers are ignored or aborted. More patterns: testing race conditions with Playwright.

Playwright. One answer held with page.route and let go last.
import { test, expect } from "@playwright/test";

// two animation frames: time for the page to apply a response that just arrived
const twoFrames = () =>
  new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));

test("the list shows results for the last query", async ({ page }) => {
  // hold the answer for "pa" until the test lets it go
  let older;
  await page.route(
    (url) => url.pathname === "/search" && url.searchParams.get("q") === "pa",
    (route) => { older = route; },
  );
  await page.goto("/"); // baseURL in playwright.config points at your app
  const box = page.getByRole("searchbox");
  // the app writes the query its list is for into data-testid="results-for"
  const shownFor = page.getByTestId("results-for");

  await box.fill("pa");
  await expect.poll(() => Boolean(older)).toBe(true); // "pa" was sent, after any debounce
  await box.fill("paris");
  await expect(shownFor).toHaveText("paris"); // the newer answer is on screen

  // now the older answer lands last
  await older.continue().catch(() => {}); // the page may have aborted it
  const late = await older.request().response(); // null when the page aborted it
  await late?.finished();
  await page.evaluate(twoFrames);
  await expect(shownFor).toHaveText("paris"); // fails while the bug is there
});

For the double charge, the first payment has to reach the server before the client gives up: take its answer with await route.fetch(), wait past the client's timeout, then route.fulfill({ response }), and count the orders. A payment held past the timeout before route.continue() is cancelled and never reaches the server, so that test passes on the broken code too. For the lost update, hold an older save and read back what the server kept.

Find it in production

A test covers the orders you thought of. GenClass's runtime watches your app in your users' browsers. It reports a response that lands after a newer one and leaves older data on screen. It also reports a request sent twice, such as a double submit. Detection is partial: scored offline on real apps kept out of training, model 0.2.0 reported 75% of duplicate submits and 30% of stale overwrites with the right diagnosis, with false detections held to at most 2% of clean decisions (benchmarks). Each report shows which requests started when, and from which user action. By default it only reports: it never holds, delays or changes a request, a response or a state write. Stale responses are reported only for state it can see: React state, Redux stores set up for Redux DevTools, Zustand stores with devtools (in production only with enabled: true), and stores you register. More in how to detect race conditions in production.

GenClass's MCP server connects your coding agent to your app's development build on your machine. While your agent or a test repeats your steps, genclass_explore delivers the responses in different orders and reports what ends differently. genclass_replay delivers one exact order again, before your fix (reproduced) and after it (not reproduced).

Read the MCP server docs
Questions

About the simulator.

Does the simulator send any requests?

No, the simulation sends nothing of its own. Like every page of genclass.dev, this page also runs GenClass, as the privacy page says.

Is debounce enough to stop stale results?

No. It sends fewer requests, but two can still land out of order.

Does disabling the pay button stop double charges?

It stops a second tap, not a retry after a timeout. An idempotency key with a unique index on the server stops both.

Does the simulator give the same result every time?

A run does, for the same settings. Explore takes the next seed on each press and shows it, and a seed always gives the same counts.

Talk to sales

Tell us about your team and what you need. A person writes back, usually within a day.