How to Implement Message Queue with Redis
To implement a message queue in Redis, use the
LPUSH command to add messages to a list and BRPOP to consume messages in a blocking way. This creates a simple, reliable queue where producers push messages and consumers pop them safely.Syntax
Redis uses list commands to implement a message queue. The main commands are:
LPUSH queue_name message: Adds a message to the start (left) of the list namedqueue_name.BRPOP queue_name timeout: Removes and returns the last (right) message from the list, blocking until a message is available or timeout expires.
This pattern ensures messages are processed in the order they were added (FIFO).
redis
LPUSH queue_name message BRPOP queue_name timeout
Example
This example shows a producer adding messages and a consumer retrieving them using Redis CLI commands.
redis
# Producer adds messages LPUSH myqueue "Message 1" LPUSH myqueue "Message 2" # Consumer waits and pops messages BRPOP myqueue 0 BRPOP myqueue 0
Output
1) "myqueue"
2) "Message 2"
1) "myqueue"
2) "Message 1"
Common Pitfalls
Common mistakes when using Redis as a message queue include:
- Using
RPOPinstead ofBRPOP, which does not block and may miss messages if the queue is empty. - Not handling message processing failures, which can cause message loss if a consumer crashes after popping a message.
- Using
LPUSHandLPOPtogether, which reverses message order and breaks FIFO.
Always pair LPUSH with BRPOP to maintain order and blocking behavior.
redis
Wrong: LPUSH myqueue "msg" LPOP myqueue Right: LPUSH myqueue "msg" BRPOP myqueue 0
Quick Reference
| Command | Description |
|---|---|
| LPUSH queue_name message | Add message to the queue start |
| BRPOP queue_name timeout | Remove message from queue end, blocking if empty |
| RPOP queue_name | Remove message from queue end, non-blocking |
| LLEN queue_name | Get current queue length |
Key Takeaways
Use LPUSH to add messages and BRPOP to consume them for a reliable Redis queue.
BRPOP blocks until a message is available, preventing busy waiting.
Pair LPUSH with BRPOP to maintain FIFO message order.
Handle message processing failures to avoid message loss.
Check queue length with LLEN to monitor queue size.