Skip to content

andp97/laravel-locky

Repository files navigation

locky-image.png

A simple Laravel package for distributed lock

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

A simple Laravel package for distributed lock around Redis atomic locks with retry + backoff (with jitter). Itโ€™s easy to read, chainable, and testable.

Installation

You can install the package via composer:

composer require andp97/laravel-locky

You can publish the config file with:

php artisan vendor:publish --tag="laravel-locky-config"

Usage

Basic

use Pavons\Locky\Facades\Locky;

$result = Locky::make("widgets:{$id}")
    ->ttl(10)
    ->run(function () use ($id) {
        processWidget($id);
        return true;
    });

With retries, exponential backoff, and full jitter

use Pavons\Locky\Facades\Locky;

Locky::make("widgets:{$orderId}")
    ->ttl(12)
    ->attempts(7)
    ->baseDelayMs(75)     // 75, 150, 300, 600, 1200, 2000โ€ฆ
    ->multiplier(2.0)
    ->maxDelayMs(2000)
    ->jitter('full')      // none|equal|full
    ->onRetry(function ($key, $attempt, $sleepMs) {
        logger()->notice("Retrying lock", compact('key', 'attempt', 'sleepMs'));
    })
    ->onFail(function ($key, $attempts) {
        // Optional graceful fallback
        report(new \RuntimeException("Lock failed for {$key} after {$attempts} attempts"));
        return null; // Returning here prevents throwing; omit to throw
    })
    ->run(function () use ($orderId) {
        settleOrder($orderId);
    });

In a queued job (recommended)

public function handle(): void
{
    Locky::make("job:import:{$this->batchId}")
        ->ttl(15)
        ->attempts(8)
        ->jitter('equal')
        ->run(function () {
            $this->performImport(); // exclusive section
        });
}

Notes & best practices

  • Use Redis (CACHE_DRIVER=redis) so Cache::lock() is truly distributed.

  • Pick TTL > worst-case critical section, but keep it tight; split long work to keep the locked part short.

  • Jitter:

    • full: best at smoothing thundering herds (default).

    • equal: narrows variance while avoiding sync.

    • none: only if you really want deterministic waits.

  • Hooks (onRetry, onFail) make it easy to add logs/metrics without cluttering business code.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

About

A simple Laravel package for distributed lock ๐Ÿ”’

Resources

License

Contributing

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Languages