Laravel's atomic locks
Learn all about the power of Laravel's atomic locks! I demonstrate how to grant unique access to resources, mitigate race conditions, and draw pretty red and green boxes on the screen.
Everything I said
Here we've got four processes fighting over the same resource, but because we're using Laravel's atomic locks, only one of these processes is going to get access to the resource at a time, whether that's looking for the next import, or processing a podcast, or making sure that some script is only running on one server at a time and not a bunch of different servers.
Laravel's atomic locks give us a nice, easy way to pull this off without having to worry about race conditions. Let me show you how we've done it. I've got a standard Laravel command here. I've emptied out a bunch of the comments and then just added a render function that's gonna render our red/green backgrounds. I'll show you that in a little bit. But before we do, we gotta talk about this locking system.
A, a locking, an atomic locking system is a way to communicate to other processes that I'm in charge. I'm the captain now. I'm the only one that's allowed to do this thing. In Laravel, the locking system is built into the caching system, so you have to have a compatible cache driver. So if you do cache, you'll see that lock is part of the cache namespace or the cache facade in this case.
Now, there are several compatible cache drivers that work. Surprisingly, database and file work, and then stuff you lo- you would probably expect, like Redis and Memcache. The array driver is listed, but there's a big caveat to that, um, which we will talk about in a little bit. But you have to have a compatible cache driver, and if you wanna communicate across servers, everyone needs to be talking to the same cache driver.
So the first thing you would do is you would give it a name. You could give it something silly, like example, or like we were talking about earlier, if you want one process to be in charge of processing a single podcast, you can name it like that, or you could name it, um, let's say you've got 10 import, uh, processes running, and you wanna make sure that only one is pulling imports off of the queue at a time.
That is something that I've definitely done. We're just gonna name ours example, and then you say how long do you want to keep this lock for? You can manually release the lock, but in the event that your process dies, how long should this lock be held before it expires? That's it. Now you have, now you have the beginnings of a lock, and now what we can do is we can say lock get.
And if we want to just pass a callback in, we can say, "This line got the lock." And that should be enough. Now we know we're the only process that is going to be doing this thing at a time. Now, in real life, this would be some sort of long process where you're calling out to an API to publish the podcast, or you're doing something with an import to mark it as, you know, started or working, but we're just gonna say, "Got the lock." If we switch over and we do PHP Artisan, my shorthand is
AR, so that's PHP Artisan app run. You'll see, got the lock, got the lock, got the lock. Not very interesting, and maybe a little bit confusing, 'cause I told you that the lock lasts for 10 seconds unless you release it. Well, if you pass a callback, the lock automatically gets released at the end of the callback. So we can say, let's say, acquired.
If acquired, then we'll say, "This line got the lock." Else we'll say, let's just say, "Sad. No lock for you." So if we switch back now, what we're gonna see is the first time, the first time we run this, we got the lock, and then for a while, it's just gonna say, "Sad," until the lock expires after 10 seconds, which should be...
There you go. I was, I was gonna see how long I had to vamp. There you go. So the lock expired. We never actually manually released it, and it didn't automatically get released. It just expired. And so now this process has the lock, and that was 10 seconds. So now you'll see now we're just waiting for the lock to be released. So you can take that lock and pass it around, and you can decide when you wanna release it, or you can pass a closure through and it will be released at the end of that closure.
This doesn't make for a very compelling example when you're only working with one process, right? Because there's no one competing against you. But when there are multiple processes or multiple processes on multiple servers, that's when you need to start communicating and say, "Hang on, everybody. I'm working on this thing. Y'all don't start working on it. I need to go in and claim my resources, and then I'll give the lock back, and y'all can start looking for resources that you should be working on." I'm gonna move all the rendering down to this render function, and I actually like the name acquired
better, so we're gonna do that. We can get rid of this guy. Let's take got the lock, come down here. So if it's acquired, we'll say, "Got the lock," otherwise we'll say, "Sad." Then we can say this render acquired. If it is acquired, we're gonna sleep for about three seconds. Well, exactly three seconds, in fact, just to mimic some processing.
So we'll say, "Sleep for a bit," and then we're going to release the lock. So this is how we would manually release the lock. Remember, it will expire after 10 seconds, but once we're done processing whatever it is we're processing, we're gonna release the lock and let the other, um, servers or processes start doing their work.
If we run this now, so if we clear this out and we run that, you'll see it's gonna sleep for about three seconds, and then it's gonna end, right? So this is pretty much working. We can flip back over to where I have four set up and run one. Run one real fast, and if we're fast enough, there we go. Run the other. So the one on the left locked the...
It acquired the lock, and the one on the right did not. And so it was sad, and we'll do it vice versa. There we go. Now, we got to start running this thing in a loop because this is way too slow for me to be doing manually. Let's not only do a loop, let's do an infinite loop. We don't, we don't get to do these very often. So let's do a while one, wrap the whole thing up in a while one.
Let's throw a little bit of a sleep at the top here. So we'll do a random between one and five times fifty thousand. That's just gonna be, uh, just a little bit of sleep, so we're not totally maxed out the whole time. If we switch back over, we'll clear this guy out, clear this guy out, and app run, got the lock, app run, sad.
Oh, there we go. And there we go. So now we're switching back and forth. We can actually do more. Why not? Let's do a whole bunch more. We're switching back and forth between now four processes, but you'll see only one gets the lock at a time, and this is exactly what we're looking for. We don't want to run two, uh, commands on, on a server at a time.
We just want to run the one, and that's what atomic locks give us. Now, let's, uh, let's make this, let's make this prettier. We're getting a little bit, uh, away from atomic locking and into making this, making this demo really pretty. But I did like the red and green background. So let's do that real fast. I have a package installed called Termwind, which gives you, eh, kind of Tailwind, but in your terminal. So what I'm gonna do is I'm gonna say the background color is if it's acquired, give me BG green six hundred.
If the lock was not acquired, give me BG red six hundred, and then the divs are going to be, let's do a string repeat. Um, so the string is going to be, uh, we're just gonna do a div with a non-breaking space in the middle, and we'll say class equals W full.
Kind of wild that you can do this in the terminal. Class equals W full with the background, and we want to repeat it. Terminal height. I think that's right. And so now we can say instead of this line, we're gonna use Termwind's render function, and we're just gonna wrap the whole thing in a div and throw out a new...
There we go. I think that should be all we need to do. Let's go ahead and just run it and see what happens. Hey, there's a green background, and there's a red background. There's a red background. There we go. We're back to our demo. It does look, if you notice, if you look really, really closely, it does look like the lock is shared there for a second, and that is actually just a rendering problem.
That is not a lock problem. The locks are atomic. What happens is we release the lock, the background stays green, and then we sleep for up to two hundred and fifty milliseconds with a green background. So we just need to re-render. So if we re-render, now we know for sure that we don't have the lock because we just released it.
So we're gonna release, or we're gonna render false, and we can run back here and say run, run, run, and run. Now we should see completely atomic switching with no overlap whatsoever. It's actually kind of fun to watch. I do, I do enjoy watching this. We need to talk about the drivers for a second.
It is very important if you're trying to coordinate across different processes that all processes are talking to the same driver. So they're all talking to the same Redis connection or the same database or the same file system. If you're gonna use the file driver, you can't use it on two separate servers that have different file systems.
Let me show you what happens if you do try to do that. So instead of using the file, I'm here on my local computer. That's fine. You can use the array. The array is only really useful for testing because if you use the array driver, the cache, the cache is basically in memory. It's in an array in memory, and each different process has its own.
So you'll see now that if we run this, it's just pure chaos. Everybody gets a lock. You get a lock, you get a lock, and you get a lock. The only time something is not locked is the microsecond after it's released before it acquires it again. So technically, all four of these processes have acquired a lock, but they've acquired an in-memory lock that is completely isolated from the other three.
And so they're all just, they're all just happy thinking, "Ah, I've got the lock." Well, yeah, everybody has a lock. So be careful what driver you choose. Now, in terms of the database, you may be thinking, I don't know. That feels weird. I don't know much about database locking. It's probably some advisory lock or shared lock or some sort of database lock thing that scares me, right? Not really.
The, the beautiful part about the way that Laravel has implemented the atomic locks in the database driver is it actually doesn't use the database locking mechanism at all. MySQL has, like, this get shared lock. So you can, you can kind of do this thing in MySQL. That's not what, that's not what Laravel uses at all. Instead, Laravel inserts a single row.
So it works with every single database driver for sure. Let me show you how this works. If we switch back here and we switch the cache driver to database, let's go ahead and just run a few. It doesn't-- We don't, we don't need all of them. If we just run one here and one here, we should see those bounce back and forth between the two.
So we know that it is working. Now, if we look at the database, we'll see we have this cache locks table, and this is a Laravel. Laravel gives you the migration to do this, so you don't have to come up with this yourself. But the only thing that is going on in this table is there is a key, and the key is unique. This key column is unique, and what Laravel does is it inserts.
You can see Laravel cache and then the name of the key that we gave it, which is example. It inserts It just inserts the row. And because databases are pretty good at making sure that if you say this is a unique column, they're pretty good at making sure that only unique values get in there. This is the way that Laravel accomplishes atomic locking with a database driver.
It relies on primary key enforcement. So a little bit of trivia. All that to say, don't be scared of the database driver for driving your atomic locks. It's not doing anything special. It's relying on the database's natural ability to enforce a primary key constraint. We've only barely scratched the surface here. There, there's a lot more that you can do.
One of the more interesting things that you can do is you can, you can acquire the lock, and then it gives you an identifier that you can pass to another process to reinstantiate the ownership of the lock. And so you can acquire a lock in one process and release it in a second process. That's a little bit of an advanced example, but it can be very useful, especially if you're passing a lock into a job that is going to be processed later.
How do locks and locking relate to jobs and queues is a good question, I think. It, it operates entirely outside of it. The queues are very robust, and the queues are good at making sure that jobs get pulled off and processed one time. This is kind of entirely separate when you need to do something else and you want to ensure that only one process or one server is doing that thing.
The way that I have used it in the past is I've had many, many worker processes waiting around for users to import CSVs, and when the users import a CSV, I only want one worker to pick it up. One worker is gonna pick it up, but I have five workers running, so I just have each one acquire a searching lock.
So every worker acquires a lock that says, "Look out, guys. I'm gonna go search for imports now. Y'all don't do it. And if I find one, I am gonna mark it as reserved." So anytime you need to do one thing across multiple processes or multiple servers, you might reach for atomic locks. They are very cool. The docs are very good. I would encourage you to check them out. See ya.