Travel request limiter
Harbor Travel's API team needs a deterministic admission component. The input supplies requests, tenant keys, nondecreasing integer times, quotas and optional costs and IDs. Deliver one boolean per request with documented fixed-window semantics and no double charging on replay.
Harbor Travel needs a limiter that explains every admission decision. A single global count is enough for the first version, but the finished component needs tenant isolation, quota overrides, weighted requests and replay-safe IDs. You add those policies one at a time.
This project uses fixed integer windows. It doesn't claim to implement a sliding window or token bucket, which have different boundaries. A request exactly on a window boundary belongs to the new window. Rejected requests consume no quota, invalid costs cannot create capacity, and an explicit zero override blocks positive-cost work. The last step remembers both accepted and rejected request IDs per tenant, so a retry returns the same decision even after time advances.
import json
def process_payload(payload: str) -> str:
data = json.loads(payload)
counts, remembered, result = {}, {}, []
for request in data['requests']:
tenant = request['key']
bucket = ('all', request['time'] // data['window'])
limit = data['limit']
cost = 1
allowed = counts.get(bucket,0) + cost <= limit
result.append(allowed)
if allowed:
counts[bucket] = counts.get(bucket,0) + cost
return json.dumps(result,separators=(',',':'))
A request at an exact window boundary belongs to the next bucket. Key counts by the fixed window and, once introduced, the tenant. Decide admission before mutating quota. Average dictionary work is constant per request; memory grows with distinct tenant windows and remembered IDs.