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

๐Ÿ“š Interview question

Design a chat system like a customer-support or team messaging app: one-to-one and group conversations, real-time delivery to web and mobile, message history, read receipts and offline users. How do you deliver messages in real time with SignalR at scale, store history, keep ordering, and handle reconnects?

A full chat system design: requirements, connection and message estimates, real-time delivery with ASP.NET Core SignalR and Azure SignalR Service, message storage partitioned by conversation in Cosmos DB, per-conversation sequence numbers, client message ids for dedup, offline delivery via push, read receipts, presence and failure modes.

Senior SystemDesign Advanced azure-signalr-service chat cosmos-db real-time signalr system-design

๐ŸŽฏ Key points

  • Clarify: 1:1 and group size limit, history retention, read receipts, presence, attachments, mobile push
  • Estimate: 1M concurrent connections, ~20k messages/s peak, group fan-out multiplies deliveries
  • Persist first, then deliver: write the message, then publish to the conversation's SignalR group
  • Azure SignalR Service (unit-based cost) or Redis backplane with sticky sessions for scale-out
  • Storage partitioned by conversationId (Cosmos DB); watch the 20 GB logical partition limit
  • Order by per-conversation sequence; global ordering would need a single sequencer and isn't a user requirement; client message id dedups retries
  • Reconnect: client sends last seen sequence, server returns the gap; stale connections removed via keep-alive timeouts
  • Read receipts as lastReadSeq per member, batched/debounced; offline users get push via Notification Hubs

โฑ 30-second answer

Chat is durable messaging with a real-time shortcut. The send path persists the message first, assigns a per-conversation sequence number, then publishes to the conversation's SignalR group; if real-time delivery fails, nothing is lost because clients catch up from storage using their last seen sequence. Scale-out uses Azure SignalR Service so app servers don't hold a million WebSockets. History lives in Cosmos DB partitioned by conversationId, which makes "latest 50 messages" a single-partition query. Clients send a client message id so retries don't duplicate. Offline users get a push notification. The trade-off: ordering is guaranteed within a conversation, not globally, and presence is approximate, which is what users actually need.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd clarify the product first: one-to-one and groups up to, say, 500 members, history kept for a year, read receipts, typing indicators, presence, and mobile push for offline users. Attachments go to Blob Storage, so I'd leave them aside. For scale, say 10 million users with 1 million connected at peak, each sending 40 messages a day: 400 million a day is about 4,600 a second average and maybe 20,000 at peak. Group fan-out means deliveries are several times that.

The core rule is persist, then deliver. When a client sends, the API validates membership, writes the message to Cosmos DB partitioned by conversation id with the next sequence number for that conversation, and only then publishes to the SignalR group for the conversation. The client includes its own message id so a retry after a timeout doesn't create a duplicate. Delivery is best effort: if a client was disconnected, it reconnects with the last sequence it saw and fetches the gap from storage. For example, at [company] we [initially broadcast before saving, and lost messages during a deployment]; switching to persist-then-deliver with gap fill on reconnect [took missing-message complaints to zero].

For connections I'd use Azure SignalR Service in default mode: clients hold WebSockets to the service, our ASP.NET Core hubs stay stateless, and each unit handles about a thousand concurrent connections, so a million connections is a capacity and cost conversation, not a server-farm problem. Offline members get a push through Notification Hubs.

The mistake I see is using timestamps from clients to order messages, or trying for global ordering. Users only care about order within a conversation, and a sequence number per conversation gives exactly that."


Requirements

Type Requirement Assumption
Functional 1:1 and group chat (โ‰ค 500 members) Larger 'channels' are a different design
Functional History, search later 1 year retention
Functional Read receipts, typing, presence Typing and presence are ephemeral, not stored
Functional Offline push Notification Hubs
Non-functional Delivery p95 < 300 ms online Same region
Non-functional No message loss, no duplicates shown Persist first; client message id

Capacity estimate

Quantity Arithmetic Result
Messages/day 10M users ร— 40 400M
Average send rate 400M รท 86,400 โ‰ˆ 4,600/s
Peak send rate ร—4 โ‰ˆ 20,000/s
Deliveries at peak 20k ร— avg 5 recipients โ‰ˆ 100,000/s
Storage/year 400M ร— 365 ร— 1 KB โ‰ˆ 146 TB (before compression/indexes)
SignalR units 1M connections รท ~1,000 per unit โ‰ˆ 1,000 units (check current limits and pricing)

High-level design

Web / mobile clients โ”€โ”€WebSocketโ”€โ”€โ–บ Azure SignalR Service โ—„โ”€โ”€โ”€โ”€ hub servers (ASP.NET Core, stateless)
        โ”‚                                                              โ”‚
        โ””โ”€โ”€ REST: history, gap fill, send fallback โ”€โ”€โ–บ Chat API โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
                                                         โ”‚             โ”‚
                                                         โ–ผ             โ–ผ
                                      Cosmos DB: messages (pk = conversationId)
                                      conversations + members (pk = userId for inbox)
                                                         โ”‚ change feed
                                                         โ–ผ
                                      Offline fan-out โ”€โ”€โ–บ Notification Hubs (APNs/FCM)
                                      Search indexer โ”€โ”€โ–บ Azure AI Search (optional)

Key decisions

Decision Choice Alternative Why
Connections Azure SignalR Service Redis backplane + sticky sessions Offloads connection count and scale-out
Storage Cosmos DB, pk = conversationId Azure SQL Write-heavy, partition-friendly, global option
Ordering Sequence per conversation Client timestamps Clocks skew; per-conversation order is the requirement
Delivery Persist then publish Publish then persist No loss on crash

Production example

A support-chat platform with [150,000] concurrent connections delivered messages at p95 [180 ms] in Australia East. Moving connections to Azure SignalR Service let the hub tier shrink from [24] to [6] pods, and gap fill on reconnect meant deployments no longer caused lost messages.

๐Ÿ” What the interviewer is checking

Checks that the candidate can design reliable real-time delivery on top of durable storage, with correct ordering and scale-out.

Green flags

  • Persist then deliver, with gap fill on reconnect
  • Per-conversation sequence and client message ids for dedup
  • Scales connections with Azure SignalR Service or a backplane and explains why
  • Partitions storage by conversation and handles offline push

Red flags

  • Relies on SignalR for durability
  • Global ordering or client clocks
  • No membership authorisation
  • Ignores fan-out cost for groups

๐Ÿ“š Learn in depth

1. Persist, then deliver

Client โ”€โ”€ send(clientMsgId, conversationId, text) โ”€โ”€โ–บ Hub/API
   1. check membership (cached)
   2. seq = next sequence for conversation
   3. upsert message {id: clientMsgId, conversationId, seq, ...}  โ† idempotent on retry
   4. ack to sender with seq
   5. Clients.Group(conversationId).MessageReceived(message)

If step 5 fails or a recipient is offline, the message is still stored. Real-time is an optimisation over a durable log.

2. Sequence numbers per conversation

Options: a counter document per conversation updated with optimistic concurrency (ETag) or a Cosmos DB transactional batch in the same partition; or a Redis INCR on seq:{conversationId}. Both are single-partition operations, so they scale with the number of conversations. Gaps (a failed write after allocating a number) are fine; clients sort and dedupe by seq and fill holes by asking for a range.

3. Reconnects and gap fill

SignalR clients reconnect automatically (WithAutomaticReconnect), but messages sent while disconnected are not replayed by SignalR. On reconnect, the client calls GET /conversations/{id}/messages?afterSeq=1234 for each active conversation, or a single 'sync since' call against a per-user inbox. This is what makes delivery reliable.

4. Scaling connections

Each WebSocket holds memory and a socket on the server. With self-hosted SignalR across many servers you need sticky sessions (for negotiate and non-WebSocket transports) and a backplane (Redis) so a group message reaches users connected to other servers; the backplane carries every message to every server, which limits scale. Azure SignalR Service removes both: clients connect to the service; the hub server sends one message to the service, which fans it out. Serverless mode with Azure Functions is an option for simpler apps.

5. Storage layout

  • messages container, partition key /conversationId, sorted by seq: latest page is one partition query.
  • Hot conversations are bounded: a logical partition in Cosmos DB is limited to 20 GB, so very long-lived groups need hierarchical partition keys (conversationId, month) or bucketing.
  • inbox per user (pk /userId) holds last message and unread count per conversation, updated from the change feed. Read receipts update a per-member lastReadSeq, not each message.

6. Presence and typing

Ephemeral: heartbeats every 30 s set a key with a 60 s TTL in Redis; typing events go straight through SignalR and are never stored. Presence is approximate by design.

7. Security and privacy

Authenticate the hub with JWT (access token via query string only for WebSockets, never logged), authorise every send against membership, and treat chat content as personal information: encryption at rest, retention policy, deletion on request, and support staff access audited.

8. AWS mapping

API Gateway WebSocket APIs or self-hosted SignalR on ECS with ElastiCache backplane, DynamoDB (pk conversationId, sk seq), SNS mobile push.

Try it yourself

  1. Build the hub below with two browser tabs; kill the server between messages and verify gap fill restores them.
  2. Run two hub instances without a backplane and show group messages are lost across instances; add Azure SignalR Service (or the emulator) and repeat.
  3. Send the same clientMsgId twice and confirm only one message appears.
  4. Load-test connections with a small console app using HubConnectionBuilder, watching dotnet-counters Microsoft.AspNetCore.Http.Connections counters.
  5. Query the latest 50 messages in Cosmos DB and note the RU charge for single-partition vs cross-partition queries.

๐Ÿ’ป Code

A strongly typed hub that authorises, persists with an idempotent id, then delivers; plus the gap-fill endpoint.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;

namespace Chat;

public sealed record ChatMessage(string Id, string ConversationId, long Seq, string SenderId, string Text, DateTimeOffset SentAt);

public interface IChatClient { Task MessageReceived(ChatMessage message); }

public interface IMessageStore
{
    // Upsert keyed by (conversationId, clientMessageId): a retry returns the original message and seq.
    Task<ChatMessage> AppendAsync(string conversationId, string clientMessageId, string senderId, string text, CancellationToken ct);
    Task<IReadOnlyList<ChatMessage>> AfterAsync(string conversationId, long afterSeq, int take, CancellationToken ct);
}

public interface IMembership { Task<bool> IsMemberAsync(string conversationId, string userId, CancellationToken ct); }

[Authorize]
public sealed class ChatHub(IMessageStore store, IMembership membership) : Hub<IChatClient>
{
    public async Task Join(string conversationId)
    {
        if (!await membership.IsMemberAsync(conversationId, Context.UserIdentifier!, Context.ConnectionAborted))
            throw new HubException("Not a member.");
        await Groups.AddToGroupAsync(Context.ConnectionId, conversationId);
    }

    public async Task<long> Send(string conversationId, string clientMessageId, string text)
    {
        var userId = Context.UserIdentifier!;
        var ct = Context.ConnectionAborted;
        if (!await membership.IsMemberAsync(conversationId, userId, ct))
            throw new HubException("Not a member.");

        var message = await store.AppendAsync(conversationId, clientMessageId, userId, text, ct); // 1. persist
        await Clients.Group(conversationId).MessageReceived(message);                             // 2. deliver (best effort)
        return message.Seq;                                                                       // ack with seq
    }
}
// Program.cs
using Chat;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
builder.Services.AddSignalR().AddAzureSignalR(); // Microsoft.Azure.SignalR; connection string from config/Key Vault
builder.Services.AddSingleton<IMessageStore, CosmosMessageStore>();
builder.Services.AddSingleton<IMembership, CachedMembership>();
var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();
app.MapHub<ChatHub>("/hubs/chat");

// Gap fill after reconnect: SignalR does not replay messages missed while disconnected.
app.MapGet("/api/conversations/{id}/messages", async (string id, long afterSeq, IMessageStore store, IMembership members, HttpContext http, CancellationToken ct) =>
{
    var userId = http.User.FindFirst("sub")?.Value ?? "";
    if (!await members.IsMemberAsync(id, userId, ct)) return Results.Forbid();
    return Results.Ok(await store.AfterAsync(id, afterSeq, take: 200, ct));
}).RequireAuthorization();

app.Run();

โš  Common mistakes

  • Mistake: Broadcasting before persisting. Why it is wrong: a crash or failed write after the broadcast shows a message that later disappears, or loses it entirely. Instead: persist, then deliver.
  • Mistake: Assuming SignalR guarantees delivery. Why it is wrong: messages sent while a client is disconnected are not replayed. Instead: gap fill from storage on reconnect using the last seen sequence.
  • Mistake: Ordering by client timestamps. Why it is wrong: device clocks skew, so replies appear before questions. Instead: server-assigned sequence per conversation.
  • Mistake: Scaling self-hosted SignalR without a backplane. Why it is wrong: users on different servers miss group messages. Instead: Azure SignalR Service, or a Redis backplane with sticky sessions.
  • Mistake: Storing a read receipt per message per member, sent on every scroll. Why it is wrong: a 500-member group multiplies writes by 500 and floods the hub. Instead: store lastReadSeq per member per conversation, debounce updates on the client and batch writes.
  • Mistake: Ignoring stale connections and reconnect storms. Why it is wrong: half-open sockets keep users 'online' and in groups, and after an outage every client reconnects and gap-fills at once, overloading storage. Instead: keep-alive and client timeouts, presence TTLs, reconnect with randomised backoff, and cap gap-fill page sizes.
  • Mistake: Partitioning messages by user. Why it is wrong: every group message is written N times and conversation history becomes a cross-partition query. Instead: partition by conversation and keep a small per-user inbox projection.
  • Mistake: Not authorising each send and join. Why it is wrong: anyone who guesses a conversation id can read or post. Instead: check membership on every hub call.

๐Ÿ› Senior insight: trade-offs

Senior answers make one clear statement: real-time is a cache over a durable log. That decides persist-then-deliver, gap fill and idempotent sends, and it's why the system survives deployments and network drops. I'd also point out that 1 million connections is mostly a cost question once you use a managed service, so I'd estimate units and price before the interview ends.

Option When it fits Cost When not to
Azure SignalR Service Many connections, ASP.NET Core hubs Per unit; predictable Strict data path requirements against managed services
Self-hosted SignalR + Redis backplane < ~50k connections, on-prem Ops, sticky sessions, backplane limits Very large fan-out
Raw WebSockets / custom gateway Extreme scale, custom protocol Large engineering effort Most business apps

I measure delivery latency (send to receive), reconnect rate, gap-fill volume after deployments, Cosmos DB RU per message and hot partition metrics, and SignalR connection counts against unit capacity.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions running SignalR on several servers Why: Checks sticky sessions, the Redis backplane, Azure SignalR Service and connection limits
    How to answer

    A SignalR server only knows its own connections and groups, held in memory. Scale out to several instances and Clients.Group("x") on server A never reaches users connected to server B. Self-hosted, you also need sticky sessions, because the negotiate request and the SSE or long-polling requests must reach the same server (WebSockets-only with SkipNegotiation avoids that). Affinity costs you even load distribution, and clients on a failed instance must reconnect. The Redis backplane fixes delivery by publishing every message to every server. It works well at moderate scale, but every server processes every message, and pub/sub doesn't buffer during a Redis failover, so run Redis highly available. Azure SignalR Service moves the client connections off your app: your servers keep a handful of connections to the service, which handles fan-out, at about 1,000 concurrent connections per Standard unit.

    For 100,000 connections, I would use Azure SignalR Service, plan units from peak connections and fan-out, and design for reconnect storms.

  2. When: Candidate talks about message ordering Why: Checks what breaks ordering in distributed systems and how to avoid needing global order
    How to answer

    Global ordering means one consumer processing one message at a time, which kills throughput, so real systems guarantee order per key: per order, customer or account.

    • Service Bus: set SessionId; a ServiceBusSessionProcessor locks a session to one receiver and processes it in order, while different sessions run in parallel.
    • Kafka: the message key picks the partition, and order holds within it. Adding partitions remaps keys.
    • SQS FIFO: the MessageGroupId works like a session.

    Order breaks with competing consumers, retries, dead-lettering and rebalances. Better still, design so order doesn't matter: version numbers with "ignore older", events that carry full state, or commutative updates. The trade-off is that per-key order lets one stuck message block every later message for that key.

  3. When: Candidate defaults to WebSockets without comparing options Why: Checks polling, SSE, WebSockets and SignalR trade-offs
    How to answer

    There are five ways to get server changes to a client. Short polling asks on a timer: simple and cache-friendly, but wasteful, and data is up to one interval stale. It suits reports and KPIs. Long polling holds each request open until something happens, giving near real-time over plain HTTP when nothing else gets through a proxy. Server-Sent Events (SSE) keep one HTTP response open and stream text/event-stream messages one way, server to client, with automatic reconnect. They suit notifications, progress and AI token streams. WebSockets upgrade the connection to a full-duplex channel for low-latency two-way traffic such as chat or collaborative editing. SignalR sits on top: it negotiates WebSockets, falls back to SSE or long polling, and adds reconnects, groups and hub methods.

    The trade-off: polling costs requests, while push costs one held connection per client. Those connections need capacity planning, proxy idle-timeout settings and a scale-out story.

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

Messages lost during deployments in a support chat
Situation
A customer-support chat for [an insurer], [80,000] concurrent connections, self-hosted SignalR on [AKS] with a Redis backplane. Agents and customers in Australia.
Signals
Agents reported customers saying 'I already answered that'; transcripts missing messages; spikes in reconnects in Application Insights every time a deployment rolled pods.
Investigation
Correlated missing messages with pod restarts using Application Insights and Kubernetes events. The hub broadcast messages before persisting them and clients did no gap fill, so anything sent during a reconnect window was lost.
Resolution
Immediate: paused daytime deployments. Long term: persist-then-deliver with client message ids, per-conversation sequence numbers, gap fill on reconnect, and moved connections to Azure SignalR Service so hub pods could roll without dropping client sockets.
Prevention
Chaos test in staging that restarts hub pods during a scripted conversation and asserts no gaps; dashboard of gap-fill volume; ADR stating real-time delivery is best effort over durable storage.

How to tell it (STAR)

**S:** At [company] our support chat lost messages every time we deployed, which agents noticed in [dozens] of transcripts a week. **T:** I needed to make delivery reliable without freezing deployments. **A:** I found we broadcast before saving and never filled gaps after reconnects. I changed the hub to persist first with client message ids and per-conversation sequence numbers, added gap fill on reconnect, and moved connections to Azure SignalR Service. A chaos test now restarts pods mid-conversation in staging. **R:** Missing-message reports went to [zero] and we went back to [daily] daytime deployments.

More in Systems to Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

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