📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Design a distributed cache from scratch, as if Redis didn't exist: it must hold hundreds of gigabytes, serve hundreds of thousands of reads per second at sub-millisecond latency, survive node failures and let you add nodes without a full reshuffle. Walk me through partitioning, replication, eviction, client routing and failure handling, and then tell me what you would actually build and what you would buy.

A staff-level distributed cache design and build-vs-buy decision: requirements and memory and throughput estimates, consistent hashing or hash slots, replication and failover, eviction (LRU/LFU approximations) and TTLs, client-side routing, hot keys and the thundering herd, consistency with the database, multi-region, and why you would buy Azure Managed Redis and build only the client-side layer (HybridCache, key design, invalidation) in .NET.

Staff / Architect SystemDesign Expert build-vs-buy consistent-hashing distributed-cache redis replication system-design

๐ŸŽฏ Key points

  • Clarify: data size, read/write ratio, latency target, value sizes, consistency tolerance, durability (cache vs store), multi-region
  • Estimate: memory per node with overhead and headroom; ops per node; network bandwidth often the limit before CPU
  • Partitioning: consistent hashing with virtual nodes, or a fixed number of hash slots (Redis Cluster uses 16,384) mapped to nodes, so adding a node moves ~1/N of keys
  • Replication: primary + replica per shard, asynchronous by default (failover can lose recent writes); WAIT or a durable store like MemoryDB when that loss isn't acceptable
  • Eviction: approximate LRU/LFU by sampling, TTLs with jitter, a maxmemory policy; memory fragmentation headroom
  • Client routing: smart clients cache the slot map and follow MOVED redirects; connection multiplexing (one connection per node)
  • Hot keys and stampedes: detect from per-key or per-shard telemetry, then local L1 cache, key replication, request coalescing, early refresh
  • Multi-region: regional caches invalidated by regional events by default; active geo-replication only for warm failover, accepting cross-region lag and conflict rules
  • Buy Azure Managed Redis (or ElastiCache/Valkey); build the client layer: HybridCache, key design, invalidation via events, observability

โฑ 30-second answer

A distributed cache is partitioned in-memory storage. Keys map to hash slots (Redis Cluster uses 16,384), and slots map to shards, so adding a node moves only the slots it takes over; consistent hashing with virtual nodes achieves the same thing. Each shard has a primary and asynchronous replicas; on failure a replica is promoted, accepting the loss of a few recent writes, which is fine for a cache. Memory is bounded by TTLs and approximate LRU/LFU eviction. Smart clients keep the slot map and follow redirects. Hot keys need a local L1 cache or key replication, and stampedes need request coalescing. Then the honest answer: I'd buy Azure Managed Redis and build only the .NET client layer: HybridCache, key design, invalidation and observability. The trade-off: building teaches the internals but gives you a tier-one system to run forever.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd pin the requirements first: [300 GB] of cached data, [400,000] reads and [20,000] writes per second at peak, p99 under [1 ms] inside the region, values mostly under [10 KB], data that can always be rebuilt from the database, and Australia East with a warm copy in Southeast. Then the shape: a cluster of shards, each a primary with one replica, holding a range of hash slots.

Partitioning is the heart of it. Naive hash(key) % N reshuffles almost every key when N changes, which empties the cache and stampedes the database. So I use a fixed number of hash slots, say 16,384 like Redis Cluster: a key's slot is CRC16 of the key mod 16,384, and a slot map assigns slot ranges to shards. Adding a shard migrates some slots, about 1/N of the data, while the rest stay put. Clients cache the slot map and route directly to the right node; if a slot has moved, the node replies with a redirect and the client updates its map. Replication is asynchronous to keep writes fast; when a primary dies, the replicas and a quorum agree to promote one, which takes seconds, and the last few writes may be lost. For a cache that's acceptable; if it isn't, it's a database, not a cache.

Memory is bounded with TTLs and eviction. True LRU needs a linked list across every key, so real systems sample a handful of keys and evict the best candidate, which approximates LRU or LFU cheaply. Hot keys are the classic failure: one key getting [50,000] reads a second pins one shard's CPU, so clients keep a short-lived local copy, the L1 in HybridCache. For example, at [company] we [had a single configuration key hammering one shard]; [adding a 5-second in-process L1] [cut that shard's CPU from 90% to 20%].

And what I'd actually do: buy Azure Managed Redis. Building a cache server means owning replication, failover, persistence and upgrades of a tier-one system. Where I'd invest engineering is the client side: key design, HybridCache with stampede protection, invalidation driven by events, and metrics on hit rate and latency.

The mistake I see is building the server and neglecting the client patterns, which is where most cache incidents actually happen."


Requirements

Type Requirement Assumption
Functional GET/SET/DELETE with TTL; batch get Values < 10 KB typical, 1 MB max
Functional Tags or prefixes for invalidation Via client layer
Non-functional 400k reads/s, 20k writes/s peak Read-heavy (20:1)
Non-functional p99 < 1 ms in region Same zone or region
Non-functional Node failure: seconds of disruption, no full cold cache Replicas
Non-functional Add capacity online Slot migration

Capacity estimate

Quantity Arithmetic Result
Raw data 300 GB Given
With overhead ร—1.5 (keys, pointers, fragmentation) 450 GB
With headroom รท0.7 (keep 30% free for spikes, forks, rebalancing) โ‰ˆ 640 GB of primary memory
Shards 640 GB รท ~50 GB usable per node โ‰ˆ 13 primaries + 13 replicas
Ops per shard 420k รท 13 โ‰ˆ 32k ops/s each (well within one node)
Bandwidth 400k ร— 2 KB avg โ‰ˆ 800 MB/s โ‰ˆ 6.4 Gbit/s total; ~0.5 Gbit/s per shard

At this size memory sets the shard count, not CPU; bandwidth and hot keys are the next limits.

High-level design

 App instances (.NET) โ”€ HybridCache: L1 in-process (seconds) โ”€โ”€โ–บ smart client (slot map, multiplexed connections)
                                                                โ”‚ CRC16(key) mod 16384 โ†’ slot โ†’ shard
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ–ผ                         โ–ผ                         โ–ผ                         โ–ผ
  Shard 1 [0โ€“1260]          Shard 2 [1261โ€“2520]        ...                 Shard 13 [...โ€“16383]
  primary โ”€asyncโ”€โ–บ replica  primary โ”€asyncโ”€โ–บ replica                        primary โ”€โ–บ replica
  (zone 1)       (zone 2)                                       
        โ–ฒ gossip + failure detection: majority of primaries agree, promote replica, update slot map
 Database (source of truth) โ”€โ”€ change events (outbox/CDC) โ”€โ”€โ–บ invalidator โ”€โ”€โ–บ DEL keys + L1 invalidation broadcast

Build vs buy

Component Build or buy Why
Cache servers, replication, failover, persistence, upgrades Buy: Azure Managed Redis (AWS: ElastiCache / MemoryDB with Valkey or Redis OSS) Tier-one infrastructure, mature, zone-redundant
L1 + L2 composition, stampede protection Use: HybridCache in .NET 10 Built in, tags, serialisation
Key naming, versioning, TTL policy Build Domain-specific
Event-driven invalidation Build Tied to your data changes
Dashboards and alerts Build on Azure Monitor Your SLOs

Production example

A pricing service serving [350,000] reads a second moved from a self-managed Redis cluster on VMs to Azure Managed Redis with HybridCache in front: p99 stayed under [1 ms], an L1 of [5 seconds] cut cache-tier traffic by [60%], and the team stopped spending [about two days a month] on patching, failover drills and rebalancing.

๐Ÿ” What the interviewer is checking

Checks staff-level understanding of distributed cache internals (partitioning, replication, eviction, routing, hot keys) together with the judgement to buy the server and build the client-side patterns.

Green flags

  • Hash slots or consistent hashing, and why modulo fails
  • Async replication with an explicit data-loss trade-off and quorum-based failover
  • Memory sizing with overhead and headroom; sampling eviction; jittered TTLs
  • Hot keys and stampede protection with an L1 and coalescing
  • Buys managed Redis, builds HybridCache usage, key design and invalidation

Red flags

  • Modulo hashing
  • Cache treated as the source of truth
  • No plan for hot keys or failover
  • Insists on building a custom cache server for production

๐Ÿ“š Learn in depth

1. Why not modulo hashing

With hash % N, going from 10 to 11 nodes changes the owner of ~91% of keys. The cache effectively empties and the database takes the full read load. Consistent schemes move only ~1/N.

2. Consistent hashing vs hash slots

Consistent hashing ring              Hash slots
  node A (vnodes a1..a100)            slot = CRC16(key) mod 16384
  key โ†’ first vnode clockwise         slot map: 0โ€“5460 โ†’ A, 5461โ€“10922 โ†’ B, 10923โ€“16383 โ†’ C
  add node โ†’ takes arcs from others   add node โ†’ migrate some slots to it

Virtual nodes even out load. Hash slots make ownership explicit and easy to migrate and inspect; Redis Cluster uses them, and hash tags ({user:42}:cart) force related keys into the same slot for multi-key operations.

3. Replication and failover

Asynchronous replication: the primary acknowledges before the replica has the write, so failover can lose the last writes. Failure detection via gossip and timeouts; a majority of primaries must agree a node is down before promoting, which avoids split brain on a network partition. Replicas in another availability zone survive zone loss. Synchronous replication would double write latency for a guarantee a cache doesn't need.

4. Memory management and eviction

  • TTL on every key, with jitter to avoid mass expiry.
  • maxmemory with a policy: allkeys-lru, allkeys-lfu, volatile-ttl. Sampling-based approximation (check a few random keys, evict the best) instead of a global list.
  • Overhead: per-key metadata, allocator fragmentation, replication buffers and fork copy-on-write during persistence can need 30%+ headroom.

5. Client routing and connections

Smart clients fetch the slot map, route each command to the owning node, pipeline requests and handle redirects during migration. One multiplexed connection per node per process (StackExchange.Redis's ConnectionMultiplexer is a singleton) rather than a connection per request.

6. Hot keys and stampedes

Problem Fix
Hot key saturates one shard L1 in-process cache for seconds; replicate the key under N suffixes and read a random one; read from replicas
Big values Compress, split, or don't cache them
Stampede on expiry Request coalescing (HybridCache does this per process), early refresh, jittered TTLs

7. Consistency with the database

Cache-aside: read through, delete on write. Race: a slow reader can repopulate stale data after a delete, so use short TTLs, versioned keys, or delete again after a delay. Event-driven invalidation from an outbox or CDC makes deletes reliable even when the writer crashes after committing.

8. Multi-region

Each region has its own cache, invalidated from regional change events; cross-region replication (active geo-replication in Azure Managed Redis) helps warm starts but adds cost and conflict rules. Usually, regional caches plus regional invalidation are simpler.

Try it yourself

  1. Simulate hash % N vs consistent hashing for 1M keys going from 10 to 11 nodes and count moved keys.
  2. Compute the slot for a few keys with CRC16 and compare with CLUSTER KEYSLOT on a local Redis Cluster.
  3. Run a local 3-shard Redis Cluster in Docker, kill a primary and time failover from the client's view.
  4. Load-test one hot key with and without a HybridCache L1 and compare shard CPU.
  5. Measure memory overhead per key for 1M small keys with INFO memory.

๐Ÿ’ป Code

A small slot router showing how keys map to shards (for understanding), and the production shape: Azure Managed Redis behind HybridCache with tags and an L1.

namespace CacheDesign;

// Educational: CRC16-CCITT (XMODEM) as used for Redis Cluster key slots, with hash-tag support.
public static class KeySlot
{
    public const int SlotCount = 16_384;

    public static int For(string key)
    {
        var s = key.IndexOf('{');
        if (s >= 0)
        {
            var e = key.IndexOf('}', s + 1);
            if (e > s + 1) key = key[(s + 1)..e]; // only the hash tag is hashed: related keys share a slot
        }
        return Crc16(System.Text.Encoding.UTF8.GetBytes(key)) % SlotCount;
    }

    private static int Crc16(ReadOnlySpan<byte> data)
    {
        int crc = 0;
        foreach (var b in data)
        {
            crc ^= b << 8;
            for (var i = 0; i < 8; i++)
                crc = (crc & 0x8000) != 0 ? (crc << 1) ^ 0x1021 : crc << 1;
        }
        return crc & 0xFFFF;
    }
}

public sealed record SlotRange(int From, int To, string Node);

public sealed class SlotMap(IReadOnlyList<SlotRange> ranges)
{
    // Smart clients cache this map and refresh it when a node answers with a MOVED redirect.
    public string NodeFor(string key)
    {
        var slot = KeySlot.For(key);
        return ranges.First(r => slot >= r.From && slot <= r.To).Node;
    }
}
// What you actually ship: buy the cluster, build the client layer.
// Program.cs (excerpt) - packages: Microsoft.Extensions.Caching.Hybrid, Microsoft.Extensions.Caching.StackExchangeRedis
builder.Services.AddStackExchangeRedisCache(o =>
    o.Configuration = builder.Configuration.GetConnectionString("Redis")); // Azure Managed Redis, Entra auth in production

builder.Services.AddHybridCache(o =>
{
    o.DefaultEntryOptions = new HybridCacheEntryOptions
    {
        LocalCacheExpiration = TimeSpan.FromSeconds(5), // L1 absorbs hot keys
        Expiration = TimeSpan.FromMinutes(10)          // L2 (Redis) TTL
    };
});
using Microsoft.Extensions.Caching.Hybrid;

namespace Pricing;

public sealed record Price(string Sku, decimal Amount, int Version);
public interface IPriceRepository { Task<Price?> GetAsync(string sku, CancellationToken ct); }

public sealed class PriceService(HybridCache cache, IPriceRepository repo)
{
    public ValueTask<Price?> GetAsync(string sku, CancellationToken ct) =>
        cache.GetOrCreateAsync(
            $"price:v2:{sku}",                         // versioned key: change the shape, bump v2
            async token => await repo.GetAsync(sku, token), // one factory call per key per process (stampede protection)
            tags: [$"sku:{sku}"],
            cancellationToken: ct);

    // Called from the change-event consumer after the database commit.
    public ValueTask InvalidateAsync(string sku, CancellationToken ct) => cache.RemoveByTagAsync($"sku:{sku}", ct);
}

โš  Common mistakes

  • Mistake: hash(key) % N for partitioning. Why it is wrong: adding or removing a node moves almost every key and empties the cache. Instead: hash slots or consistent hashing with virtual nodes.
  • Mistake: Defaulting to synchronous replication without a reason. Why it is wrong: it adds a replica round trip to every write and couples write availability to replica health, for durability a pure cache usually doesn't need. Instead: asynchronous replication by default, and accept losing recent writes on failover. When some keys really need it (rate-limit counters, locks), use Redis WAIT to require replica acknowledgement for those writes only, knowing it still doesn't give strong consistency; if data loss is unacceptable overall, you need a durable store (Amazon MemoryDB, a database), not a cache.
  • Mistake: Treating the cache as the source of truth. Why it is wrong: eviction and failover lose data by design. Instead: always be able to rebuild from the database; if you can't, use a database.
  • Mistake: Sizing memory for raw data only. Why it is wrong: key overhead, fragmentation and replication buffers push nodes into eviction or out-of-memory. Instead: ร—1.5 overhead and 30% headroom, measured with INFO memory.
  • Mistake: Ignoring hot keys. Why it is wrong: one key can saturate a shard while the cluster looks idle. Instead: L1 cache, key replication, read replicas, and hot-key monitoring.
  • Mistake: Same TTL for everything. Why it is wrong: mass expiry causes synchronised misses and stampedes. Instead: jittered TTLs and early refresh.
  • Mistake: A new Redis connection per request. Why it is wrong: connection storms and latency. Instead: one multiplexed ConnectionMultiplexer per process.
  • Mistake: Replicating the cache across regions by default. Why it is wrong: cross-region lag (tens of milliseconds between Australia East and Southeast, much more overseas) means stale reads and conflict rules, at extra cost. Instead: a cache per region invalidated from regional change events, and geo-replication only when warm failover justifies it.
  • Mistake: Building your own cache server for production. Why it is wrong: you now operate replication, failover and upgrades of a tier-one system. Instead: buy managed Redis and invest in the client layer.

๐Ÿ› Senior insight: trade-offs

The interviewer wants two things: proof you understand the internals (slots, replication trade-offs, eviction, routing, hot keys) and the judgement not to build it. The same reasoning applies to the API gateway variant of this question: understand routing, connection pooling, auth offload and rate limiting, then buy Azure API Management or Front Door, or use YARP as a library when you need custom routing in .NET, rather than writing a proxy.

Option When it fits Cost When not to
Azure Managed Redis (clustered) Shared L2 cache, sessions, rate limits Per-node pricing, sized by memory Tiny apps (L1 only may do)
In-process L1 only Single instance or tolerant staleness Duplicate memory per instance Many instances needing coherence
HybridCache L1 + Redis L2 Most multi-instance .NET services Invalidation design Data that must never be stale
Build your own Learning, or a truly novel requirement A team to run it forever Almost every production case

I measure hit ratio per key prefix, p50/p99 latency from the client, evictions and memory fragmentation, per-shard CPU and network (to spot hot shards), failover duration in drills, and database load when the cache is cold.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions an L1 in-process cache Why: Checks local vs distributed caching across many instances and keeping L1 caches in sync
    How to answer

    With 20 instances, a local cache is fastest but each instance holds its own version, while a distributed cache (Redis) gives one shared version at the cost of a network hop. I usually combine them: a short-lived L1 in each instance in front of a shared L2, which is exactly what HybridCache provides.

    To keep L1 copies in line, I publish invalidation messages (Redis pub/sub or an Azure Service Bus topic) that every instance uses to evict keys. Messages can be missed, so the L1 lifetime is the real staleness bound.

    I choose per data class: data that must agree everywhere skips L1, tolerant data gets longer L1. The trade-off is latency and Redis load versus how long instances may disagree.

  2. When: Candidate says they would buy Azure Managed Redis Why: Checks IDistributedCache, Redis capabilities and choosing an Azure Redis offering
    How to answer

    IDistributedCache is a minimal, byte-array cache API: GetAsync, SetAsync, RefreshAsync, RemoveAsync with absolute or sliding expiration. With AddStackExchangeRedisCache the values live in Redis, so every instance shares them and they survive deployments.

    • You own serialisation (System.Text.Json, ideally source-generated, or MessagePack), and its CPU and size cost.
    • Each read is a network round trip, roughly 0.5-2 ms in the same Azure region, so hot keys still benefit from an in-memory L1.
    • Redis is more than a cache: atomic counters, sorted sets, pub/sub, streams.

    For new Azure work I'd pick Azure Managed Redis, because Azure Cache for Redis is retiring. The trade-off is shared consistency versus a network hop and another dependency.

  3. When: Candidate mentions the gateway version of build vs buy Why: Checks the API gateway variant: what belongs in a gateway, APIM vs YARP
    How to answer

    An API gateway is a single entry point in front of your services that routes requests and applies cross-cutting concerns: TLS termination, token validation, rate limiting and quotas, request ids, IP filtering, header rewriting and sometimes caching. Azure API Management is a managed gateway with XML policies, products and subscriptions, a developer portal and analytics; YARP is a .NET reverse-proxy library you host yourself and extend in C#. A backend-for-frontend (BFF) is a gateway per client (web, mobile) that aggregates and shapes data for that client. The danger is a smart gateway: business rules and orchestration in policies become untested, hard-to-version logic owned by nobody. Keep the gateway thin and services authoritative.

๐Ÿ›  Real-world problems: how you handle them

One hot key saturated a single cache shard during a sale
Situation
A [retail pricing] service on [ASP.NET Core] with a [6-shard] Redis cluster serving [300,000] reads a second during a [Black Friday] sale.
Signals
p99 cache latency jumped from [0.8 ms] to [40 ms]; one shard at [95%] CPU while others sat at [20%]; API timeouts on product pages; database reads rising as clients fell back.
Investigation
Azure Monitor per-shard metrics showed the imbalance; Redis `--hotkeys`/`MONITOR` sampling on a replica identified a [global promotions] key read on every page view; client telemetry confirmed the key's request rate.
Resolution
Immediate: deployed a 5-second in-process cache for the promotions key. Long term: moved the service to HybridCache with an L1 for all hot reference data, jittered TTLs, event-driven invalidation by tag, and migrated to Azure Managed Redis with zone redundancy.
Prevention
Per-shard CPU and network alerts, a load test with realistic key skew before peak events, a review checklist item for keys read on every request, and quarterly failover drills.

How to tell it (STAR)

**S:** At [company], during a [Black Friday] sale, product pages timed out because one cache shard was at [95%] CPU while the rest were idle. **T:** I had to restore latency during the sale and stop it recurring. **A:** Per-shard metrics and hot-key sampling showed a single promotions key read on every page. I shipped a 5-second in-process cache for it within the hour, then moved the service to HybridCache with an L1 for hot reference data, jittered TTLs and tag-based invalidation, and moved to managed Redis with zone redundancy. **R:** p99 went from [40 ms] back under [1 ms], cache-tier traffic dropped [60%], and the next sale ran without cache incidents.

โ†ฉ Usually asked after

More in Systems to Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me