Join us for RedisConf and Hackathon, April 20-21

Register Now!

Redis Best Practices

Bit Counting Pattern

BITCOUNT counts the number of bits set to 1 in a bitfield at a key. This can be leveraged to provide insight to a series of activities during a time period (akin to the pattern covered in Bitfield time series). The process involves selecting a known point in time and a period each bit represents. Every time an action is performed during that time period, you run SETBIT on the distance in units from the known point. As an example, take user activity:


12:00 12:02 12:03 12:04
> SETBIT btct 2 1
> SETBIT btct 3 1
> SETBIT btct 4


[known point] Activity Activity Activity

To find out how minutes were active from 12:00 to 12:30, we can run the command:

> BITCOUNT btct 0 30
(integer) 3

In general, this pattern answer the question of “how often?” rather than “how many?” as a user could, for example, been “active” 20 times during a single minute, but that will only result in a single count.

The real advantage of this pattern is that is provides the smallest possible account during a given time period as bits are the most elemental building blocks of storage. It is literally the smallest (uncompressed) storage possible for counting.