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.
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.
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.0, 8.1 or 8.2
- Laravel 9.33 or later 9.x releases
- A database supported by Laravel (MySQL, MariaDB, PostgreSQL, SQLite) or Redis (phpredis or predis)
#Composer Installation
composer require pharaonic/laravel-api-idempotencyThe 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.
php artisan vendor:publish --tag=api-idempotency-migrationsphp artisan migrateUsing Redis? Skip this step and set IDEMPOTENCY_STORE=redis (see Stores).
#Publish Configuration
php artisan vendor:publish --tag=api-idempotency-configThe file lands in config/pharaonic/api-idempotency.php.
#Schedule Pruning
Expired database records are deleted by a command. Schedule it in app/Console/Kernel.php:
1protected function schedule(Schedule $schedule)2{3 $schedule->command('idempotency:prune --apply')->hourly();4}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. |
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. |
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-Keyheader, and replays carryIdempotency-Replayed: true. - Request bodies are JSON (
application/jsonor any+jsontype) or empty; the method, path, query string and body make the fingerprint. - Any
2xxresponse with a JSON (or+json) type or an empty body is stored and replayed with itsContent-Type,Location,Content-Location,ETagandLast-Modifiedheaders. Cookies and credentials never replay. - Any other
4xxreleases the key; everything else locks it as an unknown outcome.
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.
1use App\Http\Controllers\OrderController;2use Illuminate\Support\Facades\Route;3 4Route::middleware('auth:api')->group(function () {5 Route::post('orders', [OrderController::class, 'store'])->name('orders.store')->idempotent();6});#Per-route TTL
ttl is optional, in seconds, and works positionally or by name.
1Route::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.
1Route::apiResource('invoices', InvoiceController::class)->idempotent();For a whole group, use the idempotent middleware alias, with the TTL as its parameter:
1Route::middleware(['auth:api', 'idempotent:600'])->group(function () {2 Route::post('exports', [ExportController::class, 'store']);3});#What clients send
1POST /api/orders2Authorization: Bearer <token>3Idempotency-Key: 6f1c3a52-8f2e-4d0b-9a7e-1b2c3d4e5f604Content-Type: application/json56{"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:409withidempotency_key_conflict. - Same key while the first request still runs:
409withidempotency_in_progressandRetry-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:
- Key: the header must hold one valid key, or the request gets
400. - Scope: the scope resolver must name a principal, or the request gets
401. - Body: the body must be empty or JSON within the limits, or it gets
415,413or400. - Reservation: the store atomically inserts a
processingrecord for the storage key, with a random owner token. - Existing record: if the key is taken, the request is answered from that record (see below) and your route does not run.
- Route: your controller runs once.
- Outcome: the owner records the outcome with a write that only succeeds while it still owns the record.
#States
1ABSENT --reserve--> PROCESSING --stored response--> COMPLETED --ttl--> ABSENT2 | \--4xx not listed-----> ABSENT (released)3 \--5xx, exception,4 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
ttlseconds after it finished. At that second the key is new again. - A processing record holds its lease for
leaseseconds and is kept at leastttlseconds from when it started. - An unknown record expires
ttlseconds after its outcome was recorded.
Times use your application's clock (Carbon::now()), so keep servers in sync with NTP.
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.
1namespace App\Idempotency; 2 3use Illuminate\Http\Request; 4use Pharaonic\Laravel\ApiIdempotency\Contracts\ScopeResolver; 5 6class TenantScope implements ScopeResolver 7{ 8 public function resolve(Request $request): ?string 9 {10 $tenant = $request->attributes->get('tenant_id');11 12 return $tenant === null ? null : 'tenant:'.$tenant.':user:'.optional($request->user())->getAuthIdentifier();13 }14}1'scope' => App\Idempotency\TenantScope::class,The resolver is resolved from the container on every request, so it can read request state safely under Octane.
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.
1'store' => [2 'driver' => env('IDEMPOTENCY_STORE', 'database'),3 'connection' => env('IDEMPOTENCY_CONNECTION'),4 'table' => 'idempotency_keys', // database5 'prefix' => 'idempotency:', // redis6],#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); without it, idempotent requests get 503 idempotency_store_unavailable.
Expired rows stay in the table until you prune them:
php artisan idempotency:prune # counts what would be deletedphp artisan idempotency:prune --apply # deletes expired completed recordsphp artisan idempotency:prune --apply --unresolved # also expired unknown and abandoned recordsThe command keeps unresolved records unless you pass --unresolved, and says how many are left.
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.
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
leaseends, retries get409 idempotency_in_progresswithRetry-After; - after the lease, retries get
409 idempotency_outcome_unknownuntil 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
- Find the records: in the database store,
state = 'unknown', orstate = 'processing'withlease_expires_atin the past. Themethodandroutecolumns say which endpoint they belong to. - Reconcile with your own data: did the order, charge or email happen?
- 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
409until it expires and should look the result up instead of retrying.
Listen to IdempotentRequestUnresolved (see 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:
1{2 "message": "This Idempotency-Key was already used with a different request.",3 "code": "idempotency_key_conflict"4}| 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 your exception handler to match your API's envelope:
1use Pharaonic\Laravel\ApiIdempotency\Exceptions\IdempotencyException; 2use Throwable; 3 4public function render($request, Throwable $exception) 5{ 6 if ($exception instanceof IdempotencyException) { 7 return response()->json([ 8 'error' => ['code' => $exception->errorCode(), 'detail' => $exception->getMessage()], 9 ], $exception->getStatusCode(), $exception->getHeaders());10 }11 12 return parent::render($request, $exception);13}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.
1use Pharaonic\Laravel\ApiIdempotency\Events\IdempotentRequestUnresolved; 2 3public function boot() 4{ 5 parent::boot(); 6 7 Event::listen(IdempotentRequestUnresolved::class, function (IdempotentRequestUnresolved $event) { 8 Log::channel('alerts')->warning('Idempotent request needs reconciliation', [ 9 'key' => $event->key,10 'route' => $event->request->path(),11 'reason' => $event->reason,12 ]);13 });14}#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.
#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.
1Route::middleware('auth:api')->group(function () {2 Route::post('checkout', [CheckoutController::class, 'store'])->idempotent();3}); 1const key = crypto.randomUUID(); 2 3async function checkout(cart) { 4 const response = await fetch('/api/checkout', { 5 method: 'POST', 6 headers: { 'Content-Type': 'application/json', 'Idempotency-Key': key, Authorization: `Bearer ${token}` }, 7 body: JSON.stringify(cart), 8 }); 9 10 if (response.status === 409 && response.headers.has('Retry-After')) {11 await new Promise(r => setTimeout(r, response.headers.get('Retry-After') * 1000));12 return checkout(cart);13 }14 15 return response.json();16}#2. Payments with a provider key and a unique reference
Keep replays for a week, and protect the charge on both sides.
1Route::post('payments', [PaymentController::class, 'store'])->middleware('auth:api')->idempotent(ttl: 604800); 1public function store(Request $request) 2{ 3 $reference = $request->user()->id.':'.$request->header('Idempotency-Key'); 4 5 $payment = Payment::firstOrCreate(['reference' => $reference], ['amount' => $request->input('amount')]); 6 7 if ($payment->wasRecentlyCreated) { 8 $this->gateway->charge($payment->amount, ['idempotency_key' => $reference]); 9 }10 11 return response()->json($payment, 201);12}The unique reference column stops a second charge even after the idempotency record expires.
#3. Multi-tenant API with API clients
1class ClientScope implements ScopeResolver2{3 public function resolve(Request $request): ?string4 {5 $client = $request->attributes->get('api_client');6 7 return $client === null ? null : 'client:'.$client->id;8 }9}1'scope' => App\Idempotency\ClientScope::class,#4. High-traffic endpoints on Redis
1IDEMPOTENCY_STORE=redis2IDEMPOTENCY_CONNECTION=idempotency1'redis' => [2 // ...3 'idempotency' => [4 'host' => env('REDIS_HOST', '127.0.0.1'),5 'port' => env('REDIS_PORT', 6379),6 'database' => 3,7 ],8],#5. Alert on outcomes that need a human
1class ReportUnresolvedRequest2{3 public function handle(IdempotentRequestUnresolved $event)4 {5 report(new RuntimeException("Idempotent request {$event->key} ended as {$event->reason}."));6 }7}#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. 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.
Contributors
Amazing people who made this package possible
This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel API Idempotency!
Want to Contribute?
We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.
Was this page helpful?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .