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

API › HTTP methods and idempotency

PUT vs PATCH and Idempotency-Key in fintech

PUT replaces a resource fully and PATCH changes only the fields sent, so a field missing from PUT must not survive. A retried POST in payments is protected by Idempotency-Key: the client adds a unique key, and on a retry the server returns the stored response without acting again. The same key with a different body is rejected (the draft recommends 422). Parallel requests with one key are tested.

API · Methods

A user clicked "Pay" twice. How to guarantee the money is charged once?

Two scenarios that reach production too often. In the first, a PUT without one field silently wipes it in the database, because the developer implemented "replace" as "update". In the second, a retry of a payment request after a timeout charges twice. Both are testable in minutes if you know what to compare.

PUT and PATCH: replace or change

PUT says "here is the full state of the resource". Anything missing from the body is considered absent. PATCH says "here is what to change". The rest stays. By the specification, a PATCH document must describe a change, and its format is a separate agreement: most often JSON Merge Patch (RFC 7396, application/merge-patch+json) or JSON Patch (RFC 6902, application/json-patch+json).

// current state of the resource
{ "id": 7, "firstName": "Olena", "nickname": "olena", "city": "Kyiv" }

// PUT body (no "city")        // PATCH body (no "city")
{ "firstName": "Olena",        { "nickname": "ol" }
  "nickname": "ol" }
// result: city is gone or     // result: city stays "Kyiv"
// reset to a default

The same request without the "city" field

PUT without city

It is a full replace. The field disappears or is reset to a default.

PATCH without city

The field is not touched. State changes only where the body has a value.

Figure 1. The same data gives a different result. That is not a mistake as long as the contract says so.

A test for PUT checks the state through GET, not the response:

test('PUT without a field: documented replace', async ({ request }) => {
  await request.put('/v1/users/7', {
    data: { firstName: 'Olena', nickname: 'ol' }, // "city" is missing
  });
  const user = await (await request.get('/v1/users/7')).json();
  expect(user.nickname).toBe('ol');
  // contract says PUT is a full replace, so city must be reset
  expect(user.city ?? null).toBeNull();
});

If the documentation says "PUT replaces the resource" but city stayed, the API behaves like PATCH, and that is a deviation from the contract. If the field is required, a PUT without it should give 400 or 422, not silently wipe it.

PATCH idempotency is subtler. Merge Patch { "tier": "gold" } is idempotent in practice. A JSON Patch with an add at the end of an array, or a counter increment, is not:

PATCH /v1/accounts/42 HTTP/1.1
Content-Type: application/json-patch+json

[{ "op": "add", "path": "/tags/-", "value": "vip" }]
# repeated: "vip" is appended again, so this PATCH is not idempotent

PATCH /v1/accounts/42 HTTP/1.1
Content-Type: application/merge-patch+json

{ "tier": "gold" }
# repeated: the same state, idempotent in practice

Idempotency-Key: how not to charge twice

POST is not idempotent, and in fintech it is repeated all the time: a timeout, a dropped network, a second click, a library retry. The client does not know whether the server executed the request. The solution: the client generates a unique key (a UUID v4) and puts it in a header. The server stores the pair "key, result" and on a repeat returns the saved response without performing the action again. The header is described in an IETF draft (Idempotency-Key) and is widely used by payment APIs (Stripe and others).

POST /v1/transfers HTTP/1.1
Idempotency-Key: 7f3c9a10-5d2e-4b8a-9c11-0e6f2a7b1d34
Content-Type: application/json

{ "toAccount": "UA21...", "amount": 150.00, "currency": "UAH" }

HTTP/1.1 201 Created
Location: /v1/transfers/tr_91

The idempotency key at work

ClientServer POST + K1 payment created 201 (lost) POST + K1 (retry) K1 known: no new payment 201, same id
Figure 2. The response got lost, but the client knows the key and may retry. The server sees K1, returns the stored result and does not create a second payment.

What to test. Below is a scenario with four checks: a repeat with the same key and body, the same key with a different body, one transfer in the list.

test('same Idempotency-Key does not create a second transfer', async ({ request }) => {
  const key = crypto.randomUUID();
  const send = (amount: number) =>
    request.post('/v1/transfers', {
      headers: { 'Idempotency-Key': key },
      data: { toAccount: 'UA21...', amount, currency: 'UAH' },
    });

  const first = await send(150);
  const retry = await send(150);
  expect(first.status()).toBe(201);
  const id = (await first.json()).id;
  expect((await retry.json()).id).toBe(id);

  const other = await send(999); // same key, different body
  expect([409, 422]).toContain(other.status());

  const list = await (await request.get('/v1/transfers?limit=50')).json();
  expect(list.items.filter((t: { id: string }) => t.id === id)).toHaveLength(1);
});

The same key with a different body means the client reused a key by mistake, and silently executing a new payment would be dangerous. The draft advises rejecting such a request with 422, and a request that is still being processed with 409. So the test accepts 409 or 422 and is compared with the contract of a particular service.

The most interesting case: two parallel requests with one key. This is where implementations break, because the check "the key already exists" and writing the key are not atomic:

test('two parallel requests with one key create one transfer', async ({ request }) => {
  const key = crypto.randomUUID();
  const send = () =>
    request.post('/v1/transfers', {
      headers: { 'Idempotency-Key': key },
      data: { toAccount: 'UA21...', amount: 150, currency: 'UAH' },
    });
  const [a, b] = await Promise.all([send(), send()]);
  const ids = new Set<string>();
  for (const r of [a, b]) {
    expect([200, 201, 409]).toContain(r.status()); // 409 = still in progress
    if (r.ok()) ids.add((await r.json()).id);
  }
  expect(ids.size).toBe(1);
});

Limits and common mistakes

  • A key lives a limited time. Usually 24 hours or more; after that the same key may be accepted as new. A test for the expiry needs a controlled clock or a server with a short TTL.
  • A key is bound to a user. Someone else's key must not return someone else's response. That is a security check.
  • A key does not replace business uniqueness. Two different keys with the same intent give two payments, and separate rules protect from that (for example a unique order number).
  • Storing only success. If a retry after a 500 has a chance to succeed while a 4xx is stored forever, that rule must be in the documentation.
  • Forgetting that PATCH is not idempotent. It may need a key or a conditional request with If-Match too.

Check yourself

A PUT without the city field returned 200, and GET shows the old city. What does that mean?

Answer

If the contract says PUT is a full replace, it is a defect: the API behaves like PATCH. If the contract describes a partial update, the defect is in the documentation. Either way the state is checked through GET, not by the response.

What must the server do when the same Idempotency-Key arrives with a different body?

Answer

Not perform a new action and reject the request with an error, 422 by the draft (or 409 by the service contract). Silently executing a new payment under an old key is dangerous, so it is a separate negative test.

Why is it not enough to check that the second request returned 201?

Answer

Because a 201 with a different id means a second payment. The ids in the responses must be compared and the records counted through GET or the history: one transaction must remain in the system.

In an interview. Junior: PUT replaces a resource fully, PATCH changes only the passed fields. A second click on "Pay" can create two payments because POST is not idempotent, so payments use Idempotency-Key. Middle/Senior: For PUT I check through GET that a missing field is reset per the contract. For the key I check a repeat with the same body (the same id, one record), a different body (409 or 422), parallel requests with one key and the binding of the key to a user. I also clarify the key's lifetime and whether an error response is stored.

More articles in this chapter