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 j

The Exceeding Cleverness of Laravel's Atomic Database Locks

submited by
Style Pass
2021-07-23 02:00:04

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:

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.

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

Laravel supports 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.

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.

Leave a Comment