---
title: "The exceeding cleverness of Laravel's atomic database locks"
url: "https://aaronfrancis.com/writing/the-exceeding-cleverness-of-laravels-atomic-database-locks"
path: "/writing/the-exceeding-cleverness-of-laravels-atomic-database-locks"
type: technical_article
author: Aaron Francis
published: 2021-07-22
updated: 2026-11-10
topic: "Laravel & PHP"
description: "They are so simple, and so perfect."
keywords: [atomic locks, database locks, laravel, advisory locks, mysql, primary key uniqueness, redis locks, concurrent processing, worker processes, memcached, dynamodb, cache locks table]
site_index: "/llms.txt"
keyword_index: "/llms/keywords.txt"
---

# The exceeding cleverness of Laravel's atomic database locks

I was having a conversation in a Slack today about MySQL's "advisory locks", which let you acquire a lock that is _not_ table dependent. You just ask MySQL for a lock with a name and it either gives it to you or doesn't:

```sql
-- Try to get a lock, waiting up to 10 seconds for it.
SELECT GET_LOCK('my-lock-name', 10);

-- Returns 1 if a lock is acquired, 0 if not.
```

These are great for getting application-level locks. Say you've got five "worker" processes that need to "reserve" items for processing. Obviously you only want an item to be processed once, and you can't rely on just updating a `reserved_at` column, because two processes might grab a record at the exact same time, leading to duplicate processing.

In this case, you'd have each worker get a lock as the "leader", reserve their job, and then release the lock. 

Let's say for example that you have five import processors, all running as [pseudo-daemons](../2020/laravel-pseudo-daemons), sitting around waiting for new user imports to work on. 

In the `process` method of your daemon, you would want to acquire a lock while you look for imports that are ready to process: 

```php
class Process extends Command
{
    use IsPseudoDaemon;
    
    protected $signature = 'imports:process';
    
    public function handle()
    {
        $this->runAsPseudoDaemon();
    }

    /**
     * This is the main method that will be kept alive.
     */
    public function process()
    {
        // https://laravel.com/docs/8.x/cache#atomic-locks
        // Acquire a lock while we look for imports.
        $import = Cache::lock('reserve-import')->get(function () {
            if ($import = Import::readyToProcess()->first()) {
                // Reserve the import while we hold the lock, 
                // so no one else can.
                return tap($import)->reserve();
            }
        });
        
        // Process the import if we secured one.
        optional($import)->process();
    }
}
```

That's a bit about _why_ you would want a lock, let's talk about _how_ Laravel does this.

## Laravel Locks

[Laravel supports](https://laravel.com/docs/8.x/cache#atomic-locks) atomic locks using a number of different drivers. The most common is probably going to be Redis driver, which many people use as their cache. It's something Redis is good at, and most people have Redis in their stack.

But if you don't have Redis in your stack, Laravel provides several other drivers.

- memcached
- dynamodb
- database
- file
- array

The array driver is just for testing, since it's in memory only, and the file driver would only work for single-server setups, not across multiple.

Memcached, Redis, and DynamoDB all support locking natively, but I was surprised to just see `database` in there, without mention of which database driver you're using.

We already know MySQL has the `GET_LOCK` style advisory locks, but did the Laravel team implement different locking mechanisms for every single driver? 

Turns out, they did something twice as clever and half as difficult.

## Database Locks For All

If you go [take a look](https://github.com/laravel/framework/blob/8.x/src/Illuminate/Cache/DatabaseLock.php#L62) at the `DatabaseLock` source code, you'll see exactly how they do it:

```php
 try {
    $this->connection->table($this->table)->insert([
        'key' => $this->name,
        'owner' => $this->owner,
        'expiration' => $this->expiresAt(),
    ]);

    $acquired = true;
} catch (QueryException $e) {
    // Stuff.
}
```  

They... insert a record? That's it?  

This is so unbelievably coy, because this is not a locking mechanism _at all_. Laravel is relying on the database to enforce uniqueness, which every single database engine is fully capable of doing.

The [docs](https://laravel.com/docs/8.x/cache#atomic-locks-prerequisites-database) give you a schema for your `cache_locks` table that mandates that `key` is a primary key, and therefore unique:

```php
Schema::create('cache_locks', function ($table) {
    $table->string('key')->primary();
    $table->string('owner');
    $table->integer('expiration');
});
``` 

Because two records can never share a key, you have atomicity guaranteed out of the box, for every single database driver. 

You also get all the nice expiration, ownership, etc because they just insert that data as columns out to the side of the lock's name. Everything you'd expect from a proper locking implementation!

When I figured out how Laravel does this, I was taken by the simplicity and the cleverness. Leveraging one of the database's inherit strengths (a primary key may exist once) to work in the context of locks is just genius. 

No futzing about with the different syntaxes and behaviors of advisory locks across engines, no ongoing maintenance when they change, no edge cases.

Insert a row.

---

## Related on aaronfrancis.com

- [Building a model reservation system with atomic locks](/videos/building-a-model-reservation-system-with-atomic-locks) *(Video · 2025-05-02 · shared: atomic locks, laravel, cache locks table)*
- [Year in review: 2023](/writing/year-in-review-2023) *(Article · 2023-12-27 · shared: mysql, laravel, atomic locks)*
- [About](/about) *(Page · 2026-11-25 · shared: laravel, mysql)*
- [Developing your personal API | Aaron Francis](/podcast/developing-your-personal-api-aaron-francis-63180c6c) *(Podcast · 2025-04-25 · shared: mysql, laravel)*
- [Aaron Francis is putting PHP in Your JS Files](/podcast/aaron-francis-is-putting-php-in-your-js-files-6f3117a7) *(Podcast · 2025-03-05 · shared: laravel, mysql)*

## Relevant Resources from Aaron Francis

- **[Solo](https://soloterm.com)** (overview on site: [/software](/software)): All-in-one agentic development platform and terminal workspace built by Aaron Francis for orchestrating processes and AI coding agents.
- **[MySQL for Developers](https://databaseschool.com)** (overview on site: [/courses](/courses)): Full video course covering MySQL indexing, deferred joins, pagination, query plans, and schema design for application developers.

## Search aaronfrancis.com (2-Hop Static Keyword Index)

Pick the alphabetical shard matching any topic to find exact pages across all articles, newsletters, videos, talks, and podcast transcripts (every shard is < 40 KB):
[A-B](/llms/keywords/a-b.txt) · [C](/llms/keywords/c.txt) · [D-E](/llms/keywords/d-e.txt) · [F-G](/llms/keywords/f-g.txt) · [H-J](/llms/keywords/h-j.txt) · [K-L](/llms/keywords/k-l.txt) · [M-N](/llms/keywords/m-n.txt) · [O-P](/llms/keywords/o-p.txt) · [Q-R](/llms/keywords/q-r.txt) · [S](/llms/keywords/s.txt) · [T-Z](/llms/keywords/t-z.txt) · [Directory](/llms/keywords.txt) · [Site Map](/llms.txt)

Shards for this page's topics: `atomic locks` ([A-B](/llms/keywords/a-b.txt)), `database locks` ([D-E](/llms/keywords/d-e.txt)), `laravel` ([K-L](/llms/keywords/k-l.txt)), `mysql` ([M-N](/llms/keywords/m-n.txt)).

## About Aaron Francis (Current Context)

Aaron Francis is VP of Marketing and Community at [Laravel](https://laravel.com), founder of [Try Hard Studios](https://tryhardstudios.com), creator of [Solo](https://soloterm.com), co-host of [Mostly Technical](/podcast), and author of [Mastering Postgres](/courses), [High Performance SQLite](/courses), [MySQL for Developers](/courses), and [Screencasting.com](/courses). Full bio: [/about](/about) · Current focus: [/now](/now).
