PHPackages                             pyaesoneaung/atomic-locks-middleware - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. pyaesoneaung/atomic-locks-middleware

ActiveLibrary[Queues &amp; Workers](/categories/queues)

pyaesoneaung/atomic-locks-middleware
====================================

A package designed to ensure that only one request is processed at a time.

v1.3.0(11mo ago)33441[4 PRs](https://github.com/PyaeSoneAungRgn/atomic-locks-middleware/pulls)MITPHPPHP ^8.1CI passing

Since Aug 24Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/PyaeSoneAungRgn/atomic-locks-middleware)[ Packagist](https://packagist.org/packages/pyaesoneaung/atomic-locks-middleware)[ Docs](https://github.com/pyaesoneaung/atomic-locks-middleware)[ RSS](/packages/pyaesoneaung-atomic-locks-middleware/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (8)Dependencies (12)Versions (13)Used By (0)

Atomic Locks Middleware
=======================

[](#atomic-locks-middleware)

A package designed to ensure that only one request is processed at a time.

Installation
------------

[](#installation)

```
composer require pyaesoneaung/atomic-locks-middleware
```

Usage
-----

[](#usage)

By default, the atomic-locks-middleware uses `$request->user()?->id ?: $request->ip()` within atomic locks.

```
Route::post('/order', function () {
    // ...
})->middleware('atomic-locks-middleware');
```

If you prefer to implement IP-based locking, you can use `atomic-locks-middleware:ip`.

```
Route::post('/order', function () {
    // ...
})->middleware('atomic-locks-middleware:ip');
```

However, you have the flexibility to define `atomic-locks-middleware:{anything}` to customize the locking mechanism according to your preferences.

```
Route::post('/order', function () {
    // ...
})->middleware('atomic-locks-middleware:{anything}');
```

You can also pass additional parameters to the middleware for more customization. The available parameters are:

- `{anything} (string)` : Your custom locking mechanism.
- `{lockDuration} (int)` : Duration for which the lock will be held.
- `{canBlock} (bool)` : Whether the request can wait for the lock or not.
- `{blockDuration} (int)` : If waiting is allowed, the maximum duration to wait for the lock.

> If no additional parameters are provided, the default values from the config file will be used.

```
Route::post('/order', function () {
    // ...
})->middleware('atomic-locks-middleware:{anything}');

Route::post('/purchase', function () {
    // ...
})->middleware('atomic-locks-middleware:{anything},60,true,60');

Route::post('/payment/process', function () {
    // ...
})->middleware('atomic-locks-middleware:{anything},60,false');
```

How Does It Work?
-----------------

[](#how-does-it-work)

```
// AtomicLocksMiddleware.php

 public function handle(Request $request, Closure $next, string $option = null, int $lockDuration = null, string $canBlock = null, int $blockDuration = null): Response
{
    if (! empty($canBlock)) {
        $canBlock = filter_var($canBlock, FILTER_VALIDATE_BOOLEAN);
    }

    $name = match ($option) {
        null => $request->user()?->id ?: $request->ip(),
        'ip' => $request->ip(),
        default => $option
    };

    $name = "{$request->path()}_{$name}";

    $lock = Cache::lock(
        config('atomic-locks-middleware.lock_prefix') . $name,
        $lockDuration ?: config('atomic-locks-middleware.default_lock_duration')
    );

    if (! $lock->get()) {
        if (! ($canBlock ?? config('atomic-locks-middleware.can_block'))) {
            return response()->json([
                'message' => config('atomic-locks-middleware.message'),
            ], 429);
        }

        try {
            $lock->block($blockDuration ?: config('atomic-locks-middleware.default_block_duration'));
        } catch (LockTimeoutException) {
            $lock->release();

            return response()->json([
                'message' => config('atomic-locks-middleware.block_timeout_error_message'),
            ], 500);
        } catch (Throwable $th) {
            $lock->release();

            return response()->json([
                'message' => $th->getMessage(),
            ], 500);
        }
    }

    app()->instance(config('atomic-locks-middleware.instance'), $lock);

    return $next($request);
}

/**
 * Handle tasks after the response has been sent to the browser.
 */
public function terminate(Request $request, Response $response): void
{
    $instanceName = config('atomic-locks-middleware.instance');

    if (app()->bound($instanceName)) {
        app($instanceName)->release();
    }
}
```

The Atomic Locks Middleware uses [Laravel Atomic Locks](https://laravel.com/docs/10.x/cache#atomic-locks) in the background. It initiates a lock at the beginning of the middleware's execution and releases the lock once the response is dispatched to the browser.

Publish Configuration
---------------------

[](#publish-configuration)

Publish the configuration for customization

```
php artisan vendor:publish --provider="PyaeSoneAung\AtomicLocksMiddleware\AtomicLocksMiddlewareServiceProvider"
```

```
return [

    'middleware_name' => 'atomic-locks-middleware',
    'middleware_class' => PyaeSoneAung\AtomicLocksMiddleware\AtomicLocksMiddleware::class,

    'instance' => 'AtomicLocksMiddleware',

    'lock_prefix' => 'atomic_locks_middleware_',
    'default_lock_duration' => 60,

    'can_block' => false,
    'default_block_duration' => 60, // It's generally recommended to set the block duration to be longer than the lock duration.
    'block_timeout_error_message' => 'Timeout: Unable to acquire lock within the specified time.',

    'message' => 'Too Many Attempts',
];
```

Testing
-------

[](#testing)

```
composer test
```

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance72

Regular maintenance activity

Popularity22

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~92 days

Recently: every ~161 days

Total

8

Last Release

344d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b4a938e91069afb632288ccdb87813e19c0d0fc86189f73daa33464e0d2a0367?d=identicon)[pyaesoneaung](/maintainers/pyaesoneaung)

---

Top Contributors

[![PyaeSoneAungRgn](https://avatars.githubusercontent.com/u/44226349?v=4)](https://github.com/PyaeSoneAungRgn "PyaeSoneAungRgn (37 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (14 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (10 commits)")

---

Tags

double-clickhacktoberfestlaravelmiddlewaremiddlewarelaravelpyaesoneaungatomic-locks-middleware

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/pyaesoneaung-atomic-locks-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/pyaesoneaung-atomic-locks-middleware/health.svg)](https://phpackages.com/packages/pyaesoneaung-atomic-locks-middleware)
```

###  Alternatives

[lorisleiva/laravel-actions

Laravel components that take care of one specific task

2.8k7.5M115](/packages/lorisleiva-laravel-actions)[croustibat/filament-jobs-monitor

Background Jobs monitoring like Horizon for all drivers for FilamentPHP

254255.2k6](/packages/croustibat-filament-jobs-monitor)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

3786.5k](/packages/harris21-laravel-fuse)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)[pyaesoneaung/sportmonks-football-api

Laravel package for Sportmonks Football Api(V3)

271.8k](/packages/pyaesoneaung-sportmonks-football-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
