Have you ever purchased a movie ticket? You must have noticed the selected seat will be locked for a while. I think the lock is for about 15 minutes. The reason for this implementation is to prevent several customers from paying for the same seat. It's no fun arriving at an entertainment center only to discover a stranger already sitting on "your" seat.
I had to implement a similar mechanism at my workplace. Once a customer selects a resource, it should become temporarily unavailable to other users until the lock is released.
In order to lock the resource, i need to add a column to the resource’s table. There are two criteria for the column value:
- acts as a flag on the resource's lock status
- provides user end time of the lock status
If I only need the lock status, I would simply add a is_locked
column with boolean
type to the resource. However, I would like to inform users of the remaining lock time. Hence, I opted for lock_end_at
which stores either datetime
or null
value.
Another important aspect of the locking mechanism is that it is only temporary. After a set period, the lock should be removed. One way to accomplish that is to run a scheduler that executes a job to unlock resources with an expired lock_at_value
every minute. If I am running this in Laravel, it would be something like this: $schedule->job(new UnlockResource)->everyMinute();
However, I recognized the inefficiency of querying the database every minute, especially when there might not be resources requiring unlocking at that frequency.
Instead, I opted for a more targeted approach. When a user interacts with a resource, the lock_end_at
value is updated based on the lock duration, and a job is scheduled to execute after the specified lock duration. This job checks if the resource's lock_end_at
value is in the past, indicating that the resource should be unlocked. By executing the job only for specific locked resources, we minimize unnecessary database queries and ensure efficient resource management.
To handle scenarios where a resource's status changes, such as when a customer completes a purchase, we introduced a flag to indicate that the resource should be excluded from job processing. This approach streamlines resource management and prevents unnecessary processing of locked resources.