Messaging Backend with a Tiered, Partitioned Cache Layer
System DesignModel answerLast updated
Design a durable, ordered, deduplicated messaging backend for DMs and small groups, and explain how a local and distributed cache is partitioned and kept correct under failures.
Problem
Design the backend of a team messaging product that supports one-to-one conversations and small group conversations (at most 50 members). Every acknowledged message must be durable, ordered identically for everyone in the conversation, and delivered quickly to anyone who is online. People who were offline must be able to catch up without seeing duplicates, and a sender who retries after a timeout must not create a second copy.
Caching is the main theme. You should say what belongs in per-server memory and what belongs in a shared distributed cache, how cache keys are split across nodes, and how you keep results correct during invalidation, failover, and traffic spikes on a single busy conversation.
Functional requirements
- Send text messages to one person or to a group of up to 50.
- Within one conversation, all participants see messages in the same strictly increasing order.
- A returning user can sync what they missed, with no duplicates.
- Retries caused by network timeouts must be deduplicated.
Non-functional requirements
- 50 million daily active users and 500 million messages per day (about 6,000 writes/s on average, about 20,000 writes/s at peak).
- p99 delivery latency under 100 ms for online recipients; p99 history fetch under 150 ms.
- No acknowledged message may ever be lost (RPO = 0), and the service must stay highly available.
What to cover
- Architecture and data flow: ingestion, persistence, real-time fan-out over persistent connections such as WebSockets, and offline inbox sync.
- Data model and ordering: how per-conversation sequence numbers are produced and how idempotency keys are handled.
- Caching design:
- the roles of local in-process caches (gateway and service nodes) versus a shared cache such as Redis or Memcached;
- the partitioning scheme (for example by conversation ID with consistent hashing);
- eviction, TTLs, and write-through versus write-around behavior.
- Failure handling: cache misses, stale data after a partition rebalance, stampedes on a hot group, and a network partition between the cache and the durable store.
Hints
Hint 1
Do the capacity math first: peak writes times average recipients gives delivery rate, and concurrent sockets divided by sockets per node gives the gateway count. Those numbers tell you the hot read set is small and cacheable.
Hint 2
Never use wall clocks for ordering. Keep a per-conversation counter on the same shard as the messages and allocate the sequence number, the message row and the idempotency record in a single transaction before acknowledging.
Hint 3
Treat the cache as pure acceleration that never acknowledges writes. Co-locate a conversation's keys with a hash tag, make appends conditional on sequence contiguity, and make readers compare the cached max sequence to a known last sequence so any hole turns into a miss.
Hint 4
For hot conversations combine single-flight loading on misses, short jittered local tail caches, and request coalescing. When the database is down, reject writes rather than acknowledge from the cache.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing
- Writes: 20k msgs/s at peak. With roughly 4 recipients per message on average, that is about 80k deliveries/s.
- Storage: 500M messages/day at about 1 KB each including indexes is about 0.5 TB/day, roughly 180 TB/year before replication. A horizontally sharded store is required.
- Connections: perhaps 10-15M concurrent sockets. At about 100k sockets per gateway, that is around 150 gateways.
- Reads: history and catch-up dominate, and almost all of them touch the most recent few dozen messages of active conversations. The hot set is small, so caching pays off.
- Hard rules: RPO = 0 means no ack before a durable quorum commit. Ordering is per conversation, not global, which lets us shard by conversation.
2. Data model and ordering
Shard everything by conversation_id (Cassandra with LWT, CockroachDB, Spanner or Vitess all work).
conversations(conversation_id, last_seq, type, participant_version)participants(conversation_id, user_id, joined_seq)messages(conversation_id, seq, sender_id, client_msg_id, body, server_ts)with primary key(conversation_id, seq)idempotency(conversation_id, sender_id, client_msg_id)unique, mapping tosequser_conversations(user_id, conversation_id, last_seq)as the per-user inbox index for catch-up
Sequence allocation. Because a conversation's rows live on one shard, one transaction can:
- look up the idempotency key and, if present, return the stored
seq; - increment
last_seq; - insert the message and the idempotency row.
After quorum commit the server acks the sender with seq. Sequences are gap-free and monotonic, and a retried send resolves to the same seq. An optional per-partition "owner" with a lease can batch allocations, but the transaction stays as the correctness backstop.
3. Data flow
- Client sends over WebSocket to a gateway, which forwards to the message service routed by
conversation_id. - The service commits the transaction, acks the sender, then publishes to a log (Kafka, partitioned by
conversation_idto keep order) and conditionally appends to the cache. - Fan-out workers consume the log, load participants (cache), look up presence (
user_id -> gateway), group recipients per gateway, send one RPC per gateway, and update each recipient's inbox index. - Gateways push to sockets. Clients remember
last_seen_seqper conversation; if they see N+2 after N they pull the missing range. - On reconnect the client calls a sync endpoint to list conversations whose
max_seqexceeds its cursor, then pages byafter_seq. Clients upsert by(conversation_id, seq), so overlap between push and pull is harmless.
4. Caching design
Local (per-process, never authoritative)
- Gateway: user-to-connection map, session/auth data, a small outbound buffer for retransmit until the client acks.
- Message and fan-out services: participant lists and conversation metadata with a 5-30 s TTL, invalidated by pub/sub keyed on
participant_version. For very hot conversations, a tiny recent-tail cache with a 1-2 s jittered TTL absorbs read bursts.
Distributed (Redis Cluster)
| Key | Value | TTL / eviction |
|---|---|---|
msgs:{cid} | sorted set of last ~200 messages by seq | 24 h sliding, LFU |
meta:{cid} | participants, version, last_seq | 1 h, invalidated on change |
presence:{uid} | gateway id | 60 s, refreshed by heartbeat |
idem:{cid}:{sender}:{id} | seq | 24 h, fast path only |
Partitioning. The {cid} hash tag puts a conversation's keys in one slot so a Lua script can touch messages and metadata atomically. The 16,384 hash slots give consistent-hashing-like rebalancing. Presence is partitioned by user ID separately. The database unique constraint, not the cache, is the source of truth for idempotency.
Write semantics
- Messages: database first, then a conditional append. A script appends only if the key exists and
new_seq == cached_max + 1; otherwise it deletes the key. This is append-through for warm conversations and write-around for cold ones, and it prevents silent holes. - Metadata: invalidate by delete, with a version check so a slow reader cannot repopulate older data over newer.
- The cache never acknowledges a write.
5. Failure handling
Cache miss. Read-through with single-flight: the first reader takes a short lock (SET lock:{cid} NX PX 2000), loads the last N messages, and seeds the key with a short TTL that is extended only after contiguous appends. Others wait briefly on the lock or a local future, then re-read. On lock timeout they fall back to a rate-limited read replica.
Stale data after rebalance or failover. An async replica can lose recent appends. Defenses:
- Cached entries carry
max_seq; readers compare againstlast_seqfrom metadata or the push hint and treat a mismatch as a miss. - The contiguity check on append turns holes into deletions.
- Clients detect gaps and backfill from the database.
- Optionally embed a cluster epoch in keys to bulk-invalidate on failover.
Hot group stampede. Layer single-flight locks, jittered local tail caches, and per-instance coalescing of identical in-flight requests. Because fan-out pushes bodies directly, most online users never read history.
Cache-to-database partition.
- Cache unreachable: trip a circuit breaker, read the database under token-bucket limits. Latency degrades, correctness does not.
- Database unreachable: reject writes, since RPO = 0 forbids acknowledging from cache. Reads can be served from cache, flagged as possibly stale, and clients keep retrying with the same idempotency key.
6. Trade-offs and common mistakes
- Using timestamps or a global counter for ordering: clocks skew, and a global counter becomes a bottleneck. Per-conversation sequences scale with sharding.
- Acking after the cache write instead of the durable commit, which breaks RPO = 0.
- Setting cache entries on write without a contiguity check, leaving permanent holes.
- Relying on cache-based idempotency alone; it must be backed by a unique constraint.
- Using one giant TTL: short TTLs on metadata bound staleness, while long sliding TTLs on message tails keep hit rates high.
- Ignoring hot keys: a single slot can saturate, so use local tails and coalescing rather than only adding nodes.
- Expecting a sizable hit rate from an LRU on cold conversations; the working set is the recent tail of active chats, so size the cache for that (for example 200 messages x 1 KB x tens of millions of active conversations is a few TB spread across the cluster).