Building a model reservation system with atomic locks
We're using Laravel's atomic locks and database-generated columns to build a reliable reservation system—without race conditions or extra tables. I'll show you how to hook into Laravel’s cache lock system, add polymorphic relationships, and use generated columns to power powerful query scopes.
Everything I said
Okay, here's the plan. We're gonna cover these topics, but we're gonna cover them in a way that is integrated. Uh, this is a direction I kinda wanna take this channel, which is instead of teaching these things discreetly, which I have done. I have a video on atomic locks. You can find it down below. I've got, I've got 10-hour courses on everything you need to do- know about databases, which you can find down below.
Um, but I, I think it's maybe better to make these YouTube videos show how all of these things work together rather than, um, an academic approach of how one of these things works. So we're gonna create a full system whereby you can reserve models in your database using atomic locks. All right, I've got two scenarios here, which I'll show you in just one second, but, but just generally, an atomic lock is a way to solve the coordination problem.
So in this first scenario, we've got an import. We've got one import with an ID of number one in the database, and then we have four worker processes whose job it is to look for new imports to process. So somebody uploaded a CSV file, and now these guys are like, "I'm on it. I'm on it. I'm on it." The problem is we don't want all four of these to process the same one CSV.
Worst case scenario, we get, uh, the data in there four times. Best case scenario, we did four times the work and ended up with the same result. So ideally, one of these processes will be able to claim this import, it will be able to reserve this import, and then these three will not get the import at all because they will be locked out.
So process one comes in and says, "I reserve import number one." Process two, three, and four come along and say, "I reserve... Oh, wait, I can't. It's already locked. Somebody else owns the lock. I'll move on and start looking for other ones." That way we're guaranteed that this import is going to be processed by process number one, and these guys are left out in the cold.
Sorry, two, three, four. Now, another scenario could be something like this. You, you wanna try some action. Maybe that is, um, syncing to an external provider, uh, maybe that is, uh, downloading something from an external provider, or maybe it's just some sort of like health check that you want to do every, we'll say, four hours.
So in this case, you have the action. You want to wait at least four hours, and then you wanna come back and do the action again. And you could change this. I, I don't care. You could change this to wait at least seven days. Now, the scenario here is you could actually put a, um, you could actually put like a last synced at timestamp on there, and that's totally fine if you put that on your database, and then you can have your process come through and say, "Hey, who hasn't synced in the past four hours?" Totally legit,
totally fine. The problem is, um, when you get, when you get a bunch of these, and now you're like, "Well, do I have to create a new column for every one of these things that I'm doing?" And you could. That's kind of a pain. Um, you could also have an events table, which is something I'm very fond of. But in this scenario, we're gonna use cache locks to accomplish that as well.
We'll start with some design by wishful thinking. So I'll show you what I want the end state to be, and then we'll take steps to get there together, okay? Here's my desired outcome. So if we did user query, and then we drop down here, uh, we could do give me all the unreserved for the purposes of syncing. That's a pretty good-- I like that experience.
Um, I want all the users that are not currently reserved under this particular key of syncing. I think we can take it one step further and say reserve for syncing, and we'll say reserve them for plus four hours. Or we'll say we sync, we sync once a day, so reserve them for twenty-four hours. Um, this kind of inherently includes make sure they're not already reserved, and then when you grab them out of the database, go ahead and reserve them.
I like that. That seems reasonable. Uh, maybe we only wanna do, we only wanna do ten per minute or something, and then we'll get them, and we'll each over them, and we'll do, you know, whatever. We'll sync down here. This I like. I like this quite a bit. Um, user reserve for syncing for one day.
Only give me ten right now. Go ahead and grab them, and then each over them. This is the end goal. We can't get there yet. So let's just, uh, put our dreams aside for a second. Whoops, didn't mean to be dark. Let's put our future state that we will get to aside for one second and look at this. So we're gonna do, um, we're gonna do cache lock, and we'll say user, um, we need to grab-- The-- We're gonna create a cache here.
Uh, let's do user one sync, okay? So, uh, we already have the cache. We're gonna create a lock here. And so if we did lock equals cache user one sync get. Let's take a look at that. We'll DD the lock out, and what is this signature? I think this signature... Where did it go? Where did you go?
I hate it when it does that. Um, lock, string, name, int, seconds. So we're gonna say we'll lock this for five seconds. So now if we hop over to the terminal, what's the app reserve? Let's clear this out. PHP Artisan app reserve. So we did get the lock, and if we try again within five seconds, now we're locked out.
So that it-- atomic lock was created. We got it the first time, and now that it's been five seconds, we should be able to get it again. Boom. There we go. So we got the atomic lock the first time, and then we ran it quickly again within five seconds, and it said, "Sorry, somebody else owns that lock." We waited for the lock to expire and tried again, and we got it. So that proves that these cache locks do work.
Let me show you what it looks like in the database. Here it is in the database. You'll see Laravel cache. Uh, that part is a prefix, which I don't like. We'll change it in a second. And then that is the key that we gave that cache lock. Notice that this exists in a database table called cache locks, and the structure is such that the key right here, that's the primary key.
That's how we ensure that it is atomic. Databases are good at a lot of things. One thing they're super good at is making sure that a unique column only has one value of that type. So we can't enter another one down here. No matter how hard we try, it's gonna say, "Nope. No can do. Sorry, friendo." And that is what we want.
Um, when you have an atomic lock, you have to have some central store that can enforce the atomicity. That doesn't sound right. Um, and in our case, we're using the database. Now, I don't like this cache key because that's-- I wanna see that in the database. So here we can go over to Laravel's configuration, cache key prefix, and we're just gonna say, in fact, I don't want any prefix.
Now, if you are, um... If somebody else is writing to this cache besides this particular Laravel application, you're gonna be hosed 'cause you're gonna have, uh, key collisions here. So make sure that if a bunch of people are writing to maybe the same Redis store or a bunch of applications, make sure that you do use a prefix. Not the case here, so it doesn't super matter.
So now, if we run this again, uh, if we reserve, we did get our reservation, and we have a cleaner key there. So that first one is now invalid 'cause that's never gonna match anything 'cause we changed the prefix. So we're getting close. Um, actually, we're still pretty far away, but we have, we have a locking mechanism working.
So if we come down here, we can go to, uh, yep. And so this is how it would normally look. If, uh, if you got the lock, then say, like, I don't know, this, this info, starting processing, uh, else we would say locked out.
And this is, um, this is okay. This is a little... Again, this is a little wordy. I don't super love it. Starting processing and locked out, locked out, locked out, locked out. Starting processing. So yeah, so we know it works. All right. What do we need to do next? Um, let's come back here and look over.
So that's atomic locks. Um, here's what we need to do. We need to talk about generated database columns. So let's come back here, and we're gonna get rid of you. We don't need you. Back to our dreams, our hopes and dreams right here. How are we going to implement this reserve for bit? Because this is a query scope, which means it needs to work at the database at the query level.
So we can, um... I created a trait called reservable 'cause I wanna be able to add this to a bunch of different models. The only one I've added it to is, this is a, a default Laravel application, so all I have is the user model, and I've put reservable on there. Okay, so we have an empty trait. Now, by wishful thinking, we're gonna say public function, uh, scope.
Yes, I know you can use an attribute, but I'm not going to. Public function scope reserve for, I think is what we called that. Is that what we called that? Not you, you. Reserve for, and then we have a key and a duration. So we'll come back here, and we'll say that key should be, sure, we'll just make it a string key, and we'll just make it an int duration.
That's fine. Um, because it is seconds, that's good enough. So reserve for, and because this is a scope, we need to pass in the builder as the first argument. Builder query string key, and now we have to do something. Query where what? Query where what?
Um, where doesn't have is actually pretty good. That's a good start. Where it doesn't have a, uh, reservation. And we need to figure out... We'll, we'll need to figure out the key here in a second, but we also-- Let's just go ahead and scope that down, and we'll say, uh, builder. Yeah, that's actually correct. Uh, yep, that's correct.
And then inside, we'll say query where key, key. Uh, sure. I don't, I don't like the, I don't like the magic. We'll say where key, key. I think that's reasonable. So what we've done here is we've just created a scope that doesn't actually work, um, but we are programming by wishful thinking.
And we've said, all right, on this user, I want all users where they don't have a relationship called reservations. They don't have any of those records. But specifically, they don't have a reservation where the key is whatever the user passed in up here. Now, this relationship doesn't exist yet, so let's go ahead and create that relationship first.
So we're gonna say that this is relationships, and I always do this on my models. Um, may not be necessary in traits. So we've got scopes, and then we've got re-relationships, and we called this one reservations. So public function reservations. Okay. Now, because many different models, because many different models could be reserved, that is, uh, that leads us to believe that this is a polymorphic relationship,
meaning, um, a reservation could reference a user, a, an import, a file, uh, a podcast. It could reference many different things, and so this is going to be a polymorphic relationship. Now- Whoa, what's the table? We're actually going to use the cache locks table as our reservations table.
So we're getting a little wonky, but what I definitely don't wanna do is re-implement atomic locks from scratch. Uh, I'm not doing that. Laravel's got that. I- that's not, that's not my problem. So we're gonna use the cache locks table, which means we're gonna make a model. Um, so we're gonna say, make model cache lock, and that's all we have to do.
Um, and now we can say return this morph Many cache locks, uh, morph Many cache lock class, and we'll just call this, uh... we'll call it the model. This is close. Okay, this is, this is close. Um, it's a little wonky, but I kinda love it. Uh, we need to do one more thing, and we need to say where.
What is this column called? Expiration. So expiration is a timestamp. We need to say where expiration is. Uh, expiration is in the future, correct? So greater than, and then we'll just say now timestamp. Okay, so this is kind of getting to the right spot.
We're saying that a user has a relationship called reservation. In fact, it is the model type cache lock. Um, and we'll implement this part in a second. And the reservations must have a future expiration. If it's got an expiration in the past, that just means it's a p- it's a cache lock that hasn't been cleaned up yet, but it's no longer applicable.
Now, we don't have enough information in the database to associate this whatsoever with, uh, the model that we are supposedly reserving, right? And so one thing I don't wanna do is, um, I don't wanna... I, I kinda want everything to be driven off of the information that we have right here, off of the Laravel default information, which means we could do something like this.
We could do app model user, and then that's the ID, and then that's our, like, our reservation key. We could do that. Uh, one problem that I see here is putting app model user in the database. I never, ever, ever, ever wanna put class names in the database, and so usually you end up with something like this.
Uh, you have a, what's called a morph map, which we'll set up here in a second, but I don't like that either. I like that. It is way less readable, um, but it is going to come out to be a little bit smaller and a little bit faster. So in our minds, one is going to equal user, and then maybe two is going to equal podcast or something like that.
So let's go ahead and set that part up. In Laravel, you can pop open your app service provider, and you can clear out these very generous comments, and you can say, um, you can say that you want to create a morph map. And so to create a morph map, you're gonna do that in the-- I'm just looking.
You're gonna do that in the boot method, and you can say relation. Uh, well, you can say, uh, no, that's not right. Relation morph map. This is, uh, this is not, this is not good. This is not good. You want enforce morph map. So now anytime a model is missing from your morph map, Laravel's gonna throw an exception.
If you just do morph map, then, uh, you could end up with some mapped keys in the database and some that are unmapped, which I think is very silly. So let me show you this. Enforce morph map, and we're gonna say that, um, that's what, you know, the overlords want you to do. User is one. Here's what I like to do.
I like to say that one is user class. That's it. And then anytime I add a new model, eh, just add another one. You just say, two is, uh, two is podcast class. And that way, uh, the keys in your database end up super small. It's not very readable in the database, but that doesn't super bother me. Um, okay. So what we've done is we've disassociated the name of the class with whatever we're gonna put in the database, and we have that little translation layer in the middle.
Let me show you, uh, just real quick. We'll say, uh, we'll just do new user and get morph class. So if we were to dump that, so the user is, uh, reserve. The user is one. And if we come over, uh, app service provider and we comment you out, it's gonna say, "Whoops.
Hey, hold on. You're trying to use a model that has no morph map defined, and you told me that you need to enforce the morph map." So requires morph map is true, and then it says, "It's not there. Don't know what to do." And, um, this is the, uh, this is the method through which Laravel always runs these things before it puts it into the database.
So, uh, like the AI said, you could also use a string, which is totally fine, and that would come out as user. The, the only thing that matters is that you never, ever, ever change the keys. Now, you can move this guy around. You can rename it. You can do whatever you want, and that is the point, that is the purpose of the morph map. So now we've got this down to, uh, a morph class.
So w- let's change the key just a little bit. Um, so we are going to-- This is still wishful thinking. So we're gonna do, uh, cache lock, and we're gonna say, um... Let's factor this out just a little bit. We're gonna say that the class equals that, and, uh, let's go ahead and just pull the first user.
Uh, user equals, we're gonna get user first So we'll pull you up there, and then we can say user get morph class, and then ID is user ID. But we don't wanna do that because it might not be called ID. We want get key, I think is correct. And then we're gonna make it out of this.
So we're gonna say the class comes first, and then the ID, and then our key, which I think was sync, something like that. Um, now... Okay, so now if we run this, we can see app reserve, and then we check in the database, uh, one one sync. That felt like we put that, that there earlier.
So reserve, and it's not working at all 'cause I forgot to call get on it. So get and app reserve. Boom, there we go. One, one, sync. So now we have the type of model on the left, then we have, um, the ID of that model, and then we have our, uh, reservation key.
So what we're gonna move on to now is breaking these things up, but making the database do it, right? I just wanna write the key and have the correct information show up. I don't wanna have to change the way I acquire locks in my code. I just, I just want it to work. And we're gonna use generated columns for that. Generated columns are awesome.
They, they, they really don't get enough love. So we're gonna make a new migration, and we're going to alter the cache locks table. And yep, that seems good enough. Now, we are using Postgres here. We're using, looks like Postgres seventeen point four locally. If you like Postgres, go to masteringpostgres.com. You can use generated columns in SQLite, in MySQL, in MariaDB, uh, and if you like SQLite, go to highperformancesqlite.com.
Now, coming back here, let's do, uh, alter cache locks table. So what we're gonna do is we're gonna tell the database, "Listen, you've got this key. In fact, I'm gonna go ahead and break that apart and put it into three different columns." So I'm gonna copy, um, this statement here 'cause it's a little bit gnarly, but I will walk you through it.
So let me copy that and then import this class. Uh, yes, that is correct. So walking you through this, uh, one thing is wrong here, but that's okay. Alter table cache locks, so that's the table we're working with, add a column called model type. The type of the model. We just went over that, uh, from the morph map. It's a big int.
It's generated always as. So this, this right here alerts the database, you're in charge. You're the captain now. I don't get to put data in there. The database decides what goes in there. If I try to modify it, it's gonna throw an error. This is not my column anymore. And here at the end, we're tagging on this attribute of stored, meaning write it to the disk, don't calculate it at runtime.
So, um, what we're gonna do, let's start at the inside split part. We want to split the key column on the colon, and we actually wanna take the first part. Um, if it's, uh, if it's an empty string, just null it out, and we're gonna cast it to a big int. So we're splitting on this colon, which is our kind of like, uh, our agreed upon syntax here.
So we're saying that this first part is the model type, and first part is the model type. Great. What should we do next? You guessed it. Second part is the model ID. So that looks legit to me. So we have first part. Second part is the model ID. Third part is the key, but oh no, Laravel called it the key, so we'll just call it like type or something like that.
And we can come down here and say, uh, type. This is no longer a big int. This is a text, and we want the third part, but not cast as a big int. So now we're adding three columns, but we're... importantly, we're not modifying, uh, the columns that Laravel is relying on. Like I said, I don't want to be in charge of cache.
I just kinda wanna, I just kinda wanna hook in there and get a little... add some sprinkles on top, right? So let's go ahead and run this. AR, uh, I think it's just migrate, not roll back. Migrate. There we go. And what do we see? Is it gonna work? It works. So look at this. I am not in charge.
If I change the model type to two, the model type changes on its own, I didn't touch it, to two. If I change this to three, what do you think's gonna happen? Freaking nothing. You can't. You're not allowed to. Database is the captain. So coming back here, um, okay, I feel pretty good about that. That to me, that looks like a morph relation to me.
Now, is it a morph relation? Let's check it out. If we go to... We need to go to reservable. The relation is reservations morph mini cache locks, which is gonna hit the right table, and the prefix for those columns is model. So if we check, uh, yep, model type, model ID, that's what Laravel expects, model.
Expiration, let's go ahead and drop this off just for now 'cause that cache lock has expired, and I wanna show you that this does work. Uh, at least I hope it does. So user first, um, and then what did we say? Reservations. User first reservations, and we'll just, uh, we'll just dump those out.
Now, if we run, uh, what is it? App reserve? Hey. Is that a reservation? Hey, look at that. It's a cache lock. Table's cache locks. Uh, the key is one one sync. The type is sync. That is a reservation. And if we change this to belong to user number two, then we'll see that- This guy no longer has any reservations.
I kinda like that. Let's change it back to one and implement our expiration check. So you've got one reservation, but honestly, you really shouldn't. So if we turn you back on, and then we check again, hey, look at that. So, um, that did expire it. If we change it to what is presumably extremely far in the future, yeah, too far in, too far into the future, beyond the heat death of the universe, maybe.
Let's just change this to eight. Is that allowed? There we go. And do you have a reservation now? You, in fact, do. Uh, okay, this is good. This is good. I like this. We're getting closer. So now we've gotten to the point where we do have a reservation on the user model such that we can, uh, we can address it at the query level.
So now we're not gonna have to pull all the users and then check to see if they're locked. We can just do it right here at the database, kind of. And the reason, the reason that I say kind of is twofold. One, we've opened ourselves up to a timing issue, which we'll fix in a second, but the other is we've opened ourselves up to an inadvertent collision issue. So we're relying on the shape of that key to alert us that it is, in fact, uh, that it is a reservation.
And somebody may come along and use that same kind of format without knowing that we've got this really weird secretive, like, reservation system set up. So we need to change, we need to change one thing. Let's hop back here, and this is kinda what it looks like now. And what we're gonna do is we're gonna change this. Um, I'm-- I've got it up here 'cause it's a little wonky itself.
We're gonna change this, uh, a little bit up. So instead of just relying on the colon colon, I wanna rely on reservation being the first word and then the model type, the model ID, and then our internal reservation type. And this will accomplish that. So let's look at this together. Cache locks, we're gonna add an is reservation column that is a Boolean generated always as this expression and store it in, uh, on the actual disk.
And the expression is, does the key start with the word reservation and then a colon followed by literally anything? Um, and that will tell us, that'll give us an is reservation column. Because we have added another, uh, colon there, we need to change. You are now key part two, you're key part three, and you're key part four.
In fact, we're gonna come back and change all of these, but let's see if that works. So migrate, that works. Now, here's the reason we have to change them all. Look. Hey, that's kinda cool. Reservation true, model one, ID one, type is sync. Now, if we change this to baz, then it's gonna say reservation is false, but it keeps those over there. I don't care about that.
That's fine with me. Um, it is likely not true because if somebody else is doing this, the one and one might mean something fundamentally different, but I know that because the is reservation is set to false. The problem is if we drop this off, which is-- this is a reasonable thing that somebody might do, you're gonna get an error because we're trying to cast the word sync as a big int.
So we need to be a little bit more careful. Let's go ahead and, um, we're gonna drop the is reservation column, and we're gonna make these generated expressions just a little bit more robust. Now that we know what we're doing, we can modify them a little bit. So we'll say, uh, migrate, roll back, and those will go away.
Yes, discard. That's fine. Okay, so we're back to a good spot. Let's go ahead and duplicate. Let's, uh, let's do a reservation, and the owner is test, and that expiration is made up. Okay. So we have two in here that are shaped the same way, but only one is a reservation. And we're gonna change this.
We're gonna change this part right here. We're gonna change it to a little bit more gnarly, if you can believe it. So instead of just, uh, naively splitting and then casting to a big int, which is the happy path, um, but is not the guaranteed path, we are going to do this. We're gonna put a case statement in, and you may be thinking like, "Whoa, this is getting really heavy." This is fine.
This is only gonna happen, um, when the, uh, key is written to the database, and then it is stored. And so it's not gonna happen every time we query. But what we're gonna do is when we say, uh, when the split part of the key is a digit, then use that, cast it to a big int, otherwise put in null. So we're using a little bit of a regex test here, and we can do that down here as well.
And so we'll say, come on, man. There we go. Uh, when key part three matches digits, go ahead and cast it to a big int. Now, what do we do about you? The one problem, uh, the one problem with this expression right here is it's not resilient to, uh, it's not resilient to colons in the actual key.
So if we did, you know, sync, uh, we'll say sync payments, then, uh, it's just gonna take that fourth part, and it's not gonna get that whole, that's not gonna get that whole key that I misspelled, sync payments. So we need to correct this just a little bit. And so instead of using the split part, we are going to use this regex, which again is a little bit gnarly.
So we're gonna say, um, all right, we're gonna replace on the key, we're gonna replace the word reservation, which is this first part, and then a, uh, colon, then the model type and a colon, then the model ID and a colon. We're gonna replace all of that with nothing, leaving everything after the final colon.
Boy, let's hope this works. Okay. Let's check it. Yep, that's fine. Hey, that looks pretty good to me. Um, so reservation false, reservation true. They're all the same. Now, what if I add a, uh, sync payments? Does that end up over here at the end?
Oh, thank goodness, yes. And am I cool if I just do like, uh, just a normal... Am I cool if I do that? Yeah, cool. That's fine. I, I, I don't, I don't care about that at all. All of this data is now, this data over here doesn't matter 'cause is reservation is false. So I think we're in a good spot. We've made this a lot more robust and a lot more resilient, and the good thing is we never have to touch it again.
We never have to touch it again. It's not in some model observer in our code base. It's not... It's, it's just a generated column. It's even lighter than a trigger, and I don't mind generated columns, um, because they don't usually contain business logic, right? So I'm not saying like, "What is the tax rate for this person? Let me write it into the database where I can never like, uh, observe it again." It just goes there to be forgotten, right?
Generated columns I like for this sort of thing, changing formats, doing simple calculations, math calculations, changing, uh, one type to another type, or in this case, splitting apart a key. Let's go add that is reservation to our model. Back here in the reservable trait, we're down here in the relationship, and we've got, uh, expiration greater than timestamp, which is good, but not great.
Um, we also need where is... Perfect, where is reservation is true. So let's see if we got this right. Um, reservation sync payments. I don't know if that has expired yet. Um, that's fine. We'll figure that out in a second. So what I wanna do is I wanna check, um, let's add a foobar one one sync, uh, it doesn't matter, baz.
That's fine. So now, if we didn't have that is reservation in there, uh, we would probably get that one back. I'm gonna just bump these out, and we'll see if that is legit. Now, coming back to, uh, doo, doo, doo, reserve. Let me just get real fast.
Let me just get a now add hour timestamp just to make sure. Okay. Nope. AR app reserve. All right. We'll make sure that we're out at least an hour in the future. There we go. Now, let's check reservations and then, yeah, we'll just pull them out of the database and then count them.
It's not great, but it doesn't matter right now. So we have one reservation, which is correct, even though if we were to change this to reservation one one buzz baz, now we have two. So our system is working. Our system is working. We've now like hooked into, we've now hooked into the cache locks and created our own reservation system inside of Laravel's cache locks table.
And we're pretty close, but we still have one glaring error, and that is the timing issue. So it is possible that we check the database and a model is not reserved in the database, and by the time we get it out to the person requesting it, it's been reserved, and we're like, "Hey, man, sorry. I, I thought it was, I thought it was available, but now it's reserved," and we're right back into the same situation.
That's, that's not where, that's not where we wanna be. Um, so what we need to do is we need to add an after query callback, okay? We're gonna go back to our dream state, which is this one right here. So we have not yet added the reserve for method. Let's go into reservable and add a scope, uh, reserve for.
Oh, we, we added it. It's just not right yet. So where it doesn't have a reservation, um, where this needs to be changed to type, and let's just go ahead and change, um, yeah, let's just change that to type two just to be sure. Um, so this is close. This is closer, in fact, to, um, to being called, uh, unreserved, and let's go ahead and do that.
We'll say that this is unreserved, and this is gonna be unreserved at the moment of querying, okay? So unreserved for a specific use case. We're gonna drop you out for a second, and we're gonna test this. Uh, sorry. Dreams are going away again, and let's test this. We'll say, uh, user unreserved for the purposes of syncing.
Um, yeah, we'll just count it. And okay. So if we run this AR app reserve, uh, we did something wrong. Oh, I forgot to drop the key. Uh, I'm sorry, the, uh, the duration. So we actually don't need the duration here for the unreserved, and if we run that again, still did something wrong.
I'm still using duration even though I don't need it. So we have two that are unreserved for the purposes of syncing. Now, if we were to say that instead of sync payments, we're syncing, we can kill that one, and we're to come back here. All right. We have one user that is not reserved for the purposes of syncing.
Now, if we were to say, um, syncing everything, we should have two that are available. Okay. So it's working. It's working at the query level. We're getting one user that is not reserved for the purposes of syncing. Now, let's make this better. Um- Let's make this better by first generating all of that so that this looks a little bit nicer.
Okay, that should clean up. There we go. We want reserveFor. Are we finally gonna get there? We'll find out. Um, all right, let's get back to reservable. We'll do reserveFor. We can kill this whole thing and say queryUnreserved for this particular type.
And then I'm gonna do afterQuery. I'm gonna do afterQuery. This receives-- I believe this receives a collection of models. So this is really nice. This is a really nice part of Laravel here. Um, you can, in a scope, you can register a callback to be run after the query has pulled the models or the records out of the database, which is exactly what we want and what we need to do here.
Um, but it's nice that you can, like, you can tie all of this up into an individual scope where you need to accomplish some post-processing. So we're gonna do some post-processing here. We're gonna say, "Give me all of the unreserved models for this type, and then after you get them, let me do a thing. Let me do a thing." And the thing that I'm going to do is I'm actually properly going to reserve them, because this will, this will solve our timing issue.
We think they're unreserved when they come out of the database, but then we're gonna go and reserve them, and if we get back false, we know there was a race condition. That is why we're using atomic locks. Somebody else locked it. We're safe. So I think here we're getting all of the models, which we are. Um, so what we wanna do is we wanna basically do, uh, you know, model reserve, uh, which doesn't exist, which is fine.
We're in charge. Let's do this. So let's say public function reserve, and we'll pass through the type as a string, and the, uh, we'll say int seconds. I think this could be made a little better by passing through a carbon instance. Um, I'm just not worrying about that right now.
So what we need to do, um, we need to do cache lock, and then we need to generate our name here, and our name is reservation. Is that right? Alter, cache. How do we declare a reservation? Reservation. Reservation for the, uh, this getMorphClass. Um, yep, and then we want this get key, not key name, which is sometimes useful, but not right now.
And then the type, and we want to lock it for seconds. So cool. We will return. So this gives us back a Boolean, and that will tell us if we got the lock, okay? Now, sometimes you want the actual lock so you can release it. That's irrelevant, not, not relevant for right now.
So what we're gonna do is we're gonna say models filter function, um, model. It's polymorphic, so I can't hype anything or, um, type anything. So we want to reserve for this type. Uh, that's wrong. We want to reserve for this key for this long, and this should filter out the ones that are not reservable.
And because we don't want any wonky keys, we're gonna put a values on it. Uh, if you have a collection where you filter some out, there will be skipped keys, and so it'll go from zero to two to four, and if you JSON serialize that, it turns into an object instead of an array. So whenever I filter, I always throw values there at the end. Did we do everything right? Let's check this again.
Cache lock, uh, reservation, the morph class, the key, which in this case is the ID, and then the type for this many seconds. Go ahead and get it. That seems good. Unreserved we did a while ago, so presumably that's right. And then after the query, we're gonna filter based on whether or not we were able to get a reservation.
Um, and yeah, we return the values. I mean, it seems right to me. Let's go try it. Here, we need to change this, and this is why I said, um, it might be nicer to pass in, you know, add day or something like that rather than seconds here, but we're just gonna add twenty-four hours. Yeah, that's fine.
So we'll just do that, and let's add, let's add some info. Line got user, user ID. So for the purposes of syncing, we wanna reserve up to ten users, and then we'll write out some information. Here we go. Got user two.
Cool. Let's check the database. All right, hit refresh. Look at that. We got a user. We locked him up. Now, if we run this again, there should be... Yep, there are none available. That is absolutely correct. However, if we change this to, um, update payment info, whatever, um, we run this again, we got two users for the purposes of updating
their payment info, and we should have new keys in there. Boom. There we go. Look how cool this is. So if we run that again, we get none, and then we'll say this guy's expired, and we run it again, we get... It's pretty awesome. Um, I've-- I'm pretty happy with that.
It, it's kinda-- It's awesome. I, I will admit, it's awesome. We've taken, um, we've taken Laravel's existing atomic locks and built some generated columns on top of them that we don't manage. We wrote one migration. It was a little wonky, but we wrote one migration, and now the database handles it all. And remember, that works in SQLite, MySQL, Postgres, Maria.
You'll have to change the syntax, of course, but generated columns work in almost every database now. So now we're leveraging Laravel's cache locks table. We created a little model. The model is totally unnecessary, save for the fact that you need to reference it in the relationship. So that part is, is not super necessary. You could, I guess, you could make a reservation model and add some methods to that.
Oh, that's a nice-- not a crazy idea, honestly. Um, and then we now are able to ensure that there are no timing issues, right? So we leverage the database to grab as many as possible very, very quickly, 'cause we don't wanna check one by one who's reserved, who's not. We go to the database. We say, "Give me all the ones you think are unreserved. Bring it back to the application. We will do a proper atomic lock on it, and then you're able to work with them.
You're able to handle whatever you wanna do, now that you know you are the only process in the universe who is, uh, able to work on that model at that time." So hopefully you enjoyed this. Here's the thing. Listen, don't go yet. These videos are super long. They take a long time to create. Um, I need to know, are these better than, like, five-minute videos that show you how to make a generated column?
I think those are still useful. I think these, I think these are more useful. So please let me know, um, and if you wanna learn more about databases, I'll leave links to my database courses down below. But regardless, please let me know if you like this video, and I'll keep doing more like this. Until the next time. See ya.