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

Edge cases to test

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 True

C++

#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