Preparing your design workspace

Loading the problem and your saved attempt…

Design a Hit Counter with Disk-Backed Payloads

Extend a 5-minute hit counter so each hit carries a payload stored on disk, with fast hits, readable unflushed payloads, and cleanup by age.

The reported interview asked for the hit counter from LeetCode 362, Design Hit Counter: HitCounter() creates the counter, hit(timestamp) records a hit, and getHits(timestamp) returns how many hits happened in the last 5 minutes.

It added get_messages(timestamp), which returns the payload messages for one timestamp; one timestamp can have several messages. Each payload is up to a couple of KB. There are too many payloads to keep in memory, but the timestamps alone do fit in memory.

The interviewer then raised two follow-ups: when to write each message to disk right away and when to keep it in an in-memory cache, decided from the load and estimated with rough numbers; and which disk layouts would work better than an SSTable (a sorted, read-only file of keys and values that is merged with other such files in the background).

The report did not say how a payload is passed in. For this exercise, assume hit(timestamp, payload) records one hit and its payload message. For this exercise, also assume the following. Timestamps are whole seconds and never go down between calls, and getHits(t) counts hits with a timestamp in (t - 300, t].

get_messages(t) returns that second's payloads in arrival order for any t still inside a retention period of 1 hour (configurable). Older payloads may be deleted, and an older or unknown timestamp returns an empty list.

Use these rough numbers: about 1,000 hits per second on average, peaks of 10,000 per second, payloads up to 2 KB, a memory budget of about 256 MB for payload data, and one local SSD. hit must return quickly, and get_messages must also return payloads that are still in memory and not yet on disk.

If the process crashes, losing up to the last 1 second of payloads is acceptable. Everything runs in one process; hit may be called from several threads, and background work is allowed.

Design the objects, responsibilities, interfaces, and interactions for this counter. Two follow-ups then cover the write-now-or-buffer decision and the disk layout.

Several machines, replication, compression, searching payload contents, more than one counter, and full crash recovery beyond what the follow-ups discuss are out of scope.