Laravel Idempotency: HTTP Idempotency Middleware for Laravel

Published on by

Laravel Idempotency: HTTP Idempotency Middleware for Laravel image

Wendell Adriel released Laravel Idempotency, a package that adds HTTP idempotency to write-oriented Laravel routes. When a POST, PUT, or PATCH request is retried with the same idempotency key and the same payload, the package replays the original cached response instead of running the route handler again — a common requirement for payment endpoints, order creation, and any API where clients may retry on network failure.

Applying the Middleware

The package provides two ways to attach idempotency to a route. The first is a standard route middleware:

use WendellAdriel\Idempotency\Http\Middleware\Idempotent;
 
Route::post('/orders', StoreOrderController::class)->middleware(Idempotent::class);

The middleware expects an Idempotency-Key header. When the same key is sent again with identical request data, the original response is returned with an Idempotency-Replayed: true header added.

Per-route configuration is available via Idempotent::using():

Route::post('/payments', ChargePaymentController::class)->middleware(
Idempotent::using(
ttl: 600,
lockTimeout: 30,
required: false,
scope: \WendellAdriel\Idempotency\Enums\IdempotencyScope::Ip,
header: 'X-Idempotency-Key',
)
);

The second option is a PHP attribute, which works at the class or method level and accepts the same options:

use WendellAdriel\Idempotency\Attributes\Idempotent;
use WendellAdriel\Idempotency\Enums\IdempotencyScope;
 
#[Idempotent]
class PaymentController
{
#[Idempotent(ttl: 600, lockTimeout: 30, scope: IdempotencyScope::Ip)]
public function store()
{
// ...
}
}

Since the attribute extends Laravel's built-in controller middleware attribute, only and except work as expected.

Key Scoping

Idempotency keys can be scoped three ways, configured globally in config/idempotency.php or overridden per route:

Scope Behavior
user Keys are segmented by authenticated user; guest requests fall back to client IP
ip Keys are segmented by client IP address
global The same key applies across all users and IP addresses

Conflict Detection

The package handles two conflict scenarios. If a request arrives with the same key but a different payload, it returns 422 Unprocessable Entity. If a second matching request arrives while the first is still being processed — a true in-flight duplicate — it returns 409 Conflict with a Retry-After: 1 header. Both behaviors work through Laravel's cache atomic locks, so a cache driver with lock support (Redis, Memcached) is required.

Artisan Commands

Two commands let you inspect and clear cached entries without touching the cache directly.

idempotency:list renders a table of active entries with scope, identifier, key, route, status code, and expiry:

php artisan idempotency:list --scope=user --id=5

idempotency:forget removes entries by scope, identifier, or key. Destructive calls prompt for confirmation unless --force is passed:

# remove all entries for a specific user
php artisan idempotency:forget --scope=user --id=5 --force
 
# remove every entry for a given client-provided key
php artisan idempotency:forget --key=checkout-1 --force

You can find Laravel Idempotency on GitHub.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud

The latest

View all →
Generate Short, URL-Safe IDs From Numbers With Sqids image

Generate Short, URL-Safe IDs From Numbers With Sqids

Read article
Scheduler List: A Web Dashboard for Laravel's Scheduled Tasks image

Scheduler List: A Web Dashboard for Laravel's Scheduled Tasks

Read article
Community Laravel Extension for Zed image

Community Laravel Extension for Zed

Read article
Advanced Eloquent Query Filtering with Filterable image

Advanced Eloquent Query Filtering with Filterable

Read article
Bulk Job Dispatching with Bus::bulk() in Laravel 13.13 image

Bulk Job Dispatching with Bus::bulk() in Laravel 13.13

Read article
Audit Laravel Apps for Security Issues with Checkpoint image

Audit Laravel Apps for Security Issues with Checkpoint

Read article