How to Implement Queue Using Redis List
You can implement a queue in Redis using a
list by pushing items to one end with LPUSH and popping them from the other end with RPOP. This creates a First-In-First-Out (FIFO) queue where the oldest item is removed first.Syntax
Redis lists support commands to add and remove elements from either end. For queue behavior, use:
LPUSH key value: Addsvalueto the start (left) of the list.RPOP key: Removes and returns the last (rightmost) element.
This combination ensures FIFO order.
redis
LPUSH queue_name item RPOP queue_name
Example
This example shows how to add three items to a queue and then remove them in the order they were added.
redis
LPUSH myqueue "task1" LPUSH myqueue "task2" LPUSH myqueue "task3" RPOP myqueue RPOP myqueue RPOP myqueue
Output
"task1"
"task2"
"task3"
Common Pitfalls
A common mistake is using LPUSH and LPOP together, which creates a Last-In-First-Out (LIFO) stack, not a queue. To maintain FIFO order, always pair LPUSH with RPOP or RPUSH with LPOP.
redis
/* Wrong: behaves like a stack (LIFO) */ LPUSH myqueue "task1" LPUSH myqueue "task2" LPOP myqueue /* returns "task2" first, not FIFO */ /* Correct: behaves like a queue (FIFO) */ LPUSH myqueue "task1" LPUSH myqueue "task2" RPOP myqueue /* returns "task1" first, FIFO */
Quick Reference
| Command | Description | Queue Role |
|---|---|---|
| LPUSH key value | Add value to the start (left) of the list | Enqueue (add item) |
| RPUSH key value | Add value to the end (right) of the list | Enqueue (alternative) |
| LPOP key | Remove and return the first (leftmost) element | Dequeue (remove item) - alternative |
| RPOP key | Remove and return the last (rightmost) element | Dequeue (remove item) |
Key Takeaways
Use LPUSH to add items to the left and RPOP to remove from the right for FIFO queue behavior.
Avoid mixing LPUSH with LPOP as it creates a stack (LIFO), not a queue.
Redis lists are simple and efficient for queue implementations.
You can also use RPUSH with LPOP for the same FIFO effect.
Always test your queue commands to ensure correct order of processing.