Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 42 ยท Specialized Data Types

Bitmaps and Bitfields

Learn Redis bitmaps and bitfields: SETBIT, GETBIT, BITCOUNT, BITPOS, BITOP and BITFIELD for daily active users and packed counters, with a live emulator.

A Redis bitmap is not a separate data type. It is an ordinary string that you treat as a long row of bits: bit 0 is the first bit of the first byte, bit 8 the first bit of the second byte, and so on. A handful of commands (SETBIT, GETBIT, BITCOUNT, BITPOS, BITOP) read and write single bits, count them, search them and combine whole bitmaps with AND, OR, XOR and NOT. Because one bit holds one yes/no fact, the structure is extremely compact: flags for ten million users take about 1.25 MB.

The classic use is "was user number 4,217 active today?": give each user a numeric id, use that id as the bit offset, and keep one bitmap per day. Counting today's active users is one BITCOUNT, and "who was active on both Monday and Tuesday" is one BITOP AND. Bitfields (BITFIELD) take the idea further: they treat the same string as many small integers of any width (a 4-bit counter, a signed 16-bit value) and update them atomically, with overflow rules you choose.

Real Redis cannot run on this page, so the redis-cli snippets are read-only. The runnable examples use a plain JavaScript emulator built on Uint8Array, the same bytes-and-bits model Redis uses, with the same replies. It is a teaching stand-in: bitfield widths are limited to 32 bits here (real Redis allows up to 64 bits signed and 63 unsigned), and there is no 512 MB size cap.

Bits inside a string

It is a string GET, SET and STRLEN still work.
Offset = id User 42 lives at bit 42.
Grows on write Zero-filled up to the highest bit.
Tiny One bit per user.
1 / 2

Setting, reading and counting bits

SETBIT key offset value sets one bit (0 or 1) and returns the previous value of that bit. Setting a bit far beyond the current end extends the string with zero bytes. GETBIT key offset reads a bit; anything beyond the end reads as 0. BITCOUNT key [start end [BYTE|BIT]] counts the 1 bits, either in the whole string or in a range. Without a unit the range is measured in bytes; since Redis 7.0 you can ask for BIT ranges.

Text
127.0.0.1:6379> SETBIT visits:2026-11-08 4217 1
(integer) 0
127.0.0.1:6379> GETBIT visits:2026-11-08 4217
(integer) 1
127.0.0.1:6379> BITCOUNT visits:2026-11-08
(integer) 1
127.0.0.1:6379> STRLEN visits:2026-11-08
(integer) 528

Bit 4217 lives in byte 527 (the byte index is the offset divided by 8, rounded down), so the string is 528 bytes long. Notice the bit order: inside each byte, offset 0 is the most significant bit. Setting offsets 1, 2 and 7 therefore gives the binary byte 01100001, which is the character code of the letter a. The first TryIt proves it: the bitmap and the string a are the same bytes.

BITPOS key bit [start end [BYTE|BIT]] returns the offset of the first bit equal to 0 or 1. Looking for the first 1 in an empty or all-zero bitmap gives -1. Looking for a 0 in a string of all 1 bits without an explicit range returns the position just after the end, because the string would be padded with zeros there.

BITOP AND|OR|XOR|NOT destkey key [key ...] combines bitmaps byte by byte and stores the result. Shorter inputs are padded with zeros, NOT takes exactly one source, and the reply is the length in bytes of the stored result.

JS Daily active users with bitmaps

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The numbers add up the way set theory says: Monday had 7 active users and Tuesday 6, 4 were active on both days (the AND), 9 on at least one (the OR, which is 7 + 6 - 4), and 5 differ between the days (the XOR).

Patterns and trade-offs

Daily and weekly activity. One key per day (active:2026-11-08), user id as offset. Reporting "weekly actives" is a BITOP OR of seven keys followed by BITCOUNT; "users active every day this week" is a BITOP AND. Retention is the AND of a cohort bitmap with a later day. Everything is a few lines and runs in milliseconds even for tens of millions of users.

Feature flags and permissions. Give every feature a bit position. A user's flags then fit in a few bytes, and checking one costs a GETBIT.

Bloom-style marks. Hash an item to an offset and set the bit. This is the core idea of a Bloom filter; the probabilistic structures lesson builds one.

The main trade-off is sparse ids. Memory is proportional to the largest offset, not to the number of set bits: one user with id 4,000,000,000 makes the bitmap 500 MB, even if it is the only user. Bitmaps shine when ids are dense and small (auto-increment numbers). With random or huge ids, translate them to compact numbers first or use a set instead. Also remember that SETBIT on a large offset has to allocate and zero memory in one go, which can cause a latency spike on the first write of the day, so pre-create tomorrow's key off-peak if you care.

BITCOUNT and BITOP are O(N) in the size of the bitmap. They are fast per byte, but a multi-hundred-megabyte BITOP will still block other clients for a moment.

Bitfields: small integers inside a string

BITFIELD key [subcommand ...] addresses the string as packed integers. Each subcommand names a type (u8 is an unsigned 8-bit integer, i16 a signed 16-bit one, u4 an unsigned 4-bit one) and an offset in bits. Writing #3 instead of a number means "the fourth integer of that width", so the offset is 3 * width, which makes arrays of equal-sized counters easy.

  • GET type offset reads a value.
  • SET type offset value writes a value and returns the old one.
  • INCRBY type offset increment adds (the increment may be negative) and returns the new value.
  • OVERFLOW WRAP|SAT|FAIL changes how the following INCRBY calls behave when the result does not fit: WRAP (the default) wraps around like a CPU register, SAT stops at the minimum or maximum, FAIL refuses and returns (nil) without changing anything.

Several subcommands in one call are executed together, atomically, and the reply is an array with one entry per subcommand that produces a result. That makes BITFIELD a compact, cheap way to store counters: a million 4-bit counters (0 to 15) need only 500 KB, versus tens of megabytes as separate keys.

JS BITFIELD counters and overflow modes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Read the hits section carefully. Four counters share the same two bytes, #1 climbed to 15 after three increments of 5, and the next increment, made under OVERFLOW SAT, stopped at 15 instead of wrapping around to 8 (a u4 holds 0 to 15). The setting only affects the INCRBY subcommands that follow it. The last line reads the first byte as one u8, which is exactly the first two 4-bit counters glued together: that is all "packing" means.

Bitfield integers are stored in big-endian bit order, and OVERFLOW is a setting for the subcommands after it within that one call, not for the key. Reading a field with a different type or offset than you wrote it (as in the last GET u8 0 above) is legal and returns a number built from the raw bits, so keep a single, documented layout per key.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does SETBIT visits 100 1 return when bit 100 was 0 before?

    SETBIT replies with the old value of the bit, which lets you detect 'first time seen' (a reply of 0) in a single atomic step.
  2. 2. You keep one bitmap per day with the user id as the offset. Which command gives the number of users active on both Monday and Tuesday?

    AND keeps only the positions that are 1 in both bitmaps, and BITCOUNT counts them. OR would count users active on at least one day.
  3. 3. Why can a single user with id 4,000,000,000 make a bitmap huge?

    Memory is proportional to the highest offset, about offset/8 bytes. Sparse, very large ids waste memory, so bitmaps suit dense, small ids.
  4. 4. With OVERFLOW SAT, what does INCRBY u8 0 100 do when the current value is 200?

    SAT saturates at the type's limits. WRAP (the default) would give 44, and FAIL would return nil and leave the value untouched.
  5. 5. Inside a byte, which bit does offset 0 refer to?

    Redis numbers bits from the most significant end, so setting offsets 1, 2 and 7 gives 01100001, the letter a. It does not depend on the CPU.

Summary

  • A bitmap is just a string used as an array of bits; offset 0 is the most significant bit of the first byte, and the string grows (zero-filled) as you write.
  • SETBIT returns the old bit, GETBIT reads, BITCOUNT counts ones (bytes by default, BIT units in Redis 7+), BITPOS finds the first 0 or 1.
  • BITOP AND|OR|XOR|NOT combines bitmaps; daily active users, retention and feature flags are one-liners.
  • Memory follows the highest offset, so use bitmaps with dense, small ids.
  • BITFIELD packs integers of 1 to 64 bits (u8, i16, #n offsets) with atomic GET, SET and INCRBY and the overflow modes WRAP, SAT and FAIL.

Next, counting huge sets with a few kilobytes: HyperLogLog and Probabilistic Structures.