Working with Bitmaps
1. Setting Bit Values
| Command | Returns |
|---|---|
SETBIT key offset 0|1 | Previous bit value; auto-extends string |
2. Getting Bit Values
| Command | Returns |
|---|---|
GETBIT key offset | 0 or 1 |
3. Counting Set Bits
| Command | Options |
|---|---|
BITCOUNT key [start end [BYTE|BIT]] | Population count; BIT range 7.0+ |
4. Finding First Bit
| Command | Returns |
|---|---|
BITPOS key 0|1 [start [end [BYTE|BIT]]] | Offset of first matching bit, -1 if none |
5. Performing Bitwise Operations
| Command | Operation |
|---|---|
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
| Command | Description |
|---|---|
BITFIELD key GET type offset | Read 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
| Operation | Description |
|---|---|
SET | Write typed value |
INCRBY | Atomic add (signed/unsigned) |
OVERFLOW WRAP|SAT|FAIL | Behavior on overflow |
8. Using BITFIELD_RO for Read-Only Operations
| Command | Notes |
|---|---|
BITFIELD_RO key GET ... | Replica-safe; only GET ops allowed |
9. Understanding Bitmap Memory Efficiency
| Population | Memory (1M users) |
|---|---|
| All bits set | ~125 KB |
| Sparse | Allocated to max offset / 8 bytes |
| Equivalent SET | Tens of MB |
10. Using Bitmaps for Analytics
| Pattern | Implementation |
|---|---|
| Daily active users | dau:YYYY-MM-DD bitmap, SETBIT per user id |
| Retention | BITOP AND of two days |
| Funnel | Sequential 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
| Type | Range |
|---|---|
u8 | 0..255 |
u16 | 0..65535 |
i32 | ±2^31 |
i64 | ±2^63 (max signed) |