Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

You need to deduplicate 5 billion click events per day by event id and cannot keep a full set in memory. What approaches would you consider, and what are their error trade-offs?

We combine several techniques, each with a different error profile. A Bloom filter remembers ids in about 10 bits each with no false negatives and a tunable false-positive rate of about 1 percent, so it may drop a few real events. Because most duplicates arrive close together, a TTL-keyed set in Redis or RocksDB per time window is exact within the window. We partition by hash of the event id so each worker deduplicates its own slice, and where reports must be exactly right we deduplicate again in the warehouse with a unique key or MERGE. HyperLogLog only estimates how many distinct ids there are; it cannot say whether one id was seen.

Background to this question

Click streams are full of duplicates: mobile clients retry on flaky networks, producers resend after timeouts, and at-least-once delivery in Kafka means a consumer can see the same record again after a rebalance. If we count every click, billing and analytics are inflated. At 5 billion events a day, a simple HashSet of every id is out of the question, so this question tests whether we can choose between exact and approximate structures and explain exactly what kind of error each one makes. In this answer, we will size the naive approach, then look at Bloom filters, time windows, partitioning, exact downstream deduplication and HyperLogLog, and put them together into one pipeline.

1Sizing the Naive Approach

Suppose each event id is a UUID, 16 bytes in binary or 36 characters as text. 5 billion ids a day is 80 GB of raw ids per day even in binary form, before any hash table overhead. In a Java HashSet<String>, each entry costs well over 100 bytes once we count the String, its byte array and the HashMap node, so one day would need more than 500 GB of heap. And if duplicates can arrive days apart, we need several days of history. So exact deduplication over all time in memory is not possible, and we have to decide which errors we can accept and where.

2A Bloom Filter: No False Negatives, Some False Positives

A Bloom filter is a bit array of m bits and k hash functions. To add an id, we set the k bits its hashes point to. To check an id, we look at the same k bits: if any is 0, the id was definitely never added; if all are 1, it was probably added, but those bits might have been set by other ids. So a Bloom filter has no false negatives and a controlled rate of false positives.

The sizing formula is m/n = -ln(p) / (ln 2)^2 bits per element, with k = (m/n) ln 2 hash functions. For p = 1 percent this gives about 9.6 bits per element and 7 hash functions. For 5 billion ids that is about 48 billion bits, roughly 6 GB, compared with hundreds of GB for a set. A 0.1 percent rate costs about 14.4 bits per element.

Java
// Guava's BloomFilter, sized for one day
BloomFilter<CharSequence> seen = BloomFilter.create(
Funnels.stringFunnel(StandardCharsets.UTF_8), 5_000_000_000L, 0.01);
boolean isNew = seen.put(eventId); // true if the bits changed, so the id is definitely new
if (isNew) forward(event);
else dropAsDuplicate(event); // about 1 percent of genuinely new ids land here

Notice what the error means for our use case. A false positive says 'seen' for an id that is new, so we would drop a real click. At 1 percent of 5 billion that is up to 50 million lost clicks a day, which may be unacceptable for billing. Also, a standard Bloom filter cannot delete entries, so we rotate filters by time window, keeping today's and yesterday's and checking both.

3Time-Bounded Windows With a TTL Keyed Set

Duplicates are not spread evenly over time. Retries happen seconds or minutes after the original, and replays after a consumer rebalance are within the Kafka retention window. If we measure it and find, say, that 99.99 percent of duplicates arrive within 10 minutes, we only need to remember ids for 10 minutes, which is a small fraction of the daily volume.

For that window we can keep an exact set with expiry. In Redis, SET key 1 NX EX 600 atomically stores the id only if it is absent and returns whether it did, so one command both checks and records. In a stream processor, a RocksDB-backed state store with a TTL does the same locally, without a network round trip. This is exact within the window and has no false positives. Its error is a false negative: a duplicate arriving after the window passes as new.

Java
String result = jedis.set("dedup:" + eventId, "1", SetParams.setParams().nx().ex(600));
boolean isNew = "OK".equals(result); // null means the key already existed: a duplicate

4Partitioning by Hash of the Event Id

Whatever structure we use, a single node will not keep up with roughly 58,000 events per second on average and several times that at peak. The trick is to route every copy of an event to the same worker. If we key the Kafka topic by event id, the default partitioner hashes the key, so all duplicates of one id land in the same partition, and the consumer of that partition can deduplicate locally with its own Bloom filter or state store. With 64 partitions, each worker holds about 1/64 of the state, and no coordination between workers is needed.

The one subtlety is state across rebalances: when a partition moves to another consumer, its dedup state must move too, which Kafka Streams handles with changelog topics, and which custom consumers must handle by rebuilding or accepting a short window of missed duplicates.

Step throughA layered deduplication pipeline
  1. Producersclient-generated event id on every click
  2. Kafka topic keyed by event idall copies of an id in one partition
  3. Stream workers per partitionTTL state store or Bloom filter per window
  4. Warehouse loadMERGE or unique key on event_id
  5. Reports and billingexact counts from the warehouse

5 layers, from the top down. Step through them one at a time.

5Exact Deduplication Downstream

For reports that drive money, approximate is not enough. So the streaming layer removes the vast majority of duplicates cheaply, and the warehouse makes the final result exact. We load events into a table with event_id as a unique or primary key, or we use MERGE, or INSERT ... ON CONFLICT DO NOTHING in PostgreSQL, so loading the same id twice has no effect. Warehouses such as BigQuery or Snowflake do not enforce unique constraints, so there we use MERGE or a deduplicating query with ROW_NUMBER() over event_id partitioned by day.

This layering also means the streaming dedup can safely prefer false negatives, letting a rare duplicate through, over false positives that drop real clicks, because the warehouse catches the leftovers.

6What HyperLogLog Can and Cannot Do

HyperLogLog is often mentioned alongside Bloom filters, but it answers a different question. It estimates how many distinct ids there are, using a few kilobytes of memory with a standard error around 1 percent; Redis PFADD and PFCOUNT use about 12 KB per key. It is excellent for dashboards like unique users per day. But it cannot tell whether a particular id has been seen, so it cannot deduplicate individual events.

Error trade-offs
TechniqueMemory for 5 billion idsError it makes
HashSet of all idshundreds of GBnone, but not feasible
Bloom filter, 1 percentabout 6 GB per dayfalse positives: drops some new events
TTL set for a 10 minute windowids in the window onlyfalse negatives: late duplicates pass
Warehouse unique key / MERGEon disknone; exact but delayed
HyperLogLogabout 12 KBcounts only; cannot check one id

7Follow-up questions

How would you choose the window length?

From data. We log the time between the first and later copies of each duplicate id for a sample of traffic and look at the distribution, then pick a window that covers the 99.9th or 99.99th percentile. The warehouse deduplication catches the remainder, so the window does not need to be perfect.

What if producers do not send a stable event id?

Then we have to create one, ideally at the source, such as a UUID generated once when the click happens and reused on every retry. Without it, the best we can do is a content hash of user, timestamp and target, which risks merging two genuine clicks that look identical.

Can a Bloom filter be scaled out?

Yes. Since events are partitioned by id, each worker keeps a Bloom filter for its own slice, sized for its share of traffic. Redis also offers Bloom filters through the RedisBloom module if a shared filter is needed; check your Redis version and modules.

8Conclusion

In this answer, we saw that exact deduplication of 5 billion daily ids in memory needs hundreds of gigabytes, so we combined structures with known errors. A Bloom filter uses about 10 bits per id for a 1 percent false-positive rate, never misses a seen id, but may drop new ones. A TTL keyed set in Redis or RocksDB is exact within a time window, and most duplicates arrive within minutes. Partitioning by hash of the event id lets each worker deduplicate its own slice. The warehouse makes the final numbers exact with a unique key or MERGE, while HyperLogLog only counts distinct ids and cannot check individual ones.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would size it. Five billion ids a day in a Java HashSet is hundreds of gigabytes, so exact in-memory dedup over all time is out, and the question becomes which errors are acceptable where.

Then, if they want more

I would key the Kafka topic by event id so every copy of an id goes to the same partition and each worker deduplicates its own slice without coordination.

Most duplicates are retries or replays that arrive within minutes, so I would measure that and keep an exact TTL set for the window, for example Redis SET with NX and a ten minute expiry, or a RocksDB state store in Kafka Streams. That is exact inside the window and only lets very late duplicates through.

A Bloom filter is the other option for longer windows: about ten bits per id gives a one percent false-positive rate with no false negatives, around six gigabytes a day, but a false positive means dropping a real click, so it is better for analytics than billing, and I would rotate filters per day since they cannot delete.

For correctness-critical reports I would deduplicate again in the warehouse with a unique key or MERGE on event id. And I would point out that HyperLogLog only estimates distinct counts; it cannot tell whether a specific id was seen.

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 official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "You need to deduplicate 5 billion click events per day by event id and cannot keep a...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/6d6f9e0c3e/