Logger Rate Limiter solution explained
Logger Rate Limiter asks you to design a logger that prints a message only if the same message has not been printed within the last few seconds. Keep a hash map from each message to the earliest time it may print again: a call is allowed when the timestamp has reached that time, and only an allowed call moves the time forward. Each call is O(1); a queue of recent prints keeps memory bounded if the stream has endless distinct messages.
By Evin JohnPublished 9 min read
The problem, in plain terms
A service writes log lines, and some lines repeat so fast that they drown everything else. Build a filter with one method, shouldPrint(timestamp, message). Timestamps are whole seconds and never go backward. A message may be printed if it has never been printed, or if its last printed time is at least cooldown seconds ago. The classic version fixes the cooldown at 10 seconds; this page keeps it as a parameter so the same code covers any gap.
call time message printed? why
1 0 "disk full" yes first time
2 2 "disk full" no last print was at 0, too soon
3 3 "fan error" yes different message, its own clock
4 4 "disk full" no still only 4 seconds after 0
5 5 "disk full" yes exactly 5 seconds after 0
6 8 "fan error" yes 5 seconds after 3
7 9 "disk full" no only 4 seconds after 5Call 5 is the one people get wrong. The rejected call at time 2 does not restart the clock, so the next allowed print for "disk full" is still time 5. If you stored the time of every call instead of every print, call 5 would be wrongly refused. Call 5 also pins down the boundary: a gap of exactly the cooldown is allowed.
Questions to ask before coding: are timestamps guaranteed to be non-decreasing? Is a gap equal to the cooldown allowed? How many distinct messages could there be over a day? Does more than one thread call the logger? The answers decide between the plain hash map and the bounded version further down.
Why interviewers like it
It is a short design question that still has a real trap (the rejected call that should not count) and an honest follow-up about memory. It is often used as a warm-up before a bigger rate limiting or system design discussion, so the interviewer is listening for how you state the rule, how you pick a data structure, and whether you notice that the map grows forever.
Brute force: scan the print history
Keep a list of every (time, message) that was printed. For a new call, walk the list backward while entries are still inside the cooldown window; if the same message shows up, refuse. Otherwise append and allow. It is correct and easy to argue about, which makes it a good reference for testing, but each call can touch every recent print.
class HistoryLogger:
def __init__(self, cooldown=10):
self.cooldown = cooldown
self.printed = [] # (time, message), in time order
def should_print(self, timestamp, message):
for t, m in reversed(self.printed):
if timestamp - t >= self.cooldown:
break # everything earlier is older still
if m == message:
return False
self.printed.append((timestamp, message))
return TrueOptimal approach: a map of next allowed times
Only one fact per message matters: the earliest time it may print again. Store that in a hash map. On each call, look the message up. If it is missing, or the timestamp has reached the stored time, print and store timestamp + cooldown. Otherwise refuse and leave the map alone. Storing the next allowed time rather than the last print time is a small choice that keeps the comparison to a single line and makes the boundary rule obvious.
class Logger:
def __init__(self, cooldown=10):
self.cooldown = cooldown
self.next_ok = {} # message -> earliest time it may print again
def should_print(self, timestamp, message):
if timestamp < self.next_ok.get(message, timestamp):
return False
self.next_ok[message] = timestamp + self.cooldown
return TrueThe default in get is the timestamp itself, so an unseen message always passes the check. The same idea in JavaScript uses a Map, which keeps any string as a key without the prototype surprises of a plain object.
class Logger {
constructor(cooldown = 10) {
this.cooldown = cooldown;
this.nextOk = new Map();
}
shouldPrint(timestamp, message) {
const allowedAt = this.nextOk.get(message);
if (allowedAt !== undefined && timestamp < allowedAt) return false;
this.nextOk.set(message, timestamp + this.cooldown);
return true;
}
}When memory matters: evict old messages
The map never forgets. A service that logs request ids or user names in its messages will see millions of distinct strings, and every one of them stays in the map long after its cooldown has passed. Because timestamps only go forward, any print older than one cooldown can never block anything again. So keep the recent prints in a queue in time order, with a set of the messages currently blocked. Before each check, pop prints that have aged out and drop them from the set.
from collections import deque
class WindowLogger:
def __init__(self, cooldown=10):
self.cooldown = cooldown
self.recent = deque() # (time, message) of prints, oldest first
self.blocked = set()
def should_print(self, timestamp, message):
while self.recent and timestamp - self.recent[0][0] >= self.cooldown:
_, old = self.recent.popleft()
self.blocked.discard(old)
if message in self.blocked:
return False
self.recent.append((timestamp, message))
self.blocked.add(message)
return TrueEach print enters the queue once and leaves it once, so the eviction loop costs O(1) amortized per call. Discarding from the set is safe because a message can sit in the queue at most once at a time: while it is in the window, it is blocked and cannot be appended again.
Complexity summary
| Approach | Time per call | Memory | Note |
|---|---|---|---|
| Scan of print history | O(w) | O(all prints) | Simple reference, keeps everything |
| Map of next allowed times | O(1) average | O(d) | The expected answer |
| Queue plus set | O(1) amortized | O(w) | Bounded memory, needs ordered timestamps |
| Map plus periodic sweep | O(1), with an O(d) sweep now and then | Between the two | Fine when pauses are acceptable |
Edge cases to try
- Two calls exactly one cooldown apart: the second one prints.
- Several calls with the same message and the same timestamp: only the first prints.
- A call at least one cooldown after the last print but less than one cooldown after a refused call: it must print, because refused calls do not count.
- Many messages interleaved: each keeps its own clock.
- A cooldown of 0 (if allowed): everything prints. A cooldown of 1: the same message cannot print twice in one second.
- Empty string as a message: still a valid key.
Mistakes to avoid
- Updating the stored time on refused calls, which keeps a noisy message silenced forever.
- Using > where the rule needs >=, or the reverse, so the boundary second flips.
- Using a plain JavaScript object, where a message such as "__proto__" is treated as a special property and its time is silently not stored.
- Evicting from the queue by message rather than by time, which turns the amortized O(1) step into a scan.
- Claiming the queue version works with out-of-order timestamps. It does not, because a late arrival could need a print that was already evicted.
Follow-ups
- Timestamps can arrive slightly out of order. Buffer calls for a short delay and release them in time order. Without that, first agree on what a late call should mean, because the map version would compare it against a print that happened after it.
- Several threads call the logger. The check and the update must happen together. A single lock is simplest; striping locks by a hash of the message spreads the contention.
- Allow up to k prints per window instead of one. Keep a small queue of print times per message and refuse when it holds k entries newer than the window. That is the sliding log idea.
- Many servers share one limit. The state has to live in a shared store with expiry on keys, and you now have to talk about latency and what happens when that store is down. The rate limiter system design guide covers that conversation.
- Report how many lines were suppressed. Count refusals per message and print the count with the next allowed line, which is what many production log filters do.
How to explain it out loud
Fictional example
- Candidate
- Let me restate the rule. A message prints if it never printed, or if its last print was at least the cooldown ago. A refused call does not count as a print.
- Candidate
- So per message I only need one number. I will keep a map from message to the earliest time it may print again, which makes the check a single comparison.
- Interviewer
- What happens to memory after a week?
- Candidate
- The map keeps every message it has ever seen. Since timestamps only move forward, I can keep recent prints in a queue and evict anything older than the cooldown, so memory follows the last window instead of all history.
- Interviewer
- And if two threads log at once?
- Candidate
- Check and update must be one step, so I would put them under a lock, or lock per hash bucket if one lock becomes the bottleneck.
Related problems
Moving Average from Data Stream uses the same queue-of-recent-items idea, but to keep a running sum rather than a blocklist. Single-Threaded CPU is another time-ordered simulation, with a heap choosing what runs next. LRU Cache is the other common "design a small structure" question, where the eviction rule is recency instead of age. For the wider family of class-design prompts, see the data structure interview questions.
Practicing it with Natively
Design questions like this one are mostly about talking: stating the rule, naming the trap, defending the memory trade-off. When you rehearse on Mac or Windows, Natively can transcribe your mock answer so you can check afterward whether you mentioned the refused-call rule before writing code, and it can read the prompt from a screenshot and suggest the map and queue approaches to compare against yours. More on practice sessions is on the AI coding interview helper page.
Questions people ask
How do you solve Logger Rate Limiter?
Keep a hash map from each message to the earliest time it may print again. Allow the call if the message is missing or the timestamp has reached that time, then store timestamp plus the cooldown. Refused calls leave the map unchanged.
What is the time complexity of Logger Rate Limiter?
With a hash map each call is O(1) on average, and memory is O(d) for d distinct messages. A queue-plus-set version is O(1) amortized per call and keeps only the prints from the last cooldown window.
Should a refused message reset the timer in Logger Rate Limiter?
No. The cooldown counts from the last time the message was actually printed. Resetting it on refused calls would keep a message that repeats often silenced forever.
How do you stop the Logger Rate Limiter map from growing forever?
Since timestamps only move forward, keep recent prints in a queue and evict any older than the cooldown, removing them from a set of blocked messages. Memory then follows the size of one window rather than all history.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
