Two-Tier Fixed-Window Request Throttle Simulator
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a throttle that enforces a shared limit and a per-key limit over epoch-aligned fixed windows, with lazy reset and a defined precedence between the two rejection reasons.
Two-Tier Fixed-Window Request Throttle
A gateway admits requests only if they pass two independent fixed-window limits:
- Shared limit: at most
global_limitadmitted requests per window ofglobal_window_secseconds, counted across all domains. - Per-domain limit: at most
domain_limitadmitted requests per window ofdomain_window_secseconds, counted separately for each domain string.
You are given a list of operations to replay in order. Return the throttle's decision for each one.
Window rule
Windows are aligned to epoch time. For a timestamp now and a window length w, the window id is int(now // w). Two timestamps share a window exactly when their ids are equal. For example, with w = 1, the times 10 and 10.5 share window 10, while 11.01 is in window 11. A timestamp that is an exact multiple of w starts a new window.
The shared limit and the per-domain limit each compute their own window id from the same timestamp, using their own window length.
Decision procedure for one request [domain, now]
- Shared check. If the shared counter for the request's shared-window id has already reached
global_limit, reject with reason"global". - Domain check. Otherwise, if the domain's counter for the request's domain-window id has already reached
domain_limit, reject with reason"domain". - Admit. Otherwise, increase both counters by one and admit the request.
Consequences:
- If both limits are exhausted, the reason is
"global", because it is checked first. - A rejected request changes nothing. It consumes no capacity from either limit.
Lazy reset and what is remembered
To keep memory bounded, the throttle keeps only the most recently admitted bucket for each counter:
- The shared counter remembers a single
(window id, count)pair, set by the last admitted request. - Each domain remembers a single
(window id, count)pair, set by that domain's last admitted request.
When a request's window id differs from the remembered id, the effective count is 0. The remembered pair is replaced only when a request is admitted. Rejections never modify it. A domain that has never been admitted has count 0.
Operations
operations[i] is the operation name and arguments[i] holds its arguments. The only supported operation is "is_allowed", with arguments [domain, now], where domain is a string and now is a number. If any other operation name appears, raise ValueError.
Output
Return a list with one entry per operation, in order. Each entry is:
[True, None]if the request is admitted.[False, "global"]if it is rejected by the shared limit.[False, "domain"]if it is rejected by the per-domain limit.
Constraints
operationsandargumentshave the same length.global_limit,domain_limit,global_window_secanddomain_window_secare positive integers.nowis a non-negative number (integer or float).- Domain strings are compared exactly as given. No normalization is applied.
- Each request must be processed in O(1) expected time.
Examples
Example 1
Input: evaluate_dual_window_limits(100, 60, 3, 1, ['is_allowed', 'is_allowed', 'is_allowed', 'is_allowed', 'is_allowed'], [['api.partner-a.com', 10], ['api.partner-a.com', 10], ['api.partner-a.com', 10], ['api.partner-a.com', 10.5], ['api.partner-a.com', 11.01]])
Output: [[True, None], [True, None], [True, None], [False, 'domain'], [True, None]]
Example 2
Input: evaluate_dual_window_limits(100, 60, 3, 1, ['is_allowed', 'is_allowed', 'is_allowed', 'is_allowed'], [['a.example', 1], ['b.example', 1], ['c.example', 1], ['d.example', 1]])
Output: [[True, None], [True, None], [True, None], [True, None]]
Hints
Hint 1
Compute each window id as int(now // window_length). A different id than the one you remember means the count is effectively zero.
Hint 2
Do both checks before changing any state, shared first and then domain. That way a rejected request never needs rolling back.
Hint 3
Store one (window_id, count) pair for the shared counter and one per domain in a dict. Overwrite a pair only when a request is admitted.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each limit is a fixed-window counter. The window id int(now // window_length) identifies which bucket a timestamp belongs to. Instead of using timers or background cleanup, we reset lazily: we remember only one (window_id, count) pair for the shared counter and one per domain. If a request's window id differs from the stored one, the stored count is treated as 0.
For every request:
- Compute the shared and domain window ids.
- Read the effective shared count. If it has reached
global_limit, answer[False, "global"]and stop. - Read the effective domain count. If it has reached
domain_limit, answer[False, "domain"]and stop. - Otherwise write both updated pairs and answer
[True, None].
Why it is correct
- Window semantics: two timestamps are in the same aligned window exactly when their ids are equal, so comparing ids enforces "at most N per aligned window".
- Precedence: the shared check runs first, so when both limits are exhausted the reason is always
"global". - No partial consumption: both checks run before any write, so a rejected request leaves both counters untouched and never needs to be rolled back.
- Lazy reset: a stored pair from an older window fails the id comparison and counts as
0. It is overwritten on the next admission, so memory never grows with the number of windows.
Complexity
- Time: O(1) per request, so O(n) for n operations.
- Space: O(D) for D distinct domains that have been admitted at least once. The shared counter uses O(1).
Reference solution
from typing import List
def evaluate_dual_window_limits(global_limit: int, global_window_sec: int, domain_limit: int, domain_window_sec: int, operations: List[str], arguments: List[List]) -> List[List]:
shared_bucket = (None, 0) # (window_id, count) of the last admitted request
domain_buckets = {} # domain -> (window_id, count)
results = []
for operation, args in zip(operations, arguments):
if operation != "is_allowed":
raise ValueError("unsupported operation")
domain, now = args
g_id = int(now // global_window_sec)
d_id = int(now // domain_window_sec)
# Shared check (no mutation yet)
g_count = shared_bucket[1] if shared_bucket[0] == g_id else 0
if g_count >= global_limit:
results.append([False, "global"])
continue
# Domain check (stale window means count 0)
bucket = domain_buckets.get(domain)
d_count = bucket[1] if bucket is not None and bucket[0] == d_id else 0
if d_count >= domain_limit:
results.append([False, "domain"])
continue
# Commit both counters
shared_bucket = (g_id, g_count + 1)
domain_buckets[domain] = (d_id, d_count + 1)
results.append([True, None])
return results