Elementary, My Dear Engineer: Cracking the Case of Multi-Tenant Auth Caching
Ah, a classic conundrum in the fog-shrouded alleys of distributed systems! You've presented three suspects: invalidation, stampede prevention, and correctness, all lurking in the multi-tenant shadows of an authorization cache. Fear not—I shall deduce a robust architecture, drawing from the annals of systems like AWS IAM, Auth0, and custom SaaS warhorses. We'll isolate tenants like suspects in separate interrogation rooms, ensuring no cross-contamination.
Our crime scene: High-throughput auth checks (e.g., "Can tenant A's user Bob read resource /docs/42?"). Cache hits must be lightning-fast (<1ms), misses authoritative (from DB/policy engine), and the whole affair tenant-isolated to prevent leaks.
1. The Cache Structure: Partitioned and Precise
Key Design: auth:{tenant_id}:{subject}:{action}:{resource} (e.g., auth:acme:alice:read:proj/42). Use consistent hashing for even distribution.
Why multi-tenant? Prefix with {tenant_id} (or shard by it) to enforce isolation. No global caches—each tenant's data is firewalled.
Value: {decision: allow/deny, ttl: 300s, version: 5, recompute_at: now+250s}. Include a version stamp for invalidation.
Backend: Redis (Cluster for scale) or Memcached. TTLs prevent eternal staleness.
Hit Path:
code
GET cache_key → {allow, version:5} ? Serve : Miss → Compute → SET with TTL/version.
2. Invalidation: The Swift Justice Strike
Problem: Auth changes (role revoke, policy update) must purge relevant entries instantly, without scanning the world.
Solution: Event-Driven Versioned Invalidation via Pub/Sub.
Trigger
Action
User role change (tenant X, user Y)
Publish to Redis Pub/Sub: auth-invalidate:tenant:X:user:Y:*. Subscribers (workers) DEL all matching keys via SCAN or Lua script.
Policy update (tenant X)
Bump global tenant version (tenant_version:X:7). On cache read, if local version < global, invalidate.
Resource ACL change
Invalidate by resource prefix: auth:*:bob:read:proj/42. Use Redis key tags (sorted sets) for batch DEL.
Edge Case: Lazy invalidation with short TTLs (5-30min) + version checks. For hard real-time (e.g., banking), use write-through: Update cache and DB atomically.
Multi-Tenant Win: Events are tenant-scoped; no noise across tenants.
3. Stampede Prevention: Thwarting the Thundering Herd
Problem: 10k concurrent misses → DB melts under recompute load.
Solution: Lease + Probabilistic Early Refresh (inspired by Netflix's Hystrix/EVCache).
Single-Flight Locks: Use Redis SETNX (set-if-not-exists) for a lease key (lease:{cache_key}:refresh).
code
MISS:
1. SETNX lease_key "1" EX 30 # Acquire 30s lease (or 1% of TTL)
2. If acquired: Compute auth → SET cache_key → DEL lease_key
3. Else: Wait 100ms + jitter → RETRY GET (stale-but-safe)
Background Refresh: On every hit, with 1/TLL probability (e.g., 1%), queue async refresh. Keeps cache warm.
Probabilistic Stampede Shield: During lease, 99% of followers get stale read (safe for authz—better over-permissive briefly than outage). Use GET cache_key → if TTL < 10%, trigger refresh.
Multi-Tenant: Leases per-tenant/shard to avoid global contention.
Fallback: Circuit breaker (e.g., via Resilience4j) → serve deny on DB failure.
4. Correctness: The Unbreakable Alibi
Guarantees:
Level
Trade-off
How
Eventual Consistency (default)
Fast, scalable
TTL + invalidation. Worst: 5min stale allow (tolerable for most apps).
Read-Your-Own-Writes
User sees changes
On auth mutation, invalidate user's cache prefix immediately.
Monotonic Reads
No flip-flops
Version stamps: Increment on change, reject old cache.
Strong (rare)
Zero stale
Bypass cache on mutation window (e.g., 10s), use DB mutex.
Verification:
Chaos Testing: Inject policy changes, flood with queries, assert no leaks/stales > TTL.
This blueprint scales to millions of tenants/users, with <0.1% error rate. The game's afoot—deploy, measure, iterate. Got metrics, code, or a twist (e.g., OPA integration)? The violin awaits your next clue! 🔍