Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service deduplicates incoming events with if (!seen.contains(id)) seen.add(id); where seen is an ArrayList, and CPU rises sharply as traffic grows. Explain the problem and choose better operations.

ArrayList.contains is a linear scan, O(n), so as the list of seen ids grows each check gets slower, and processing n events costs O(n squared) in total. We replace it with a HashSet (or LinkedHashSet to keep arrival order), whose add returns false for a duplicate in O(1) expected time. Because the set would otherwise grow forever, we bound it with a size-limited LinkedHashMap or a cache with expiry, and for deduplication across several instances we use a database unique constraint or a shared store; a profile before and after confirms the fix.

Background to this question

Deduplication is everywhere in event-driven systems: message brokers deliver at least once, clients retry, and webhooks arrive twice. The code in this question works perfectly in development and degrades steadily in production, which makes it a favourite scenario question: it tests complexity reasoning, data structure choice, memory planning and distributed thinking in one. In this answer, we will see why the CPU climbs, fix the data structure, bound its memory, extend it to several instances, and confirm the fix with measurements.

1Why CPU Rises With Traffic

seen.contains(id) on an ArrayList compares id with each element in turn using equals(), until it finds a match or reaches the end. For a new id, which is the common case, it always reaches the end. So the cost of each check is proportional to how many ids have been seen so far.

Add that up over time. The first event checks 0 ids, the second 1, the thousandth 999. After n events the service has done about n squared over 2 comparisons. With one million ids seen, each new event costs a million string comparisons, and the total so far is about 500 billion. Traffic growth makes it worse twice over: more events per second, and each one slower than the last. That is why the CPU graph curves upwards instead of rising in a line.

Java
List<String> seen = new ArrayList<>();
void onEvent(Event e) {
if (!seen.contains(e.id())) { // O(n): scans every id seen so far
seen.add(e.id()); // the list keeps growing
process(e);
}
}
Cost of one more event as the seen list grows
Ids already seenComparisons for a new idTotal comparisons so far
1,0001,000about 500 thousand
100,000100,000about 5 billion
1,000,0001,000,000about 500 billion
Each event costs more than the last: O(n) per event, O(n squared) overall.

2Fix 1: Use a Set and Its add Result

A HashSet stores elements in a hash table, so contains and add find the right bucket from the element's hash code and compare with only the few elements there. That is O(1) expected time, independent of how many ids have been seen. Better still, Set.add returns false when the element was already present, so one call both checks and records, with no separate contains.

Java
Set<String> seen = new HashSet<>();
void onEvent(Event e) {
if (seen.add(e.id())) { // true: first time seen, false: duplicate
process(e);
}
}
Set<String> s = new HashSet<>();
System.out.println(s.add("evt-1")); // true
System.out.println(s.add("evt-1")); // false

If we need the ids in arrival order, for example to report them, LinkedHashSet gives the same O(1) operations and keeps insertion order. If events arrive on several threads, we use ConcurrentHashMap.newKeySet(), whose add is atomic, so two threads with the same id cannot both get true. The check-then-add pattern of the original code would also be a race on any set.

3Fix 2: Bound the Memory

The set fixes the CPU but not the growth: an id added is never removed, so after months the set holds hundreds of millions of strings and the service runs out of memory. Duplicates usually arrive within a short window, a retry seconds later, a redelivery within minutes, so we only need to remember recent ids. A LinkedHashMap can evict its oldest entry automatically: we override removeEldestEntry, and wrap the map as a set.

Java
static <T> Set<T> boundedSet(int max) {
return Collections.newSetFromMap(new LinkedHashMap<>(16, 0.75f, false) {
@Override protected boolean removeEldestEntry(Map.Entry<T, Boolean> eldest) {
return size() > max; // drop the oldest id once we exceed max
}
});
}
Set<String> seen = boundedSet(1_000_000); // remembers the last million ids, then evicts
Step throughChoosing a deduplication store
  1. One instance or many?
    YesIn-memory setNoShared store
  2. In-memory setHashSet, or newKeySet() for threads
  3. Can it grow forever?
    YesBound it: LRU map or expiring cacheNoPlain set is fine
  4. Shared storeDB unique constraint or Redis SET NX with expiry

4 steps in order. Play them, or step through them one at a time.

This version is not thread-safe, so a multi-threaded consumer needs a lock around it, or a cache library. Caffeine, for example, gives a concurrent cache with a maximum size or an expiry such as expireAfterWrite(Duration.ofHours(1)), which expresses the real rule, remember ids for an hour, directly. We size the bound from the redelivery window: if the broker can redeliver up to an hour later and we see 300 events per second, we need about a million entries.

4Fix 3: Deduplicating Across Several Instances

An in-memory set only knows about events this instance has seen. With three instances behind a load balancer, or after a restart, a duplicate can land on an instance that has never seen the original. For a real guarantee the record of seen ids must be shared. The most robust option is a database unique constraint, written in the same transaction as the event's effects, so either both happen or neither does.

SQL
CREATE TABLE processed_event (event_id text PRIMARY KEY, processed_at timestamptz NOT NULL);
-- PostgreSQL: insert only if new, in the same transaction as the business change
INSERT INTO processed_event (event_id, processed_at) VALUES ('evt-1', now())
ON CONFLICT (event_id) DO NOTHING; -- 1 row inserted: new event, process it
-- 0 rows inserted: duplicate, skip

A shared cache such as Redis, with SET key value NX EX 3600, is faster and expires keys by itself, but it is not in the same transaction as the database write, so a crash between the two can lose or repeat work. We choose by what a duplicate costs: double-charging a card calls for the database constraint, while double-sending a notification may be acceptable with a cache. Old rows in the table are deleted by a scheduled job once they are older than the redelivery window.

5Confirming the Fix

Finally we measure rather than assume. Before the change, a CPU profile from async-profiler or Java Flight Recorder shows most samples in ArrayList.indexOf, which contains calls, under onEvent. After the change, that frame should disappear, CPU per event should stay flat as traffic grows, and the allocation profile should show no growing backing array. We also watch heap usage over a day to confirm the bound holds, and the count of duplicates skipped, which should match what the broker's redelivery metrics suggest.

6Follow-up questions

Is HashSet always O(1)?

Expected O(1), when hash codes spread well, which String's do. In the worst case many ids land in one bucket, and since Java 8 a crowded bucket becomes a balanced tree, so even that case is O(log n) rather than O(n). In practice, for string ids, lookups are effectively constant time.

Why not keep the ArrayList and sort it for binary search?

Binary search makes lookups O(log n), but keeping the list sorted means inserting each new id in the middle, which shifts elements and is O(n) per event again. A hash set gives O(1) for both checking and recording, so it is better in every way here.

How much memory does a million-entry set of ids use?

Roughly 100 to 150 bytes per entry for short string ids in a HashSet, counting the String, its byte array and the hash table node, so on the order of 100 to 150 MB for a million. A LinkedHashSet adds two links per entry. We measure it with a heap histogram rather than trusting estimates, and size the bound accordingly.

7Conclusion

In this answer, we saw that ArrayList.contains scans the whole list, so deduplicating n events costs O(n squared) and CPU climbs faster than traffic. A HashSet whose add returns false for duplicates makes each check O(1); LinkedHashSet keeps order and ConcurrentHashMap.newKeySet() is safe across threads. We bounded memory with a size-limited LinkedHashMap or an expiring cache sized from the redelivery window, used a database unique constraint or a shared store across instances, and confirmed the fix with CPU and allocation profiles.

What to say in the interviewAbout 100 seconds aloud

Open with

The problem is that ArrayList.contains is a linear scan with equals. For a new id, which is most events, it compares against every id seen so far, so each event is O(n), and after n events the total is about n squared over two.

Then, if they want more

With a million ids seen, each new event does a million string comparisons, and as traffic grows we get both more events and slower events, so CPU curves upward.

The fix is a HashSet, and I use the return value of add: it returns false if the id was already there, so one call checks and records, in O(1) expected time. If order matters I use LinkedHashSet, and with several consumer threads ConcurrentHashMap.newKeySet, because its add is atomic and avoids the check-then-act race.

But a set that only grows will eventually exhaust memory, so I bound it. Duplicates usually arrive within a redelivery window, so I keep only recent ids, either with a LinkedHashMap overriding removeEldestEntry, wrapped with Collections.newSetFromMap, or with a Caffeine cache using expireAfterWrite, sized from the window and the event rate.

If several instances consume the same stream, an in-memory set is not enough, so I would use a processed-events table with a unique key and INSERT ON CONFLICT DO NOTHING in the same transaction as the business change, or Redis SET NX with expiry where occasional duplicates are tolerable.

Then I would confirm with a profile: ArrayList.indexOf should disappear and CPU per event stay flat.

About this answer

Last updated
12 November 2026
Versions it names
Java 8
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.
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 "A service deduplicates incoming events with if (!seen.contains(id)) seen.add(id); where...": https://scrivio-interview-library.netlify.app/java/lists/dfc16491a8/