Algo-Sim › Low-Level Design
Logger Rate Limiter
Easy · Low-Level Design · step through it in Java, Python and C++ on your own input
Print each message at most once every 10 seconds: a hash map from message to the earliest time it may print again. O(1) per call.
Problem
Design a logger that receives a stream of messages with timestamps. shouldPrintMessage(timestamp, message) returns true if the message should be printed: each unique message prints at most every 10 seconds, so a message printed at time t blocks the same message until t + 10.
Constraints
- 0 ≤ timestamp ≤ 10⁹, non-decreasing across calls
- Messages are 1–30 lowercase letters
- Up to 10⁴ calls; each is O(1) on average
Edge cases to test
- The same message exactly 10 seconds later: allowed
- Many different messages
- Messages at the same timestamp
Follow-up questions
- How do you stop the map growing forever?
- Evict stale entries: keep a queue of (time, message) and drop ones older than 10 seconds.
- What if calls come from many threads?
- Use a concurrent map with an atomic compare-and-set on the next allowed time.
Solution
Java
class Logger {
private final Map<String, Integer> nextAllowed = new HashMap<>();
public boolean shouldPrintMessage(int timestamp, String message) {
int next = nextAllowed.getOrDefault(message, 0);
if (timestamp < next) return false;
nextAllowed.put(message, timestamp + 10);
return true;
}
}Python
class Logger:
def __init__(self):
self.next_allowed = {}
def shouldPrintMessage(self, timestamp, message):
nxt = self.next_allowed.get(message, 0)
if timestamp < nxt:
return False
self.next_allowed[message] = timestamp + 10
return TrueC++
#include <bits/stdc++.h>
using namespace std;
class Logger {
public:
unordered_map<string, int> nextAllowed = {};
bool shouldPrintMessage(int timestamp, string &message) {
int next = (nextAllowed.count(message) ? nextAllowed[message] : 0);
if (timestamp < next)
return false;
nextAllowed[message] = timestamp + 10;
return true;
}
};
More Low-Level Design problems
- LRU Cache (Medium)
- LFU Cache (Hard)
- Min Stack (Medium)
- Insert Delete GetRandom O(1) (Medium)
- Design Circular Queue (Medium)
- Flatten Nested List Iterator (Medium)
- Rate Limiter: Token Bucket (Medium)
- Rate Limiter: Sliding Window Log (Medium)
- Design Hit Counter (Medium)
- Design Parking System (Easy)
- Design Tic-Tac-Toe (Medium)
- Design Twitter (Medium)
- Design Snake Game (Medium)
- Vending Machine (State pattern) (Medium)
- Elevator System (LOOK scheduling) (Medium)
- Splitwise (expense sharing) (Medium)
- Movie Ticket Booking (BookMyShow) (Medium)