SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Inverted Index
  • Trie (Prefix Tree)
  • LRU Cache Design
  • Heap and Priority Queue
  • Bitmaps and Roaring Bitmaps
  • Ring Buffer
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Data Structures for Scale

Bitmaps and Roaring Bitmaps

One bit per item to store and combine huge sets of IDs, and the Roaring trick that keeps them small.

โฑ 13 min readAdvancedHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A bitmap keeps one bit for every possible ID: 1 means "in the set", 0 means "not in the set". Combining sets (who did A and B?) becomes a few fast machine instructions. A Roaring bitmap is the same idea, but it stays small even when the set is sparse.

  • Plain bitmap: tiny and very fast when many IDs are set. Wasteful when only a few are set, because it always reserves a bit for every possible ID.
  • Roaring bitmap: split the ID space into chunks of 65,536 and store each chunk in whichever of three forms is smallest: array, bitmap or runs.
  • Used for: database bitmap indexes, search engines, analytics engines, and counters such as "daily active users".

02Concept: What is it?

Imagine every user has a number: 0, 1, 2 and so on. To remember which users logged in today, you could keep a list of their numbers. Or you could keep a long row of bits, where bit number 4,001 is 1 if user 4,001 logged in. The row of bits is a bitmap.

Three operations make it useful. Set turns a bit on. Test reads a bit. And combine uses AND, OR, NOT on whole rows at once. A computer handles 64 bits in one instruction, so "users who logged in and bought something" over a billion users takes only a few milliseconds. Popcount (count the 1 bits) then gives the answer.

The cost is size. A plain bitmap needs one bit per possible ID, whether it is used or not. For one billion IDs that is 1,000,000,000 รท 8 = 125 MB. If only a thousand users logged in, a list of their IDs (4 KB) would be far smaller than 125 MB.

One bit per ID, then AND
๐Ÿ…ฐ๏ธ1 1 0 1 0 0 1 1logged in
โ†’โ†“AND
๐Ÿ…ฑ๏ธ0 1 1 1 0 1 0 1bought
โ†’โ†“=
โœ…0 1 0 1 0 0 0 1both: 3 users
Bit i is 1 if ID i is in the set. AND keeps only the IDs that are 1 in both rows.

The Roaring idea

A Roaring bitmap splits each 32-bit ID in two. The high 16 bits choose a chunk (each chunk covers 65,536 IDs). The low 16 bits are the position inside the chunk. Each chunk picks the cheapest of three containers: an array (a sorted list of 16-bit numbers, used up to 4,096 values), a bitmap (a fixed 8 KB, used above 4,096), or runs (a list of start and length pairs). Empty chunks are not stored at all.

๐Ÿง Why 4,096?
An array costs 2 bytes per value. A bitmap chunk always costs 8,192 bytes. They are equal at 4,096 values, so below that an array is smaller, and above that a bitmap is smaller.

03Real-Life Example

๐ŸตThe Attendance Sheet
A school has 1,000 numbered seats. Each day the teacher ticks seat numbers on a sheet that has one box per seat. To find who was there on Monday and Tuesday, lay the two sheets on top of each other and look for seats ticked on both. That is an AND. It is fast because you compare box by box, with no searching. But if the school is a stadium with a million seats and only five people showed up, the sheet is almost empty paper. Roaring says: "only keep the pages of the sheet that have ticks, and for pages with just a few ticks, write the seat numbers instead".
Attendance sheet
Bitmap
One box per seat
One bit per possible ID
A tick
A bit set to 1
Lay two sheets on top of each other
AND of two bitmaps
Seats ticked on either day
OR
Count the ticks
Popcount
A stadium with five fans
A sparse set that wastes a plain bitmap
Keep only pages that have ticks
Roaring chunks, empty ones skipped
โ€œSeats 1 to 500 all tickedโ€
A run container

04Why Do We Need It?

โšกFast set maths
AND, OR and NOT work on 64 IDs per instruction, so combining filters is very quick.
๐ŸชถCompact when dense
One bit per ID is the smallest possible form when a good share of IDs are set.
๐ŸงฎInstant counts
Popcount hardware instructions count set bits very fast.
๐ŸงฉRoaring stays small
Sparse sets, dense sets and ranges each get a good form, so you do not choose one by hand.
๐Ÿ”ŽGreat for filters
โ€œCountry = DE AND plan = pro AND activeโ€ is just three bitmaps ANDed together.
๐Ÿ“ฆEasy to ship
A Roaring bitmap has a standard file format that many languages and engines read.
Bitmaps turn "which IDs match all of these filters?" into a handful of cheap bit operations. Roaring keeps the memory bill sensible.

05Where Do We Use It?

๐Ÿ—„๏ธDatabase bitmap indexes
For columns with few distinct values (status, country), one bitmap per value lets the database combine filters fast.
๐Ÿ”ดRedis bitmaps
SETBIT and GETBIT set and read a user's bit. BITCOUNT counts them. BITOP does AND and OR. Handy for daily active users.
๐Ÿ”Search engines
Lucene uses Roaring-style sets to hold which documents match a filter.
๐Ÿ“ŠAnalytics engines
Druid, ClickHouse, Spark and others use Roaring bitmaps for filters, distinct counts and joins.
๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘Audience segments
โ€œUsers in segment A and not in segment Bโ€ for marketing and experiments.
๐Ÿ”Permissions and flags
A small bitmask per user for features switched on, or a set of allowed items.

06Types / Parts / How It Works

Plain bitmap vs Roaring

FormHow it stores IDsGood whenBad when
List of integers4 bytes per IDVery few IDsMany IDs, and combining needs a merge
Plain bitmap1 bit per possible IDA good share of IDs are setFew IDs set out of a huge range
Compressed run-length bitmap (such as WAH)Store runs of 0s and 1sLong runsRandom access and updates are awkward
Roaring bitmapChunks of 65,536, each in its best containerAlmost any shape of dataVery small sets (a plain list may be simpler)

The three Roaring containers

One chunk, three possible forms
Array (up to 4,096 values)
๐Ÿ“‹[3, 17, 4200, ...]2 bytes per value
Bitmap (over 4,096 values)
๐Ÿ”ข65,536 bitsalways 8 KB
Runs (long stretches)
๐Ÿ“(0, len 65536)about 4 bytes per run
Roaring picks the smallest for every chunk on its own.

Worked arithmetic

CaseList of 32-bit intsPlain bitmapRoaring (roughly)
1 billion IDs possible, 1,000 set4 KB125 MBabout 2 KB (one small array chunk per used chunk)
1 billion possible, 500 million set2 GB125 MBabout 125 MB (bitmap chunks)
1 billion possible, all set in ranges4 GB at worst125 MBa few KB (run containers)
๐Ÿ”‘ID 200,000
โ†’โ†“high 16 bits
๐Ÿ“ฆchunk 3200,000 รท 65,536
โ†’โ†“low 16 bits
๐Ÿ“position 3,392200,000 โˆ’ 3 ร— 65,536
Chunk key Position inside chunk
VisualizerPlain bitmap vs list vs Roaring, and combining bitmapsSwitch the shape of the data (sparse, medium, dense, runs) and watch which container Roaring picks for each chunk. Then flip bits in the two small rows and try AND, OR and AND NOT.
What does the set of IDs look like?

A few hundred IDs per chunk, with one chunk empty. The universe is 4 chunks of 65,536 IDs (262,144 IDs in total).

How Roaring stores each 65,536-wide chunk (the high 16 bits of an ID pick the chunk):
Chunk 0 ยท IDs 0 to 65,535
array container
300 IDs
600 B
4,096 values or fewer: a sorted list of 16-bit numbers, 2 bytes each.
Chunk 1 ยท IDs 65,536 to 131,071
array container
120 IDs
240 B
4,096 values or fewer: a sorted list of 16-bit numbers, 2 bytes each.
Chunk 2 ยท IDs 131,072 to 196,607
not stored
0 IDs
0 B
Empty chunks cost nothing.
Chunk 3 ยท IDs 196,608 to 262,143
array container
40 IDs
80 B
4,096 values or fewer: a sorted list of 16-bit numbers, 2 bytes each.
IDs in the set
460
Plain bitmap
32.0 KB
1 bit per possible ID
List of 32-bit ints
1.8 KB
4 bytes per ID
Roaring bitmap
920 B
best container per chunk
A plain bitmap pays 32.0 KB even though only 460 IDs are set, because it reserves a bit for every possible ID. A list of integers is far smaller here. Roaring is smaller still, since each chunk is a short array and the empty chunk is skipped.
Combine two bitmaps (click a bit to flip it)
Operation
A: logged in
B: bought
Result
0
1
0
1
0
0
0
1
0
0
0
0
0
1
0
0
Count of A
8
Count of B
7
Result count
4
the popcount
AND keeps an ID only if it is set in both A and B: users who logged in and also bought. Here the answer is 4 users, found by combining whole machine words at once, not by looping over users.

Sizes follow the standard Roaring layout: an array container holds up to 4,096 values at 2 bytes each, a bitmap container is always 8 KB (65,536 bits), and a run container costs about 4 bytes per run. Real files add a small header per chunk, left out here. Only 16 IDs are shown in the combine demo, but a real bitmap does the same thing 64 IDs per machine word.

07How to Use It / Steps / Implementation

Using bitmaps in a design

  1. 1
    Give every item a small whole number ID
    Bitmaps need dense integer IDs (0, 1, 2...), not UUIDs. Keep a map from real IDs to these numbers.
  2. 2
    Pick one bitmap per fact
    For example one bitmap per day for โ€œlogged inโ€, or one per country for โ€œlives hereโ€.
  3. 3
    Choose plain or Roaring
    If sets are large and dense, a plain bitmap is fine. If sizes vary a lot, use a Roaring library.
  4. 4
    Combine with bit operations
    AND for โ€œall ofโ€, OR for โ€œany ofโ€, AND NOT for โ€œbut notโ€.
  5. 5
    Count with popcount
    Do not loop over IDs. Count the set bits in the result.
  6. 6
    Store and ship it
    Persist the bitmap in its standard serialized form so another service can read it.
  7. 7
    Rebuild or update on a schedule
    Bitmaps are very quick to read. Update them in batches for the best speed.
๐Ÿ’กDaily active users in Redis
SETBIT dau:2026-12-04 4001 1 marks user 4001 as active. BITCOUNT dau:2026-12-04 counts active users. BITOP AND both dau:2026-12-03 dau:2026-12-04 finds users active on both days.
โš ๏ธBig IDs hurt plain bitmaps
If one user has ID 4,000,000,000, a plain bitmap grows to 500 MB just to hold it. Use dense IDs, or use Roaring.

08Key Terms to Know

TermMeaning in easy words
BitmapA row of bits where bit i says whether ID i is in the set
BitsetAnother name for a bitmap
PopcountCounting how many bits are set to 1
BitmaskA small bitmap used as a set of flags
Bitmap indexA database index that keeps one bitmap per distinct value
CardinalityHow many different values a column has, or how many IDs are in a set
SparseFew IDs set out of a huge range
DenseA large share of the range is set
Roaring bitmapA compressed bitmap that splits IDs into chunks of 65,536
ContainerHow one Roaring chunk is stored: array, bitmap or run
Run-length encodingStoring a stretch of equal values as a start and a length

09Pros, Cons and Trade-offs

โœ… Pros
  • Set maths on 64 IDs per instruction
  • Instant counts with popcount
  • Roaring stays small for sparse, dense and range data
  • Standard, widely supported file format
  • Easy to combine many filters
โš ๏ธ Cons
  • Needs small dense integer IDs
  • A plain bitmap wastes space on sparse sets
  • Single updates in compressed forms cost more than in plain bitmaps
  • Poor for values that change very often
  • Not useful for non-integer or range-heavy queries on its own

Trade-offs

ChoiceWe gainWe lose
Plain bitmapSimplest and fastestWastes memory on sparse sets
List of intsSmall for tiny setsSlow to combine, large when dense
Roaring bitmapSmall and fast in most shapesMore code, a library to depend on
Bitmap index in a databaseFast multi-filter queriesCostly to update on write-heavy tables
Exact bitmap countsExact answersMore memory than HyperLogLog

10Common Problems and Mistakes

Common mistakes

  1. Using sparse, huge IDs with a plain bitmap. One large ID forces the whole row to be that long.
  2. Using bitmap indexes on high-cardinality columns. A million distinct values means a million bitmaps.
  3. Putting bitmap indexes on write-heavy tables. Many databases lock a large part of the index on update.
  4. Looping over IDs to count. Use popcount, or the library's cardinality call.
  5. Forgetting the ID mapping. UUIDs must be mapped to small integers first, and the map must be kept.
  6. Using 64-bit IDs with a 32-bit Roaring library. Use the 64-bit variant, or split the IDs.
  7. Assuming bitmaps give distinct counts of anything. They count IDs, so the same person under two IDs counts twice.

Things to watch

๐Ÿ“Universe size
A plain bitmap is sized by the largest ID, not by how many IDs there are.
โœ๏ธWrite patterns
Frequent single-bit updates are cheap in memory, but costly for bitmap indexes in some databases.
๐Ÿ”Deleted IDs
Keep or reuse retired IDs carefully, so a new user does not inherit an old userโ€™s bits.
๐ŸงชLibrary versions
Use the standard serialization format so files can be read by other tools.

11Real-World Examples

๐Ÿ”Lucene
Roaring-style doc ID sets hold which documents match a filter, so search results can be combined quickly.
๐Ÿ“ŠApache Druid
Offers Roaring bitmaps for its inverted indexes, to filter rows quickly.
๐Ÿ ClickHouse
Supports Roaring bitmap columns and functions for set operations over IDs.
โšกSpark and others
Many big data tools use Roaring bitmaps to track blocks or IDs compactly.
๐Ÿ”ดRedis
Bit commands on strings give plain bitmaps for flags and daily counts.
๐ŸงฎPilosa and Featurebase
Built around Roaring bitmaps as the main storage form.
๐Ÿ“Note
Every product above has its own settings and limits. Check the current docs before relying on a detail.
Mini case: a marketing audience
๐ŸŒcountry = DEbitmap 1
โ†’โ†“AND
โญplan = probitmap 2
โ†’โ†“AND NOT
๐Ÿšซunsubscribedbitmap 3
โ†’โ†“popcount
๐Ÿ“ฃaudience size
Three bitmaps and two operations answer a question about a billion users.

12Related Topics to Read Next

Bloom Filtersโ†’

Another bit-based structure, but it answers โ€œmaybe in the setโ€ with less memory.

HyperLogLogโ†’

Counts distinct items approximately in a few KB, where bitmaps count exactly.

Inverted Indexโ†’

Posting lists are often stored as Roaring bitmaps.

Indexingโ†’

Bitmap indexes are one of the index types a database can use.

Compression and Deduplicationโ†’

Run-length and container choices are forms of compression.

Columnar Databasesโ†’

Column stores use bitmap-style filters and encodings heavily.

Redis vs Memcachedโ†’

Redis offers bit commands that give simple bitmaps.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Bitmap: one bit per possible ID. Set, test, AND, OR, NOT, popcount.
  • โœ”Size: universe รท 8 bytes. 1 billion IDs is 125 MB.
  • โœ”Weak spot: sparse sets waste memory in a plain bitmap.
  • โœ”Roaring: chunks of 65,536 IDs (high 16 bits = chunk key).
  • โœ”Containers: array (4,096 or fewer), bitmap (more, 8 KB), runs (long stretches).
  • โœ”Needs: small dense integer IDs.
  • โœ”Used by: database bitmap indexes, Redis, Lucene, Druid, ClickHouse.
  • โœ”One line: โ€œOne bit per ID, combine with bit maths, and let Roaring pick the smallest shape.โ€
โ† Previous
Heap and Priority Queue
Next โ†’
Ring Buffer