QA Interview Hub · Knowledge base · Quizzes · Українська

API › Performance and reliability

Timeouts, retries and idempotency keys

A timeout bounds the wait, a retry repeats a call after a temporary failure, and an Idempotency-Key makes repeating a POST safe. A timeout does not report the outcome: the request may have run with only the response lost, so a retry without a key can double a payment. Only temporary failures are retried, with exponential backoff, jitter, the same key and a limit on attempts.

API · Resilience

A payment hangs on a timeout and the client repeats the request. How many times is the money charged?

A payment service answers in 30 seconds, the client waited 10 and repeated the request. The bank actually processed both. Now the customer has two charges for one purchase, and no "status 200" test saw it. This lesson is about three mechanisms that together make a call safe: a timeout, a retry and an idempotency key. Each one alone is dangerous.

How it works

The chain works like this. A timeout bounds the wait: without it a hung service holds the client's threads and connections, the request queue grows, and not just the dependency but the whole service goes down. A retry repeats the call after a temporary failure. An Idempotency-Key makes the repeat safe for methods that are not idempotent by themselves (POST).

The main danger is that a timeout does not report the outcome. The client knows only that no response arrived: the request may not have been accepted, it may have been executed, or only the response may have been lost. Without a key the client cannot tell these cases apart.

What the client knows after a timeout

Typical

A retry without a key

The server sees two independent POSTs and creates two transfers. The customer complains, and support hunts for the cause.

Better

A retry with one key

The server recognises the key, does not run the operation a second time and returns the stored response of the first attempt.

Figure 1. Retrying a non-idempotent POST is safe only together with a key that the client created once per operation.

What to retry. Temporary failures: a timeout, a dropped connection, 408, 429, 502, 503, 504. For 400, 401, 403, 404 or 422 a repeat changes nothing, because the problem is in the request itself. Per RFC 9110, GET, PUT and DELETE are idempotent and safe to repeat, while POST and PATCH need a key or another guard.

Backoff and jitter. Repeating at once means finishing off a service that is already choking. The delay grows exponentially (0.5 s, 1 s, 2 s, 4 s) and gets a random offset (jitter): without it thousands of clients that failed at the same moment retry at the same moment and create a new wave.

Example: a retry with backoff and a duplicate test

Here is a minimal wrapper. It repeats only temporary errors, respects Retry-After and otherwise waits a random time under an exponential cap:

const RETRYABLE = new Set([408, 429, 502, 503, 504]);

export async function withRetry(call: () => Promise<Response>, max = 4) {
  for (let attempt = 0; ; attempt++) {
    let res: Response | undefined;
    try {
      res = await call();
      if (!RETRYABLE.has(res.status)) return res;
    } catch {
      // network error or timeout: treat as retryable
    }
    if (attempt >= max) throw new Error('gave up after ' + (attempt + 1) + ' attempts');
    const retryAfter = Number(res?.headers.get('retry-after'));
    const base = Math.min(8000, 500 * 2 ** attempt);
    const delay = retryAfter > 0 ? retryAfter * 1000 : Math.random() * base; // full jitter
    await new Promise((r) => setTimeout(r, delay));
  }
}

Now a Playwright test. A stub of the payment provider (setStub is a hypothetical helper you write for your environment) answers in 5 seconds the first time. The client has a 2-second timeout, so the first attempt fails with an error and the retries go out with the same key until the server finishes the first attempt (while it runs, a correct server answers 409):

test('slow dependency: client times out, retries, one transfer', async ({ request }) => {
  const key = crypto.randomUUID();
  const send = () =>
    request.post('/v1/transfers', {
      headers: { 'Idempotency-Key': key }, // the same key on every attempt
      data: { toAccount: 'UA21...', amount: 150, currency: 'UAH' },
      timeout: 2000, // ms: fail fast instead of hanging
    });

  // the stub of the payment provider answers in 5 s the first time
  await setStub({ delayMs: 5000, times: 1 });
  await send().catch(() => undefined); // timeout: the client does not know the result
  // retry with the same key until the first attempt finishes (409 = still in progress)
  await expect
    .poll(async () => (await send()).status(), { timeout: 15_000 })
    .toBeLessThan(300);
  const list = await (await request.get('/v1/transfers?clientRef=' + key)).json();
  expect(list.items).toHaveLength(1); // not two payments
});

The test checks not the status of the retry but the state of the system: the list has exactly one transfer. Without the key in the request this test goes red, which shows exactly why a retry is dangerous.

Limits and alternatives

  • The key must be stored on the server together with the response, not only in a cache that can be lost. The same key with a different request body should return an error (Stripe uses 400 or 409 depending on the case) instead of silently returning someone else's result.
  • A key lives for a limited time, usually a day. This is a contractual limit you learn from the documentation, and you test it.
  • Retries multiply load: if each of three service layers makes up to three attempts, one failure below becomes 27 requests. Retries are placed at one level and limited by a budget.
  • An IETF draft exists for the Idempotency-Key header, but it is not a final RFC yet: the behaviour of a given API is checked against its documentation.
  • An alternative to a key is natural idempotency, such as a PUT to a resource with a known id or a unique constraint in the database.

Common mistakes

  • Retrying any code. A repeat on 422 only loads the server and changes nothing.
  • Generating a new key for every attempt. Then the key protects nothing: the server sees different operations.
  • Retrying without a pause and without an attempt limit. That turns a dependency failure into a self-inflicted DoS attack.
  • One big timeout for everything. A total timeout of 60 s is above a user's patience. Better separate timeouts for connect and read plus an overall cap for the operation.

Check yourself

The client got a timeout on POST /transfers and does not know whether the transfer went through. What are the safe actions?

Answer

Repeat the request with the same Idempotency-Key, or re-read the state (GET the transfer by key or clientRef). You must not send a new request with a new key: if the first one went through, the transfer is duplicated.

Why is jitter needed if there is already an exponential delay?

Answer

The exponential spreads one client's repeats in time, but thousands of clients that failed at the same moment have identical delays and return in sync. A random offset scatters those repeats, so the server receives an even stream instead of waves.

In an interview. Junior: Every call has a timeout, and only temporary errors may be retried, with a pause between attempts. For payments the repeat carries the same Idempotency-Key, and I check that the database holds one operation. Middle/Senior: A timeout does not report the outcome, so a retry without a key is dangerous. I check exponential backoff with jitter, respect for Retry-After, the attempt limit and that retries live at one level instead of multiplying across layers. Separately I test that the same key with a different body gives an error.

More articles in this chapter