Race condition vulnerabilities: when two requests pass the same check
A race condition in a web application is two requests that each pass a check, such as "one per customer" or "while stock lasts", before either has recorded its effect.
This guide explains why it surfaces as stock or money that does not add up rather than as an error, what your database's default isolation level does and does not stop, and the controls that make the check and the effect one step or make a repeat harmless. It comes with a verification checklist and a local lab with two server processes, reconciliation tables and a regression test.
In this guide
Race condition lab: checklist, parallel requests, reconciliation and regression test
An illustration written for this page, not client code. Part A is a ten-item verification checklist for a limited workflow, each item with its basis.
How to use itHide the instructions
Parts B to D are a Node.js lab with nothing to install: a voucher service for an invented bakery in a careless and a careful version, each run as two server processes on one SQLite file, five parallel-request tests with a reconciliation table for each, and a regression test that checks invariants and fails on the careless version. Every output was recorded on Node.js v26.0.0. Part E points the test at your own staging workflow.
race-conditions.txt
Introduction1 lines
Part A. Verification checklist for a limited workflow41 lines
Part B. The lab607 lines
Part C. Output of node run-lab.mjs (run 1 of 3, Node.js v26.0.0, macOS)124 lines
Part D. The regression test86 lines
Part E. Pointing it at your own staging workflow15 lines
Whole template904 lines
ILLUSTRATION FOR LEARNING. The bakery, its FREE-LOAF voucher, its north and south stores and every customer account below were invented for this page. They are not a client's system or a client's result. Run the lab on your own machine to learn, and use the checklist and the regression test on a workflow you own, against staging and test data. Do not send these requests to a system you do not own or are not authorised in writing to test.
================================================================
PART A. VERIFICATION CHECKLIST FOR A LIMITED WORKFLOW
================================================================
Use this for each workflow with a limit: one per customer, while stock lasts, or the balance must cover it. Each item gives the question, what to look for, and its basis. "This page's advice" marks the parts no cited source states.
A1. Where is the limit enforced?
Look for: the decision made by the database, by a constraint, or inside one transaction that holds the lock. Not a count held in one server's memory, and not a value read in one statement and written back in a later one.
Basis: CWE-367 (ensure that locking occurs before the check); ASVS 5.0 requirement 2.3.4 (Level 2) and 15.4.2 (Level 3). Sorting the three places into good and bad is this page's advice.
A2. Which constraint or lock backs it?
Look for: once per customer, a UNIQUE constraint on the account and the offer, with neither column allowed to be NULL. While stock lasts, a decrement that only succeeds while stock is above zero (UPDATE ... SET stock = stock - 1 WHERE ... AND stock > 0, then check the number of rows changed), with a CHECK (stock >= 0) behind it. Balance must cover it, the same conditional update on the balance.
Basis: SQLite CREATE TABLE (UNIQUE and CHECK constraints, NULLs distinct); PostgreSQL 18 section 5.5 (unique and check constraints, nulls not equal by default); PostgreSQL 18 section 13.2.1 (at Read Committed an UPDATE re-checks its WHERE clause against the updated row). NOT NULL on both columns is this page's advice.
A3. Where does the transaction start and end?
Look for: one transaction around the check and the effect, which takes the lock first (BEGIN IMMEDIATE in SQLite, SELECT ... FOR UPDATE in PostgreSQL). Every write of the operation inside it, so it succeeds whole or rolls back. No call to another service, email or payment provider inside it.
Basis: ASVS 5.0 requirement 2.3.3 (Level 2); the SQLite Transaction page; PostgreSQL 18 section 13.3 (row locks, and why holding transactions open for long periods is a bad idea). Keeping other services out is this page's advice, built on that last point.
A4. Which isolation level does the workflow run at, and what does it allow?
Look for: the level named in your code or database settings, and what it allows. PostgreSQL's default, Read Committed, allows nonrepeatable reads, phantom reads and serialization anomalies. At Repeatable Read or Serializable, code that retries serialization failures (SQLSTATE 40001).
Basis: PostgreSQL 18 section 13.2. SQLite: the Isolation In SQLite page.
A5. What is the client told when it loses?
Look for: 409 with a reason a person can act on (already redeemed, sold out); 422 when an idempotency key is reused with a different body; 503 with Retry-After when the database stays busy. Never 201 for a request that did not get the item, and never a bare 500 for a lock wait.
Basis: RFC 9110 sections 15.5.10 (409) and 15.6.4 (503, with Retry-After); the Idempotency-Key Internet-Draft, revision 08, section 2.7 (422 and 409). Which answer goes with which case is this page's advice.
A6. What is the idempotency key's scope?
Look for: keys stored per account (the account and the key together), a published key format that each key is validated against before the request is processed, and a fingerprint of the body, so a reused key with a different body is refused. The key, the effect and the stored answer committed in the same transaction.
Basis: the Idempotency-Key draft, revision 08, sections 2.2, 2.4 and 5. Section 5 recommends a unique composite key as the lookup key and says, as an example, that it MAY combine the client's key with other client-specific attributes known only to the resource; using the account is this page's choice. Section 5 also recommends always validating the key as per its published specification before processing any request. In the lab, server.mjs checks the method and path, then the account header and the JSON body, and then, in the careful version, the key's format, all before it calls the other service or opens its transaction. Committing them in one transaction is this page's advice, shown by T3 to T5 in the lab.
A7. How long does a key live?
Look for: an expiry period written in your API documentation, longer than the longest retry any of your clients makes.
Basis: the draft, section 2.3 (the resource MAY require time-based idempotency keys, to be able to purge or delete a key upon its expiry, and SHOULD define such an expiration policy and publish it in the documentation) and section 2.5.2 (resources MUST publish an idempotency-related specification, which MUST include expiration related policy if applicable). For comparison, Stripe's API reference says that for API v1 keys can be removed from the system automatically after they are at least 24 hours old. Longer than the longest retry is this page's advice.
A8. What happens on retry?
Look for: clients repeat a POST only with the same key; the server retries busy, deadlock and serialization failures itself, a bounded number of times; a busy failure leaves no row and no stored key behind, so the retry runs once.
Basis: RFC 9110 section 9.2.2 (a client SHOULD NOT automatically retry a non-idempotent request unless it has some means to know the request is idempotent, or to detect that the original was never applied); SQLite result codes (SQLITE_BUSY); PostgreSQL 18 section 13.2 (applications using Repeatable Read or Serializable must be prepared to retry transactions due to serialization failures) and section 13.3 (the best defence against deadlocks is generally to avoid them by being certain that all applications acquire locks on multiple objects in a consistent order; if it is not feasible to verify this in advance, deadlocks can be handled on the fly by retrying transactions that abort due to deadlocks). Leaving nothing behind is this page's advice, checked by T5 in the lab.
A9. Does each test reconcile counts with rows?
Look for: after each parallel test, the requests sent, the successes the clients were told about, the rows written and the stock or balance remaining, with every invariant marked held or not held.
Basis: this page's advice. The latest WSTG edition's WSTG-BUSL-10 lists multiple success responses for a single-use action, negative balances after concurrent debits and resources allocated beyond stated capacity among its indicators of vulnerability.
A10. What runs in production to catch a miss?
Look for: a scheduled query for each invariant, and an alert to a named person on any row that breaks one.
Basis: this page's advice.
================================================================
PART B. THE LAB
================================================================
WHAT IT NEEDS
Node.js, with nothing to install. The lab imports only node:sqlite, node:http, node:crypto, node:child_process, node:events, node:fs, node:path, node:url, node:assert/strict and node:test, and calls fetch without importing it. Every output below was recorded on Node.js v26.0.0 on macOS, where node:sqlite reported SQLite 3.53.4. The lab passes a timeout option to node:sqlite, which the Node.js documentation lists from versions 22.16.0 and 24.0.0; it was not run on any version other than v26.0.0. The Node.js documentation marks node:sqlite a release candidate (Stability 1.2) from version 25.7.0, and now names its database class Database, keeping DatabaseSync, the name the lab imports, as a deprecated alias.
WHAT IT TOUCHES
Two SQLite files in the lab's own folder, lab-careless.db and lab-careful.db, each created at the start of its run and deleted at the end. Two server processes per version, each listening on 127.0.0.1 on a port the operating system assigns, because the lab asks for port 0. Each server is stopped through its own child process handle, and the run prints how each one exited. Every request goes to 127.0.0.1.
THE LAB'S OWN DEVICES, STATED OPENLY
1. A fixed 40 ms wait stands in for a call to another service, such as a loyalty system. In the careless version it sits between the read and the write, and its length is what makes the careless version fail on every run. On a real system the window is however long that step takes, and it varies.
2. The account comes from an x-lab-account header, standing in for a signed-in session.
3. Requests alternate between the two server processes: even-numbered requests go to server A, odd-numbered ones to server B.
4. In T5, the lab holds the database's write lock on its own connection while the first request arrives, so that request meets a busy database, then releases it.
THE TWO VERSIONS
careless: reads the stock and the account's redemptions, waits on the other service, inserts the redemption, then writes back the stock it read, minus one. The schema has no constraints, and the version ignores any Idempotency-Key header.
careful: requires an Idempotency-Key header, written in quotes as the draft's examples are, in a format the lab sets for itself. It waits on the other service first. Then, in one BEGIN IMMEDIATE transaction, it looks up the key (a stored answer is replayed, a different body gets 422), checks the account, takes one from stock only while stock is above zero, inserts the row, stores the answer under the key and commits. A UNIQUE constraint on account and voucher and a CHECK on stock stand behind those checks. If BEGIN IMMEDIATE is still busy after the 1,000 ms busy timeout, it answers 503 with Retry-After: 1, the value set in server.mjs, and writes nothing.
THE FIVE TESTS (no test sends more than 24 requests)
T1 One account sends 20 requests at once, each with its own key. Starting stock 50.
T2 24 accounts send one request each for the last 3 vouchers. Starting stock 3.
T3 One request sent 12 times at once with the same key, then once more after all 12 have answered. Starting stock 50.
T4 One request, then the same key with a different store, then the original request again. Starting stock 50.
T5 One request meets a busy database, and the retry waits as told and resends the same key and body. Starting stock 50.
THE INVARIANTS
one redemption per account: no account has more than one row for the voucher.
redemptions within starting stock: rows do not exceed the starting stock, and stock is not below zero.
stock adds up: starting stock minus rows equals the stock remaining.
a key maps to one result (T3 to T5): every completed answer to the original request is the same, the key produced at most one row, and a reuse with a different body got 422. A 500 or 503 answer did not complete, so it is left out.
busy answer says try again (T5): the busy answer was 503 with a Retry-After header.
SET-UP
Make an empty folder, save the five files below into it under the names shown, and run the commands under RUN IT from that folder. The last command sets LAB_VERSION the way macOS and Linux shells do; on Windows, set it the way your shell does.
================================================================
FILE 1 OF 5: store.mjs
================================================================
// store.mjs: the lab's SQLite database file and its two schemas.
// Illustration only: an invented bakery, its invented voucher and accounts.
// careless: no constraints at all.
// careful: a UNIQUE constraint on account and voucher, a CHECK that stock
// never goes below zero, and a table of idempotency keys.
import { DatabaseSync } from 'node:sqlite'
export const VOUCHER = 'FREE-LOAF'
// How long a connection waits for another connection's write lock before
// SQLite reports SQLITE_BUSY. Both versions use the same value.
export const BUSY_TIMEOUT_MS = 1000
const CARELESS_SCHEMA =
'CREATE TABLE vouchers (code TEXT PRIMARY KEY, stock INTEGER NOT NULL);' +
'CREATE TABLE redemptions (id INTEGER PRIMARY KEY, account_id TEXT NOT NULL,' +
' voucher TEXT NOT NULL, store TEXT NOT NULL);'
const CAREFUL_SCHEMA =
'CREATE TABLE vouchers (code TEXT PRIMARY KEY, stock INTEGER NOT NULL CHECK (stock >= 0));' +
'CREATE TABLE redemptions (id INTEGER PRIMARY KEY, account_id TEXT NOT NULL,' +
' voucher TEXT NOT NULL, store TEXT NOT NULL, UNIQUE (account_id, voucher));' +
'CREATE TABLE idempotency_keys (account_id TEXT NOT NULL, idem_key TEXT NOT NULL,' +
' fingerprint TEXT NOT NULL, status INTEGER NOT NULL, body TEXT NOT NULL,' +
' PRIMARY KEY (account_id, idem_key));'
export function openDatabase(file) {
return new DatabaseSync(file, { timeout: BUSY_TIMEOUT_MS })
}
export function createSchema(file, version) {
const database = openDatabase(file)
database.exec(version === 'careful' ? CAREFUL_SCHEMA : CARELESS_SCHEMA)
database.close()
}
function hasKeyTable(database) {
const sql = "SELECT COUNT(*) AS n FROM sqlite_master WHERE name = 'idempotency_keys'"
return database.prepare(sql).get().n === 1
}
// Empties the tables and sets the starting stock before each test.
export function resetState(database, startingStock) {
database.exec('DELETE FROM redemptions')
if (hasKeyTable(database)) database.exec('DELETE FROM idempotency_keys')
const sql = 'INSERT OR REPLACE INTO vouchers (code, stock) VALUES (?, ?)'
database.prepare(sql).run(VOUCHER, startingStock)
}
// What the database says after a test, read on the lab's own connection.
export function readDatabaseState(database) {
const rows = database.prepare('SELECT COUNT(*) AS n FROM redemptions').get().n
const stock = database.prepare('SELECT stock FROM vouchers WHERE code = ?').get(VOUCHER).stock
const perAccount =
'SELECT COALESCE(MAX(n), 0) AS n FROM' +
' (SELECT COUNT(*) AS n FROM redemptions GROUP BY account_id, voucher)'
const mostForOneAccount = database.prepare(perAccount).get().n
return { rows: rows, stock: stock, mostForOneAccount: mostForOneAccount }
}
export function readSqliteVersion(database) {
return database.prepare('SELECT sqlite_version() AS version').get().version
}
export function readJournalMode(database) {
return database.prepare('PRAGMA journal_mode').get().journal_mode
}
================================================================
FILE 2 OF 5: server.mjs
================================================================
// server.mjs: usage: node server.mjs careless|careful DATABASE_FILE LABEL
// One process of the invented bakery's voucher service. The lab starts two
// of them on the same database file. Each listens on 127.0.0.1 on a port the
// system picks (port 0) and reports that port to the process that started it.
import { createHash } from 'node:crypto'
import { createServer } from 'node:http'
import { openDatabase, VOUCHER } from './store.mjs'
const version = process.argv[2]
const database = openDatabase(process.argv[3])
const label = process.argv[4]
// Stands in for a call to another service, such as a loyalty system. The
// fixed 40 ms wait is the lab's own device: it holds the careless version's
// window open long enough that it fails on every run.
const OTHER_SERVICE_MS = 40
function callOtherService() {
return new Promise((resolve) => setTimeout(resolve, OTHER_SERVICE_MS))
}
// CARELESS: read the count, wait for the other service, then write.
async function redeemCarelessly(account, order) {
const voucher = database.prepare('SELECT stock FROM vouchers WHERE code = ?').get(order.voucher)
const countSql = 'SELECT COUNT(*) AS n FROM redemptions WHERE account_id = ? AND voucher = ?'
const already = database.prepare(countSql).get(account, order.voucher)
if (already.n > 0) return { status: 409, body: { error: 'already redeemed' } }
if (voucher.stock < 1) return { status: 409, body: { error: 'sold out' } }
await callOtherService()
const insertSql = 'INSERT INTO redemptions (account_id, voucher, store) VALUES (?, ?, ?)'
const inserted = database.prepare(insertSql).run(account, order.voucher, order.store)
// Writes back the stock it read before the wait, minus one.
database.prepare('UPDATE vouchers SET stock = ? WHERE code = ?').run(voucher.stock - 1, order.voucher)
return { status: 201, body: { redemption: Number(inserted.lastInsertRowid) } }
}
// CAREFUL, step 1: the other service is called first, outside any
// transaction, so no lock is held while this process waits.
async function redeemCarefully(account, order, key) {
await callOtherService()
try {
database.exec('BEGIN IMMEDIATE')
} catch (error) {
if (!isBusy(error)) throw error
return { status: 503, body: { error: 'busy, try again' }, headers: { 'retry-after': '1' } }
}
try {
const result = decideInsideTransaction(account, order, key)
database.exec('COMMIT')
return result
} catch (error) {
database.exec('ROLLBACK')
throw error
}
}
// SQLite's result code 5 is SQLITE_BUSY.
function isBusy(error) {
return error.errcode === 5
}
function fingerprintOf(order) {
return createHash('sha256').update(JSON.stringify([order.voucher, order.store])).digest('hex')
}
// CAREFUL, step 2: runs while this connection holds the write lock, so no
// other connection can write anything until this one commits.
function decideInsideTransaction(account, order, key) {
const fingerprint = fingerprintOf(order)
const findSql = 'SELECT fingerprint, status, body FROM idempotency_keys WHERE account_id = ? AND idem_key = ?'
const earlier = database.prepare(findSql).get(account, key)
if (earlier && earlier.fingerprint !== fingerprint) {
return { status: 422, body: { error: 'idempotency key already used with a different request' } }
}
if (earlier) return { status: earlier.status, body: JSON.parse(earlier.body) }
const result = applyRedemption(account, order)
const saveSql =
'INSERT INTO idempotency_keys (account_id, idem_key, fingerprint, status, body) VALUES (?, ?, ?, ?, ?)'
database.prepare(saveSql).run(account, key, fingerprint, result.status, JSON.stringify(result.body))
return result
}
// CAREFUL, step 3: the account rule, then a stock decrement that refuses to
// go below zero, then the row. The UNIQUE constraint backs the first check.
function applyRedemption(account, order) {
const countSql = 'SELECT COUNT(*) AS n FROM redemptions WHERE account_id = ? AND voucher = ?'
const already = database.prepare(countSql).get(account, order.voucher)
if (already.n > 0) return { status: 409, body: { error: 'already redeemed' } }
const takeSql = 'UPDATE vouchers SET stock = stock - 1 WHERE code = ? AND stock > 0'
const taken = database.prepare(takeSql).run(order.voucher)
if (taken.changes === 0) return { status: 409, body: { error: 'sold out' } }
const insertSql = 'INSERT INTO redemptions (account_id, voucher, store) VALUES (?, ?, ?)'
const inserted = database.prepare(insertSql).run(account, order.voucher, order.store)
return { status: 201, body: { redemption: Number(inserted.lastInsertRowid) } }
}
// The draft's syntax for the header is a quoted string. This lab's own rule:
// 8 to 64 letters, digits or hyphens inside the quotes, nothing else.
const KEY_FORMAT = /^"([A-Za-z0-9-]{8,64})"$/
function readIdempotencyKey(headerValue) {
const match = KEY_FORMAT.exec(headerValue || '')
return match ? match[1] : null
}
function parseOrder(text) {
try {
const order = JSON.parse(text)
if (order.voucher !== VOUCHER || typeof order.store !== 'string') return null
return { voucher: order.voucher, store: order.store }
} catch (error) {
return null
}
}
function readBody(request) {
return new Promise((resolve) => {
let text = ''
request.on('data', (chunk) => {
text = text + chunk
})
request.on('end', () => resolve(text))
})
}
async function redeem(request, account, order) {
if (version !== 'careful') return redeemCarelessly(account, order)
const key = readIdempotencyKey(request.headers['idempotency-key'])
if (!key) return { status: 400, body: { error: 'missing or malformed Idempotency-Key' } }
return redeemCarefully(account, order, key)
}
function sendJson(response, result) {
const headers = Object.assign({ 'content-type': 'application/json', 'x-lab-server': label }, result.headers)
response.writeHead(result.status, headers)
response.end(JSON.stringify(result.body))
}
async function handleRequest(request, response) {
if (request.method !== 'POST' || request.url !== '/redemptions') {
return sendJson(response, { status: 404, body: { error: 'not found' } })
}
// The lab's stand-in for a signed-in session: the account comes from a header.
const account = request.headers['x-lab-account']
const order = parseOrder(await readBody(request))
if (!account || !order) return sendJson(response, { status: 400, body: { error: 'bad request' } })
try {
sendJson(response, await redeem(request, account, order))
} catch (error) {
console.log(' server ' + label + ' log: ' + error.message)
sendJson(response, { status: 500, body: { error: 'server error' } })
}
}
const server = createServer(handleRequest)
server.listen(0, '127.0.0.1', () => {
process.send({ port: server.address().port })
})
================================================================
FILE 3 OF 5: harness.mjs
================================================================
// harness.mjs: starts two server processes on one database file, sends each
// test's requests, then reads the database on its own connection to
// reconcile what clients were told with what was stored.
import { fork } from 'node:child_process'
import { once } from 'node:events'
import { existsSync, rmSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { createSchema, openDatabase, readDatabaseState, resetState, VOUCHER } from './store.mjs'
const LAB_FOLDER = path.dirname(fileURLToPath(import.meta.url))
function removeDatabaseFiles(file) {
rmSync(file, { force: true })
rmSync(file + '-journal', { force: true })
}
async function startServer(version, file, label) {
const child = fork(path.join(LAB_FOLDER, 'server.mjs'), [version, file, label])
const message = (await once(child, 'message'))[0]
return { label: label, child: child, port: message.port }
}
export async function startLab(version) {
const file = path.join(LAB_FOLDER, 'lab-' + version + '.db')
removeDatabaseFiles(file)
createSchema(file, version)
const servers = [await startServer(version, file, 'A'), await startServer(version, file, 'B')]
return { version: version, file: file, servers: servers, database: openDatabase(file) }
}
// Stops each server through its own child process handle, which signals
// that process id only, then deletes the database file.
export async function stopLab(lab) {
lab.database.close()
const stopped = []
for (const server of lab.servers) {
const exited = once(server.child, 'exit')
server.child.kill('SIGTERM')
const signal = (await exited)[1]
stopped.push(server.label + ' (' + signal + ')')
}
removeDatabaseFiles(lab.file)
const removed = !existsSync(lab.file) && !existsSync(lab.file + '-journal')
return { stopped: stopped, removed: removed }
}
// One request. Even-numbered requests go to server A, odd ones to server B.
export async function sendRedemption(lab, index, request) {
const server = lab.servers[index % lab.servers.length]
const headers = { 'content-type': 'application/json', 'x-lab-account': request.account }
if (request.key) headers['idempotency-key'] = '"' + request.key + '"'
const body = JSON.stringify({ voucher: VOUCHER, store: request.store })
const url = 'http://127.0.0.1:' + server.port + '/redemptions'
const response = await fetch(url, { method: 'POST', headers: headers, body: body })
return {
request: request,
status: response.status,
body: await response.json(),
server: response.headers.get('x-lab-server'),
retryAfter: response.headers.get('retry-after'),
}
}
// Sends every request without waiting for any answer first.
function sendAtOnce(lab, requests) {
return Promise.all(requests.map((request, index) => sendRedemption(lab, index, request)))
}
function keyFor(test, number) {
return test + '-key-' + String(number).padStart(3, '0')
}
function pause(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}
async function sendOneAccountManyRequests(lab) {
const requests = []
for (let number = 1; number <= 20; number++) {
requests.push({ account: 'cust-01', key: keyFor('t1', number), store: 'north' })
}
return sendAtOnce(lab, requests)
}
async function sendManyAccountsLastStock(lab) {
const requests = []
for (let number = 1; number <= 24; number++) {
const account = 'cust-' + String(100 + number)
requests.push({ account: account, key: keyFor('t2', number), store: 'north' })
}
return sendAtOnce(lab, requests)
}
async function sendSameKeyRetried(lab) {
const request = { account: 'cust-02', key: keyFor('t3', 1), store: 'north' }
const copies = []
for (let number = 1; number <= 12; number++) copies.push(request)
const atOnce = await sendAtOnce(lab, copies)
const later = await sendRedemption(lab, 12, request)
return atOnce.concat([later])
}
async function sendSameKeyDifferentBody(lab) {
const original = { account: 'cust-03', key: keyFor('t4', 1), store: 'north' }
const changed = { account: 'cust-03', key: keyFor('t4', 1), store: 'south', changedBody: true }
const first = await sendRedemption(lab, 0, original)
const second = await sendRedemption(lab, 1, changed)
const third = await sendRedemption(lab, 0, original)
return [first, second, third]
}
// The lab holds the write lock on its own connection while the first request
// arrives, so that request meets a busy database. The retry waits as told.
async function sendRetryAfterBusy(lab) {
const request = { account: 'cust-04', key: keyFor('t5', 1), store: 'north' }
lab.database.exec('BEGIN IMMEDIATE')
const first = await sendRedemption(lab, 0, request)
lab.database.exec('ROLLBACK')
const waitSeconds = first.retryAfter ? Number(first.retryAfter) : 1
await pause(waitSeconds * 1000)
const second = await sendRedemption(lab, 1, request)
return [first, second]
}
export const TESTS = [
{ id: 'T1', title: 'one account sends 20 requests at once, each with its own key', startingStock: 50, run: sendOneAccountManyRequests },
{ id: 'T2', title: '24 accounts send one request each for the last 3 vouchers', startingStock: 3, run: sendManyAccountsLastStock },
{ id: 'T3', title: 'one request sent 12 times at once with the same key, then once more', startingStock: 50, run: sendSameKeyRetried, sharedKey: true },
{ id: 'T4', title: 'the same key reused with a different body, then the original again', startingStock: 50, run: sendSameKeyDifferentBody, sharedKey: true },
{ id: 'T5', title: 'a request meets a busy database and is retried with the same key', startingStock: 50, run: sendRetryAfterBusy, sharedKey: true, busy: true },
]
// 500 and 503 answers did not complete, so they are left out of the key check.
function isCompleted(response) {
return response.status !== 500 && response.status !== 503
}
// For a test whose requests share one key: every completed answer to the
// original request is the same, the key produced at most one row, and a
// request that reused the key with a different body was refused with 422.
function keyHasOneResult(responses, state) {
const original = responses.filter((response) => isCompleted(response) && !response.request.changedBody)
const answers = new Set(original.map((response) => response.status + ' ' + JSON.stringify(response.body)))
const changed = responses.filter((response) => response.request.changedBody)
const changedRefused = changed.every((response) => response.status === 422)
return answers.size <= 1 && state.rows <= 1 && changedRefused
}
// Each check is true or false, or null where the test does not exercise it.
function checkInvariants(test, responses, state) {
const firstAnswer = responses[0]
return {
onePerAccount: state.mostForOneAccount <= 1,
withinStartingStock: state.rows <= test.startingStock && state.stock >= 0,
stockAddsUp: test.startingStock - state.rows === state.stock,
keyHasOneResult: test.sharedKey ? keyHasOneResult(responses, state) : null,
busyAnswerSaysRetry: test.busy ? firstAnswer.status === 503 && firstAnswer.retryAfter !== null : null,
}
}
export async function runTest(lab, test) {
resetState(lab.database, test.startingStock)
const responses = await test.run(lab)
const state = readDatabaseState(lab.database)
return { test: test, responses: responses, state: state, checks: checkInvariants(test, responses, state) }
}
export function listFailedChecks(checks) {
return Object.keys(checks).filter((name) => checks[name] === false)
}
================================================================
FILE 4 OF 5: run-lab.mjs
================================================================
// run-lab.mjs: usage: node run-lab.mjs
// Runs the five tests against the careless version, then the careful one,
// and prints a reconciliation table for each test.
import { openDatabase, readJournalMode, readSqliteVersion } from './store.mjs'
import { runTest, startLab, stopLab, TESTS } from './harness.mjs'
const CHECK_NAMES = [
['onePerAccount', 'one redemption per account'],
['withinStartingStock', 'redemptions within starting stock'],
['stockAddsUp', 'stock adds up (start - rows = left)'],
['keyHasOneResult', 'a key maps to one result'],
['busyAnswerSaysRetry', 'busy answer says try again'],
]
async function runVersion(version) {
const lab = await startLab(version)
console.log('Running the ' + version + ' version (SQLite journal mode: ' + readJournalMode(lab.database) + ').')
console.log(' Server log lines, if any, follow.')
const results = []
for (const test of TESTS) results.push(await runTest(lab, test))
const shutdown = await stopLab(lab)
return { version: version, results: results, shutdown: shutdown }
}
function printHeader() {
const memory = openDatabase(':memory:')
console.log('RACE CONDITION LAB: RECONCILIATION TABLES')
console.log('Node.js ' + process.version + ', SQLite ' + readSqliteVersion(memory) + ' (as node:sqlite reports it)')
console.log('Each version runs as two server processes, A and B, on one database file.')
console.log('')
memory.close()
}
function printShutdown(run) {
console.log('Servers stopped, ' + run.version + ': ' + run.shutdown.stopped.join(', '))
console.log('Database file removed, ' + run.version + ': ' + (run.shutdown.removed ? 'yes' : 'NO'))
}
function countSuccesses(result) {
return result.responses.filter((response) => response.status === 201)
}
function describeServers(result) {
const successes = countSuccesses(result)
const fromA = successes.filter((response) => response.server === 'A').length
return fromA + ' / ' + (successes.length - fromA)
}
function describeOtherAnswers(result) {
const counts = new Map()
for (const response of result.responses) {
if (response.status === 201) continue
const name = response.status + ' ' + response.body.error
counts.set(name, (counts.get(name) || 0) + 1)
}
if (counts.size === 0) return 'none'
return Array.from(counts, (entry) => entry[0] + ' x' + entry[1]).join('; ')
}
function describeCheck(value) {
if (value === null) return 'not tested'
return value ? 'held' : 'NOT HELD'
}
function printRow(name, careless, careful) {
console.log(' ' + name.padEnd(40) + String(careless).padEnd(18) + careful)
}
function printAnswersInOrder(result) {
const answers = result.responses.map((response) => {
const store = response.request.store
return response.status + ' (' + store + ') ' + JSON.stringify(response.body)
})
console.log(' ' + result.version + ': ' + answers.join(' | '))
}
function printTest(careless, careful) {
const test = careless.test
console.log(test.id + ' ' + test.title)
console.log(' starting stock ' + test.startingStock)
printRow('', 'careless', 'careful')
printRow('requests sent', careless.responses.length, careful.responses.length)
printRow('successes the clients were told (201)', countSuccesses(careless).length, countSuccesses(careful).length)
printRow(' answered by server A / server B', describeServers(careless), describeServers(careful))
const named = (result) => new Set(countSuccesses(result).map((response) => response.body.redemption)).size
printRow(' different redemptions they name', named(careless), named(careful))
printRow('rows in the redemptions table', careless.state.rows, careful.state.rows)
printRow('stock remaining', careless.state.stock, careful.state.stock)
for (const [key, name] of CHECK_NAMES) {
printRow(name, describeCheck(careless.checks[key]), describeCheck(careful.checks[key]))
}
console.log(' other answers, careless: ' + describeOtherAnswers(careless))
console.log(' other answers, careful: ' + describeOtherAnswers(careful))
if (test.sharedKey && careless.responses.length <= 3) {
console.log(' answers in order (status, store sent, body):')
printAnswersInOrder(Object.assign({ version: 'careless' }, careless))
printAnswersInOrder(Object.assign({ version: 'careful ' }, careful))
}
console.log('')
}
async function main() {
printHeader()
const careless = await runVersion('careless')
const careful = await runVersion('careful')
console.log('')
for (let index = 0; index < TESTS.length; index++) {
printTest(careless.results[index], careful.results[index])
}
printShutdown(careless)
printShutdown(careful)
}
await main()
================================================================
FILE 5 OF 5: race.test.mjs
================================================================
// race.test.mjs: a regression test that checks invariants, never exact counts,
// because timing changes from run to run and the counts change with it.
// Run: LAB_VERSION=careless node --test race.test.mjs (expect failures)
// node --test race.test.mjs (careful, expect passes)
import assert from 'node:assert/strict'
import { after, before, test } from 'node:test'
import { listFailedChecks, runTest, startLab, stopLab, TESTS } from './harness.mjs'
const version = process.env.LAB_VERSION || 'careful'
let lab
before(async () => {
lab = await startLab(version)
})
after(async () => {
await stopLab(lab)
})
for (const definition of TESTS) {
test(version + ' ' + definition.id + ': ' + definition.title, async () => {
const result = await runTest(lab, definition)
const failed = listFailedChecks(result.checks)
assert.deepEqual(failed, [], 'checks not held: ' + failed.join(', '))
})
}
================================================================
RUN IT
================================================================
node run-lab.mjs
node --test race.test.mjs
LAB_VERSION=careless node --test race.test.mjs
================================================================
PART C. OUTPUT OF node run-lab.mjs (run 1 of 3, Node.js v26.0.0, macOS)
================================================================
RACE CONDITION LAB: RECONCILIATION TABLES
Node.js v26.0.0, SQLite 3.53.4 (as node:sqlite reports it)
Each version runs as two server processes, A and B, on one database file.
Running the careless version (SQLite journal mode: delete).
Server log lines, if any, follow.
server A log: database is locked
Running the careful version (SQLite journal mode: delete).
Server log lines, if any, follow.
T1 one account sends 20 requests at once, each with its own key
starting stock 50
careless careful
requests sent 20 20
successes the clients were told (201) 20 1
answered by server A / server B 10 / 10 0 / 1
different redemptions they name 20 1
rows in the redemptions table 20 1
stock remaining 49 49
one redemption per account NOT HELD held
redemptions within starting stock held held
stock adds up (start - rows = left) NOT HELD held
a key maps to one result not tested not tested
busy answer says try again not tested not tested
other answers, careless: none
other answers, careful: 409 already redeemed x19
T2 24 accounts send one request each for the last 3 vouchers
starting stock 3
careless careful
requests sent 24 24
successes the clients were told (201) 24 3
answered by server A / server B 12 / 12 0 / 3
different redemptions they name 24 3
rows in the redemptions table 24 3
stock remaining 2 0
one redemption per account held held
redemptions within starting stock NOT HELD held
stock adds up (start - rows = left) NOT HELD held
a key maps to one result not tested not tested
busy answer says try again not tested not tested
other answers, careless: none
other answers, careful: 409 sold out x21
T3 one request sent 12 times at once with the same key, then once more
starting stock 50
careless careful
requests sent 13 13
successes the clients were told (201) 12 13
answered by server A / server B 6 / 6 7 / 6
different redemptions they name 12 1
rows in the redemptions table 12 1
stock remaining 49 49
one redemption per account NOT HELD held
redemptions within starting stock held held
stock adds up (start - rows = left) NOT HELD held
a key maps to one result NOT HELD held
busy answer says try again not tested not tested
other answers, careless: 409 already redeemed x1
other answers, careful: none
T4 the same key reused with a different body, then the original again
starting stock 50
careless careful
requests sent 3 3
successes the clients were told (201) 1 2
answered by server A / server B 1 / 0 2 / 0
different redemptions they name 1 1
rows in the redemptions table 1 1
stock remaining 49 49
one redemption per account held held
redemptions within starting stock held held
stock adds up (start - rows = left) held held
a key maps to one result NOT HELD held
busy answer says try again not tested not tested
other answers, careless: 409 already redeemed x2
other answers, careful: 422 idempotency key already used with a different request x1
answers in order (status, store sent, body):
careless: 201 (north) {"redemption":1} | 409 (south) {"error":"already redeemed"} | 409 (north) {"error":"already redeemed"}
careful : 201 (north) {"redemption":1} | 422 (south) {"error":"idempotency key already used with a different request"} | 201 (north) {"redemption":1}
T5 a request meets a busy database and is retried with the same key
starting stock 50
careless careful
requests sent 2 2
successes the clients were told (201) 1 1
answered by server A / server B 0 / 1 0 / 1
different redemptions they name 1 1
rows in the redemptions table 1 1
stock remaining 49 49
one redemption per account held held
redemptions within starting stock held held
stock adds up (start - rows = left) held held
a key maps to one result held held
busy answer says try again NOT HELD held
other answers, careless: 500 server error x1
other answers, careful: 503 busy, try again x1
answers in order (status, store sent, body):
careless: 500 (north) {"error":"server error"} | 201 (north) {"redemption":1}
careful : 503 (north) {"error":"busy, try again"} | 201 (north) {"redemption":1}
Servers stopped, careless: A (SIGTERM), B (SIGTERM)
Database file removed, careless: yes
Servers stopped, careful: A (SIGTERM), B (SIGTERM)
Database file removed, careful: yes
WHERE THE WINDOW COMES FROM
Inside one process: the careless version awaits the other service between its read and its write. While one request waits, the same process runs the other requests' code, so each of them reads the stock and the account's rows before any of them writes. In T1, server A on its own told cust-01 ten times that the voucher was theirs. node:sqlite runs each statement synchronously, so in this lab two requests in one process can only interleave at an await.
Between processes: server A and server B each hold their own connection to the same file, and each careless statement runs in its own short transaction. Nothing ties B's read to A's later write, so the window between processes is the whole gap between the read and the write. The 40 ms wait widens it; the lab was not run without the wait.
In the careful version, the decision is made only after BEGIN IMMEDIATE holds the write lock, so no other connection, in this process or the other one, can write between the check and the effect. The wait on the other service still happens, but before the transaction, where it decides nothing.
READING THE TABLES
T1 careless: 20 successes, 10 from each server, 20 rows for one account, and a stock of 49. Every request read 50 and wrote back 49.
T2 careless: 24 accounts were told they had one of 3 vouchers, 24 rows were stored, and the stock column says 2 are left.
T3 careful: 13 answers of 201, all naming redemption 1, and one row.
T4 careful: 422 for the request with the other store, then the original request got its first answer back. careless told the account's own repeat "already redeemed".
T5: both versions ended with one row, and both retries succeeded. careless answered the lock wait with 500 and its server logged "database is locked"; careful answered 503, and its "busy answer says try again" line reads held, which means the answer carried a Retry-After header. The output does not print the header's value: the 1 is set in server.mjs.
WHAT CAN DIFFER ON ANOTHER RUN
The lab ran three times. The output above is run 1. Runs 2 and 3 are summarised here, and their output is not shown on this page. Every count and every held or NOT HELD verdict was the same in all three runs. The one line that changed was which server answered the careful version's three T2 successes: 0 / 3 in run 1, and 3 / 0 in runs 2 and 3.
Can differ: which server answers which request; test timings; and the careless version's counts on a slower or busier machine, because they depend on how many requests read before the first write, which the 40 ms wait made all of them here.
Follow from the careful version's logic, so they should not differ: one success per account, no more successes than the starting stock, the stock adding up, and one answer per key. The exception: a careful request that waits longer than the 1,000 ms busy timeout gets 503 instead. That happened only in T5, where the lab caused it on purpose.
Redemption numbers start at 1 in every test, because each test empties the table first.
================================================================
PART D. THE REGRESSION TEST
================================================================
race.test.mjs runs the five tests against one version and asserts the invariants, never the counts, because timing changes the counts from run to run. With no LAB_VERSION it tests the careful version, so node --test, which finds files ending in .test.mjs, runs it in a pipeline. The Node.js test runner documentation says the process exit code is set to 1 if any test fails.
Each version was run five times. The ten runs are summarised after the two outputs.
OUTPUT OF node --test race.test.mjs (careful, run 1 of 5)
✔ careful T1: one account sends 20 requests at once, each with its own key (282.299708ms)
✔ careful T2: 24 accounts send one request each for the last 3 vouchers (62.965667ms)
✔ careful T3: one request sent 12 times at once with the same key, then once more (89.959792ms)
✔ careful T4: the same key reused with a different body, then the original again (130.325208ms)
✔ careful T5: a request meets a busy database and is retried with the same key (2215.477208ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2882.781333
OUTPUT OF LAB_VERSION=careless node --test race.test.mjs (run 1 of 5), with cuts marked
✖ careless T1: one account sends 20 requests at once, each with its own key (277.804833ms)
✖ careless T2: 24 accounts send one request each for the last 3 vouchers (55.142417ms)
✖ careless T3: one request sent 12 times at once with the same key, then once more (50.765917ms)
✖ careless T4: the same key reused with a different body, then the original again (46.418625ms)
server A log: database is locked
✖ careless T5: a request meets a busy database and is retried with the same key (2187.425625ms)
ℹ tests 5
ℹ suites 0
ℹ pass 0
ℹ fail 5
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2720.605875
✖ failing tests:
test at race.test.mjs:21:3
✖ careless T1: one account sends 20 requests at once, each with its own key (277.804833ms)
AssertionError [ERR_ASSERTION]: checks not held: onePerAccount, stockAddsUp
(cut: the diff, stack trace and error object follow here in the real output; the stack trace names local file paths)
test at race.test.mjs:21:3
✖ careless T2: 24 accounts send one request each for the last 3 vouchers (55.142417ms)
AssertionError [ERR_ASSERTION]: checks not held: withinStartingStock, stockAddsUp
(cut: the diff, stack trace and error object follow here in the real output; the stack trace names local file paths)
test at race.test.mjs:21:3
✖ careless T3: one request sent 12 times at once with the same key, then once more (50.765917ms)
AssertionError [ERR_ASSERTION]: checks not held: onePerAccount, stockAddsUp, keyHasOneResult
(cut: the diff, stack trace and error object follow here in the real output; the stack trace names local file paths)
test at race.test.mjs:21:3
✖ careless T4: the same key reused with a different body, then the original again (46.418625ms)
AssertionError [ERR_ASSERTION]: checks not held: keyHasOneResult
(cut: the diff, stack trace and error object follow here in the real output; the stack trace names local file paths)
test at race.test.mjs:21:3
✖ careless T5: a request meets a busy database and is retried with the same key (2187.425625ms)
AssertionError [ERR_ASSERTION]: checks not held: busyAnswerSaysRetry
(cut: the diff, stack trace and error object follow here in the real output; the stack trace names local file paths)
ALL TEN RUNS, copied by a script from each run's summary lines and exit code
LAB_VERSION run tests pass fail exit code
careful 1 5 5 0 0
careful 2 5 5 0 0
careful 3 5 5 0 0
careful 4 5 5 0 0
careful 5 5 5 0 0
careless 1 5 0 5 1
careless 2 5 0 5 1
careless 3 5 0 5 1
careless 4 5 0 5 1
careless 5 5 0 5 1
Failed checks, the same in all five careless runs:
T1 onePerAccount, stockAddsUp
T2 withinStartingStock, stockAddsUp
T3 onePerAccount, stockAddsUp, keyHasOneResult
T4 keyHasOneResult
T5 busyAnswerSaysRetry
================================================================
PART E. POINTING IT AT YOUR OWN STAGING WORKFLOW
================================================================
1. Pick one limited workflow and write its rule in a sentence: who may do it, how many times, and against what stock or balance.
2. Work on staging with test accounts and test data, never production records. Seed enough test accounts for T2, and a stock or balance you can reset between tests.
3. Replace sendRedemption in harness.mjs with a request to your staging endpoint, signed in as each test account. Replace readDatabaseState with read-only queries on the staging database: the most rows any one account has, the total rows, and the stock or balance left.
4. Keep each test to a few dozen requests at most. This checks a rule, not how much load the system can take.
5. Keep the invariant checks exactly as they are, and run the test in the pipeline that deploys the workflow, so a change that moves the check out of the transaction, or drops the constraint, fails a build.
================================================================
WHAT THE LAB DID NOT TEST
================================================================
The lab uses SQLite only. The PostgreSQL behaviour this page describes comes from the PostgreSQL 18 documentation, as read on 14 November 2026, and was not run here.
SQLite ran in its delete journal mode, as printed in the output. WAL mode was not tested.
It ran on macOS only, on Node.js v26.0.0 only.
It does not expire idempotency keys, and it does not claim a key before a slow step that has effects of its own, the case where the draft's 409 for a request still being processed applies.What a race condition vulnerability is
A web application that enforces a limit usually does it in two steps.
First it checks: has this account already used the voucher, is any stock left, does the balance cover the payment. Then it records the effect: the redemption, the lower stock, the debit. A race condition vulnerability is what happens when two requests arrive close enough together that both pass the check before either has recorded its effect. Each request was checked, and each was allowed. The limit was not kept.
MITRE catalogues the general weakness as CWE-362, Concurrent Execution using Shared Resource with Improper Synchronization, and lists Race Condition as its alternate term. Its description: the product contains a concurrent code sequence that requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence operating concurrently.
The entry names two properties a race breaks. Exclusivity means no other code sequence can modify the shared resource before the original sequence has completed.
Atomicity means no other thread or process can run the same sequence against the same resource at the same time.
The check-then-act form has an entry of its own, CWE-367, Time-of-check Time-of-use (TOCTOU) Race Condition: the product checks the state of a resource before using it, but the state can change between the check and the use in a way that invalidates the results of the check.
CWE-367 says this can be security-relevant when an attacker can influence the state of the resource between check and use. In a web application nobody needs access to the database to do that. A second request is enough.
In the standards, the OWASP Top 10:2025 lists CWE-362 among the CWEs mapped to A06:2025 Insecure Design. ASVS 5.0 gives the subject a section, V15.4 Safe Concurrency, which opens by giving race conditions, time-of-check to time-of-use vulnerabilities, deadlocks, livelocks, thread starvation and improper synchronization as examples of concurrency issues that can lead to unpredictable behaviour and security risks.
This guide is about timing: two requests that both pass a check before either records its effect, what that does to a limit, and the controls that close the gap.
One per customer, while stock lasts, balance must cover it: what a race does to each limit
The same gap breaks three kinds of limit, and each leaves a different trace.
- One per customer. A first-order discount, a free trial or a launch voucher checks whether this account has used it, then records the use. Two requests from one account both see "not yet", and the account gets the benefit twice. In the lab on this page, one test account sent 20 requests at once to the careless version and was told 20 times that the voucher was theirs.
- While stock lasts. The last seats, the last delivery slot or the last few vouchers check whether any are left, then take one. Every request that reads before the first one writes sees stock left. In the lab, 24 accounts competed for 3 vouchers, and the careless version told all 24 they had one.
- Balance must cover it. Store credit, a gift card or a wallet checks the balance, then debits it. This is the double spending form, and MITRE's first worked example for CWE-362 is a version of it: an e-commerce application that supports transfers between accounts, where the attacker makes two simultaneous calls for the same account. In MITRE's sequence, the first instance of the program reads a balance of 100.00, calculates a new balance of 20.00 for a transfer of 80.00 and calls the function that sends it to the database, and that call encounters a delay due to high server load. The second instance then reads 100.00 as well, because the first request was not processed yet, and determines a new balance of 99.00 for a transfer of 1.00. After the delay the first instance commits its balance of 20.00, and the second then sets the balance to 99.00. After 81.00 of transfers, the database records 99.00 where 19.00 was due.
The latest OWASP testing guide covers it under payment functionality
The latest edition of OWASP's Web Security Testing Guide covers the problem in WSTG-BUSL-10, Payment Functionality. Its race conditions subsection says that in payment contexts a race condition typically manifests when multiple concurrent requests interact with shared state, such as an account balance, an inventory count or a one-time-use coupon code, without adequate synchronisation, and says race conditions are particularly impactful in financial transactions, one-time-use tokens or codes, resource allocation with limited availability, and state transitions that should happen exactly once.
A published example: promotion limits in Sylius
The Sylius project published advisory GHSA-7mp4-25j8-hp5q, CVE-2026-31824, for a time-of-check to time-of-use race condition in its promotion usage limit enforcement. The advisory says the same class of flaw affected three limits: a promotion's usage limit, a coupon's usage limit and a coupon's per-customer usage limit.
It says that in all three cases the eligibility check reads the used counter (or order count) from an in-memory Doctrine entity during validation, while the actual usage increment happens later, during order completion, with no database-level locking or atomic operations between the two phases.
It then says that because Doctrine flushes an absolute value, SET used = 1, rather than an atomic increment, SET used = used + 1, and because the affected entities lack optimistic locking, concurrent requests all read the same stale usage counts and pass the eligibility checks simultaneously. The lab's careless version writes back an absolute value in the same way.
The advisory says the flaw may lead to direct financial loss, rates it high with a CVSS v3.1 score of 8.2, and lists fixed versions of Sylius: 1.9.12, 1.10.16, 1.11.17, 1.12.23, 1.13.15, 1.14.18, 2.0.16, 2.1.12 and 2.2.3.
Why one server process, or one thread, does not prevent it
Node.js uses a single JavaScript thread by default, so it is tempting to assume two requests in one process cannot overlap.
The Node.js documentation's description of the event loop shows why they can. The event loop is what allows Node.js to perform non-blocking I/O operations, despite a single JavaScript thread being used by default, by offloading operations to the system kernel whenever possible.
When one of these operations completes, the guide says, the kernel tells Node.js so that the appropriate callback may be added to the poll queue to eventually be executed.
A request that awaits a network call to a database, a payment provider or any other service gives the thread back while it waits, and the process runs other requests' code in the meantime.
The window, then, is the await between the check and the write. CWE-362 describes the assumption that hides it: programmers may assume that certain code sequences execute too quickly to be affected by an interfering code sequence. In the lab's careless version, server process A on its own told one test account ten times that the voucher was theirs, because all ten of its requests had read "not yet redeemed" before any of them came back from the wait.
More processes add a second window. Behind a load balancer, two processes or two containers each hold their own connection to the database, and what one of them read a moment ago says nothing about what the other is writing now. In the lab, the careless version's 20 successes for one account came 10 from process A and 10 from process B.
A lock, flag or counter kept in one process's memory cannot see the other process at all. The rate limiting guide in this library works through the same arithmetic for request counters kept in each server.
Why it shows up as stock that does not add up, not as an error
A race does not look like a failure while it happens.
In the lab's T2, all 24 requests to the careless version got a 201 and a redemption number, and neither server logged an error, because nothing failed: each request did exactly what its code said, with information that was true when it read it.
The evidence is in the arithmetic afterwards. In the lab's T2, the redemptions table held 24 rows against a starting stock of 3, and the stock column said 2 were left. The careless version reads the stock, waits, and writes back the value it read minus one, so 24 requests that all read 3 all wrote 2.
Each write replaced the one before it instead of building on it. CWE-362's transfer example ends the same way, with 99.00 recorded where 19.00 was due.
So a race needs a reconciliation, not a search of the error log. Count what clients were told, count what was stored, and compare both with the starting stock or balance. The latest WSTG payment test says indicators of vulnerability include multiple success responses for a single-use action, negative balances after concurrent debits, resources allocated beyond stated capacity, or duplicate side effects such as multiple emails or double charges.
It is also why a race can go unnoticed. CWE-362 says black box methods may be able to identify evidence of race conditions via methods such as multiple simultaneous connections, but that race conditions with very narrow timing windows would not be detectable. A research gap note in the same entry says race conditions in web applications are under-studied and probably under-reported.
Two kinds of fix: one indivisible step, or a harmless repeat
Two different problems hide under the one name, and each has its own control.
The first is two different requests that must not both succeed: two clicks from one account, or two customers after the last voucher. The fix is to make the check and the effect one indivisible step, so the second request sees the first one's effect. The second is one request that arrives twice: a phone that lost its connection and resent, a payment page submitted again, a queue that delivered a message twice.
The fix is to make the repeat harmless, so the second copy gets the first copy's answer instead of doing the work again.
Neither control does the other's job, and the lab shows both gaps. An idempotency key cannot enforce "one per customer", because nothing stops one account sending 20 requests with 20 different keys, which is what the lab's T1 does. The careful version allowed one of them, and its keys played no part in that.
A check that refuses a second redemption cannot give a retry its original answer either. In T4, the careless version told the account's own repeat of a successful request "already redeemed"; only the careful version, which stores each key's answer, returned the first answer again.
ASVS 5.0 has requirements that bear on the first kind of fix. Requirement 2.3.3, at Level 2, asks that transactions are used at the business logic level, so that a business logic operation either succeeds in its entirety or is rolled back to the previous correct state.
Requirement 2.3.4, also at Level 2, asks for business logic level locking mechanisms so that limited quantity resources, such as theatre seats or delivery slots, cannot be double-booked by manipulating the application's logic.
Requirement 15.4.2, at Level 3, asks for checks on a resource's state and the actions that depend on them to run as a single atomic operation, and gives checking that a file exists before opening it, or verifying a user's access before granting it, as examples.
Requirement 2.1.3, at Level 2, asks that expectations for business logic limits are documented, both per user and globally across the application. That written list is where your race tests start.
For "one per customer", the strongest control is a constraint the database checks on every write, whichever code path made it. SQLite's documentation says that for each UNIQUE constraint on a table, each row must contain a unique combination of values in the columns it names.
PostgreSQL's says a unique constraint over a group of columns makes the combination unique across the whole table, and that adding one creates a unique B-tree index.
With UNIQUE (account_id, voucher), a second redemption for the same account fails at the database even when two requests both passed the application's own check. The lab's careful version has that constraint behind its transaction.
Two details decide whether the constraint holds. The first is NULL. SQLite says that for UNIQUE constraints NULL values are considered distinct from all other values, including other NULLs, and PostgreSQL says that by default two null values are not considered equal, so rows with a null in a constrained column can repeat unless the constraint uses NULLS NOT DISTINCT.
A guest checkout with no account id would pass straight through a constraint on account and voucher, so make both columns NOT NULL or give guests an identifier of their own. The second is a backstop for counts.
A CHECK constraint such as stock >= 0 refuses a write that would take the stock below zero: SQLite evaluates it each time a row is inserted or updated, and its documentation notes that verification of CHECK constraints can be temporarily disabled with PRAGMA ignore_check_constraints=ON.
For "while stock lasts" and "balance must cover it", the check and the change have to happen together. CWE-367 gives the rule as a mitigation: ensure that locking occurs before the check, as opposed to afterwards, such that the resource, as checked, is the same as it is when in use.
Of the alternative, shortening the time between check and use, it says this will not fix the problem, though it could make an attack harder to pull off.
In SQLite the lock is the database's single write lock. Its documentation says SQLite supports multiple simultaneous read transactions but only one simultaneous write transaction, and that BEGIN IMMEDIATE causes the connection to start a new write immediately, without waiting for a write statement. The default, BEGIN DEFERRED, starts as a read when the first statement is a SELECT and tries to upgrade at the first write, returning SQLITE_BUSY if it cannot.
The lab's careful version opens every decision with BEGIN IMMEDIATE, so no other connection can write between its check and its change.
In PostgreSQL, SELECT ... FOR UPDATE locks the rows it returns: the documentation says other transactions that try to update, delete or lock those rows are blocked until the current transaction ends. A shorter form needs no separate read at all. UPDATE vouchers SET stock = stock - 1 WHERE code = ?
AND stock > 0, then check how many rows changed: none means sold out. PostgreSQL documents that at its default isolation level, an UPDATE whose target row was changed by a concurrent transaction waits for that transaction and, if it commits, re-evaluates its WHERE clause against the updated version of the row.
The stock > 0 condition is therefore tested against the latest value. The lab's careful version uses the same statement on SQLite.
For an insert that may collide, PostgreSQL's ON CONFLICT clause replaces the unique violation error with an alternative action. DO NOTHING skips the row; DO UPDATE updates the existing one, and the documentation says it gives an atomic insert-or-update outcome, provided there is no independent error, even under high concurrency.
A transaction that holds a lock while it waits on another service holds up every other transaction that needs that lock. On SQLite, where the lock is the database's single write lock, that is every other writer. On PostgreSQL the effect can be narrower: section 13.3.2 of the documentation says row-level locks block only writers and lockers to the same row.
PostgreSQL's documentation says a transaction seeking a conflicting lock waits indefinitely as long as no deadlock is detected, and calls it a bad idea for applications to hold transactions open for long periods of time, for example while waiting for user input.
The lab's careful version calls the other service first and opens its transaction afterwards, so nothing inside the transaction waits on anything but the database.
That order is only safe when the outside call has no effect of its own, such as a lookup. If it charges a card or sends an email, the effect needs the protection in the next section: an idempotency key, claimed before the call, so a repeat of the request cannot repeat the effect. That is this page's advice, and the lab does not implement it.
What your database's default isolation level does and does not stop
An isolation level decides what one transaction can see of another's work.
It is easy to read it as a promise that concurrency is handled. For a limit check, it is narrower than that.
The PostgreSQL 18 documentation, read on 14 November 2026, says Read Committed is the default isolation level in PostgreSQL, and the table in the same section shows that at Read Committed dirty reads are not possible, while nonrepeatable reads, phantom reads and serialization anomalies are.
At Read Committed, it says, a SELECT query without a FOR UPDATE/SHARE clause sees a snapshot of the database as of the instant the query begins to run, and two successive SELECT commands within a single transaction can see different data if other transactions commit changes after the first SELECT starts and before the second SELECT starts.
A count read in one statement can therefore be out of date by the next statement, inside the same transaction: two transactions that each read "1 left" with a plain SELECT, then write, can both sell it.
What Read Committed does give you is the WHERE re-check on UPDATE described above, which is why a conditional update or a FOR UPDATE lock works at this level where a read followed by a write does not.
The stricter levels change how the problem fails, not whether you handle it. PostgreSQL says applications using Repeatable Read or Serializable must be prepared to retry transactions due to serialization failures, which always return SQLSTATE 40001. It adds that at Repeatable Read, attempts to enforce business rules are not likely to work correctly without careful use of explicit locks to block conflicting transactions.
Of Serializable, it says the level works exactly the same as Repeatable Read except that it also monitors for conditions which could make execution of a concurrent set of serializable transactions behave in a manner inconsistent with all possible serial (one at a time) executions of those transactions.
Its worked example has two serializable transactions for which there is no serial order of execution consistent with the result: one is allowed to commit and the other is rolled back with a serialization failure. The code has to catch that failure and run the whole transaction again.
SQLite works differently. Its documentation says all transactions in SQLite show serializable isolation, apart from shared-cache connections with read_uncommitted turned on, because SQLite actually serializes the writes: there can only be a single writer at a time.
That protects one transaction. It does not join two. The lab's careless version runs its SELECT and its later INSERT and UPDATE as separate statements, and SQLite's transaction page says any command that accesses the database automatically starts a transaction if one is not already in effect, and that automatically started transactions are committed when the last SQL statement finishes. Each of those statements was isolated, and the limit still broke.
Idempotency keys: making a retried request harmless
HTTP already says which requests may be repeated.
RFC 9110 calls a request method idempotent if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request, and says that of the request methods it defines, PUT, DELETE and the safe request methods are idempotent.
The Internet-Draft introduced in the next paragraph says that, per RFC 9110, the methods OPTIONS, HEAD, GET, PUT and DELETE are idempotent while POST and PATCH are not. RFC 9110 says a client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied.
An idempotency key gives a POST that means. An IETF Internet-Draft, The Idempotency-Key HTTP Header Field, defines a request header that, in its abstract's words, can be used to make non-idempotent HTTP methods such as POST or PATCH fault-tolerant. In revision 08 of the draft, section 2 defines an idempotency key as a unique value generated by the client which the resource uses to recognise subsequent retries of the same request, and section 2.6 treats a request as a duplicate when its idempotency key and fingerprint have been seen.
This page reads those two sections as meaning that a retry has to carry the key the original request carried.
"Resource" is the draft's term: section 1.1 says it is to be interpreted as defined in Section 3.1 of RFC 9110, that is, identified by a URI. This page's own gloss is the server-side endpoint that receives the request.
On 14 November 2026 the IETF Datatracker listed revision 08, dated 22 October 2026 and expiring on 25 April 2027, as an active Internet-Draft of the httpapi working group, with no newer revision and no RFC. That is a snapshot from that day, so check the Datatracker for the draft's current state.
The draft's own boilerplate says Internet-Drafts may be updated, replaced or obsoleted by other documents at any time, and that it is inappropriate to cite them other than as work in progress.
Revision 08 sets out what the resource should do:
- The key MUST be unique and MUST NOT be reused with another request with a different request payload. Section 2.1 says the header field's value MUST be a String, citing section 3.3.3 of RFC 9651 for that type, and section 2.2 says it is RECOMMENDED that a UUID or a similar random identifier be used as an idempotency key.
- A resource MAY use a fingerprint of the request payload alongside the key, such as a checksum of the whole payload or of selected parts of it.
- A retry after the original request completed SHOULD get a response consistent with the request being completed according to the user's intent. A retry while the original is still being processed SHOULD get 409. A key reused with a different payload SHOULD get 422, and a missing key on an operation documented as requiring one SHOULD get 400.
- The resource MAY require time-based idempotency keys, to be able to purge or delete a key upon its expiry, and SHOULD define such an expiration policy and publish it in the documentation. Resources MUST publish an idempotency-related specification, which MUST include expiration related policy if applicable.
- Its security considerations recommend establishing a fixed format for the key and publishing its specification, always validating the key against that specification before processing any request, and implementing a unique composite key on the resource as the idempotent cache lookup key. As an example, they say a composite key MAY be implemented by combining the key the client sent with other client-specific attributes known only to the resource. They warn that low-entropy keys may let attackers determine other keys and fetch cached entries belonging to other clients.
The wording is still moving
Revision 07, dated 15 October 2025, said a retry after completion SHOULD get the result of the previously completed operation, success or an error. Revision 08 replaced that with the wording above, and its change list says the new text for the Retry case was adopted and is still open for discussion. Check the current revision before building to either.
Providers publish their own rules. Stripe's API reference says that for its API v1 it saves the status code and body of the first request made with a key after endpoint execution begins, and that retries with the same key return the saved response, including 500 errors.
Its idempotency layer compares incoming parameters with the original request's and errors if they differ. Keys are up to 255 characters long. For API v1, the reference says keys can be removed from the system automatically after they are at least 24 hours old, and that Stripe generates a new request if a key is reused after the original is pruned.
For API v1, Stripe also says that a request which conflicts with another one executing concurrently has no result saved, and can be retried.
Where the key lives in your own code
The lab's careful version stores keys per account, with the account and the key together as the primary key. That is a composite lookup key, which the draft's security considerations recommend; using the account as its second part is the lab's own choice.
In server.mjs, the handler checks the method and path first, then the account header and the JSON body, and then, in the careful version, the key's format, answering 400 for a missing or malformed key before it calls the other service or opens a transaction.
That order is read from the code: no test in the lab sends a missing or malformed key, so no output in the asset shows that 400. Inside the same BEGIN IMMEDIATE transaction as the redemption it looks the key up: a stored answer with the same body fingerprint is replayed, a different fingerprint gets 422, and a new key runs the redemption and stores its answer before COMMIT.
In T3, twelve copies sent at once and a thirteenth sent later all got 201 naming the same redemption, and the table held one row.
Because the key, the row and the stored answer commit together, the busy failure in T5 left no row and no key behind, and the retry ran once.
That design holds when everything the request changes lives in the same database. When the request also calls something with effects of its own, such as a payment provider, claim the key in its own committed transaction before the call, answer duplicates that arrive meanwhile with the draft's 409, and record the final answer afterwards.
Decide in advance what happens to a claim whose request died halfway, because a key stuck in "processing" turns every retry into a 409. This is this page's advice; the lab does not implement it.
What to return to the request that lost
Every race has a loser, and what it is told decides whether a customer understands, retries in a loop, or rings support.
RFC 9110 defines 409 Conflict as a request that could not be completed due to a conflict with the current state of the target resource, used where the user might be able to resolve the conflict and resubmit, and says the server SHOULD generate content that includes enough information for a user to recognise the source of the conflict. The mapping below is this page's advice, with sources named where they apply.
- Already redeemed, or sold out: 409, with a message a person can act on. The lab's careful version sends "already redeemed" and "sold out" as different messages, because one means "you have it" and the other means "nobody can have it".
- A key reused with a different body: 422, as the Idempotency-Key draft says, and the request does not run.
- A duplicate that arrives while the first copy is still running, where the key is claimed before a slow step: 409, as the draft says.
- The database stayed busy: 503 with Retry-After. RFC 9110 says 503 indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay, and that the server MAY send Retry-After to suggest how long the client should wait. In T5 the careless version answered a lock wait with 500 and logged "database is locked"; the careful version answered 503 with a Retry-After header, and the client's retry succeeded. The lab's output shows that the header was present, not its value, which server.mjs sets to 1.
- Never 201 for a request that did not get what it asked for, and never a 201 after the fact for an effect the database refused.
Retry inside the server first, within a limit
A short wait inside the server spares the client a refusal. SQLite's documentation says sqlite3_busy_timeout() sets a busy handler that sleeps for a specified amount of time when a table is locked: the handler sleeps multiple times until at least the given number of milliseconds of sleeping have accumulated, after which it returns 0, which causes sqlite3_step() to return SQLITE_BUSY.
The Node.js documentation describes node:sqlite's timeout option as the busy timeout in milliseconds, the maximum amount of time that SQLite will wait for a database lock to be released before returning an error, with a default of 0.
SQLite's documentation says that calling sqlite3_busy_timeout() with an argument less than or equal to zero turns off all busy handlers. The lab sets 1,000 ms for both versions.
PostgreSQL's documentation asks for transactions that hit serialization failures to be retried from the beginning. On deadlocks, it says the best defence is generally to avoid them by being certain that all applications using a database acquire locks on multiple objects in a consistent order, and adds that one should also ensure the first lock acquired on an object in a transaction is the most restrictive mode that will be needed for that object.
If it is not feasible to verify this in advance, it says, deadlocks can be handled on the fly by retrying transactions that abort due to deadlocks. Past your limit, answer 503 with Retry-After and let the client wait.
How to test for race conditions on staging with a few dozen requests
A race test asks one question per limit: when several requests that should not all succeed arrive together, how many does the application say succeeded, and how many does it store?
Answering that takes a few dozen parallel requests, not volume. Run them against your own staging environment, with test accounts and test data you can reset, and only against a system you own or are authorised in writing to test.
The tests worth running for each limited workflow are the lab's five: many requests for one account; many accounts competing for the last few items; the same request retried with the same key; the same key with a different body; and a retry after a busy result.
Write the expected result for each down before sending anything. The introduction to business logic testing in WSTG v4.2 says a third-party tester is going to have to use common sense and ask the business whether different operations should be allowed by the application. This page's advice is to treat the answers to those questions as your expected results.
Which edition of the OWASP testing guide you read matters here. The stable edition, v4.2, lists nine business logic tests, and none of their titles names race conditions or concurrent requests. Its nearest, WSTG-BUSL-05, checks that a function which must be limited, such as a discount an e-commerce site may only allow once per transaction, really is.
The latest edition, which OWASP says represents the latest contributions to the guide and may frequently change, adds WSTG-BUSL-10, Payment Functionality, with a race conditions subsection.
It says to focus on endpoints where a value is checked and then modified, or where an action should only succeed once, to send multiple identical requests simultaneously, and to observe whether more than one succeeds when only one should.
CWE-362 describes the same idea from the code's side. Under automated dynamic analysis, which it rates moderate in effectiveness, it says race conditions may be detected with a stress-test that calls the software simultaneously from a large number of threads or processes, and that breakpoints or delays inserted between relevant code statements artificially expand the race window, making it easier to detect.
The lab's 40 ms wait is that kind of delay, in the lab's own code. It uses a few dozen requests instead of a large number.
None of this is load testing. Load, volumetric and denial-of-service testing measure how much a system can take, and they are separate work for a load-testing specialist, with your host's written approval.
Reconciling the counts after each test
After each test, set four numbers side by side: the requests sent, the successes the clients were told about, the rows the database holds, and the stock or balance remaining. Then mark each invariant held or not held: one redemption per account, no more redemptions than the starting stock, the stock adding up (starting stock minus rows equals stock remaining), and one result per key.
Timing varies from run to run, so the counts can change between runs, while the invariants should not.
A regression test should assert the invariants and never an exact count, which is how the lab's race.test.mjs is written.
What the parallel-request lab shows
The lab is an illustration written for this page: an invented bakery with one voucher, FREE-LOAF, two stores and invented test accounts.
Each version, careless and careful, runs as two Node.js server processes on one SQLite database file. Every process listens on 127.0.0.1 on a port the operating system assigns, because the lab asks for port 0, and each is stopped through its own process handle when the run ends.
The lab imports only node:sqlite, node:http, node:crypto, node:child_process, node:events, node:fs, node:path, node:url, node:assert/strict and node:test, and installs no packages. It was recorded on Node.js v26.0.0, where node:sqlite reported SQLite 3.53.4. The SQLite behaviour this page describes comes from the documentation on sqlite.org as it read on 14 November 2026.
The PostgreSQL behaviour comes from the PostgreSQL 18 documentation, read on the same day at its version 18 addresses. A later PostgreSQL version may behave differently, so check the documentation for the version you run. None of the PostgreSQL behaviour was run in the lab.
The careless version reads, waits 40 ms on a stand-in for another service, then writes. That fixed wait is the lab's own device for making the careless failure appear on every run, and the asset says so.
Inside one process, the window is that await. Between the two processes, it is the whole gap between the read and the write, because each process has its own connection and each statement its own short transaction.
The careful version waits first, then decides and writes inside one BEGIN IMMEDIATE transaction, with a UNIQUE constraint, a CHECK on stock and a table of idempotency keys behind it.
What the runs showed
The T1 to T5 results in this paragraph, and wherever else this page quotes them, are from run 1 of the lab, whose output Part C of the asset shows. Careless: in T1, 20 successes and 20 rows for one account, with the stock showing 49 of 50 left.
In T2, 24 successes and 24 rows against 3 vouchers, with the stock showing 2 left. In T3, 12 rows for one key. In T4, the account's repeat of its own request was told "already redeemed". In T5, a 500. Careful: one success in T1, three in T2 with the stock at 0, thirteen answers naming one redemption in T3, 422 and then the original answer in T4, and 503 with a Retry-After header followed by a 201 in T5. The header's value, 1, is set in server.mjs and is not printed in the output.
The lab ran three times. The asset shows the output of run 1 and summarises runs 2 and 3 without showing their output: every count and every verdict matched across the three runs, and the one difference was which server process answered the careful version's T2 successes.
The regression test ran five times on each version. Part D of the asset shows the output of run 1 for each version, the careless one with its cuts marked, and a table built from the summary lines and exit code of each of the ten runs; the output of runs 2 to 5 is not shown.
The careful version passed all five tests in every run, with exit code 0.
The careless version failed all five in every run, with the same failed checks each time and exit code 1, which the Node.js test runner documentation says it sets when any test fails.
What to watch for in production
A race that testing missed leaves the same arithmetic behind in production, so check the arithmetic on a schedule.
The lab's invariants become queries, and any row they return is worth an alert to a named person:
- Any account with more than one redemption of an offer meant to be used once.
- Total redemptions above the stock that was issued, and any stock or balance below zero.
- Stock that does not add up: issued minus redeemed, set against what the stock column says.
- One idempotency key linked to more than one effect, where you store keys.
- A burst of 409 or 422 answers for one account, and the counts of busy, deadlock and serialization failures, which show where requests are colliding.
- Duplicate side effects. The latest WSTG payment test names multiple emails and double charges among its indicators of vulnerability.
Keep what you need to explain a broken invariant
Keep the request records that would show which requests produced a broken row: the account, the key, the time and the answer given. Collecting and alerting on security events across an application is the subject of the planned security logging and monitoring guide in this library.
What this guide leaves to other guides
Race conditions sit beside several neighbouring topics, each with a guide of its own in this library:
- Business logic vulnerabilities: steps that one caller performs out of order or skips, such as confirming an order before paying, where timing plays no part.
- Broken access control and IDOR: whether the caller may touch a record at all, which no amount of locking decides.
- API security, a planned guide: the wider API surface, including which endpoints exist and what each one accepts.
- Rate limiting: how many requests a client may send in a window, and why counters kept in each server multiply a limit.
- Security logging and monitoring, a planned guide: collecting the events listed above and alerting on them.
Where an outside test fits
Your own tests cover the limits you have written down.
In a Clever Ops web application and API penetration test, business logic is tested against the rules you give in writing, and the test methodology has a checkpoint for limited resources booked twice (ASVS 5.0 requirement 2.3.4). With test accounts, two of them request the last slot, seat or stock item at nearly the same moment, using a handful of requests, to see whether both succeed.
Where read-only code access is in scope, the booking code is read for a lock or transaction around the availability check and the write.
Requests stay under an agreed rate, and Clever Ops does not run load or denial-of-service testing. Destructive actions are off by default for real people's accounts and records that existed before the test, and reset, lockout and deletion checks run only on test accounts and test records where the rules of engagement allow them.
Test data is tracked as it is created, then removed or listed in the report for your team to remove.
Very logic-heavy products, such as marketplaces, lending platforms and multi-tenant billing, are scoped individually or referred to a larger firm. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
Two or more requests arrive close enough together that each passes a check, such as "one per customer" or "is any stock left", before any of them records its effect, so more of them succeed than the limit allows. MITRE catalogues the general weakness as CWE-362 and the check-then-use form as CWE-367. It shows up afterwards as stock, credit or redemptions that do not add up, rather than as an error.
The balance form of the problem: two debits each read a balance that covers one of them, and both go through. MITRE's first worked example for CWE-362 has two simultaneous transfers both read 100.00, and the database ends at 99.00 where 19.00 was due. The fix is a debit that carries its own condition, or a row lock taken before the check, inside one transaction, so the second debit sees the first.
Only when the check and the change are in the same transaction and the lock is taken before the check, with SELECT ... FOR UPDATE in PostgreSQL or BEGIN IMMEDIATE in SQLite, or when the change carries the condition itself, as in UPDATE ... WHERE stock > 0. In the PostgreSQL 18 documentation, the default isolation level, Read Committed, allows nonrepeatable reads and serialization anomalies. The documentation says that at this level two successive SELECT commands can see different data, even though they are within a single transaction, if other transactions commit changes after the first SELECT starts and before the second SELECT starts. This page's conclusion from that: a value read in one statement is not protected for the next.
No. While one request awaits a network call to a database or another service, the event loop runs other requests' code on the same thread. In the lab on this page, one server process told the same account ten times that its single voucher was theirs, and a second process told it ten more times.
Checking that a request repeated with the same idempotency key has the effect of one request: every repeat gets the first answer back, the database holds one row, and the same key with a different body is refused. The lab's T3 and T4 do this. The Idempotency-Key header comes from an IETF Internet-Draft. On 14 November 2026 the IETF Datatracker listed revision 08, dated 22 October 2026, and no RFC; check the Datatracker for its current state.
A few dozen at most per test, sent at once to your own staging environment with test accounts and test data. The question is whether more requests succeed than the limit allows, not how much load the system takes. Load and denial-of-service testing is separate work for a load-testing specialist, with your host's written approval.
The winner gets its normal success. The loser gets 409 Conflict with a reason it can act on, such as "sold out". RFC 9110 section 15.5.10 says the 409 status code indicates that the request could not be completed due to a conflict with the current state of the target resource, and that it is used in situations where the user might be able to resolve the conflict and resubmit the request. Using it for a sold-out item, where the user may have nothing to resolve, is this page's own judgement: the request did conflict with the current state of the resource, and the message says why. If the database was too busy to decide, 503 with Retry-After tells the client to try again later.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.