Quick revision
The short answer
A HashSet<Long> costs around 50 to 60 bytes per id and every retainAll touches every element, so per-request intersections of millions of ids grow linearly in both latency and memory. I would replace them with compressed bitmaps such as RoaringBitmap over dense integer ids, precompute and cache popular segments, and for ad hoc combinations push the set operations into a store built for them, such as a search engine or an analytical database. I would also estimate how costs grow with the data, so the design holds for several years.
What to remember
In this answer, we measured the current design: boxed HashSets cost about 55 bytes per id and every intersection touches every element, so latency, memory and GC all grow with data. We replaced them with RoaringBitmap over dense integer ids, precomputed and cached popular segments with canonical keys, considered pushing ad hoc set algebra into a search engine or analytical database, and estimated memory and latency for the next three years so the choice is justified by numbers.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A HashSet<Long> costs around 50 to 60 bytes per id and every retainAll touches every element, so per-request intersections of millions of ids grow linearly in both latency and memory. I would replace them with compressed bitmaps such as RoaringBitmap over dense integer ids, precompute and cache popular segments, and for ad hoc combinations push the set operations into a store built for them, such as a search engine or an analytical database. I would also estimate how costs grow with the data, so the design holds for several years.
Why this question is asked
Audience targeting is set algebra at scale: users in a region, users who bought a product, users who opened an email, combined with AND, OR and NOT. A first version with HashSet and retainAll works fine at a few hundred thousand users and then degrades steadily, because its cost is proportional to the size of the sets on every single request. Interviewers ask this to see whether we can quantify the problem, know the data structures designed for it, and choose where the computation should live. In this answer, we will measure what the current design costs, see how compressed bitmaps work, add precomputation and caching, consider moving the work into a specialized store, and estimate growth.
1What the Current Design Really Costs
A HashSet<Long> stores each id as a Long object (16 bytes), inside a HashMap node (about 32 bytes), referenced from a slot in the table array (4 to 8 bytes, with the table kept at most three quarters full). That is roughly 55 bytes per id. A segment of 10 million users therefore takes about 550 MB of heap, compared with 80 MB for the raw long values and much less for a good compressed form.
Each request does more than look this up. retainAll must not mutate the cached segment, so the code copies one set first, which allocates another few hundred megabytes, then calls contains on the other set for every element. With two 10-million-element segments, one request makes ten million hash lookups, each a likely cache miss because the nodes are scattered across the heap, and creates a large amount of garbage that drives long GC pauses.
So latency grows linearly with segment size, heap grows with the number of cached segments, and GC pressure grows with request rate. All three get worse together as the user base grows.
2How Compressed Bitmaps Represent a Set of Ids
A bitmap stores a set of integers as bits: bit n is 1 if id n is in the set. For 50 million users, a plain bitmap takes 50 million bits, about 6 MB, regardless of how many users are in the segment, and an intersection is a word-by-word AND over about 780,000 64-bit words, which takes well under a millisecond.
RoaringBitmap, an open-source library used by many analytical systems, improves on this by splitting the 32-bit id space into chunks of 65,536 ids and choosing the best container for each chunk. A sparse chunk becomes a sorted array of 16-bit values, a dense chunk becomes an 8 KB bitmap, and a chunk of consecutive ids becomes a list of runs. Intersections and unions work container by container, using the fastest algorithm for each pair, so both sparse and dense segments stay small and fast.
| Representation | Memory | Intersection with a 4M segment |
|---|---|---|
HashSet<Long> | about 550 MB | 4M hash lookups plus a copy: hundreds of ms |
| Plain bitmap over 50M ids | about 6 MB | 780K word ANDs: under 1 ms |
RoaringBitmap | a few MB, often less | container-wise AND: about 1 ms |
There is one requirement: ids should be dense integers. RoaringBitmap works on 32-bit values; the library also has 64-bit variants, but they are less compact when ids are spread across a huge range. If user ids are random longs or UUIDs, we add a dictionary that maps each user to a dense int index, assigned once and stored, and translate at the edges.
3Precomputing and Caching Common Segments
Even fast intersections are wasted work if a thousand requests per second ask for the same combination. Most targeting traffic is dominated by a small number of popular segments and combinations, so we precompute those. A batch or streaming job builds the base segments as bitmaps, such as region:X or bought:Y, writes them to a store, and the service loads them into memory and refreshes them on a schedule or on change events.
For combinations, a cache keyed on a canonical form of the expression, for example the sorted list of segment ids with their operators, stores the resulting bitmap or just its cardinality, with a short time to live. The cache key must be canonical, otherwise region:X AND bought:Y and bought:Y AND region:X become two entries.
- Targeting APIparses the expression, canonical cache key
- Result cachepopular combinations, short TTL
- In-memory bitmap segments
RoaringBitmapper segment, refreshed - Segment builderbatch or streaming job computes base segments
- Id dictionary and event datauser id -> dense int, purchases, regions
5 layers, from the top down. Step through them one at a time.
4Pushing Set Operations Into a Store Built for Them
When the expressions are ad hoc, with many attributes and date ranges, precomputing every combination is impossible. Then the right move is often to let a system designed for this do the work. A search engine such as Elasticsearch or OpenSearch answers boolean filters across many attributes using compressed posting lists and cached filter bitsets. Analytical databases such as ClickHouse, Apache Druid or Apache Pinot store columns compressed, use bitmap indexes, and some offer bitmap aggregate functions directly in SQL. Redis has bitmap commands such as BITOP AND for simpler cases.
The trade-off is operational. A new store means new infrastructure, data pipelines to keep it fresh, and freshness measured in seconds or minutes rather than immediate. For a team that only needs a dozen fixed segments, bitmaps in the service are cheaper. For a product where marketers build arbitrary audiences, a specialized store usually wins within a year.
5Estimating Growth So the Design Holds
Before choosing, we put numbers on the next few years. Suppose there are 50 million users today, growing 40 percent a year, so about 140 million in three years, and 200 segments are kept warm. With HashSet, if the average segment holds 5 million ids, 200 segments take 200 x 5,000,000 x 55 bytes, about 55 GB of heap today and more than 150 GB in three years, which is not realistic on a service instance. With bitmaps over dense ids, each segment is bounded by about 6 MB today and 18 MB in three years even if completely dense, so 200 segments fit in 1 to 4 GB.
We also estimate per-request cost: intersection time for bitmaps grows with the id space, not with request count, so it stays in the low milliseconds. And we check where the id dictionary lives, how it is updated, and whether 32-bit ids give enough room, since 4 billion ids is plenty for users but may not be for events. These estimates go into the design document, together with the measurement we will repeat each quarter.
6Follow-up questions
Why not just give the service a bigger heap?
Because the cost is linear in data and request rate, a bigger heap only buys months. It also makes garbage collection pauses longer and more expensive, and each instance must still hold all segments. Changing the representation reduces memory by one to two orders of magnitude, which buys years.
What if user ids are UUIDs?
Then we assign each user a dense integer index once, store the mapping, and build bitmaps over the indexes. The mapping is consulted only when results leave the system, for example when the campaign sends messages. New users get the next index, and deleted users simply leave unused bits.
How would you migrate without downtime?
Build bitmap segments alongside the existing sets, compare the results of both paths on a sample of live requests for a while, and switch per segment once they match. Keeping the old path behind a flag allows a quick rollback.
7Conclusion
In this answer, we measured the current design: boxed HashSets cost about 55 bytes per id and every intersection touches every element, so latency, memory and GC all grow with data. We replaced them with RoaringBitmap over dense integer ids, precomputed and cached popular segments with canonical keys, considered pushing ad hoc set algebra into a search engine or analytical database, and estimated memory and latency for the next three years so the choice is justified by numbers.
Open with
First I would quantify the problem. A HashSet of Long costs around 55 bytes per id, so a 10-million-user segment is roughly half a gigabyte of heap, and retainAll needs a copy plus one hash lookup per element, which scatter across memory.
Then, if they want more
So latency, heap and GC pressure all grow linearly with the data, and that will keep getting worse. Architecturally I would make three changes. The first is the representation: compressed bitmaps such as RoaringBitmap over dense integer user ids. A segment then takes a few megabytes, and intersections and unions are word-wise operations that take about a millisecond.
If ids are not dense, I add a dictionary that maps each user to a dense int. The second is precomputation: a batch or streaming job builds the base segments, the service keeps them in memory and refreshes them, and popular combinations are cached by a canonical expression key, because most traffic asks for the same few audiences.
The third is for ad hoc audiences with many attributes, where I would consider pushing the set operations into a system built for them, like Elasticsearch or an analytical database such as ClickHouse or Pinot, accepting the operational cost and some freshness delay.
Finally I would estimate growth: for example 200 warm segments would be tens of gigabytes as HashSets today and well over a hundred in three years, but a few gigabytes as bitmaps. I would put those numbers in the design and measure each quarter.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An audience-targeting service intersects sets of millions of user ids per request (for...": https://scrivio-interview-library.netlify.app/java/sets/127e9aa729/