0
0
RedisHow-ToBeginner · 3 min read

How to Use BLPOP in Redis: Syntax, Example, and Tips

Use the BLPOP command in Redis to block and remove the first element from one or more lists. It waits until an element is available or a timeout occurs, returning the list name and the popped element.
📐

Syntax

The BLPOP command syntax is:

  • BLPOP key [key ...] timeout

Here, key is the name of one or more lists to check, and timeout is the number of seconds to wait if all lists are empty. If timeout is 0, it waits indefinitely.

redis
BLPOP mylist 5
💻

Example

This example shows how BLPOP waits for an element in a list and returns it once available.

redis
127.0.0.1:6379> LPUSH mylist "apple"
(integer) 1
127.0.0.1:6379> BLPOP mylist 2
1) "mylist"
2) "apple"
Output
1) "mylist" 2) "apple"
⚠️

Common Pitfalls

Common mistakes include:

  • Using BLPOP on keys that are not lists, which causes errors.
  • Setting a very short timeout and expecting to always get an element immediately.
  • Not handling the null response when the timeout expires without any element.

Always check the return value to handle empty results gracefully.

redis
127.0.0.1:6379> BLPOP notalist 1
(error) WRONGTYPE Operation against a key holding the wrong kind of value

# Correct usage:
127.0.0.1:6379> BLPOP mylist 1
(nil)  # if list is empty and timeout expires
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value (nil)
📊

Quick Reference

ParameterDescription
keyName of the list(s) to pop from
timeoutSeconds to wait for an element; 0 means wait forever
ReturnArray with list name and popped element, or null if timeout expires

Key Takeaways

BLPOP blocks and pops the first element from one or more lists, waiting if needed.
Use a timeout to avoid waiting forever; 0 means wait indefinitely.
Check for null return to handle timeout without elements.
Only use BLPOP on list keys to avoid errors.
BLPOP returns the list name and the popped element as a two-item array.