Advertisement
Intermediate Redis, Redis as a Message Queue

How do you implement a priority queue pattern using Redis, where certain tasks should be processed before others?

Short answer

You can use a sorted set instead of a plain list, storing each task with a score representing its priority, and have workers retrieve the highest or lowest priority task using ZPOPMIN or ZPOPMAX, ensuring that more urgent tasks are always processed ahead of lower priority ones…

Save Redis mock interview
Advertisement
AModel answer
You can use a sorted set instead of a plain list, storing each task with a score representing its priority, and have workers retrieve the highest or lowest priority task using ZPOPMIN or ZPOPMAX, ensuring that more urgent tasks are always processed ahead of lower priority ones regardless of the order they were originally added.
Example

ZADD priority_queue 1 'urgent_task' ZADD priority_queue 5 'normal_task' ZPOPMIN priority_queue

Real-world example
A customer support ticketing system uses a sorted set based priority queue, ensuring tickets marked as urgent are always processed by available agents before lower priority tickets, regardless of when each ticket was originally submitted.
Likely follow-ups
  • How do you handle two tasks that happen to have the exact same priority score?
  • Is ZPOPMIN an atomic operation safe for multiple concurrent workers?
Related topics