Working with Bitmaps

1. Setting Bit Values

CommandReturns
SETBIT key offset 0|1Previous bit value; auto-extends string

2. Getting Bit Values

CommandReturns
GETBIT key offset0 or 1

3. Counting Set Bits

CommandOptions
BITCOUNT key [start end [BYTE|BIT]]Population count; BIT range 7.0+

4. Finding First Bit

CommandReturns
BITPOS key 0|1 [start [end [BYTE|BIT]]]Offset of first matching bit, -1 if none

5. Performing Bitwise Operations

CommandOperation
BITOP AND|OR|XOR|NOT dst k1 [k2 ...]Combine bitmaps; length = longest input

Example: Daily active users intersection

SETBIT dau:2026-05-19 42 1
SETBIT dau:2026-05-20 42 1
BITOP AND dau:both dau:2026-05-19 dau:2026-05-20
BITCOUNT dau:both

6. Getting Bit Field Values

CommandDescription
BITFIELD key GET type offsetRead typed integer (e.g. u8, i16)
Offset prefix ##3 means index 3 * type-width

7. Setting Multiple Bit Fields

BITFIELD counter SET u16 #0 1000 INCRBY u16 #0 5 GET u16 #0
BITFIELD stats OVERFLOW SAT INCRBY i8 #1 200
OperationDescription
SETWrite typed value
INCRBYAtomic add (signed/unsigned)
OVERFLOW WRAP|SAT|FAILBehavior on overflow

8. Using BITFIELD_RO for Read-Only Operations

CommandNotes
BITFIELD_RO key GET ...Replica-safe; only GET ops allowed

9. Understanding Bitmap Memory Efficiency

PopulationMemory (1M users)
All bits set~125 KB
SparseAllocated to max offset / 8 bytes
Equivalent SETTens of MB

10. Using Bitmaps for Analytics

PatternImplementation
Daily active usersdau:YYYY-MM-DD bitmap, SETBIT per user id
RetentionBITOP AND of two days
FunnelSequential BITOP AND across steps

11. Implementing Bitmap-Based Counters

Example: Packed per-user counters with BITFIELD

# 16-bit counter per user, supports 1M users in ~2MB
BITFIELD events INCRBY u16 #42 1     # user 42 +1 event
BITFIELD events GET u16 #42
TypeRange
u80..255
u160..65535
i32±2^31
i64±2^63 (max signed)