Skip to content

Idempotency ​

Networks fail. A client that sends POST /v1/orders and loses the connection cannot tell whether the order was created. Retrying might create it twice. Fusion Stack lets clients retry safely: they send an Idempotency-Key header, and every retry with the same key gets the first response back instead of running the request again.

How clients use it ​

Send a new random key, such as a UUID, with each request that changes something, and send the same key again when retrying it:

sh
curl -X POST localhost:8000/v1/orders \
  -H "Authorization: Bearer fs_live_…" \
  -H "Idempotency-Key: 9b0f6c1e-2f4a-4d0e-8a4b-3c6e1f2d7a90" \
  -H "Content-Type: application/vnd.api+json" \
  -d '{"data":{"type":"orders","attributes":{"total_cents":1250,"currency":"gbp"},"relationships":{"customer":{"data":{"type":"customers","id":"1"}}}}}'

The first request creates the order and returns 201 Created. A retry with the same key gets the same 201 and the same body, with one extra header:

http
HTTP/1.1 201 Created
Idempotent-Replayed: true

The TypeScript client sends a key with every mutating request and reuses it when it retries; pass idempotencyKey to choose your own. MCP tool calls get one too.

What can go wrong ​

SituationResponse
The key is reused for a different request: another body, query or pinned version422 idempotency_key_mismatch. Use a new key for each new request.
A retry arrives while the first request is still running409 idempotency_in_progress. Wait and retry.
The first request failed with a 5xx, a 401 or a 429Nothing is stored, so a retry runs the request again.
json
{
  "errors": [
    {
      "status": "422",
      "code": "idempotency_key_mismatch",
      "title": "Idempotency key reused",
      "detail": "This Idempotency-Key was used for a different request. Use a new key for each new request.",
      "source": {
        "header": "Idempotency-Key"
      },
      "meta": {
        "request_id": "req_01m8r9qw766d933fvtbemzqrj4"
      }
    }
  ]
}

Only 2xx and 4xx responses are stored. A 4xx is replayed because the same request would fail the same way again. Two are not stored: a 429, because the rate limit resets, and a 401, because it is about the caller's credentials rather than the request, so a retry after signing in runs.

Scope ​

Keys are scoped to the authenticated client, the method and the path, so two clients can never see each other's responses, even if they pick the same key. A request without a client is a guest's, and its key is scoped to the address it came from, as guest rate limits are. Guests at one address share their keys, which is every guest when the API is behind a proxy it does not trust, and a guest's retry from another address runs again. Require authentication on endpoints where either matters.

In PHP, a key belongs to whoever the request is from when it reaches the idempotency step. Laravel's auth middleware always runs before it, wherever it is listed. Your own authentication middleware does not, unless it is listed before the fusion-stack group: listed after, it signs the user in once the key has already been looked up as a guest's. The response is then not stored, so nobody else can be replayed it, but a retry runs again. List such middleware before the group, as in ->middleware([AuthenticateMember::class, 'fusion-stack']), or make it a guard and use auth:.

In Rust, a user signed in through Laravel's own guards (the session guard, or Authenticate::via) is not a client, and the crate cannot tell such users apart. Their requests run without their key: nothing is stored or replayed, so a retry runs again. To give those users working idempotency, resolve them as clients with Config::client_resolver, which scopes their keys to them.

The crate only sees a user who was signed in before the FusionStack middleware ran. Keys are looked up before a route's own middleware, so with Authenticate listed on a route inside the FusionStack group, responses are stored in the guest scope of the caller's address and a retry from there is replayed without the guard running. List Authenticate before FusionStack, as in .middleware((Authenticate::via::<ApiKeys>(), api)), or use a client resolver.

Configuration ​

php
// config/api.php
'idempotency' => [
    'enabled' => true,
    'methods' => ['POST', 'PATCH', 'DELETE'],
    'ttl' => 60 * 60 * 24,   // how long a response is replayed, in seconds
    'lock_seconds' => 60,    // how long a running request holds its key
    'store' => null,         // a cache store with atomic locks; null for the default
],
rust
Config::new()
    .idempotency(true)
    .idempotent_methods(["POST", "PATCH", "DELETE"])
    // How long a response is replayed, and how long a running request holds its key, in seconds.
    .idempotency_times(60 * 60 * 24, 60)
    // A cache store with atomic locks; None for the default.
    .idempotency_store(None)

The store must support atomic locks. Redis is recommended in production; the array and file stores are fine for tests and local work.

Requests without an Idempotency-Key header run as normal. Test replays with assertIdempotentReplay() from the package's testing helpers, or assert_idempotent_replay() from fusion_stack::testing in Rust.

Released under the MIT License.