The user wants a "tenant-aware cache." This is a common requirement in multi-tenant applications where data from different tenants (organizations, customers) coexists in a shared infrastructure.
Key requirements mentioned:
- Key Scoping: Ensuring Tenant A cannot access Tenant B's data.
- Invalidation: Clearing data for specific tenants or keys without affecting others.
- Fairness: Ensuring one noisy tenant doesn't evict all the data of other tenants.
- Correctness: Handling concurrency and race conditions properly.
Mental Model & Architecture:
- Underlying Store: What data structure? A simple in-memory map (for demonstration) or an interface that could wrap Redis/Memcached. For a code example, a generic interface + an in-memory implementation is best.
- Key Scoping: The keys need to be namespaced.
tenant_id:key.
- Fairness (Eviction Policy): Standard LRU is global. If Tenant A hammers the cache, they evict Tenant B.
- Approach 1: Segregated Pools. Each tenant gets a fixed size. Problem: Hard to balance. Tenant B might need more space than allocated, while Tenant A's allocated space sits empty.
- Approach 2: Weighted/LRU with tags. Most production caches (Redis) don't have perfect per-tenant fairness built-in easily without sharding.
- Approach 3 (The "Fair" approach): A variation of LRU where we track usage per tenant or use a segmented LRU.
- Simpler approach for a coding interview/design: A "Partitioned" cache or a "Scoped" cache where we track memory usage per tenant and apply a global LRU but with a cap per tenant (quota). Let's go with a Quota-based approach combined with a global LRU, or perhaps a "Segmented LRU" where each tenant has their own LRU list, and a background process balances them.
- Refined Fairness Strategy: Let's stick to a practical implementation: A
Map<TenantID, Map<Key, Value>> is too rigid (O(N) to find global LRU). A single global LRU is easiest but unfair. A good middle ground is LRU with Count-Based Quotas. If a tenant exceeds their quota, we evict their oldest items first before evicting globally.
Implementation Steps:
- Interface Definition:
Get, Set, Invalidate, InvalidateTenant.
- Key Structure: Composite key
TenantKey struct.
- Storage: A
map[TenantKey]Entry.
- Eviction/Fairness:
- Use a doubly linked list for LRU.
- Maintain a
map[TenantID]*list.List (per-tenant LRU) and a global list.List.
- Wait, managing two lists is complex.
- Alternative: Single global LRU list for recency, but a counter for usage per tenant.
- Fairness Logic: When
Set happens:
- Check global capacity. If full, evict global LRU.
- Check tenant quota. If tenant full, evict tenant's LRU.
- Actually, implementing a per-tenant LRU list linked to a global map is the standard way to achieve "fairness" (also called Segmented LRU or simply partitioned cache). But for a code sample, let's keep it simpler:
- Composite Key + Global LRU is the baseline.
- Fairness addition: Maintain a
sizePerTenant map. If sizePerTenant[tenant] > limit, trigger an eviction specifically for that tenant before checking global limits.
Drafting the Code (Mental or Scratchpad):
Refining the Fairness Aspect:
True fairness usually means preventing the "Noisy Neighbor" problem.
If I have a global cache of size 100.
Tenant A pushes 100 items. Tenant B pushes 1 item.
If A pushes 1 more, should it evict B's item? (Global LRU says yes).
Fairness says: No, A should evict its own oldest item.
So, we need a per-tenant eviction queue.
Implementation: A map[TenantID]*list.List (Per-tenant LRU) AND a map[TenantID]map[Key]*Entry.
Actually, let's try a hybrid.
Global Map: map[CompositeKey]*Entry.
Per-Tenant Tracker: map[TenantID]*TenantStats (Count + LinkedList of keys).
When inserting:
- Check if Tenant is over limit. If yes, remove from that Tenant's tail.
- Check if Global is over limit. If yes, remove from Global LRU tail.
Wait, if we have a Global LRU, we remove anyone.
To enforce fairness, we generally enforce a Cap per Tenant.
So,
MaxItemsPerTenant = GlobalMax / ExpectedTenants (or a fixed quota).
If Tenant > Quota -> Force evict Tenant's LRU.
Else If Global > GlobalMax -> Evict Global LRU.
Design Rationale for the User:
I should provide a high-level architectural design first, then the code.
- Architecture:
- Namespacing: Composite keys.
- Storage: Hash Map.
- Eviction: Two-tiered.
- Tier 1: Per-Tenant Quota (Fairness).
- Tier 2: Global Capacity (Hard Limit).
- Concurrency:
sync.RWMutex.
Let's write the Go Code.
-
Item struct: value, expiration, element (for list).
-
TenantState: lruList, count.
-
Cache struct:
mu sync.RWMutex
items map[string]map[string]*Item -> Double map is cleaner for per-tenant ops. map[tenant]map[key]*Item.
globalList *list.List (Optional, if we want global eviction).
quotas map[string]int (Tenant specific limits).
-
Simplification: To keep the code readable but demonstrate the concept, I will use a Per-Tenant LRU inside a Global Cache.
Structure: Cache -> map[TenantID]*TenantCache.
TenantCache -> LRU.
This ensures perfect isolation.
Correction: The prompt asks for "Fairness". Isolation implies fairness regarding eviction (Tenant A cannot evict Tenant B), but might waste memory if A is idle and B is full.
Better approach for "Fairness": A global pool with a soft limit per tenant.
Let's stick to Tenant Isolation with Global Limits.
Code structure:
type Cache struct { mu ...; data map[ScopedKey]*entry; tenants map[ID]*tenantMeta }
tenantMeta holds the LRU list for that tenant.
Logic:
Set(Tenant, Key, Val):
- Lock.
- Check Tenant Meta. Does it exist?
- Check Tenant Count. If
TenantCount > TenantLimit:
-> Evict LRU item from this tenant.
- Check Global Count. If
GlobalCount > GlobalLimit:
-> (Optional) Evict from Global LRU? Or just rely on Tenant Limits?
-> Let's rely on Tenant Limits for fairness (Strict Partitioning). This is the easiest way to guarantee correctness and fairness.
-> Wait, strict partitioning is inefficient if load is uneven.
-> Let's implement Weighted Fairness:
-> Try to set item.
-> If Global Full:
-> If TenantSize > AverageSize, evict from Self.
-> Else, evict from Global LRU (victim).
-> Too complex for a concise answer.
Chosen Strategy: Shared Pool with Per-Tenant Quotas (The "Fairness" solution).
Each tenant has a max utilization cap (e.g., 10%). If they hit it, they can only evict their own data. If they are under, they use shared space.
Code Plan:
Writing the solution sections:
- Conceptual Design: Address Scoping, Invalidation, Fairness, Correctness.
- Data Structures: Explain the composite key and the LRU separation.
- Code (Golang):
- Thread-safe.
Get, Set, Delete, FlushTenant.
- LRU logic.
- Production Considerations: Distributed locking (Redis), Stampede protection (singleflight), Metrics.
Refining the Code Details:
- Need
sync.Mutex.
- Need
container/list.
type entry struct { key, value, tenantID }
type tenantMeta struct { lru *list.List, count int }
Set logic:
-
If key exists, update value, move to front of tenant LRU. Done.
-
If key new:
- If
tenantMeta.count >= tenantLimit: evict tail of tenantMeta.lru.
- Else if
globalCount >= globalLimit:
- Policy Choice: Evict from global LRU?
- This is where "Fairness" gets hard.
- Let's implement a simplified "Soft Limit" fairness.
if tenant.count > (globalLimit / 2) -> Force self-eviction. (Don't allow one tenant to take more than half).
- Else -> Global eviction.
-
Actually, let's keep it simple for the prompt. The standard "Fair" cache is usually Partitioned. (e.g., Redis for Tenant A, Redis for Tenant B).
-
But if we are building one cache:
-
I will implement Per-Tenant Quotas.
-
If a tenant exceeds quota, they can only evict their own keys.
-
If they are under quota, they can evict globally (via a global LRU list).
-
Wait, maintaining two lists (Global and Tenant) for the same item is pointer hell.
-
Simpler approach:
Just use a Global LRU but check counts during eviction.
Set:
- If full ->
evict()
evict():
- Check tail of Global LRU.
- Does the tail belong to a tenant who is under their quota?
This implies we need to know quotas to enforce fairness.
If Tenant A is small and Tenant B is huge. Global fills up. A adds one item.
The LRU tail is likely A's old item (since B is constantly accessing/writing B items).
So A evicts A.
This is the "Noisy Neighbor" problem.
- Solution: Scanning Eviction. If we need to evict, scan backwards from LRU tail until we find a victim that belongs to a tenant over their fair share, or is just old.
-
Let's stick to the "Separate LRU per Tenant" architecture.
-
Map: .
Correctness Checks:
- Concurrency:
sync.RWMutex.
- Invalidation:
delete from map + remove from list.
- Key Scoping: Nested map
map[Tenant]map[Key].
Structure of Response:
- Theory: Scoping (Namespaces), Fairness (Quotas/Isolation), Invalidation (Cascade), Correctness (Mutex/Atomic).
- Implementation (Go):
TenantCache struct holding a map of LRUCaches.
LRUCache struct with standard implementation.
- Thread-safe wrapper.
- Discussion: Why this design? (Simplicity vs Flexibility).
Self-Correction during drafting:
The prompt asks for a cache. A fully isolated cache (map[tenant]lru) is technically multiple caches. The user might want a single shared cache pool where fairness is enforced algorithmically (like a W-TinyLFU or weighted LRU).
However, coding a W-TinyLFU from scratch is error-prone and complex for a single response.
I will implement a Shared Storage with Isolated Eviction Lists.
Storage: map[string]map[string]*entry.
Eviction: Each tenant has their own LRU list.
When Set is called:
- If
len(tenant_map) > tenant_quota: Evict from tenant_lru.
- Else: Just insert. (Assuming infinite global memory for simplicity, or add a global check).
Actually, let's add a
GlobalCapacity.
If total_items > global_capacity AND len(tenant_map) < tenant_quota: We have a problem. The tenant is "nice" (small) but the cache is full. We must evict.
Who do we evict? We must pick a "victim" tenant who is over quota.
If all are under quota, we evict globally (LRU).
This "Victim Search" makes the eviction O(N) in worst case (scanning lists), which is bad.
Back to Simple: Per-Tenant Quotas (Hard Limits).
If Tenant A hits limit, they evict themselves.
Global limit is sum of tenant limits.
This is the most practical implementation for a "build" request. It sacrifices memory efficiency (slack space) for guaranteed fairness and O(1) performance.
Final Design for Code:
- Architecture: Strict Partitioning (Buckets).
- Why: O(1) performance, guaranteed isolation (security/fairness), trivial invalidation.
- Interface:
Set(tenant, key, val), Get(tenant, key), Invalidate(tenant, key), Purge(tenant).
Let's refine the code to be high-quality Go.
Use sync.RWMutex.
Use container/list.
Step-by-step Implementation Plan:
- Define
TenantAwareCache struct.
- It holds a map of
tenantID -> *tenantShard.
tenantShard holds the data and the LRU list for that tenant.
- Implement
Get: Read lock -> lookup shard -> lookup key.
- Implement
Set: Write lock -> lookup/create shard -> check capacity -> evict if needed -> set.
- Implement
PurgeTenant: Write lock -> delete shard.
Bonus: Add a "loader" function pattern (cache-aside) to handle concurrent loading of the same missing key (preventing thundering herd). This touches on "Correctness". The singleflight pattern is perfect here.
Summary of features to build:
- Key Scoping: Nested Maps (
tenant -> key -> val).
- Invalidation: Ability to drop a whole tenant map.
- Fairness: Hard memory caps per tenant (Hard Quotas).
- Correctness:
sync.RWMutex + singleflight (to prevent duplicate computation on misses).
Let's write it.
Building a tenant-aware cache requires moving beyond a simple key -> value map. You must isolate data access, enforce resource fairness to prevent the "Noisy Neighbor" problem, and ensure thread safety.
Below is a comprehensive design and implementation in Go, focusing on four pillars:
- Key Scoping: Transparent namespacing.
- Fairness: Per-tenant memory quotas.
- Correctness: Thread safety and preventing cache stampedes (Singleflight).
- Invalidation: Targeted and global strategies.
Architecture Pattern: Strict Partitioning
To guarantee fairness, we cannot use a single global Least Recently Used (LRU) list. If we did, a high-traffic tenant could flood the cache, evicting data from a quiet tenant.
Instead, we use Strict Partitioning:
- The Cache is a collection of "Buckets" (Shards) to reduce lock contention.
- Inside each bucket, every Tenant has its own isolated LRU list and Memory counter.
- This ensures Tenant A's traffic never evicts Tenant B's data.
Implementation (Golang)
package main
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
)
var (
ErrItemNotFound = errors.New("item not found")
ErrQuotaExceeded = errors.New("tenant quota exceeded")
)
// Item represents a cached entry
type Item struct {
Key string
Value interface{}
Size int64
CreatedAt time.Time
}
// TenantState tracks the resource usage for a specific tenant
type TenantState struct {
BytesUsed int64
ItemCount int
}
// Bucket represents a partition of the cache to reduce lock contention.
// In a real system, you would have many of these (e.g., 64-256).
type Bucket struct {
mu sync.RWMutex
// data stores the actual items.
// Map Key is Composite Key: "tenantID:objectKey"
data map[string]*Item
// indexes keeps separate LRU metadata per tenant.
// This is the crucial part for FAIRNESS.
// Map Key is TenantID
indexes map[string]*TenantIndex
}
// TenantIndex manages the LRU list and stats for a single tenant
type TenantIndex struct {
State TenantState
LRUList []string // Simple slice for demo; use container/list in prod
}
// TenantAwareCache is the main cache structure
type TenantAwareCache struct {
buckets []*Bucket
bucketMask int
// Configuration
globalMaxSize int64
tenantQuota int64 // Max bytes per tenant
}
func NewTenantAwareCache(numBuckets int, globalMaxSize, tenantQuota int64) *TenantAwareCache {
buckets := make([]*Bucket, numBuckets)
for i := 0; i < numBuckets; i++ {
buckets[i] = &Bucket{
data: make(map[string]*Item),
indexes: make(map[string]*TenantIndex),
}
}
return &TenantAwareCache{
buckets: buckets,
bucketMask: numBuckets - 1,
globalMaxSize: globalMaxSize,
tenantQuota: tenantQuota,
}
}
// --- 1. KEY SCOPING ---
// makeScopedKey creates a composite key to namespace data.
// This prevents Tenant A from overwriting Tenant B's key "settings".
func (c *TenantAwareCache) makeScopedKey(tenantID, key string) string {
return fmt.Sprintf("%s|%s", tenantID, key)
}
// getBucket shards data based on key hash to reduce lock contention.
func (c *TenantAwareCache) getBucket(key string) *Bucket {
// Simple FNV hash (use a better one like xxHash/Murmur in production)
h := uint32(2166136261)
for i := 0; i < len(key); i++ {
h ^= uint32(key[i])
h *= 16777619
}
return c.buckets[h&uint32(c.bucketMask)]
}
// --- 2. CORRECTNESS & CONCURRENCY ---
// Get retrieves an item safely
func (c *TenantAwareCache) Get(tenantID, key string) (*Item, error) {
sKey := c.makeScopedKey(tenantID, key)
b := c.getBucket(sKey)
b.mu.RLock()
defer b.mu.RUnlock()
item, exists := b.data[sKey]
if !exists {
return nil, ErrItemNotFound
}
// Update LRU (promote to front)
// Note: requires promoting in the specific tenant's LRU list
if idx, ok := b.indexes[tenantID]; ok {
// Remove from back, add to front logic would go here
_ = idx // placeholder for LRU logic
}
return item, nil
}
// --- 3. FAIRNESS & EVICTION ---
// Set adds an item enforcing tenant quotas
func (c *TenantAwareCache) Set(tenantID, key string, value interface{}, size int64) error {
sKey := c.makeScopedKey(tenantID, key)
b := c.getBucket(sKey)
b.mu.Lock()
defer b.mu.Unlock()
// 1. Get or Create Tenant Index (for isolation)
idx, exists := b.indexes[tenantID]
if !exists {
idx = &TenantIndex{LRUList: []string{}}
b.indexes[tenantID] = idx
}
// 2. FAIRNESS CHECK: Enforce Quota
// If this tenant is over the limit, force an eviction from THEIR list ONLY.
// This prevents Tenant A from flooding the cache and evicting Tenant B.
if idx.State.BytesUsed+size > c.tenantQuota {
c.evictFromTenant(b, tenantID, size)
// If still over quota after eviction, reject write (or allow with strict limit)
if idx.State.BytesUsed+size > c.tenantQuota {
return ErrQuotaExceeded
}
}
// 3. Write Data
item := &Item{
Key: key,
Value: value,
Size: size,
CreatedAt: time.Now(),
}
// Update stats
idx.State.BytesUsed += size
idx.State.ItemCount++
idx.LRUList = append(idx.LRUList, sKey) // Add to LRU tail
b.data[sKey] = item
return nil
}
// evictFromTenant performs eviction STRICTLY within a tenant's scope
func (c *TenantAwareCache) evictFromTenant(b *Bucket, tenantID string, requiredSpace int64) {
idx := b.indexes[tenantID]
// Evict until we have enough space
for idx.State.BytesUsed > 0 && (idx.State.BytesUsed+requiredSpace > c.tenantQuota) {
// Pop from LRU front (oldest)
if len(idx.LRUList) == 0 { break }
keyToEvict := idx.LRUList[0]
idx.LRUList = idx.LRUList[1:]
item, exists := b.data[keyToEvict]
if exists {
idx.State.BytesUsed -= item.Size
idx.State.ItemCount--
delete(b.data, keyToEvict)
}
}
}
// --- 4. INVALIDATION ---
// Invalidate removes a specific key
func (c *TenantAwareCache) Invalidate(tenantID, key string) {
sKey := c.makeScopedKey(tenantID, key)
b := c.getBucket(sKey)
b.mu.Lock()
defer b.mu.Unlock()
item, exists := b.data[sKey]
if !exists { return }
// Update tenant stats
if idx, ok := b.indexes[tenantID]; ok {
idx.State.BytesUsed -= item.Size
idx.State.ItemCount--
// In prod, remove from LRU List
}
delete(b.data, sKey)
}
// ClearTenant completely wipes a tenant's data (useful for account deletion/reset)
func (c *TenantAwareCache) ClearTenant(tenantID string) {
// In a sharded environment, we must iterate all buckets
for _, b := range c.buckets {
b.mu.Lock()
if idx, ok := b.indexes[tenantID]; ok {
// Iterate all keys in this tenant's index and delete from map
for _, k := range idx.LRUList {
delete(b.data, k)
}
// Delete the index itself
delete(b.indexes, tenantID)
}
b.mu.Unlock()
}
}
// --- 5. ADVANCED CORRECTNESS: SINGLEFLIGHT ---
// Prevents Cache Stampede (Thundering Herd).
// If 100 requests for same missing key come in at once, only 1 calculates (DB hit),
// the other 99 wait for the result.
type call struct {
wg sync.WaitGroup
val interface{}
err error
}
type Group struct {
mu sync.Mutex
m map[string]*call
}
func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, error) {
g.mu.Lock()
if g.m == nil {
g.m = make(map[string]*call)
}
if c, ok := g.m[key]; ok {
g.mu.Unlock()
c.wg.Wait() // Wait for existing call
return c.val, c.err
}
c := new(call)
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
// Execute the expensive function
c.val, c.err = fn()
c.wg.Done()
// Cleanup
g.mu.Lock()
delete(g.m, key)
g.mu.Unlock()
return c.val, c.err
}
func main() {
// Example Usage
cache := NewTenantAwareCache(16, 1e9, 1e6) // 1GB Global, 1MB per Tenant
// Set with Scoping
cache.Set("tenant_A", "user:1", "data", 100)
cache.Set("tenant_B", "user:1", "other_data", 100) // Same key, different tenant
// Get
val, err := cache.Get("tenant_A", "user:1")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Value:", val.Value)
}
// Invalidation
cache.Invalidate("tenant_A", "user:1")
}
Design Deep Dive
1. Key Scoping (Isolation)
We do not rely on the user to manually prefix keys. The API forces Set(tenantID, key, value).
- Internal Key: We transform
tenantID and key into tenantID|key internally.
- Security: This guarantees that a request authenticated as Tenant A can never retrieve keys belonging to Tenant B, even if they guess the key name.
2. Fairness (The Noisy Neighbor Problem)
In a standard LRU cache, the most active tenant dominates the memory.
- Strict Quotas: We define
tenantQuota. When Set is called, we check that specific tenant's usage.
- Isolated Eviction: If Tenant A hits their limit, we run
evictFromTenant. This function looks only at Tenant A's LRU list. Tenant B's data remains untouched, regardless of how idle it is.
3. Correctness
- Sharding (Lock Striping): We use multiple
Bucket structs (arrays of maps) instead of one global map. This allows high concurrency; Thread 1 accessing Tenant A locks Bucket 1, while Thread 2 accessing Tenant C locks Bucket 2 simultaneously.
- Singleflight: The
Group struct demonstrates how to handle a "Thundering Herd". If a popular key expires and 100 requests come in simultaneously, you don't want to hit the database 100 times. Singleflight ensures the first request performs the load, and the other 99 wait for the result.
4. Invalidation
- Targeted:
Invalidate removes a specific key and updates the tenant's byte counter so the space is freed immediately.
- Mass Invalidation:
ClearTenant is crucial for SaaS applications. If a user deletes their account or changes their plan, you need to wipe their cache footprint efficiently without flushing the entire cache for all users.