Redis BZPOPMIN Command Explained

In Redis, the BZPOPMIN command is the blocking variant of the ZPOPMIN command.

The BZPOPMIN command works similar to ZPOPMIN when any of the sorted sets contain elements. That is, it pops a member with the lowest score from the sorted set.

More specifically, BZPOPMIN pops a member with the lowest score from the first non-empty sorted set, with the given keys being checked in the order that they are given.

However, if all of the specified sorted sets are empty, then BZPOPMIN will block the connection until another client adds members to one of the keys or until the specified timeout elapses. It’s possible to block the connection indefinitely by using a timeout of zero.

One other difference between BZPOPMIN and ZPOPMIN is that (at least at the the time of writing), the BZPOPMIN command accepts multiple keys whereas the ZPOPMIN command accepts just one.

Syntax

The syntax for BZPOPMAX goes like this:

BZPOPMIN key [key ...] timeout

Example

Here’s an example of what happens when all keys we pass to the BZPOPMIN command contain empty sorted sets:

BZPOPMIN birds cats 2

Result:

(nil)
(2.04s)

Here, I provided a timeout of 2, which means that it waits for two seconds if all sorted sets are empty. We can see by the result that it took 2.04 seconds to run, and the result of the operation is nil.

Passing a timeout argument of 0 (zero) blocks the connection indefinitely.

This blocking feature is what distinguishes BZPOPMIN from ZPOPMIN. The ZPOPMIN command would simply return nil without waiting.

When the Key is Not Empty

When there’s a key that contains a non-empty sorted set, BZPOPMIN works like ZPOPMIN, in that it returns the result immediately without waiting. In the above example, both the birds and the cats keys didn’t exist. Let’s create one called cats:

ZADD cats 1 Meow 2 Fluffy 3 Scratch 4 Purr 5 Bite 6 Bunting

Now let’s run BZPOPMIN again:

BZPOPMIN birds cats 2

Result:

1) "cats"
2) "Meow"
3) "1"

This time my results were returned immediately. There was no waiting period like in the previous example.

Here I provided two sorted sets; birds and cats. The birds key didn’t exist and so it was treated as an empty sorted set. The cats key did exist with a sorted set, and so the operation was performed against that key.

Let’s take a look at the cats sorted set now:

ZRANGE cats 0 -1

Result:

1) "Fluffy"
2) "Scratch"
3) "Purr"
4) "Bite"
5) "Bunting"

We can see that Meow no longer exists in the sorted set.

Wrong Data Type

When the key contains the wrong data type, an error is returned:

BZPOPMIN countries 1

Result:

(error) WRONGTYPE Operation against a key holding the wrong kind of value

In this case, the countries key contains a set (not a sorted set), and so we got an error.

We can use the TYPE command to check the key’s data type:

TYPE countries

Result:

set

As suspected, it’s a set.