Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

You keep a sliding five-minute window of events keyed by timestamp in a ConcurrentSkipListMap<Long, Event>, written by many threads. Show how to evict old events, and point out the bug in using epoch milliseconds as the key.

To evict, take the view of everything older than the cutoff and clear it: events.headMap(now - 300_000).clear(). The clear is not atomic as a whole, but each removal is safe, and an event inserted near the cutoff during eviction may simply survive until the next round. The bug is the key: two events in the same millisecond have the same Long key, so the second put silently overwrites the first. The fix is a composite key of timestamp plus a tie-breaking sequence from an AtomicLong, ordered by a comparator, or a map from each timestamp to a concurrent queue of events.

Why this question is asked

Sliding windows are everywhere in backend work: rate limits over the last minute, fraud rules over the last five minutes, dashboards showing recent errors. ConcurrentSkipListMap is a natural fit because it keeps entries sorted by time and lets many threads insert while another evicts. Interviewers like this question because the eviction is a one-liner that needs careful explanation, and because the obvious key choice hides a data-loss bug that only shows up under load. In this answer, we will recap the map's range views, write the eviction, discuss what concurrent eviction guarantees, reproduce the key collision, and fix it with a composite key.

1A Quick Recap of Range Views

ConcurrentSkipListMap keeps its keys sorted and offers views of key ranges: headMap(k) contains all keys strictly less than k, tailMap(k) contains keys greater than or equal to k, and subMap(a, b) the keys from a up to but not including b. A view is not a copy. It is a window onto the same skip list, so reading it shows live entries and removing through it removes them from the map.

That makes eviction by time natural. If every key is an event timestamp in epoch milliseconds, then everything older than five minutes is exactly the head of the map below now minus 300,000 milliseconds.

2Evicting Old Events

Here is the window with its eviction. Writers call record from many threads; a scheduled task calls evict every second.

Java
ConcurrentSkipListMap<Long, Event> events = new ConcurrentSkipListMap<>();
void record(Event e) {
events.put(e.timestampMillis(), e); // bug: see the next section
}
void evict() {
long cutoff = System.currentTimeMillis() - 300_000;
events.headMap(cutoff).clear(); // removes every key < cutoff
}
// keys before: 1000, 2000, 301000, 302000 now = 601500 -> cutoff = 301500
// after evict: 302000 (1000, 2000 and 301000 removed)

headMap(cutoff) is exclusive, so an event exactly at the cutoff stays; use headMap(cutoff, true) if the boundary should be removed too. Notice that clear() on the view walks the matching entries from the smallest key and removes them one by one. Because the map is sorted, it never needs to look at the recent events, so eviction costs time proportional to the number of expired entries, not the size of the window.

3What Concurrent Eviction Guarantees

The clear is not one atomic step. While it runs, writers keep inserting and readers keep reading. A reader in that moment may see some old events already gone and others still present. Each individual removal is safe, though: no entry is corrupted, no recent entry is removed, and nothing throws.

Inserts near the cutoff are the only interesting case. If a writer inserts an event whose timestamp is just below the cutoff, for example because the event was created a few milliseconds earlier and delayed, after clear has already passed that position, the event survives this round. It is removed in the next eviction a second later. For a sliding window, that small overshoot is harmless, but it is worth saying explicitly, because the window can briefly contain events slightly older than five minutes. If readers need an exact boundary, they should read with a view such as events.tailMap(cutoff) rather than trusting eviction alone.

Step throughEviction while writers insert
WriterMapEvictor
headMap(cutoff).clear() starts
remove 1000, 2000
put(301400) just below cutoff
remove 301000
round ends; 301400 may survive
next round removes 301400

6 messages in order. Play them, or step through them one at a time.

4The Bug: Same Millisecond, Same Key

A map holds one value per key. Under load, many events share a millisecond: a service receiving 20,000 events per second sees about 20 per millisecond. With the timestamp as the key, each put for an existing millisecond replaces the previous event.

Java
events.put(1_700_000_000_000L, eventA);
events.put(1_700_000_000_000L, eventB); // same millisecond: replaces eventA
System.out.println(events.size()); // 1, eventA is lost without any error

Nothing fails and nothing is logged; counts in the window are just too low, and the shortfall grows with traffic. Rate limits become too generous and fraud rules miss bursts, exactly when they matter most. Using System.nanoTime() as the key only makes collisions rarer, not impossible, and it is not related to wall-clock time across processes.

5The Fix: A Composite Key With a Sequence

We make every key unique by adding a tie-breaker. An AtomicLong hands out a strictly increasing sequence number, and the key becomes the pair of timestamp and sequence, ordered by timestamp first. Two events in the same millisecond now have different keys, and the order within the millisecond follows arrival.

Java
record EventKey(long ts, long seq) {}
static final Comparator<EventKey> ORDER =
Comparator.comparingLong(EventKey::ts).thenComparingLong(EventKey::seq);
final ConcurrentSkipListMap<EventKey, Event> events = new ConcurrentSkipListMap<>(ORDER);
final AtomicLong sequence = new AtomicLong();
void record(Event e) {
events.put(new EventKey(e.timestampMillis(), sequence.incrementAndGet()), e);
}
void evict() {
long cutoff = System.currentTimeMillis() - 300_000;
events.headMap(new EventKey(cutoff, Long.MIN_VALUE)).clear(); // every event with ts < cutoff
}
events.put(new EventKey(1000, 1), a);
events.put(new EventKey(1000, 2), b);
System.out.println(events.size()); // 2, both kept

Notice the eviction bound. EventKey(cutoff, Long.MIN_VALUE) sorts before every real key with timestamp cutoff, so headMap of it contains exactly the events with a timestamp strictly below the cutoff.

The alternative is ConcurrentSkipListMap<Long, Queue<Event>>, adding with events.computeIfAbsent(ts, k -> new ConcurrentLinkedQueue<>()).add(e). It works, but it has two traps. This map's computeIfAbsent is not guaranteed to run the function only once, although only one queue is kept. And an event added to a queue at the very moment eviction removes that timestamp's entry is lost with the removed queue. The composite key avoids both, which is why I would choose it.

6Follow-up questions

Why use an AtomicLong rather than a counter per millisecond?

A single AtomicLong is one lock-free increment per event and guarantees uniqueness across all threads without any extra structure. A counter per millisecond would itself need a concurrent map and cleanup. At tens of thousands of events per second, one shared AtomicLong is not a bottleneck; LongAdder cannot be used here because it does not hand out unique values.

What if event timestamps come from clients with skewed clocks?

Then events can arrive with timestamps far in the past, which are evicted at once, or in the future, which stay too long. We either use the server's receive time as the window key, keeping the client time as data, or clamp timestamps into a reasonable range on arrival.

How do you count events in the window efficiently?

size() on a range view walks the range, which is O(n). If a count is needed on every request, keep a separate LongAdder that is incremented on insert and decremented by the evictor for each removed entry, or use fixed time buckets, for example one counter per second, instead of storing individual events.

7Conclusion

In this answer, we built a five-minute sliding window on ConcurrentSkipListMap. Eviction is events.headMap(now - 300_000).clear(), which removes every entry below the cutoff one by one; it is not atomic as a whole, but each removal is safe and an insert near the cutoff can survive one more round. Using epoch milliseconds as the key loses events that share a millisecond, because the second put overwrites the first. We fixed it with a composite key of timestamp and a sequence from an AtomicLong, ordered by a comparator, and compared it with a timestamp-to-queue map.

What to say in the interviewAbout 100 seconds aloud

Open with

For eviction I'd use the sorted view: compute the cutoff as now minus 300,000 milliseconds and call events.headMap(cutoff).clear(). headMap gives a live view of every key below the cutoff, and clear removes those entries from the real map, walking from the oldest, so it only touches expired entries.

Then, if they want more

It isn't atomic as a whole, it removes entries one at a time while writers keep inserting, but each removal is safe, and the only effect is that an event inserted just below the cutoff during eviction survives until the next round a second later.

That's fine for a window, and if a reader needs an exact boundary it can read tailMap of the cutoff. The real bug is the key. A map keeps one value per key, so two events in the same millisecond have the same Long key and the second put silently replaces the first.

At twenty thousand events a second that's about twenty per millisecond, so we'd lose most of them under load without any error. I'd fix it with a composite key: a record of timestamp and a sequence number from a shared AtomicLong, with a comparator that orders by timestamp, then sequence.

Every key becomes unique, and eviction uses headMap of the key with the cutoff and Long.MIN_VALUE as the sequence. The other option is mapping each timestamp to a concurrent queue, but that has a race where an event added to a queue being evicted is lost, so I prefer the composite key.

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.
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 keep a sliding five-minute window of events keyed by timestamp in a...": https://scrivio-interview-library.netlify.app/java/concurrent-collections/d8f5da0fdc/