Video in progress

For a monitoring service, what structure do you use to keep an in-memory time window of the last 5 minutes of metrics: a ring buffer, an ArrayDeque or a TreeMap?

If events arrive almost in order and you only need aggregates (sum, average, percentile), a ring buffer over time buckets is the cheapest and most predictable solution. With late-arriving events and arbitrary range queries, a TreeMap/skip list, but it is considerably more expensive.

📖 Answer

I pin down the requirements: how many events per second, whether they arrive in order, how much delay is allowed, what queries (just "the last 5 minutes" or arbitrary ranges), exact or approximate values.

A ring buffer + time buckets. I split 5 minutes into 300 one-second buckets, where each bucket is an aggregate (count, sum, max or an HdrHistogram). The array is fixed-size, and the index is second % 300. An old bucket is overwritten automatically.

final class Window {
    private final long[] counts = new long[300];
    private final long[] stamps = new long[300];

    synchronized void record(long epochSec) {
        int i = (int) (epochSec % 300);
        if (stamps[i] != epochSec) { stamps[i] = epochSec; counts[i] = 0; } // clear the stale bucket
        counts[i]++;
    }
}

Memory doesn't depend on the number of events per second, and there is no allocation. The accuracy is one bucket (1 s). Under high concurrency, use a LongAdder in each bucket, or separate windows per thread and merge them on read.

An ArrayDeque with every event is exact, but memory is proportional to the number of events. At 50,000 events per second, 5 minutes is 15 million elements. It only fits low rates (a list of errors, for example).

A TreeMap/ConcurrentSkipListMap by time puts a late event in the right place and gives an arbitrary range with subMap. The cost: O(log n) on every write, a node per event, and heavy GC pressure.

For late events in the ring buffer, I set a "lateness limit": an event older than the limit is dropped and counted in a counter, so you know how many were lost.

And I always ask: do we have to write this ourselves? Micrometer's DistributionSummary/Timer already have a sliding window histogram, and Prometheus computes the window on the server side.