Count a server's requests over any recent window and any time range with binary search

mediumAbout 30 minutesUpdated CodingProAsked atCareembinary-searchdesigntime-seriesqueuesarrays
Not solved

Share this question

Problem

A server logs the time of every request it receives. Operators want to ask "how many requests in the last n minutes?" for any n chosen at query time, and "how many between these two times?". Build a RequestCounter class that answers both quickly.

Timestamps are whole seconds (non-negative safe integers) and arrive in chronological order: each one is greater than or equal to the one before.

new RequestCounter(options)

  • options is optional. options.retentionSeconds, if given, must be a positive safe integer; otherwise throw a RangeError.
  • Without a retention limit, the counter keeps every timestamp.
  • With one, each record(t) drops every stored timestamp <= t - retentionSeconds. Queries only see what is still stored.

record(timestamp)

  • Stores one request. Several requests may share a timestamp.
  • Throw a TypeError if timestamp is not a non-negative safe integer.
  • Throw a RangeError if it is smaller than the last recorded timestamp. Nothing is stored in either case.

countLast(minutes, now)

  • Returns how many stored requests have a time t with now - minutes * 60 < t <= now.
  • minutes is any finite number >= 0, so 0.5 means 30 seconds. now is optional and defaults to the last recorded timestamp (or 0 if nothing was recorded).

countBetween(start, end)

  • Returns how many stored requests have start <= t <= end. Both ends are included.

For both queries, throw a TypeError if an argument is not a finite number, and a RangeError if minutes < 0 or start > end.

size (a getter) is the number of timestamps currently stored.

Both queries must run in O(log n) time. A store can hold 200,000 requests and answer 200,000 queries, so scanning the stored timestamps per query is too slow.

const counter = new RequestCounter();
[10, 20, 20, 65, 125, 300].forEach((t) => counter.record(t));
counter.countLast(1, 125);     // 1  (65 < t <= 125: only 125)
counter.countLast(2, 125);     // 5  (5 < t <= 125)
counter.countLast(5);          // 6  (now = 300, so 0 < t <= 300)
counter.countBetween(20, 125); // 4  (20, 20, 65, 125)
counter.record(5);             // RangeError: earlier than 300

const recent = new RequestCounter({ retentionSeconds: 60 });
recent.record(0); recent.record(30); recent.record(61);
recent.size;                   // 2  (0 was dropped: 0 <= 61 - 60)

Ref. UR-1535 · © UIRound · uiround.com/questions/count-a-server-s-requests-over-any-recent-window-and-any-time-range-with-binary-search

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment