REAL-WORLD SCENARIOS

Testing Idempotency in APIs That Handle Payments or Orders

Idempotency sounds academic until a customer is charged twice for one order. In payment and order APIs it means that sending the same request more than once has the same effect as sending it once. A client that times out and retries shouldn't create a second charge, and a resent request shouldn't create a second shipment. Getting this wrong isn't a cosmetic bug; it's a financial and operational incident.

In practice, teams skip idempotency tests because they feel hard to set up: you have to simulate retries, track side effects and read back state, not just check one response. There's also a newer source of duplicate requests that makes the tests more important. AI agents that can place orders or issue refunds through tools will sometimes call the same tool twice, because the model repeated itself or because the agent framework retried after a slow response. If the tool generates a fresh idempotency key for every HTTP call, your API's protection does nothing.

This article walks through what an idempotency key must guarantee, how to test it in pytest and Behave, how to simulate realistic retries and races, the mistakes that let these bugs through, and how to test agent tools so a repeated call can't double-charge anyone.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

What an idempotency key must guarantee

Most payment APIs use a client-supplied key, commonly sent as an Idempotency-Key header containing a UUID. The contract has two halves: a repeated request with the same key returns the same result, and it causes no new side effect such as a charge, order record or inventory decrement. Tests must verify both.

import uuid

import pytest
import requests


@pytest.fixture
def idempotency_key():
    return str(uuid.uuid4())


def place_order(api_url, token, payload, key):
    return requests.post(
        f"{api_url}/orders",
        json=payload,
        headers={"Authorization": f"Bearer {token}", "Idempotency-Key": key},
        timeout=10,
    )


def test_repeated_order_request_creates_one_order(api_url, token, idempotency_key):
    payload = {"product_id": "SKU-001", "quantity": 1}

    first = place_order(api_url, token, payload, idempotency_key)
    second = place_order(api_url, token, payload, idempotency_key)

    assert first.status_code == 201
    assert second.status_code in (200, 201)  # pin whichever your API documents
    assert first.json()["order_id"] == second.json()["order_id"]

    orders = requests.get(f"{api_url}/orders", params={"product_id": "SKU-001"},
                          headers={"Authorization": f"Bearer {token}"}, timeout=10).json()
    matching = [o for o in orders if o["order_id"] == first.json()["order_id"]]
    assert len(matching) == 1

The second half is the one teams skip. An API can return the cached response to the retry and still write a second row behind it. Only reading back state catches that. If the test environment has no way to list orders or charges, raise it as a testability gap.

Then test key reuse with a different payload. A server should refuse it, commonly with 409 or 422, rather than process a different order under an old key:

def test_key_reused_with_different_payload_is_rejected(api_url, token, idempotency_key):
    place_order(api_url, token, {"product_id": "SKU-001", "quantity": 1}, idempotency_key)
    response = place_order(api_url, token, {"product_id": "SKU-002", "quantity": 5}, idempotency_key)
    assert response.status_code in (409, 422)

Also check what your API promises for a missing key, an expired key and a key used by a different customer. Each is a decision someone made; tests make it visible.

Retries that look like real retries

Two clean sequential requests are the easy case. Real retries happen because the client never saw the first response, while the server may already have committed. A Behave scenario keeps that intent readable for anyone reviewing payment behaviour:

Feature: Payment idempotency under retry

  Scenario: A retried charge is not duplicated
    Given a payment of "99.99" "USD" with a new idempotency key
    When the client submits the payment
    And the client retries the same payment after a timeout
    Then exactly one charge exists for that payment
    And both responses reference the same transaction ID
import uuid

import requests
from behave import given, then, when


def submit_payment(context):
    return requests.post(
        f"{context.api_url}/payments",
        json=context.payload,
        headers={"Authorization": f"Bearer {context.token}",
                 "Idempotency-Key": context.idempotency_key},
        timeout=10,
    )


@given('a payment of "{amount}" "{currency}" with a new idempotency key')
def step_payment(context, amount, currency):
    context.payload = {"amount": amount, "currency": currency}
    context.idempotency_key = str(uuid.uuid4())


@when("the client submits the payment")
def step_submit(context):
    context.first = submit_payment(context)


@when("the client retries the same payment after a timeout")
def step_retry(context):
    context.second = submit_payment(context)


@then("exactly one charge exists for that payment")
def step_one_charge(context):
    txn = context.first.json()["transaction_id"]
    charges = requests.get(f"{context.api_url}/charges",
                           headers={"Authorization": f"Bearer {context.token}"}, timeout=10).json()
    assert sum(1 for c in charges if c["transaction_id"] == txn) == 1


@then("both responses reference the same transaction ID")
def step_same_txn(context):
    assert context.first.json()["transaction_id"] == context.second.json()["transaction_id"]

To get closer to a true timeout, send the first request with a very short client timeout so it raises before the response arrives, then retry. Whether the server finished the first request is then genuinely unknown, which is exactly the situation idempotency keys exist for.

Concurrent retries

Retries can also arrive at nearly the same moment. Some APIs process one and return a 409 to the others while the first is still in flight; others make the duplicates wait and return the same result. Both are reasonable, so the test should allow the documented behaviour and focus on the outcome that must never vary:

from concurrent.futures import ThreadPoolExecutor


def test_concurrent_retries_produce_one_charge(api_url, token, idempotency_key, count_charges):
    payload = {"amount": "49.99", "currency": "USD"}
    headers = {"Authorization": f"Bearer {token}", "Idempotency-Key": idempotency_key}

    def submit(_):
        return requests.post(f"{api_url}/payments", json=payload, headers=headers, timeout=10)

    with ThreadPoolExecutor(max_workers=3) as pool:
        responses = list(pool.map(submit, range(3)))

    assert all(r.status_code in (200, 201, 409) for r in responses)
    succeeded = {r.json()["transaction_id"] for r in responses if r.status_code in (200, 201)}
    assert len(succeeded) == 1, f"expected one transaction, got {succeeded}"
    assert count_charges(idempotency_key) == 1

Race tests are noisy by nature and may pass many times before exposing a bug, so run them repeatedly in a nightly job rather than trusting one green run. If your sandbox rate-limits, a 429 can mask the result; testing rate-limited APIs without tripping the limit covers how to keep that out of the way, and writing API tests that catch race conditions early goes deeper on concurrency.

Mistakes that let idempotency bugs through

  • Checking responses, not side effects. Same order ID in both responses is not proof of one order. Count the records.
  • Generating the key inside the retry loop. If client code or a test helper creates a new UUID on each attempt, every retry is a brand-new request. The key belongs to the intended operation, not the HTTP attempt.
  • Testing only the order endpoint. Refunds, captures and cancellations need the same protection, and they're where duplicates cost the most.
  • Ignoring downstream effects. One order record but two "order placed" events on a queue still means two shipments. Check the events your tests can observe.

Agents that call the same tool twice

If an assistant in your product has a place_order or issue_refund tool, duplicate calls are a normal event, not an edge case. The model may emit the same call twice in a turn, or the framework may retry a call that was slow. The tool wrapper should derive the idempotency key from the intended action, for example the conversation, the turn and the arguments, so a repeated call reuses the key:

import hashlib
import json


def action_key(conversation_id: str, turn_id: str, tool: str, args: dict) -> str:
    raw = json.dumps([conversation_id, turn_id, tool, args], sort_keys=True)
    return hashlib.sha256(raw.encode()).hexdigest()


def test_repeated_tool_call_in_one_turn_charges_once(refund_tool, fake_payments):
    args = {"order_id": "ord_123", "amount": "20.00"}
    refund_tool(conversation_id="c1", turn_id="t1", **args)
    refund_tool(conversation_id="c1", turn_id="t1", **args)
    assert fake_payments.refund_count("ord_123") == 1

This test needs no model: it calls the tool function directly, so it's fast and deterministic. Check that your payment API accepts a key in this format and length; some cap key length, in which case truncate or use a UUID derived from the hash. For money-moving tools I'd also keep a human approval step before the call and test that the tool refuses to run without it. When a coding agent writes your idempotency tests, put the "count the records, reuse the key" rules in .github/copilot-instructions.md or your agent's equivalent; generated tests otherwise stop at comparing two response bodies.

Idempotency is a property of the whole system, not one endpoint, and with agents in the loop the number of callers who will retry is only going up. If you'd like to practise these patterns in a full suite with Behave or Cucumber and GitHub Copilot, my API testing courses are the place to start.