# Laravel API Idempotency documentation (v13.x)

> Canonical: https://pharaonic.dev/packages/laravel/api-idempotency/13.x  
> Version: v13.x (latest release 13.0.0, 2026-11-23)  
> Install: composer require pharaonic/laravel-api-idempotency  
> Requires: PHP 8.3 – 8.5, Laravel 13  
> Repository: https://github.com/Pharaonic/laravel-api-idempotency  
> All versions: https://pharaonic.dev/packages/laravel/api-idempotency/13.x.md https://pharaonic.dev/packages/laravel/api-idempotency/12.x.md https://pharaonic.dev/packages/laravel/api-idempotency/11.x.md https://pharaonic.dev/packages/laravel/api-idempotency/10.x.md https://pharaonic.dev/packages/laravel/api-idempotency/9.x.md https://pharaonic.dev/packages/laravel/api-idempotency/8.x.md https://pharaonic.dev/packages/laravel/api-idempotency/7.x.md https://pharaonic.dev/packages/laravel/api-idempotency/6.x.md

:::badges
- Laravel Package {color=blue}
- v13.0.0 {color=green}
- MIT License {color=purple}
- AI Ready {color=violet}
:::

# Laravel API Idempotency

API Idempotency makes unsafe Laravel routes safe to retry. Add `->idempotent()` to a route; clients send an `Idempotency-Key` header. The first request reserves the key atomically and runs. A retry with the same key and the same request gets the stored response back without running your controller again. The same key with a different request, a duplicate that arrives while the first is still running, and a request whose outcome is unknown are all refused with a clear `409`.

:::success AI Ready
API Idempotency ships Laravel Boost resources: a guideline loaded in every session and an `api-idempotency-development` skill loaded when your agent works on idempotent endpoints. Run `php artisan boost:install` and Claude Code, Cursor, Codex, Copilot or Gemini CLI mark the right routes, scope keys and handle every error code. See [AI Ready](#ai-ready).
:::

:::features
### One Route Macro
Route::post(...)->idempotent() keeps the fluent chain and survives route caching.

### Atomic Reservation
A unique insert on the database, or one Lua script on Redis. Never a read followed by a write.

### Exact Replay
The stored status, body and allow-listed headers, without cookies or credentials.

### Request Fingerprints
Method, path, query and JSON body through pharaonic/php-fingerprint, with strict types.

### Scoped Keys
Keys belong to one user or tenant; nobody sees another principal's response.

### Fail Closed
Crashes, server errors and store outages never cause a silent second run.

### Events and Quiet Logs
Four events for every outcome; logs never carry the client's key, the user or the body.

### Safe Pruning
idempotency:prune counts first, deletes with --apply, and keeps unresolved records until you ask.

### AI Ready
Laravel Boost resources teach your coding agent the macro, scopes, outcomes and error codes.
:::

:::warning Not exactly-once
No HTTP layer can promise exactly-once side effects. This package guarantees that one key never runs twice at the same time and that an uncertain outcome is never retried automatically. For payments, also store a unique business reference and pass an idempotency key to your payment provider.
:::

## Installation

Install the package with Composer and run its migration.

### Requirements

- PHP 8.3, 8.4 or 8.5
- Laravel 13.x
- A database supported by Laravel (MySQL, MariaDB, PostgreSQL, SQLite) or Redis (phpredis or predis)

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-api-idempotency
```

The service provider is registered automatically.

### Run Migrations

The `idempotency_keys` table is needed only by the `database` store, the default. The package never runs its migration on its own: publish it, then migrate.

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=api-idempotency-migrations
php artisan migrate
```

Using Redis? Skip this step and set `IDEMPOTENCY_STORE=redis` (see [Stores](#stores)).

### Publish Configuration

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=api-idempotency-config
```

The file lands in `config/pharaonic/api-idempotency.php`.

### Schedule Pruning

Expired database records are deleted by a command. Schedule it in `routes/console.php`:

```php title="routes/console.php"
use Illuminate\Support\Facades\Schedule;

Schedule::command('idempotency:prune --apply')->hourly();
```

:::success Installation Complete
Add `->idempotent()` to an authenticated POST route and you are done.
:::

## Configuration

Every option lives under `pharaonic.api-idempotency`. Invalid values throw an `InvalidArgumentException` when a request uses them; nothing is silently corrected.

| Key | Default | Description |
| --- | --- | --- |
| `ttl` | `86400` | Seconds a finished request stays replayable, counted from when it finished. 1 to 31536000. Routes may override it. |
| `lease` | `120` | Seconds a request may run before it counts as abandoned. 1 to 86400. See [Failures and Recovery](#failures-and-recovery). |
| `scope` | `Scopes\AuthenticatedUser::class` | A `ScopeResolver` class that decides whose key space a request uses. |
| `store.driver` | `env('IDEMPOTENCY_STORE', 'database')` | `database` or `redis`. See [Stores](#stores). |
| `store.connection` | `env('IDEMPOTENCY_CONNECTION')` | The database or Redis connection name; `null` uses the default one. |
| `store.table` | `idempotency_keys` | The table of the database store. |
| `store.prefix` | `idempotency:` | The key prefix of the Redis store. |
| `max_response_bytes` | `1048576` | Largest response body that is stored and replayed. |

### Fixed rules

These are not options, because changing them would weaken the guarantees:

- The key travels in the `Idempotency-Key` header, and replays carry `Idempotency-Replayed: true`.
- Request bodies are JSON (`application/json` or any `+json` type) or empty; the method, path, query string and body make the fingerprint.
- Any `2xx` response with a JSON (or `+json`) type or an empty body is stored and replayed with its `Content-Type`, `Location`, `Content-Location`, `ETag` and `Last-Modified` headers. Cookies and credentials never replay.
- Any other `4xx` releases the key; everything else locks it as an unknown outcome.

:::tip Keep ttl and lease apart
`ttl` is how long a result can be replayed. `lease` is how long one execution may take. An expired lease never makes a request retryable by itself.
:::

## Basic Usage

Call `idempotent()` on any route. It returns the same route, so the chain continues.

```php title="routes/api.php"
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:api')->group(function () {
    Route::post('orders', [OrderController::class, 'store'])->name('orders.store')->idempotent();
});
```

### Per-route TTL

`ttl` is optional, in seconds, and works positionally or by name.

```php title="routes/api.php"
Route::post('payments', [PaymentController::class, 'store'])->idempotent(ttl: 604800);
```

A TTL outside 1 to 31536000 throws when the route is defined.

### Resources and groups

`apiResource()` and `resource()` accept the macro too. Safe methods (`GET`, `HEAD`, `OPTIONS`, `TRACE`) always pass through, so only `store`, `update` and `destroy` are protected.

```php title="routes/api.php"
Route::apiResource('invoices', InvoiceController::class)->idempotent();
```

For a whole group, use the `idempotent` middleware alias, with the TTL as its parameter:

```php title="routes/api.php"
Route::middleware(['auth:api', 'idempotent:600'])->group(function () {
    Route::post('exports', [ExportController::class, 'store']);
});
```

### What clients send

```http title="HTTP" no-copy
POST /api/orders
Authorization: Bearer <token>
Idempotency-Key: 6f1c3a52-8f2e-4d0b-9a7e-1b2c3d4e5f60
Content-Type: application/json

{"product_id": 15, "quantity": 2}
```

- First request: your controller runs, for example `201 {"id":101,"status":"created"}`.
- Same key, same request, within the TTL: the same status and body, plus `Idempotency-Replayed: true`. The controller does not run.
- Same key, `"quantity": 5`: `409` with `idempotency_key_conflict`.
- Same key while the first request still runs: `409` with `idempotency_in_progress` and `Retry-After`.

A key is 1 to 255 visible ASCII characters. A UUID per user action is a good choice.

### Authentication runs first

The package puts its middleware after Laravel's authentication, route model binding and authorization in the router's middleware priority, so `->idempotent()->middleware('auth:api')` still authenticates first. Requests refused by those middleware never reserve a key.

### Route caching

The macro only adds a middleware string such as `Pharaonic\Laravel\ApiIdempotency\Http\Middleware\EnsureIdempotency:600`, so `php artisan route:cache` keeps it exactly.

## How It Works

Every unsafe request on an idempotent route goes through these steps, in this order:

1. **Key**: the header must hold one valid key, or the request gets `400`.
2. **Scope**: the scope resolver must name a principal, or the request gets `401`.
3. **Body**: the body must be empty or JSON within the limits, or it gets `415`, `413` or `400`.
4. **Reservation**: the store atomically inserts a `processing` record for the storage key, with a random owner token.
5. **Existing record**: if the key is taken, the request is answered from that record (see below) and your route does not run.
6. **Route**: your controller runs once.
7. **Outcome**: the owner records the outcome with a write that only succeeds while it still owns the record.

### States

```text title="Record states" no-copy
ABSENT --reserve--> PROCESSING --stored response--> COMPLETED --ttl--> ABSENT
                        |   \--4xx not listed-----> ABSENT (released)
                        \--5xx, exception,
                           unstorable response----> UNKNOWN --ttl--> ABSENT
```

### Answering an existing record

| Stored record | Same fingerprint | Different fingerprint |
| --- | --- | --- |
| `completed` | Replay the stored response | `409 idempotency_key_conflict` |
| `processing`, lease running | `409 idempotency_in_progress` with `Retry-After` | `409 idempotency_key_conflict` |
| `processing`, lease expired | `409 idempotency_outcome_unknown` | `409 idempotency_key_conflict` |
| `unknown` | `409 idempotency_outcome_unknown` | `409 idempotency_key_conflict` |

### Times

- A completed record expires `ttl` seconds after it **finished**. At that second the key is new again.
- A processing record holds its lease for `lease` seconds and is kept at least `ttl` seconds from when it started.
- An unknown record expires `ttl` seconds after its outcome was recorded.

Times use your application's clock (`Carbon::now()`), so keep servers in sync with NTP.

:::danger After the TTL, a key is new
A retry that arrives after the TTL runs your route again. Choose a TTL longer than any client retries, and never rely on this package alone to prevent duplicate charges.
:::

## Scopes

Two requests share an idempotency key only when they resolve the same scope. The storage key is a SHA-256 of the scope, the HTTP method, the route (domain and URI pattern) and the client's key, so the same key on another route, method, user or tenant is a different record.

### Authenticated user (default)

`Pharaonic\Laravel\ApiIdempotency\Scopes\AuthenticatedUser` uses `$request->user()`: the user's class and identifier. A request without a user is refused with `401 idempotency_unauthenticated`, so anonymous clients never share one key space.

### Your own resolver

Implement `Pharaonic\Laravel\ApiIdempotency\Contracts\ScopeResolver` for tenants, API clients or guest checkouts. Return `null` when the request has no principal.

```php title="app/Idempotency/TenantScope.php"
namespace App\Idempotency;

use Illuminate\Http\Request;
use Pharaonic\Laravel\ApiIdempotency\Contracts\ScopeResolver;

class TenantScope implements ScopeResolver
{
    public function resolve(Request $request): ?string
    {
        $tenant = $request->attributes->get('tenant_id');

        return $tenant === null ? null : 'tenant:'.$tenant.':user:'.optional($request->user())->getAuthIdentifier();
    }
}
```

```php title="config/pharaonic/api-idempotency.php"
'scope' => App\Idempotency\TenantScope::class,
```

The resolver is resolved from the container on every request, so it can read request state safely under Octane.

:::warning A scope must identify one principal
Returning a constant, or an IP address shared by many users, lets one client replay another client's response. Scope by something you authenticated.
:::

## Fingerprints

The request fingerprint is a SHA-256 built with `pharaonic/php-fingerprint` from:

- the method, path and query string;
- the decoded JSON body.

Headers are not part of it, so a new trace ID or a refreshed token never turns a retry into a conflict.

Raw bodies are never stored; only their fingerprint is.

### JSON rules

| Compared | Result |
| --- | --- |
| `{"a":1,"b":2}` and `{"b":2,"a":1}` | same: object key order never matters |
| `{"a":[1,2]}` and `{"a":[2,1]}` | different: lists keep their order |
| `1`, `1.0` and `"1"` | all different |
| `true` and `1` | different |
| `{}` and `[]` | different |
| `{"a":null}` and `{}` | different |
| `1e2` and `100.0` | same: both decode to the same float |
| integers beyond PHP_INT_MAX | compared by their digits |

### Supported bodies

Requests must have a JSON body (`application/json` or any `+json` type) or no body. Form and multipart requests get `415 idempotency_request_unsupported`; invalid JSON, or JSON nested deeper than `json_decode()` allows, gets `400 idempotency_request_invalid`. Limit body sizes where you already do: your web server and `post_max_size`.

### Volatile fields and API versions

A retry must resend the exact same request, so keep client timestamps and other volatile values out of the body.

Put API versions in the URL: `/v1/orders` and `/v2/orders` are different routes, so they never share keys. A version sent only in a header is not part of the fingerprint, so a retry under another version gets the first response replayed.

## Stores

`store.driver` picks one of two drivers, and both reserve keys atomically; any other driver throws, because a store without atomic reservation could run a request twice.

```php title="config/pharaonic/api-idempotency.php"
'store' => [
    'driver' => env('IDEMPOTENCY_STORE', 'database'),
    'connection' => env('IDEMPOTENCY_CONNECTION'),
    'table' => 'idempotency_keys',   // database
    'prefix' => 'idempotency:',      // redis
],
```

### Database

The primary key on `storage_key` is the lock: `INSERT ... ON CONFLICT DO NOTHING` (or `INSERT IGNORE` / `INSERT OR IGNORE`) succeeds for exactly one request. Every later change is one conditional `UPDATE` or `DELETE` on the owner token. MySQL, MariaDB and PostgreSQL work across servers; SQLite works within one machine.

Its table comes from the published migration (see [Installation](#installation)); without it, idempotent requests get `503 idempotency_store_unavailable`.

Expired rows stay in the table until you prune them:

```bash title="Terminal" no-line-numbers
php artisan idempotency:prune            # counts what would be deleted
php artisan idempotency:prune --apply    # deletes expired completed records
php artisan idempotency:prune --apply --unresolved   # also expired unknown and abandoned records
```

The command keeps unresolved records unless you pass `--unresolved`, and says how many are left.

:::tip Use a dedicated connection
Point `IDEMPOTENCY_CONNECTION` at its own connection when your controllers wrap work in transactions on the default one, so a rollback in your code never touches the idempotency record.
:::

### Redis

Set `IDEMPOTENCY_STORE=redis`, and `IDEMPOTENCY_CONNECTION` to a connection of `database.redis` (the default one when empty). Each record is a hash changed only by Lua scripts, one key per script, so it also works on Redis Cluster. Keys expire by themselves with `PEXPIRE`, never before their TTL; there is nothing to prune and no migration to publish. Both phpredis and predis work.

:::warning Redis persistence
A Redis restart without persistence (AOF or RDB) forgets every record, and retries then run again. Use a persistent Redis, or the database store, for routes with real side effects.
:::

### Store outages

When the store cannot reserve a key, the request is refused with `503 idempotency_store_unavailable` and your route does not run. There is no option to run unprotected.

## Failures and Recovery

The package never assumes that a request without a stored outcome did nothing. When it cannot know, it keeps the key locked.

### What each outcome does

| Your route returned | Record | A retry with the same key gets |
| --- | --- | --- |
| A storable `2xx` | `completed` | The stored response |
| Any other `4xx` | released (deleted) | A new run, so a corrected request can succeed |
| A `5xx`, or a thrown exception | `unknown` | `409 idempotency_outcome_unknown` |
| A success that cannot be stored (HTML, streamed, file download, too large, non-UTF-8, a redirect) | `unknown` | `409 idempotency_outcome_unknown` |

A `2xx` response is storable when its `Content-Type` is `application/json` or any `+json` type (or its body is empty), and its body is valid UTF-8 within `max_response_bytes`. Your client still receives the original response the first time.

### Crashes and timeouts

A worker that dies after your side effect and before the outcome is stored leaves a `processing` record:

- until its `lease` ends, retries get `409 idempotency_in_progress` with `Retry-After`;
- after the lease, retries get `409 idempotency_outcome_unknown` until the record expires or you remove it. The route never runs again by itself.

The original worker can never overwrite a record it no longer owns: its final write is conditional on its owner token and is dropped with a warning in the log.

Set `lease` above your longest request time (and above PHP's `max_execution_time`), so a slow request is not mistaken for an abandoned one.

### Resolving an unknown outcome

1. Find the records: in the database store, `state = 'unknown'`, or `state = 'processing'` with `lease_expires_at` in the past. The `method` and `route` columns say which endpoint they belong to.
2. Reconcile with your own data: did the order, charge or email happen?
3. If it did not happen and the client should be able to retry, delete the record. If it did, leave it; the client keeps getting `409` until it expires and should look the result up instead of retrying.

Listen to `IdempotentRequestUnresolved` (see [Events](#events)) to alert someone when this happens.

### Transactions and side effects

The idempotency record is written outside your controller's database transaction, before and after it runs, and nothing makes it atomic with your own writes, Redis, queues or external APIs. For strong guarantees:

- give the business record a unique reference (for example the idempotency key itself, or an order number) and enforce it with a unique index;
- send an idempotency key to providers that support one (most payment gateways do);
- dispatch jobs and emails after your own transaction commits.

## Errors

Refused requests throw `Pharaonic\Laravel\ApiIdempotency\Exceptions\IdempotencyException`, an `HttpException` that renders this JSON with its status:

```json title="Response" no-copy
{
    "message": "This Idempotency-Key was already used with a different request.",
    "code": "idempotency_key_conflict"
}
```

| Status | `code` | When |
| --- | --- | --- |
| 400 | `idempotency_key_missing` | The `Idempotency-Key` header is missing or empty. |
| 400 | `idempotency_key_invalid` | The key is longer than 255 characters, contains anything but visible ASCII, or is sent twice. |
| 401 | `idempotency_unauthenticated` | The scope resolver found no principal. |
| 409 | `idempotency_key_conflict` | The key was used with a different request. |
| 409 | `idempotency_in_progress` | The first request with this key is still running. Has `Retry-After`. |
| 409 | `idempotency_outcome_unknown` | The first request's outcome is unknown, so it will not run again. |
| 415 | `idempotency_request_unsupported` | The body is not JSON. |
| 400 | `idempotency_request_invalid` | The body is invalid JSON or nested deeper than `json_decode()` allows. |
| 503 | `idempotency_store_unavailable` | The store failed while reserving the key. |

Each code is also a constant on the exception (`IdempotencyException::KEY_CONFLICT`), and `errorCode()` returns it.

### Your own error format

Render the exception yourself in `bootstrap/app.php` to match your API's envelope:

```php title="bootstrap/app.php"
use Illuminate\Foundation\Configuration\Exceptions;
use Pharaonic\Laravel\ApiIdempotency\Exceptions\IdempotencyException;

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (IdempotencyException $e) {
        return response()->json([
            'error' => ['code' => $e->errorCode(), 'detail' => $e->getMessage()],
        ], $e->getStatusCode(), $e->getHeaders());
    });
})
```

Replays are never changed: they carry your application's original body and status.

## Events and Logs

The middleware dispatches four events. Each has public `$request` and `$key` properties; `$key` is the SHA-256 storage key, which never reveals the client's key or identity.

| Event | Dispatched when | Extra |
| --- | --- | --- |
| `IdempotentRequestReserved` | A request reserved its key and your route is about to run. | |
| `IdempotentRequestReplayed` | A stored response was returned instead of running the route. | |
| `IdempotentRequestRejected` | A request was refused because of its key's record. | `$reason`: `idempotency_key_conflict`, `idempotency_in_progress` or `idempotency_outcome_unknown` |
| `IdempotentRequestUnresolved` | A request ran but its outcome could not be stored. | `$reason`: `server_error`, `exception`, `unstorable_response` or `store_failed` |

All four live in `Pharaonic\Laravel\ApiIdempotency\Events`. Requests refused before reservation (bad key, no scope, bad body) dispatch nothing.

```php title="app/Providers/EventServiceProvider.php"
use Pharaonic\Laravel\ApiIdempotency\Events\IdempotentRequestUnresolved;

public function boot()
{
    parent::boot();

    Event::listen(IdempotentRequestUnresolved::class, function (IdempotentRequestUnresolved $event) {
        Log::channel('alerts')->warning('Idempotent request needs reconciliation', [
            'key' => $event->key,
            'route' => $event->request->path(),
            'reason' => $event->reason,
        ]);
    });
}
```

### Logs

The package logs only problems: store failures (`error`), unknown outcomes and lost ownership (`warning`). Log context holds the first 16 characters of the storage key, the method and the route pattern, and for store failures the exception's class and code (and its message, except for database errors, whose SQL would carry the stored response); never the client's key, the user, the request body or the response.

## AI Ready

API Idempotency is AI ready. It ships [Laravel Boost](https://laravel.com/docs/boost) resources, so the coding agent in your application (Claude Code, Cursor, Codex, Copilot, Gemini CLI, Junie…) knows how to use the package.

### Install

With Laravel Boost in your application, run:

```bash title="Terminal" no-line-numbers
php artisan boost:install
```

Boost finds the package's guideline and skill in `vendor/` and adds them for the agents you choose. After updating the package, refresh them with:

```bash title="Terminal" no-line-numbers
php artisan boost:update
```

### What the Agent Learns

| Resource | Loaded | Covers |
| --- | --- | --- |
| Guideline (`resources/boost/guidelines/core.blade.php`) | In every session | Marking routes with `->idempotent()`, the `Idempotency-Key` contract, scopes, what is stored and replayed, and the limits of idempotency |
| Skill `api-idempotency-development` | When the agent works on idempotent endpoints | The macro and middleware, every configuration key, scope resolvers, outcomes, error codes, events, pruning, pitfalls and testing |

:::tip Keep Them Current
Add `@php artisan boost:update --ansi` to your Composer `post-update-cmd` scripts so the agent always matches the installed release.
:::

## API Reference

### Route macro

| Method | Description | Returns |
| --- | --- | --- |
| `Route::...->idempotent(?int $ttl = null)` | Adds the idempotency middleware to the route. Throws `InvalidArgumentException` for an invalid TTL. | The same `Route` |
| `Route::resource(...)` / `apiResource(...)->idempotent(?int $ttl = null)` | The same for every route of the resource. | The same `PendingResourceRegistration` |

### Middleware

| Name | Description |
| --- | --- |
| `idempotent` | Alias of `EnsureIdempotency`; optional parameter `idempotent:{ttl}`. |
| `Pharaonic\Laravel\ApiIdempotency\Http\Middleware\EnsureIdempotency` | The middleware class, placed after authentication, route model binding and authorization in the router's priority. |

### Contracts and classes

| Class | Description |
| --- | --- |
| `Contracts\ScopeResolver` | `resolve(Request $request): ?string`, the key space of a request. |
| `Scopes\AuthenticatedUser` | Default resolver: the authenticated user's class and identifier. |
| `Exceptions\IdempotencyException` | Refused request. `errorCode(): string`, `getStatusCode(): int`, `getHeaders(): array`, `render(): JsonResponse`, and one constant per code. |
| `Events\IdempotentRequestReserved` | `$request`, `$key` |
| `Events\IdempotentRequestReplayed` | `$request`, `$key` |
| `Events\IdempotentRequestRejected` | `$request`, `$key`, `$reason` |
| `Events\IdempotentRequestUnresolved` | `$request`, `$key`, `$reason` |

All classes are in the `Pharaonic\Laravel\ApiIdempotency` namespace.

### Artisan

| Command | Description |
| --- | --- |
| `idempotency:prune` | Counts expired completed records of the database store. The Redis store needs no pruning. |
| `--apply` | Deletes them. |
| `--unresolved` | Also expired `unknown` and abandoned `processing` records. |

### Table

`idempotency_keys`: `storage_key` (primary), `request_fingerprint`, `state` (`processing`, `completed`, `unknown`), `owner_token`, `method`, `route`, `created_at`, `lease_expires_at`, `expires_at` (indexed), `completed_at`, `response_status`, `response_headers`, `response_body`. Times are Unix timestamps.

### Publish tags

| Tag | Publishes |
| --- | --- |
| `api-idempotency-config` | `config/pharaonic/api-idempotency.php` |
| `api-idempotency-migrations` | The migration, to `database/migrations` |
| `pharaonic`, `laravel-api-idempotency` | Both |

## Examples

### 1. Checkout that survives a double click

The browser generates one key per checkout attempt and reuses it on every retry.

- ===Routes

  ```php title="routes/api.php"
  Route::middleware('auth:api')->group(function () {
      Route::post('checkout', [CheckoutController::class, 'store'])->idempotent();
  });
  ```

- ===Client

  ```js title="resources/js/checkout.js"
  const key = crypto.randomUUID();

  async function checkout(cart) {
      const response = await fetch('/api/checkout', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key, Authorization: `Bearer ${token}` },
          body: JSON.stringify(cart),
      });

      if (response.status === 409 && response.headers.has('Retry-After')) {
          await new Promise(r => setTimeout(r, response.headers.get('Retry-After') * 1000));
          return checkout(cart);
      }

      return response.json();
  }
  ```

### 2. Payments with a provider key and a unique reference

Keep replays for a week, and protect the charge on both sides.

- ===Routes

  ```php title="routes/api.php"
  Route::post('payments', [PaymentController::class, 'store'])->middleware('auth:api')->idempotent(ttl: 604800);
  ```

- ===Controller

  ```php title="app/Http/Controllers/PaymentController.php"
  public function store(Request $request)
  {
      $reference = $request->user()->id.':'.$request->header('Idempotency-Key');

      $payment = Payment::firstOrCreate(['reference' => $reference], ['amount' => $request->input('amount')]);

      if ($payment->wasRecentlyCreated) {
          $this->gateway->charge($payment->amount, ['idempotency_key' => $reference]);
      }

      return response()->json($payment, 201);
  }
  ```

The unique `reference` column stops a second charge even after the idempotency record expires.

### 3. Multi-tenant API with API clients

```php title="app/Idempotency/ClientScope.php"
class ClientScope implements ScopeResolver
{
    public function resolve(Request $request): ?string
    {
        $client = $request->attributes->get('api_client');

        return $client === null ? null : 'client:'.$client->id;
    }
}
```

```php title="config/pharaonic/api-idempotency.php"
'scope' => App\Idempotency\ClientScope::class,
```

### 4. High-traffic endpoints on Redis

```dotenv title=".env" no-copy
IDEMPOTENCY_STORE=redis
IDEMPOTENCY_CONNECTION=idempotency
```

```php title="config/database.php"
'redis' => [
    // ...
    'idempotency' => [
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'port' => env('REDIS_PORT', 6379),
        'database' => 3,
    ],
],
```

### 5. Alert on outcomes that need a human

```php title="app/Listeners/ReportUnresolvedRequest.php"
class ReportUnresolvedRequest
{
    public function handle(IdempotentRequestUnresolved $event)
    {
        report(new RuntimeException("Idempotent request {$event->key} ended as {$event->reason}."));
    }
}
```

## Troubleshooting

### Every request gets 401 idempotency_unauthenticated

The default scope needs an authenticated user. Add authentication to the route (`auth:api`, `auth:sanctum`), or configure a `ScopeResolver` for public endpoints.

### Every request gets 503 idempotency_store_unavailable

The store cannot be reached or the table is missing. Publish the migration with `php artisan vendor:publish --tag=api-idempotency-migrations` and run `php artisan migrate`, or check the store's connection name. The log has the underlying exception.

### Retries keep getting 409 idempotency_outcome_unknown

The first request returned a 5xx, threw, timed out, or returned a response that cannot be replayed. Reconcile it as described in [Failures and Recovery](#failures-and-recovery). If the route returns HTML, files or redirects, it should not be idempotent; JSON responses need an `application/json` or `+json` type.

### Retries get 409 idempotency_in_progress long after the first request finished

The first worker died or exceeded the lease. After `lease` seconds it becomes an unknown outcome. Raise `lease` above your slowest request if requests are just slow.

### A correct retry gets 409 idempotency_key_conflict

Something in the request changed: a timestamp in the body or a query parameter. Have the client resend the exact same request, and keep volatile values out of the body.

### The same request runs twice

Check that the retry arrived after the TTL, that both requests resolved the same scope (same user or tenant), the same route and the same method, and that your Redis is persistent.

### The idempotency_keys table keeps growing

Schedule `php artisan idempotency:prune --apply`. Unknown and abandoned records are kept until you add `--unresolved`.
