Skip to main content
Security guideReviewed

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.

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 it

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

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.

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.

Constraints: let the database refuse the second row

For "one per customer", the strongest control is a constraint the database checks on every write, whichever code path made it. 1 min read

Locks and transactions: take the lock before the check

For "while stock lasts" and "balance must cover it", the check and the change have to happen together. 2 min read

Keep the slow call outside the transaction

A transaction that holds a lock while it waits on another service holds up every other transaction that needs that lock. 1 min read

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.

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.