Skip to content
Laravel Packagev9.0.0MIT License

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.

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.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

Terminal
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.

Terminal
php artisan vendor:publish --tag=api-idempotency-migrations
php artisan migrate

Using Redis? Skip this step and set IDEMPOTENCY_STORE=redis (see Stores).

#Publish Configuration

Terminal
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 app/Console/Kernel.php:

app/Console/Kernel.php
1protected function schedule(Schedule $schedule)
2{
3 $schedule->command('idempotency:prune --apply')->hourly();
4}
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.

KeyDefaultDescription
ttl86400Seconds a finished request stays replayable, counted from when it finished. 1 to 31536000. Routes may override it.
lease120Seconds a request may run before it counts as abandoned. 1 to 86400. See Failures and Recovery.
scopeScopes\AuthenticatedUser::classA ScopeResolver class that decides whose key space a request uses.
store.driverenv('IDEMPOTENCY_STORE', 'database')database or redis. See Stores.
store.connectionenv('IDEMPOTENCY_CONNECTION')The database or Redis connection name; null uses the default one.
store.tableidempotency_keysThe table of the database store.
store.prefixidempotency:The key prefix of the Redis store.
max_response_bytes1048576Largest 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.
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.

routes/api.php
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.

routes/api.php
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.

routes/api.php
1Route::apiResource('invoices', InvoiceController::class)->idempotent();

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

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

#What clients send

HTTP
1POST /api/orders
2Authorization: Bearer <token>
3Idempotency-Key: 6f1c3a52-8f2e-4d0b-9a7e-1b2c3d4e5f60
4Content-Type: application/json
5
6{"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

Record states
1ABSENT --reserve--> PROCESSING --stored response--> COMPLETED --ttl--> ABSENT
2 | \--4xx not listed-----> ABSENT (released)
3 \--5xx, exception,
4 unstorable response----> UNKNOWN --ttl--> ABSENT

#Answering an existing record

Stored recordSame fingerprintDifferent fingerprint
completedReplay the stored response409 idempotency_key_conflict
processing, lease running409 idempotency_in_progress with Retry-After409 idempotency_key_conflict
processing, lease expired409 idempotency_outcome_unknown409 idempotency_key_conflict
unknown409 idempotency_outcome_unknown409 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.

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.

app/Idempotency/TenantScope.php
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}
config/pharaonic/api-idempotency.php
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.

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

ComparedResult
{"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 1different
{} and []different
{"a":null} and {}different
1e2 and 100.0same: both decode to the same float
integers beyond PHP_INT_MAXcompared 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.

config/pharaonic/api-idempotency.php
1'store' => [
2 'driver' => env('IDEMPOTENCY_STORE', 'database'),
3 'connection' => env('IDEMPOTENCY_CONNECTION'),
4 'table' => 'idempotency_keys', // database
5 'prefix' => 'idempotency:', // redis
6],

#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:

Terminal
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.

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.

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 returnedRecordA retry with the same key gets
A storable 2xxcompletedThe stored response
Any other 4xxreleased (deleted)A new run, so a corrected request can succeed
A 5xx, or a thrown exceptionunknown409 idempotency_outcome_unknown
A success that cannot be stored (HTML, streamed, file download, too large, non-UTF-8, a redirect)unknown409 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) 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:

Response
1{
2 "message": "This Idempotency-Key was already used with a different request.",
3 "code": "idempotency_key_conflict"
4}
StatuscodeWhen
400idempotency_key_missingThe Idempotency-Key header is missing or empty.
400idempotency_key_invalidThe key is longer than 255 characters, contains anything but visible ASCII, or is sent twice.
401idempotency_unauthenticatedThe scope resolver found no principal.
409idempotency_key_conflictThe key was used with a different request.
409idempotency_in_progressThe first request with this key is still running. Has Retry-After.
409idempotency_outcome_unknownThe first request's outcome is unknown, so it will not run again.
415idempotency_request_unsupportedThe body is not JSON.
400idempotency_request_invalidThe body is invalid JSON or nested deeper than json_decode() allows.
503idempotency_store_unavailableThe 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:

app/Exceptions/Handler.php
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.

EventDispatched whenExtra
IdempotentRequestReservedA request reserved its key and your route is about to run.
IdempotentRequestReplayedA stored response was returned instead of running the route.
IdempotentRequestRejectedA request was refused because of its key's record.$reason: idempotency_key_conflict, idempotency_in_progress or idempotency_outcome_unknown
IdempotentRequestUnresolvedA 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.

app/Providers/EventServiceProvider.php
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

MethodDescriptionReturns
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

NameDescription
idempotentAlias of EnsureIdempotency; optional parameter idempotent:{ttl}.
Pharaonic\Laravel\ApiIdempotency\Http\Middleware\EnsureIdempotencyThe middleware class, placed after authentication, route model binding and authorization in the router's priority.

#Contracts and classes

ClassDescription
Contracts\ScopeResolverresolve(Request $request): ?string, the key space of a request.
Scopes\AuthenticatedUserDefault resolver: the authenticated user's class and identifier.
Exceptions\IdempotencyExceptionRefused 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

CommandDescription
idempotency:pruneCounts expired completed records of the database store. The Redis store needs no pruning.
--applyDeletes them.
--unresolvedAlso 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

TagPublishes
api-idempotency-configconfig/pharaonic/api-idempotency.php
api-idempotency-migrationsThe migration, to database/migrations
pharaonic, laravel-api-idempotencyBoth

#Examples

#1. Checkout that survives a double click

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

routes/api.php
1Route::middleware('auth:api')->group(function () {
2 Route::post('checkout', [CheckoutController::class, 'store'])->idempotent();
3});
resources/js/checkout.js
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.

routes/api.php
1Route::post('payments', [PaymentController::class, 'store'])->middleware('auth:api')->idempotent(ttl: 604800);
app/Http/Controllers/PaymentController.php
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

app/Idempotency/ClientScope.php
1class ClientScope implements ScopeResolver
2{
3 public function resolve(Request $request): ?string
4 {
5 $client = $request->attributes->get('api_client');
6 
7 return $client === null ? null : 'client:'.$client->id;
8 }
9}
config/pharaonic/api-idempotency.php
1'scope' => App\Idempotency\ClientScope::class,

#4. High-traffic endpoints on Redis

.env
1IDEMPOTENCY_STORE=redis
2IDEMPOTENCY_CONNECTION=idempotency
config/database.php
1'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

app/Listeners/ReportUnresolvedRequest.php
1class ReportUnresolvedRequest
2{
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!

Moamen Eltouny

@MoamenEltouny

55 contributions

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?

Something wrong or missing? Report it on GitHub .