Money and repeated requests: races, idempotency, precision, partial failures
Races, repeated requests, precision errors and partial failures rarely show in one request, so tests check the state after a series of requests. Parallel charges are reproduced with N identical requests at once, checking the balance and record count. A repeated POST is protected by Idempotency-Key, money is tested with invariants in minor units, and partial failures by simulating a dependency outage at each step.
API · Typical bugs
One request works, while two parallel ones charge twice. How do you reproduce that in a test?
A user quickly clicked “Pay” twice, or a mobile client repeated a request after a timeout. A single request in a test works correctly, while the logs show two charges. The bugs of this lesson are invisible in one request: they appear with parallelism, repeats, calculations and the failure of a dependent service. They are caught by tests on the state after a series of requests, not on one response.
Four cases: a race, a non-idempotent repeat, money precision, a partial failure.
How it works
A race. The handler reads the balance, checks there is enough money and writes the new balance. There is a gap between the read and the write. Two requests that enter it simultaneously both see 10000 and both charge. The fix is not in the request code but in the database: a conditional update (UPDATE … WHERE balance >= amount), a row lock, a unique index or a transaction of a sufficient isolation level.
A repeat. HTTP does not guarantee that the client learns the outcome. The request may have been executed and the response got lost (a timeout, a 502 from the gateway). GET, PUT and DELETE are safe to repeat because they are idempotent by definition (RFC 9110). POST is not, so payments introduce the Idempotency-Key header: the server remembers the key together with the result and returns the same on a repeat without a new effect.
Two parallel charges of the whole balance
Read, then write
Both requests see 10000, both pass the check, the balance goes negative or two operations take one amount.
An atomic condition in the database
The second request waits or is refused. One success, balance 0, it does not go negative.
Example: reproducing the race
A race is non-deterministic: one run is not enough. The test sends N identical requests at once and looks at the state, not only at the responses. The idempotency key is deliberately different, to test the locking and not the key:
test('5 parallel transfers of the whole balance: only one passes', async ({ request }) => {
// precondition: account 42 holds 10000 minor units
const send = () =>
request.post('/v1/accounts/42/transfers', {
headers: { 'Idempotency-Key': crypto.randomUUID() }, // a new key each time
data: { toAccount: 'UA21...', amountMinor: 10000, currency: 'UAH' },
});
const results = await Promise.all(Array.from({ length: 5 }, send));
const passed = results.filter((r) => r.status() === 201).length;
expect(passed).toBe(1);
const acc = await (await request.get('/v1/accounts/42')).json();
expect(acc.balanceMinor).toBe(0); // never below zero
});
If the test is sometimes green, it does not mean there is no bug: repeat it 5-10 times and record the frequency (“3 of 10”). A regular Postman Runner run sends requests one by one (in parallel only in performance-test mode), so for races a script, k6 or curl with xargs -P is handier.
Example: a repeat and the idempotency key
The client got a timeout and repeated the POST. The correct behaviour: the same key and the same body give the same response without a new effect, while the same key with a different body gives an error. Under the IETF draft “The Idempotency-Key HTTP Header Field” that is 422, and a parallel request with the same key that is still running gets 409; take the exact codes from your API’s documentation:
test('same key and body: one effect; same key, other body: error', async ({ request }) => {
const key = crypto.randomUUID();
const body = { toAccount: 'UA21...', amountMinor: 500, currency: 'UAH' };
const post = (data: object) =>
request.post('/v1/accounts/42/transfers', {
headers: { 'Idempotency-Key': key },
data,
});
const first = await post(body);
const replay = await post(body);
expect(replay.status()).toBe(first.status());
expect((await replay.json()).id).toBe((await first.json()).id); // same transfer
const other = await post({ ...body, amountMinor: 900 });
expect(other.status()).toBeGreaterThanOrEqual(400); // key reused with other data
});
Repeating a POST after a timeout
No key
The first request was executed, the response got lost. The repeat creates a second payment, the money is charged twice.
With Idempotency-Key
The server recognises the key and returns the stored response. One effect, the client gets the result.
Money precision
Floating-point numbers cannot store decimal fractions exactly: in JavaScript 0.1 + 0.2 gives 0.30000000000000004. If the JSON contains "total": 0.30000000000000004 or cents vanish on a discount, the money is calculated as a double. Safe representations are whole minor units (cents) or a decimal number in a string. The test checks invariants, not specific numbers: the sum of lines minus the discount equals the total, the total is an integer, rounding follows one policy. Handy boundaries: 2.675, percentage discounts on odd amounts, currencies with a different number of decimals (JPY has none, KWD has three):
test('order total equals the sum of its lines, in whole minor units', async ({ request }) => {
const res = await request.post('/v1/orders', {
data: {
items: [{ sku: 'a', priceMinor: 10, qty: 3 }, { sku: 'b', priceMinor: 20, qty: 3 }],
discountPercent: 15,
},
});
const order = await res.json();
const lines = order.lines.reduce((s: number, l: { totalMinor: number }) => s + l.totalMinor, 0);
expect(Number.isInteger(order.totalMinor)).toBe(true);
expect(lines - order.discountMinor).toBe(order.totalMinor);
});
A partial failure
The payment went through, the order was not created. The API answered 500, but part of the effects had already happened. The cause: several systems change without a shared transaction. The check: simulate a failure of the dependent service at every step (a stub, a stopped service, a timeout), look at the state in all systems, repeat the request. The fix is usually compensation (cancel the first step) or a transactional outbox with idempotent handlers. The test must check that no “orphaned” records remain after a failure and that a repeat completes the operation without a duplicate.
Limits and alternatives
- A parallel test does not prove the absence of a race, it only finds an existing one. It is more reliable to add a code review (is there a condition in the UPDATE or a lock) and a database-level test.
- A gateway or a load balancer may serialise requests, so the race disappears on a test environment but shows up in production with several replicas. Test on a configuration close to production.
- Idempotency by key has a lifetime. A repeat after it expires is a new operation, which you need to know and verify in the documentation.
- Decimal arithmetic in the test can also go wrong: calculate the expected value in whole minor units.
Common mistakes
- Looking only at the responses of parallel requests. All of them may be 201, while the balance is right or wrong, which is visible only from the state.
- One run of a race. A non-deterministic bug may not show up, so the test is repeated and the frequency recorded.
- Checking the idempotency key only on a successful repeat. You also need a different body with the same key and an expired key.
- Comparing money as
toBe(0.3). The test itself fails on floating point, compare minor units. - Not checking the state of other systems after a 500. An “error” response does not say that no effects happened.
Check yourself
5 parallel requests to charge the whole balance returned five 201 responses. Which check do you add and what do you expect?
Answer
I read the state: the balance must not be negative and exactly one record must be created. If the balance covers one operation, I expect one 201 and four refusals (for example 409 or 422). Five 201 responses mean a race, a critical bug for money: I record the frequency and record ids and suggest a conditional update or a lock.
A client repeated POST /payments with the same Idempotency-Key but a different amount. What should the server do?
Answer
Do nothing and not silently return the old success: the same key with a different body is a client error. Under the IETF draft that is 422. If the server created a new payment or returned a response for the first amount, it is a bug, because the client will believe it paid a different amount.