0
0
RedisHow-ToBeginner · 3 min read

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: Adds value to 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

CommandDescriptionQueue Role
LPUSH key valueAdd value to the start (left) of the listEnqueue (add item)
RPUSH key valueAdd value to the end (right) of the listEnqueue (alternative)
LPOP keyRemove and return the first (leftmost) elementDequeue (remove item) - alternative
RPOP keyRemove and return the last (rightmost) elementDequeue (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.