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.
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.
"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) % Nreshuffles 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."
| 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 |
| 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.
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
| 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 |
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.
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
Red flags
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.
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.
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.
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.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.
| 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 |
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.
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.
hash % N vs consistent hashing for 1M keys going from 10 to 11 nodes and count moved keys.CLUSTER KEYSLOT on a local Redis Cluster.INFO memory.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);
}
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.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.INFO memory.ConnectionMultiplexer per process.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.
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.