I recently encountered a situation that called for a work queue. The system seemed simple enough at the outset – only producers and consumers, with jobs prioritized by when they are enqueued. There is, however, a curious twist – the consumers are people doing work in a single page app. There are enough concurrent users to warrant a datastore with atomic operations.
Jobs cannot simply be dequeued when people start them because many jobs go unfinished for one reason or another. The behavior we want is a timeout – the person has some amount of time to complete the job after it was dequeued, else the system considers the job abandoned and must it back in the inbound queue.
Redis does not have primitives for this specific use case, but it turns out we don’t need them – we can run Lua scripts on our Redis server to get the exact behavior we need.
First, a script to reserve jobs:
1 2 3 4 5 6 7 8
This takes jobs from our default queue and moves them to a reserved queue. Both queues are sorted sets – the time is passed in as a string (ARGV), converted to a number and used as the score. Using a sorted set keeps the inbound queue ordered by the time when jobs were queued up and prevents duplicate jobs. We can also use the timestamp/score to determine which jobs in the reserved queue have timed out and move them back to the inbound queue:
1 2 3 4 5 6 7
Redis scripts run as atomic operations and, as Antirez notes, much more performant than using
The server used as a backend for our single page app would interact with Redis like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
This server needs a cron job or some other way to periodically call
#clear to clear the reserved queue of timed-out jobs. A more fully baked implementation might also use SCRIPT LOAD to upload the script to our Redis server and then call it via EVALSHA instead of sending the entire script every time.
The tour of Lua on Learn X in Y Minutes and the examples on the Redis homepage are all you need to get started and extend the usefulness of Redis in meaningful way within a couple of hours. I recommend giving this a shot the next time you encounter a unique problem where Redis seems close but not quite right for your specific use case.