Why This Matters at Engineering Leadership Scale
Rate limiting sits on the critical path of every multi-tenant SaaS API and AI gateway. When one tenant runs an unthrottled backfill script, a missing or leaky limiter turns a customer bug into a platform outage.
In Atlassian M60/M70 and Big Tech Engineering Manager coding loops, this drill tests the 50-minute playbook: clarify scale in minutes 0 to 5, lock in O(1) structures by minute 12, test core logic by minute 30, and cleanly absorb Minute-30 curveballs without rewriting your core class. That same rigor prevents flaky Date.now() tests and unbounded-map OOM crashes in production PRs.
Core Mental Model & Architecture
| Algorithm | Data Structure | Time / Req | Space / Tenant | Burst Behavior | Best Fit |
|---|---|---|---|---|---|
| Token Bucket | Map<id, { tokens, lastRefillMs }> | O(1) | O(1) | Controlled bursts up to capacity | Tiered SaaS APIs (1,000/min+) |
| Sliding Window Log | Map<id, Deque<timestampMs>> | O(1) amort. | O(k) | Exact rolling window count | Strict small-k limits |
| Fixed Window | Map<id, { start, count }> | O(1) | O(1) | Up to 2x boundary spike | Coarse internal throttles |
A Token Bucket holds O(1) space even for Enterprise 1,000/min limits. Two design seams matter most: inject a Clock interface for deterministic tests, and isolate resolvePolicy(tenantId) from token math so tier overrides drop in cleanly.
Step-by-Step Implementation Tutorial
1. Implement the Clock, Policy Resolver, and Token Bucket (Minutes 5 to 28)
export interface Clock { nowMs(): number; }
export interface RateLimitPolicy { capacity: number; refillPerSec: number; }
export interface RateLimitDecision { allowed: boolean; remaining: number; retryAfterMs: number; }
interface BucketState { tokens: number; lastRefillMs: number; lastSeenMs: number; }
export class InMemoryRateLimiter {
private readonly buckets = new Map<string, BucketState>();
private readonly tierPolicies = new Map<string, RateLimitPolicy>();
private readonly tenantTiers = new Map<string, string>();
constructor(
private readonly defaultPolicy: RateLimitPolicy,
private readonly clock: Clock = { nowMs: () => Date.now() },
private readonly idleTtlMs = 15 * 60 * 1000,
private readonly maxBuckets = 100_000
) {
if (defaultPolicy.capacity <= 0 || defaultPolicy.refillPerSec <= 0) {
throw new Error("capacity and refillPerSec must be positive");
}
}
public setTierPolicy(tier: string, policy: RateLimitPolicy): void {
this.tierPolicies.set(tier, policy);
}
public assignTenantTier(tenantId: string, tier: string): void {
if (!this.tierPolicies.has(tier)) throw new Error(`Unknown tier: ${tier}`);
this.tenantTiers.set(tenantId, tier);
}
public allow(tenantId: string, cost = 1): RateLimitDecision {
if (!tenantId || cost <= 0) throw new Error("Invalid tenantId or cost");
const now = this.clock.nowMs();
const policy = this.resolvePolicy(tenantId);
const prev = this.buckets.get(tenantId);
const bucket: BucketState = !prev || now - prev.lastSeenMs > this.idleTtlMs
? { tokens: policy.capacity, lastRefillMs: now, lastSeenMs: now }
: {
tokens: Math.min(policy.capacity, prev.tokens + ((Math.max(0, now - prev.lastRefillMs) / 1000) * policy.refillPerSec)),
lastRefillMs: now,
lastSeenMs: now,
};
// Refresh insertion order so oldest idle keys sit at front of Map
this.buckets.delete(tenantId);
this.buckets.set(tenantId, bucket);
this.evictIfOverCapacity(now);
if (bucket.tokens >= cost) {
bucket.tokens -= cost;
return { allowed: true, remaining: Math.floor(bucket.tokens), retryAfterMs: 0 };
}
const retryAfterMs = Math.ceil(((cost - bucket.tokens) / policy.refillPerSec) * 1000);
return { allowed: false, remaining: Math.floor(bucket.tokens), retryAfterMs };
}
// Minute-30 Extension: O(expired) sweep stopping at first active key
public purgeIdle(nowMs = this.clock.nowMs()): number {
let removed = 0;
for (const [id, state] of this.buckets.entries()) {
if (nowMs - state.lastSeenMs > this.idleTtlMs) {
this.buckets.delete(id);
removed++;
} else {
break;
}
}
return removed;
}
private resolvePolicy(tenantId: string): RateLimitPolicy {
const tier = this.tenantTiers.get(tenantId);
return (tier && this.tierPolicies.get(tier)) ?? this.defaultPolicy;
}
private evictIfOverCapacity(nowMs: number): void {
if (this.buckets.size <= this.maxBuckets) return;
this.purgeIdle(nowMs);
while (this.buckets.size > this.maxBuckets) {
const oldest = this.buckets.keys().next().value;
if (oldest !== undefined) this.buckets.delete(oldest);
}
}
}2. Write Deterministic Unit Tests (Minutes 30 to 35)
Use a fake clock (let now = 1000; const clock = { nowMs: () => now };) to assert: (1) burst exhaustion returns exact retryAfterMs, (2) refill clamps at capacity, (3) free: 10/min and enterprise: 1000/min stay isolated, and (4) purgeIdle() drops keys past idleTtlMs.
3. Walk Through the Minute-30 Extension (Minutes 35 to 50)
When asked to add per-tier overrides and prevent 5 million mostly idle users from exhausting RAM:
resolvePolicy(tenantId)handles tier overrides inO(1), andMath.min(policy.capacity, ...)clamps burst immediately on tier downgrades.- Re-inserting active keys keeps idle entries at the front of
buckets, sopurgeIdle()runs inO(expired)time andmaxBucketscaps heap deterministically.
Worked Production Scenario: Before vs. After
Context: A multi-tenant SaaS gateway (12 Node.js pods, 180k workspaces) ran a hardcoded 60 req/min Sliding Window Log using Date.now() with zero eviction. Enterprise syncs hit false 429s, 140k trial tenants leaked 420 MB/day until pods OOM-restarted every 36 hours, and setTimeout tests flaked on 14% of CI runs.
After: The platform squad deployed InMemoryRateLimiter with injected Clock, tier policies (free: 10/min, pro: 120/min, enterprise: 1000/min), 15-minute idleTtlMs, and maxBuckets = 50_000.
| Metric | Before | After |
|---|---|---|
| Memory per 50k active tenants | ~310 MB (unbounded) | ~6.4 MB (hard-capped) |
| Gateway OOM restarts / week | 4 to 6 pods | 0 pods |
| Unit test runtime & flakiness | 14.2s (14% flaky) | 18ms (0% flaky) |
| Enterprise false-positive 429s / week | 1,850 | 0 |
Common Failure Modes & Anti-Patterns
- Calling
Date.now()directly inside logic: Forces slow, flaky sleep-based tests. Fix: InjectClockwith a defaultDate.nowimplementation. - Unbounded per-tenant maps: Long-tail idle traffic exhausts pod RAM. Fix: Combine lazy expiry on read, ordered
purgeIdle()sweeps, andmaxBuckets. - Treating local limits as global limits: Running
1,000/minlocally across 12 pods permits12,000/minglobally. Fix: Use local limiters as fast per-node guardrails and put a Redis Lua bucket behind the same interface for strict global quotas.
How to Handle Pushback in the Room
Skeptical Principal Engineer: "Why build an in-memory limiter when Redis handles distributed rate limiting?"
Calm Response: "Redis is right for strict global quotas, and our interface swaps to Redis cleanly. Even with Redis, an O(1) in-memory guardrail protects pods if Redis spikes in latency or one tenant floods a single node."
Pushing Product Manager: "Can we hardcode Enterprise IDs in an if check and skip idle cleanup for now?"
Calm Response: "Hardcoding IDs forces a deploy for every new Enterprise deal. Adding resolvePolicy and maxBuckets takes twenty minutes today and prevents both deploy toil and OOM pages next month."
Key Takeaways & This Week's Action Rep
- Keep state
O(1)per tenant: Prefer Token Bucket over timestamp logs for high-quota tiers. - Inject
Clockeverywhere: Turn flaky sleep tests into 10ms deterministic unit tests. - Separate policy lookup from math: Absorb per-tier overrides without rewriting refill logic.
- Bound every in-memory map: Pair lazy expiry with
purgeIdle()andmaxBuckets.
This Week's Action Rep: Disable autocomplete for 45 minutes in your IDE. Implement InMemoryRateLimiter with an injected Clock, add tier overrides and purgeIdle() at minute 30, and pass all 4 unit tests in under 50ms.