Twice, at Once, Eventually
Testing races, retries and slow work, and keeping a growing suite trustworthy

In Part 1 we saw that a 200 proves less than it seems. Part 2 checked whether an API keeps its promises, and Part 3 asked who's allowed to do what. Every test so far has had one thing in common. It sends one request, waits calmly for the answer, and checks it.
Real clients aren't that polite. They double-click, retry when the network drops, and send requests at the same moment as a thousand other users. Some work doesn't finish when the response arrives. This part is about what breaks then, and how to keep a growing suite honest while you test it.
This is Part 4 of Beyond the 200: An Advanced Guide to API Testing, and the last one. By the end you'll be able to test races, retries and slow work without flaky tests, generate test inputs instead of picking them, and decide where each kind of test belongs.
Before you start
This part builds on the earlier ones. An idempotent request has the same effect on the server whether you send it once or many times. Read-back verification means confirming a write with a separate request. A flaky test sometimes passes and sometimes fails with no change to the code, and a known issue is a failure you've written down and expect until it's fixed.
Load testing, which measures how much traffic a system can take, is out of scope. "Scale" here means a test suite that keeps growing. The examples use the same imaginary bookshop API as the earlier parts, and every request and response is an illustration.
When requests overlap
A race condition is a bug where the result depends on the timing of requests that overlap. Each request is correct on its own. Together, they get in each other's way.
The classic shape is check, then act. For example, imagine adding a book to a cart. The server checks whether the cart already has a row for that book. If it does, it adds to the quantity. If not, it creates a row. Now send two of those requests at the same moment.

Both requests saw an empty cart, so both created a row. Nothing failed, and the cart is wrong.
To test this, you need requests that really overlap. In Playwright, Promise.all sends them close together:
const add = () => request.post('/cart/items', { data: { book_id: 'b-17', quantity: 1 } });
const results = await Promise.all([add(), add(), add(), add()]);
for (const res of results) expect(res.ok(), await res.text()).toBe(true); // shows the body if not
const cart = await (await request.get('/cart')).json();
const rows = cart.items.filter((item) => item.book_id === 'b-17');
const total = rows.reduce((sum, item) => sum + item.quantity, 0);
expect(total).toBe(4); // a lost addition makes this short
expect(rows).toHaveLength(1); // duplicate inserts make this 2 or more
In REST Assured, an ExecutorService does the same job. Postman's collection runner sends requests one after another, so it can't produce an overlap on its own.
Both checks are rules a correct API always meets. Something that should be true whatever happens is called an invariant. They catch different races, though. If one request's addition is lost, the total comes out short. If two requests both create a row, the row count is wrong. Timing decides whether a buggy API breaks either rule on a given run. On a quiet run, the requests may not overlap at all, and the bug stays hidden.
๐ก Expert tip
I've seen parallel additions to an empty cart create two or three rows for the same book, while the total quantity stayed correct. A test that checked only the total would never notice. So check both, and send several rounds of parallel requests in one test to give the race a fair chance. If the row check fails now and then, it looks like a flaky test, but the variation may come from the API. Rule out the test first, then report a confirmed race as a product bug.
Remember that a passing race test proves less than other tests do. It shows the race didn't happen this time, not that it can't.
Two writes, one winner
Part 1 promised a closer look at a quieter race. Two people edit the same book at the same moment, and one change silently replaces the other. That's called a lost update. Both PUT requests are idempotent, and the result is still wrong.
The standard fix uses the ETag from Part 1, the version label the server sends with a response. The client sends back the version it read in an If-Match header, and the server refuses the write if the record has changed since. The refusal is a 412 Precondition Failed, which means a condition in the request headers wasn't met. This needs a strong ETag. If-Match never matches a weak one, marked W/, so every conditional write would be refused.
GET /books/b-17 โ 200 OK, ETag: "v3"
PUT /books/b-17 If-Match: "v3" { "price": 12.99 } โ 200 OK, ETag: "v4"
PUT /books/b-17 If-Match: "v3" { "price": 9.99 } โ 412 Precondition Failed
Test that a stale version is refused, that the record still holds the first change, and that a fresh version is accepted. If the API doesn't support this, "last write wins" is a design choice, so ask whether it was made on purpose.
Double submission
Double submission means the same action arrives twice, usually from a double-click or a client that retried. For example, send the same checkout twice, first one after the other, then in parallel:
POST /orders { "cart_id": "c-301" } โ 201 Created (order 1042)
POST /orders { "cart_id": "c-301" } โ 201 Created (order 1043)
One cart, two orders. The second request should have been refused, or it should have returned the first order. Read back the customer's orders and count them, because the statuses alone look perfectly healthy.
โ ๏ธ Common mistakes
- Checking only the response when a write fails. A failed checkout should leave nothing behind. I've seen one return an error while an empty order stayed in the customer's history. Read back after failures too.
- Running overlap tests against shared data. Give each test its own cart and its own book, as Part 2 described, or parallel tests will race each other instead of the API.
๐งช Try it
Pick a write you're allowed to test, such as adding to a cart or placing an order, in an environment you own. Send the same request four times at once, then read back the result. Is it what four requests one after another would give? Run it a few more times before you decide.
Retries and idempotency keys
Networks fail. When a request times out, the client can't tell whether the server never got it or did the work and lost the reply. RFC 9110 says idempotent requests can be retried automatically after a failure like that. It also says a client SHOULD NOT automatically retry other requests unless it knows they're safe to repeat.
So how do you retry a payment safely? A common answer is an idempotency key, which is a unique value the client sends with a request so the server can recognise a retry of it. When the same key comes back, the server doesn't do the work again. It usually returns the response it stored for the first request, or one consistent with it.

Several payment APIs use this pattern, and an IETF draft is standardising an Idempotency-Key header. As of November 2026 it's still a draft, not an RFC, so check what your API documents. Here's what to test, with the statuses the draft suggests:
| Situation | What should happen |
|---|---|
| Same key, same body | The original result, or one consistent with it, and only one order exists |
| Same key, different body | Refused, 422 in the draft, if the server compares bodies |
| Same key while the first request is still running | Refused, 409 in the draft |
| Key missing where the API requires one | Refused, 400 in the draft |
| Key used again after it has expired | Whatever the API documents. Servers keep keys for a limited time |
๐ก Expert tip
Test that a key belongs to the client that sent it. If customer B sends a key customer A already used, B should not get A's stored response back. That would be a quiet version of BOLA from Part 3, where a user reaches a record that isn't theirs, with someone else's order handed over in full.
Waiting for slow work
Some work takes too long to finish inside one request. With asynchronous processing, the API accepts the job, answers straight away and finishes later. A common answer is 202 Accepted, which means the request was accepted but isn't finished yet. The response often says where to check on it:
POST /orders/1042/receipt โ 202 Accepted, Location: /jobs/55
GET /jobs/55 โ 200 OK { "status": "pending" }
GET /jobs/55 โ 200 OK { "status": "done", "file": "/orders/1042/receipt.pdf" }
The tempting test waits ten seconds and then checks. That's a trap. On a fast day the job finishes in three, and the test wastes seven. On a slow day it takes twelve, and the test fails with nothing wrong. A fixed wait is usually too long and sometimes too short.

Polling, as Part 2 described, means asking again until the answer is what you expect or a time limit runs out. In Playwright, expect.poll does this:
const accepted = await request.post('/orders/1042/receipt');
const jobUrl = accepted.headers()['location'];
let status = '';
await expect.poll(async () => {
status = (await (await request.get(jobUrl)).json()).status;
return status;
}, { message: 'receipt job to finish', timeout: 20_000, intervals: [1_000, 2_000, 5_000] })
.toMatch(/^(done|failed)$/);
expect(status).toBe('done');
Stopping on failed as well as done matters. A job that has already failed then fails the test at the last line, straight away, instead of after the full time limit. In Java, Awaitility does the same job, and in Postman's collection runner a script can repeat a request with pm.execution.setNextRequest.
โ Best practices
- Set the time limit from the slowest run you've measured, not the typical one. The first job on a freshly started environment is often much slower than the rest.
- Keep the test's own time limit longer than the poll's. In Playwright, a test times out after 30 seconds by default.
- Don't poll too fast. Every check is a real request, and a tight loop can run into the rate limits from Part 3.
- Make the failure message name what you were waiting for and the last value you saw.
- Follow the
Locationheader from the202, as the snippet does, instead of building the job's path yourself. Then the test checks the address the API actually gave.
The same pattern handles the eventual consistency from Part 2, where a read-back may lag behind a write for a moment.
Property-based testing
Every test so far has used examples you picked. Property-based testing turns that around. You describe a rule that should hold for every valid input, called a property, and a tool generates many inputs to try it. The code that produces those inputs is called a generator.
APIs are full of properties. For example:
- Filtering by a category never returns a book from another category.
- Sorting by price gives prices in order, for any filter.
- The pages of a list add up to the total, with no gaps or repeats.
- Any quantity outside 1 to 99 gets a
422and leaves the cart unchanged.
Here's the last one with fast-check, a property-based testing library for JavaScript and TypeScript:
await fc.assert(fc.asyncProperty(
fc.oneof(fc.integer({ max: 0 }), fc.integer({ min: 100 })),
async (quantity) => {
const res = await request.post('/cart/items', { data: { book_id: 'b-17', quantity } });
expect(res.status()).toBe(422);
}), { numRuns: 30 });
By default fast-check tries 100 inputs. Every input here is a real HTTP request, so a smaller number keeps the test fast. A failure takes longer, because each shrinking step, explained next, sends another request. The full version would also read the cart back. Give each run its own fresh cart, too. Shrinking replays inputs, and if a buggy API accepted one, a shared cart would no longer start the same for the runs after it.
When a property fails, the tool doesn't just hand you a huge random number. It tries smaller and simpler inputs until it finds the smallest one that still fails. That's called shrinking, and it turns a confusing failure into a clear one. Each run also starts from a seed, a number that fixes which inputs get generated. fast-check prints the seed and a path when a property fails, and passing them back replays exactly the same failure. In Java, jqwik offers the same ideas.
Part 1 suggested pinning boundaries as fixed test cases and letting randomness explore the space between them. That's the right split. A property might never generate exactly 100, so 0, 1, 99 and 100 still deserve their own tests.
โ ๏ธ Common mistakes
- Writing a property that passes because it checked nothing. If most filter combinations match no books, the loop over the results never runs, and every run passes. Count what you actually checked, and fail if it's zero.
- Using a generator that mostly produces invalid input, so the interesting path barely gets tested.
- Throwing away the seed. Make sure the seed is in the failure output, or a failure on CI may never come back.
Should CI use a new random seed every run? In my opinion, not on pull requests. A new seed can find an old bug and block a change that has nothing to do with it. Use a fixed seed there, and a new one on nightly runs, where exploring new inputs pays off. Either way, log the seed, so any failure can be repeated.
Keeping the suite trustworthy
A suite is only useful while people believe it. Three things wear that belief down. Tests fail for no reason, known failures hide new ones, and failure output is either useless or full of secrets.
Flaky tests
API tests get flaky for a handful of reasons:
- Shared data, where tests change records other tests depend on, as Part 2 described.
- Fixed waits instead of polling.
- Order, where a test passes only when another one ran first.
- Things the suite doesn't control, such as an external service.
That last one is easy to miss. I've seen registration in a test environment time out once in a long while. The likely cause was a third-party password check the API called on every sign-up. No change to the test could fix that. A fake for that service, which we'll come to shortly, takes it out of the picture.
Retries are useful as evidence, not as a cure. Playwright calls a test that fails and then passes on a retry "flaky", and reports it that way. Allow retries on CI if you need them, but read that report. Then either fix the test, or quarantine it, which means running it apart from the main suite so it can't block other work while it's fixed. Give quarantine an exit rule, such as a week of clean runs, or it becomes a place where tests go to be forgotten.
Known issues
Part 2 suggested recording existing failures as known issues. How you mark one matters.
In Playwright, test.fail() marks a test as expected to fail. The trap is calling it at the top of the test. Then any failure counts as the expected one, including a broken setup step or a new 500. Mark it right before the assertion that shows the bug:
await checkoutTwice(cartId);
const orders = await listOrders({ cartId }); // only orders from this cart
test.fail(true, 'Known issue: one cart can be checked out twice');
expect(orders).toHaveLength(1);
When someone fixes the bug, the assertion passes, and Playwright fails the test because it was expected to fail. That's the reminder to remove the marker, so the check becomes an ordinary test that guards against the bug coming back.
This only works for a bug that fails every time. A race that's lost only on some runs would make the marked test pass now and then, and fail as an unexpected pass. For a timing-dependent bug, keep the checks that pass reliably in the main suite, and run the one that fails only sometimes apart from it, such as nightly, until the bug is fixed.
Failure output that helps without leaking
A good API failure shows the request that was sent, the status, the response body and what the test expected. Without that, someone has to rerun the test to see what happened.
That same output can leak secrets. Redaction means replacing sensitive values, like tokens, passwords and card numbers, with a placeholder before anything is logged.
โ Best practices
- Match sensitive field names loosely, so
access_token,AuthorizationandX-Api-Keyare all caught. Hiding a few harmless fields is the safe way to be wrong.- Also look for token patterns in free text, such as error messages, not just in named fields.
- Redact first, then shorten long bodies. Cutting a token in half first can stop the pattern from matching it.
- Remember that redaction only covers what you log yourself. A Playwright trace, a recording of a test run, stores request and response headers and bodies as they were. Treat traces from authenticated tests as secret, and be careful where reports are published.
Where each technique fits
The test pyramid, an idea Martin Fowler credits to Mike Cohn, suggests many fast, narrow tests at the bottom and fewer slow, broad ones at the top. For APIs, a useful version has unit tests, which check small pieces of code on their own, at the base. API and contract tests sit in the middle. At the top are a few end-to-end tests, which follow a whole user journey through the real system, often through the UI.

Most of this series lives in the middle layer. That's where you can test status codes, contracts, authorization, races and properties quickly, without a browser.
Faking what you don't control
The API you're testing usually calls other services, such as a payment provider or a book metadata service. Two kinds of fake help here. Mocking replaces a dependency with a fake inside the test code. Service virtualization runs a fake version of a service over the network, so the API under test calls it exactly as it would call the real one. WireMock is a well-known tool for this.
A network fake lets you test what the real service rarely does on demand. Make it slow, make it return 500, or send back the odd data from Part 3, such as huge values or unexpected types. Then check your API copes. It also takes flaky third parties out of the main suite.
Two rules keep fakes honest. Never fake the API you're testing, or you're testing the fake. And keep each fake in line with the real service, ideally with the contract tests from Part 2, or it slowly drifts into fiction.
What runs when
In my opinion, a pull request should run what's fast and dependable. That means unit tests, schema and contract checks, the authorization matrix if it runs quickly, and a smoke set, which is a small group of API tests covering the most important paths. Nightly runs can take the slow and noisy work, such as repeated race tests, longer property runs, the token expiry test from Part 3, and anything that polls for a long time. Whatever you choose, a failure in either place should get looked at the same day.
Tools
The ideas in this series work in any tool. Here's roughly where each popular one fits:
| Tool | Where it fits |
|---|---|
| Postman | Exploring an API and sharing collections. Its command-line runners bring the same collections into CI |
| Bruno | An open-source API client that stores collections as plain files, so they live in version control with the code |
| REST Assured | API tests in Java, alongside JUnit or TestNG |
| Playwright | API tests in TypeScript, especially when the same team also tests the UI |
| Karate | Readable, step-style tests with parallel runs and a built-in mock server |
Choose by who will maintain the tests and what language your team already uses, not by feature lists.
Recap
- In a race test, check every rule a race could break, such as the total and the row count, and repeat the overlap several times. A pass doesn't prove the race is gone.
- Use
If-Matchand412to catch lost updates, and count the orders after a double submission. - Retrying a non-idempotent request needs an idempotency key, or another way for the server to spot repeats. Test same key and same body, a changed body, an overlap and a key from another user.
- Poll instead of sleeping, stop early on a failed state, and set the limit from the slowest run you've measured.
- Properties cover the space between your fixed boundary cases. Keep the seed, and check that each property actually checked something.
- Treat retries as evidence, give quarantine an exit rule, and mark known issues right before the failing assertion.
- Redact secrets in failure output, and remember that traces aren't redacted.
That's the end of Beyond the 200. Over four parts we went from why a 200 proves little to contracts, data, security and now robustness. If there's one habit to keep, it's this. Don't stop at the status. Ask what the response actually proves, and go and check the rest.
What's the hardest race condition or flaky test you've had to track down? Share the pattern in the comments. I'd love to hear how you found it.
References
- RFC 9110: HTTP Semantics. Idempotent methods and retries (section 9.2.2),
202 Accepted,If-Matchand412 Precondition Failed. - The Idempotency-Key HTTP Header Field (IETF Internet-Draft).
- Playwright: Assertions,
expect.poll. - Awaitility. Waiting for asynchronous work in Java.
- fast-check: Runners. Number of runs, seeds and replaying a failure.
- jqwik. Property-based testing on the JVM.
- Playwright: Retries. How retried and flaky tests are reported.
- Playwright: Trace viewer. What a trace records.
- Martin Fowler: TestPyramid. The origin of the test pyramid.
- WireMock documentation. Stubbing HTTP services and simulating faults.
Comments
Join the discussionNo comments yet. Be the first to comment.
Beyond the 200: An Advanced Guide to API Testing.
A 200 tells you far less than most tests assume. This four-part series goes beyond status codes to show what strong API testers check and why. It covers test design, contracts and test data, security testing with the OWASP API Security Top 10, and robustness under concurrency and delay. The ideas work in any tool, from Postman to REST Assured to Playwright.



