In Redis, the BLPOP
command is the blocking version of the LPOP
command. It blocks the connection when there are no elements to pop from any of the given lists.
The way the command works is that an element is popped from the head of the first list that is non-empty, with the given keys being checked in the order that they are given. When there are no elements to pop from any of the lists, it blocks the connection.
Even though BLPOP
is considered the blocking version of LPOP
, they actually accept different arguments and function slightly differently. As of this writing, BLPOP
accepts multiple keys, whereas LPOP
doesn’t. Also, LPOP
allows us to specify how many list elements to pop whereas PLPOP
doesn’t. In this sense, BLPOP
is also similar to the LMPOP
command, however, there’s also a BLMPOP
command that’s the blocking variant of the LMPOP
command.
Syntax
The syntax for BLPOP
goes like this:
BLPOP key [key ...] timeout
When a non-zero timeout is specified, the client will unblock returning a nil
multi-bulk value when the specified timeout has expired without a push operation against at least one of the specified keys.
Prior to Redis 6.0.0 timeout
was interpreted as an integer. However, from 6.0.0 timeout
is interpreted as a double.
Example
Suppose we create a list like this:
RPUSH scores 1 2 3 4 5 6 7 8 9 10
Result:
(integer) 10
Let’s look at its contents:
LRANGE scores 0 -1
Result:
1) "1" 2) "2" 3) "3" 4) "4" 5) "5" 6) "6" 7) "7" 8) "8" 9) "9" 10) "10"
We can use BLPOP
to pop the first element like this:
BLPOP scores 0
Result:
1) "scores" 2) "1"
The first value is the key, and the second is the value of the element that was popped. In this case I specified a timeout of zero, which is used to block indefinitely. A value was popped however, and so the connection wasn’t blocked.
Now when we return all elements in the list, we see that the first element is no longer there:
LRANGE scores 0 -1
Result:
1) "2" 2) "3" 3) "4" 4) "5" 5) "6" 6) "7" 7) "8" 8) "9" 9) "10"
Multiple Lists
We can specify multiple lists. As mentioned, BLPOP
pops the element from the head of the first list that is non-empty list:
BLPOP emptylist scores 0
Result:
1) "scores" 2) "2"
In this case, the emptylist
key is an empty list, and so the operation was performed on the scores
key.
Wrong Type
If the key is the wrong type, an error is returned:
BLPOP customer 0
Result:
(error) WRONGTYPE Operation against a key holding the wrong kind of value
We can use the TYPE
command to check the key’s type:
TYPE customer
Result:
hash
In this case it’s a hash.
Non-Existent Key
If the key doesn’t exist, nil
is returned after the timeout period has elapsed:
BLPOP nonexistentkey 3
Result:
(nil) (3.02s)
When I ran that example in my Redis client, there was a three second pause before the results were returned.
More Information
See the Redis documentation for more information about the BLPOP
command.