Architecting a Real-Time Messaging System at Scale
System DesignModel answerLast updated
Design a messaging backend that sustains 1M concurrent connections and 50K messages per second with sub-100ms end-to-end latency.
Context
Your team is building a communication platform — think real-time chat combined with a system notification layer. Product has signed off on the following requirements and you need to walk through the architecture in a technical discussion.
Functional Requirements
- Users can send and receive messages in real time.
- Users can retrieve their message history for any conversation.
- Critical system notifications (e.g., payment confirmations, security alerts) must be delivered reliably.
Non-Functional Requirements
- Scale: Support 1 million concurrent connections and sustain 50,000 messages per second (MPS).
- Latency: End-to-end message delivery in under 100 ms.
- Availability: The system must remain operational during partial failures and rolling deployments.
- Durability: No messages lost, even if a downstream consumer temporarily falls behind.
What You Are Asked to Do
Describe a high-level architecture that satisfies the requirements above. Your answer should cover the following four areas:
-
Message Broker: What technology handles buffering and fan-out between producers and consumers? Justify your choice and explain how you would partition the data.
-
Storage Layer: How and where do you persist messages? Compare a relational approach to a NoSQL approach for this specific workload and explain which you would choose and why.
-
Connection Management: How do you maintain and route 1 million persistent connections across a fleet of gateway servers? What does load balancing look like, and where do you store connection state?
-
Backpressure: What happens when a consumer cannot process messages as fast as they arrive? Describe the mechanisms at each layer of the system that prevent cascading failure.
Be concrete: name technologies, estimate numbers, and call out trade-offs. A strong answer will also identify where the most common failure modes live.
Hints
Hint 1
Start with back-of-the-envelope math before touching architecture. 50K MPS × 1 KB per message gives you ~50 MB/s of ingest, but the real bottleneck is fan-out: if each message has 5 recipients on average, that's 250K deliveries per second. Let that number drive your design choices.
Hint 2
A single server can hold roughly 50–100K WebSocket connections when properly tuned. That immediately tells you how many gateway nodes you need for 1M connections — and reminds you that gateways should be stateless so you can scale them independently from your business logic.
Hint 3
Separate the real-time delivery path from the history/persistence path. They have different consistency requirements, different read/write patterns, and different failure modes. Trying to serve both from one data store is where many designs go wrong.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Step 1: Turn Requirements into Numbers
Good system design starts with arithmetic, not boxes and arrows. Here are the key numbers that shape every decision that follows.
Ingest: 50K MPS × 1 KB average message size = ~50 MB/s of write traffic. That is modest for a well-configured broker cluster.
Fan-out: Assuming an average of 5 recipients per message, delivery volume is ~250K events/s. Fan-out is almost always the real bottleneck, not raw ingest.
Storage: 50K × 86,400 seconds ≈ 4.3 billion messages per day. At 1 KB each, that is ~4.3 TB/day raw, or ~13 TB/day with 3x replication.
Connections: A well-tuned gateway (Go, Netty, or Erlang/OTP) can hold roughly 50–100K WebSocket connections. For 1M connections you need ~20 gateway nodes at capacity, so plan for ~30 including headroom and rolling deploy tolerance.
Latency budget (100 ms end to end):
- Client → gateway: ~25 ms
- Broker produce with durable acks: ~5–10 ms
- Routing lookup and forward: ~5 ms
- Gateway → recipient: ~25 ms
- Remaining ~35 ms covers network jitter and retries.
Step 2: High-Level Architecture
The system splits into two delivery paths that share the same broker but serve different consumers:
Clients ──L4 LB──► WebSocket Gateways ──► Chat Service ──► Kafka
▲ │
│ ┌────────────────┤
│ ▼ ▼
Delivery/Router ◄── Session Registry Persistence
(online push) (Redis) Consumers ──► Cassandra
│
└──► Offline Push (APNs / FCM)
Push path serves online users. The Delivery service consumes from Kafka, looks up where each recipient is connected in the session registry, and forwards the message to that gateway over gRPC or a Redis pub/sub channel.
Pull path serves history and reconnect sync. Cassandra is the source of truth for message history. When a client reconnects or detects a gap in the sequence, it calls GET /conversations/{id}/messages?before=&limit=50 and reconciles locally.
Keeping these two paths separate lets each scale and fail independently.
Step 3: Message Broker
Use Kafka (or Pulsar, which shares the same log-based model).
- It is a durable, replicated log. A slow consumer never causes data loss.
- Pull-based consumers apply backpressure naturally — they only fetch what they can process.
- The log is replayable, so a crashed consumer or a new storage consumer can catch up without re-ingesting from clients.
- 50 MB/s is well within range for a small cluster.
Why not the alternatives:
- RabbitMQ has excellent per-message routing, but queue depth degrades performance and there is no replay capability.
- Redis Pub/Sub has lower latency but is fire-and-forget with no durability guarantees. Redis is still useful as the gateway routing fabric for ephemeral events like typing indicators and presence, where losing an event is fine.
Partitioning strategy: Key by conversation_id. This preserves per-conversation message order and distributes load evenly across partitions. Do not key by sender — a high-volume account creates a hot partition. Use 128–256 partitions to allow that many parallel consumers per group while staying well under Kafka's per-partition throughput ceiling.
Use separate topics for chat and critical notifications with independent consumer groups and SLOs. A chat traffic spike should never delay a payment alert.
Step 4: Storage Layer
The dominant access pattern is: "append a new message" and "read the last N messages in a conversation, sorted by time." This is append-only, write-heavy, and almost never uses joins. That points squarely to a wide-column NoSQL store like Cassandra or ScyllaDB.
messages
PRIMARY KEY ((conversation_id, bucket), message_id)
CLUSTERING ORDER BY (message_id DESC)
columns: sender_id, body, type, created_at
bucket is a time window (e.g., month) that prevents any single partition from growing unbounded. message_id is a Snowflake-style time-sortable ID.
| Aspect | PostgreSQL | Cassandra |
|---|---|---|
| Horizontal write scale | Manual sharding required | Native, add nodes linearly |
| Write amplification | High (B-tree maintenance) | Low (LSM-tree, sequential) |
| Flexible queries | Yes | Limited |
| Replication / multi-DC | Complex | Built-in, tunable consistency |
| Fit for this access pattern | Poor at this volume | Excellent |
Keep PostgreSQL for relational data with low write volume: user accounts, conversation membership, and settings.
Step 5: Connection Management
Gateway design: Gateways are intentionally dumb — they hold sockets, authenticate connections, and forward frames. All business logic lives in stateless downstream services. This separation is what makes independent scaling possible.
Session registry: Store user_id → {device_id → gateway_id} in Redis with a TTL refreshed by heartbeats (every 30 s). The Delivery service reads this to route each message to the right gateway. If a user has no entry, they are offline — route to APNs/FCM and let them sync on reconnect.
Load balancing: Use an L4 load balancer with least-connections routing. An L7 balancer would terminate millions of long-lived connections, adding unnecessary overhead. Sticky sessions are not needed because routing state is in Redis, not on the gateway.
Deployments: Drain gateways gracefully. Clients reconnect with jittered exponential backoff to avoid a thundering herd when nodes come back.
Step 6: Backpressure
Apply backpressure in layers so that no single point absorbs all the pressure.
-
Ingress (gateway): Token-bucket rate limits per user and per tenant. When a client exceeds its limit, the gateway returns a
RETRY_AFTERsignal rather than accepting and queuing indefinitely. -
Broker (Kafka): Pull-based consumers naturally self-throttle — they request the next batch only after finishing the previous one. Lag metrics on consumer groups are the primary operational signal. Alert when lag grows faster than it drains.
-
Storage consumers: If persistence consumers fall behind, Kafka retains the data safely on disk. The consumer can catch up at its own pace without affecting the real-time delivery path — this is one of the main reasons to separate the two paths.
-
Delivery service: If a gateway's inbound queue is full, the Delivery service sheds load for that recipient and marks the message as undelivered. The recipient will sync on reconnect. For critical notifications, use a dedicated higher-priority queue that is never shed.
Common mistakes to avoid:
- Keying Kafka partitions by sender rather than conversation, creating hot partitions under broadcast accounts.
- Combining real-time delivery and history reads in the same data store, causing read latency to spike under write load.
- Using a stateful gateway that stores routing information locally, making rolling deploys painful and reconnect storms worse.
- Treating backpressure as a single mechanism rather than a layered concern — skipping rate limiting at the edge means all pressure lands on the broker.