Hierarchical Sliding-Window Throttle for Outbound Alerts
System DesignModel answerLast updated
Design a distributed throttle that accepts or rejects alerts using exact 10-minute rolling limits for a user, their team and their company, atomically and correctly across many stateless servers.
Hierarchical Sliding-Window Throttle for Outbound Alerts
You are building the gatekeeper for a messaging platform that pushes alerts to end users. Before any alert goes out, a service must decide whether the send is allowed.
The decision API is:
allow_alert(user_id, timestamp) -> bool
Each user belongs to exactly one team, and each team belongs to exactly one company, so a fixed user -> team -> company lookup exists.
An alert is allowed only if, at the moment of the request, all three of these hold over an exact rolling 10-minute window:
| Scope | Max accepted alerts per 10 minutes |
|---|---|
| User | 3 |
| Team | 10 |
| Company | 20 |
Rules:
- If allowing the alert would break any of the three limits, it is denied and no counter changes at any level.
- If it is allowed, it counts against all three scopes.
- The window is a true sliding window: an accepted event stops counting exactly 10 minutes after it occurred. This is not a fixed or tumbling bucket.
- The answer must stay correct when many stateless application servers call the limiter concurrently.
Assumptions (confirm them in your answer)
- Roughly 10^7 users, up to about 10^6 decisions per second at peak, p99 decision latency in single-digit milliseconds.
- The hierarchy is a strict tree. Mappings change rarely (reorgs, transfers) but they do change.
- The limits are small (3 / 10 / 20). You are expected to take advantage of that.
What to deliver
- Core algorithm. Explain the decision logic and why it is exact. Walk through a concrete example that includes (a) an event landing exactly at the 10-minute boundary and (b) a case where the team or company limit rejects a request even though the user is under their own limit.
- Distributed design. Cover the API (including idempotency), storage choice and data model, how the three-scope check-and-update is made atomic, sharding and horizontal scaling, handling of
user -> team -> companylookups and their changes, and operational concerns (clock skew, hot keys, failure behavior, observability). - Trade-offs. Name the main ones explicitly and say which side you pick and why.
Also list the clarifying questions you would ask before committing to a design.
Hints
Hint 1
Because the limits are tiny (3, 10, 20), you can afford to store the actual timestamps of accepted events per scope rather than approximating with counters. Memory per key is bounded by the limit.
Hint 2
A rejected request must change nothing, so the check across all three scopes must happen before any write, and the check plus the writes must be one indivisible step. Think about what single-node primitive gives you that (a server-side script or a transaction on one shard).
Hint 3
To make a multi-key atomic operation possible, the user, team and company keys have to live on the same shard. Ask what that does to load for a large company, and what you would do if one company becomes a hotspot.
Hint 4
Think about what can go wrong beyond the happy path: retried requests double-counting, caller-supplied versus server-assigned timestamps, a user moving teams mid-window, and the store being unreachable.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying questions
- Is the window required to be exact, or is a cheaper approximation acceptable? (I assume exact, since the limits are small.)
- Should a denial report which scope blocked it?
- What are the p99 budget, peak QPS, and skew across companies?
- On a store outage, fail-open or fail-closed?
- How fresh must the user-to-team-to-company mapping be?
- Are timestamps server-assigned, or can callers supply them (possibly late or out of order)?
Core algorithm
For each scope key (user, team, company) keep a small sorted list of the timestamps of accepted events. On a request at time t:
- Resolve
user -> team -> company. - For each of the three lists, drop entries with
ts <= t - 600s. The boundary is a design choice: an event att0stops counting at exactlyt0 + 600s, so a request att0 + 600sees it as expired. - If
len(user) >= 3orlen(team) >= 10orlen(company) >= 20, returnfalseand write nothing. - Otherwise append
tto all three lists and returntrue.
This is exact because every accepted event is stored individually and evicted precisely when it ages out. Memory is bounded by 3, 10 and 20 entries per key, so there is no need for approximation.
WINDOW = 600
LIMITS = {"user": 3, "team": 10, "company": 20}
def allow_alert(user_id, t, store, meta):
team, comp = meta.lookup(user_id)
keys = [("user", user_id), ("team", team), ("company", comp)]
lists = []
for scope, k in keys:
q = store[(scope, k)]
while q and q[0] <= t - WINDOW:
q.popleft()
lists.append((scope, q))
if any(len(q) >= LIMITS[s] for s, q in lists):
return False
for _, q in lists:
q.append(t)
return True
Per request this is O(1) amortised, since each entry is added and removed once and lists are tiny.
Walk-through
Say user U is in team T (which already holds 9 accepted events from other users) in company C.
- t=0: U's first alert. User=0, team=9, company well under 20. Accepted, so team goes to 10, user to 1.
- t=60: U sends again. Team already has 10, so it is denied by the team limit even though U has only 1. Nothing is incremented; U stays at 1.
- t=600: the t=0 event is exactly 10 minutes old and is evicted, so team drops to 9 (assuming the other 9 are later) and U to 0. The request is accepted.
The rule "reject increments nothing" matters here: if the denial at t=60 had bumped the user counter, U would be penalised for a request that was never sent.
Distributed design
API
POST /v1/alerts/decision {request_id, user_id, timestamp?} returns {allowed, blocked_scope?, retry_after?}. Returning the blocking scope and a retry_after (the oldest entry's expiry) is cheap and helps callers and debugging.
Idempotency: store the decision for request_id for a short TTL. A retried request returns the same answer without double-counting. Without this, a network retry can burn quota.
Storage and atomicity
Use an in-memory store with server-side scripting, for example Redis with Lua, or a custom sharded service. Each scope key is a sorted set (or small list) with a TTL slightly above 600s so idle keys disappear.
The whole check-and-update runs as one script on one shard: trim three keys, compare against limits, then conditionally append. Single-threaded script execution gives atomicity with no distributed locks and no read-modify-write races across stateless servers. Do not do "read counts, decide in the app, then write"; two servers will both pass the check and overshoot.
Sharding
A multi-key script requires all three keys on one shard. Partition by company id (hash tag such as {company}:user:...). The user, team and company keys for the same company then colocate, and the script stays atomic.
Trade-off: a very large company concentrates load on one shard. Since the company limit is 20 per 10 minutes, a company can only accept about 20 events per window, but it can still receive huge numbers of rejected requests. Mitigations:
- Cheap early rejection: once a company is full, cache a "blocked until X" marker in the app server's local memory and short-circuit without hitting the store.
- Replicas for failover only; reads for decisions must go to the primary.
- If one company truly dominates, split its keys by team and use a two-phase approach, accepting extra complexity. I would only do this if measurements demand it.
At 10^6 decisions per second, a Redis shard handles on the order of 50-100k simple scripts per second, so plan for 15-30 primaries with headroom, plus replicas.
Hierarchy lookups and changes
- Keep
user -> team -> companyin a separate metadata service, cached in the app servers with a short TTL (say 30-60s) plus invalidation events on change. - Because sharding is by company, a cross-company transfer moves a user's keys between shards. Accept that a transferred user's recent events stay counted against the old team/company until they expire (at most 10 minutes), and start counting against the new scope immediately. This is a deliberate freshness-versus-complexity trade-off.
- Cache misses fall through to the metadata store; if that fails, use the stale entry rather than blocking.
Time and ordering
Prefer server-assigned time from the limiter shard (or a single trusted clock source). Caller-supplied timestamps allow skew and out-of-order events, which break the sorted-list invariants. If caller time must be supported, clamp it to within a small tolerance of server time and reject or clamp anything older than the window.
Failure behavior
Decide per use case. For marketing alerts, fail-closed protects users from floods; for critical alerts (security codes), fail-open, ideally with a coarse local fallback limiter. Make it configurable per alert class.
Observability
Track decision latency percentiles, allow/deny ratio by blocking scope, per-shard QPS and hottest keys, script errors, metadata cache hit rate and staleness, and idempotency-store hit rate. Alert on sudden changes in deny ratio.
Trade-offs
- Exact vs approximate: exact lists cost at most 33 timestamps per user-team-company chain; trivially cheap, so choose exact.
- Colocation vs hot shards: colocation gives atomicity; hot companies are handled with local blocked-caches.
- Freshness vs latency: cached hierarchy is fast but can be briefly stale after transfers.
- Fail-open vs fail-closed: depends on the cost of a missed versus an extra alert.
Common mistakes
- Checking and writing in separate round trips (race, overshoot).
- Incrementing counters before all scopes have been checked, then trying to roll back.
- Using fixed buckets and calling it a sliding window; this permits up to 2x bursts at bucket boundaries.
- Sharding by user, which makes team and company checks cross-shard.
- Ignoring retries, so duplicates consume quota.
- Trusting caller clocks.