In ASP.NET Core without SignalR, how would you push each new auction bid to thousands of open raw WebSockets safely?
answer
- a registry of live sockets
- one SendAsync in flight per socket
- a bounded Channel per connection
- slow clients must not stall others
- remove on close, abort or exception
basics
~20 sRegister each connection with its own bounded Channel and one writer loop calling SendAsync. The broadcaster TryWrites into every channel without awaiting sockets; each handler awaits its loops and deregisters when the socket closes or faults.
solid answer
~40 sEach accepted socket gets a connection object in a concurrent registry, with a bounded `Channel<T>` as its outbox. The handler runs two loops and awaits both: a receive loop (for the client's close and pongs) and a send loop that reads the channel and calls `SendAsync`, so only one send is ever in flight on that socket, as the `WebSocket` type requires. The bid service broadcasts by `TryWrite`-ing the serialised bid into every outbox, so one slow bidder never blocks the others; a full outbox drops the oldest update or disconnects that client. When either loop ends (close, `WebSocketException`, `RequestAborted`) the handler removes the connection from the registry, completes its channel and returns, which ends the request. This is the plumbing SignalR's groups would otherwise give you.
code
csharp · 26 linesapp.Map("/bids", async (HttpContext context, BidderRegistry registry) =>
{
if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = 400; return; }
using var socket = await context.WebSockets.AcceptWebSocketAsync();
var outbox = Channel.CreateBounded<byte[]>(new BoundedChannelOptions(64)
{
FullMode = BoundedChannelFullMode.DropOldest // a ticker only needs fresh bids
});
using var cts = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
var id = registry.Add(outbox.Writer); // the broadcaster TryWrites here
var sending = SendLoopAsync(socket, outbox.Reader, cts.Token);
var receiving = ReceiveLoopAsync(socket, cts.Token);
try { await Task.WhenAny(sending, receiving); } // either loop ending ends the connection
finally
{
registry.Remove(id);
outbox.Writer.TryComplete();
cts.Cancel(); // stop whichever loop is still running
}
});
static async Task SendLoopAsync(WebSocket socket, ChannelReader<byte[]> outbox, CancellationToken ct)
{
await foreach (var bid in outbox.ReadAllAsync(ct)) // one SendAsync in flight per socket
await socket.SendAsync(bid.AsMemory(), WebSocketMessageType.Text, endOfMessage: true, ct);
}go deeper
Know that you must keep your own list of connected sockets, because raw WebSockets have no built-in broadcast.
Explain why each socket needs a single writer and how a per-connection channel serialises sends from several sources.
Design the full lifecycle: bounded outboxes with a back-pressure policy, both loops awaited by the handler, and one cleanup path for close, drop, timeout and shutdown.
Judge when this hand-built fan-out plus a backplane costs more than adopting SignalR, and where the raw protocol still earns its keep.
## The problem A live auction has one producer (the bid service accepting a new high bid) and many consumers (every bidder's open WebSocket). Without SignalR there is no `Clients.All`: you must keep track of sockets yourself and write to each. The naive version, a `foreach` over a list of sockets calling `await socket.SendAsync(...)`, fails in three ways: - **One slow client stalls everyone.** The loop waits on each send in turn; a bidder on a bad link holds up the bid for all the others. - **Concurrent sends are not supported.** The `System.Net.WebSockets.WebSocket` type supports one outstanding send at a time. If the broadcaster and the handler (an acknowledgement, a heartbeat message) both call `SendAsync` on the same socket, they collide. - **Dead sockets accumulate.** Without cleanup, the list grows with closed and aborted sockets, each send to them throwing. ## The shape that works Give every connection an **outbox** and a **single writer**: | Piece | Responsibility | |---|---| | connection registry (`ConcurrentDictionary<Guid, BidderConnection>`) | who is connected right now | | `BidderConnection.Outbox` (`Channel.CreateBounded<byte[]>`) | queued messages for one socket | | send loop (one per socket) | `await foreach` over the outbox, one `SendAsync` at a time | | receive loop (one per socket) | keeps a `ReceiveAsync` pending, sees the client's close | | broadcaster | `TryWrite` the serialised bid into every outbox, never awaiting a socket | The handler that accepted the socket registers the connection, starts both loops, awaits whichever finishes first, then cleans up: 1. Remove the connection from the registry. 2. Complete the outbox (`Writer.TryComplete()`) so the send loop ends. 3. Close or abort the socket and return, so the HTTP request completes. Because the handler awaits the loops, the request stays alive exactly as long as the socket, which is what ASP.NET Core requires. If you would rather run the send side elsewhere (a `BackgroundService`), the handler awaits a `TaskCompletionSource` that the background side completes. ## Back-pressure policy A bounded channel turns "slow client" into an explicit decision: - `BoundedChannelFullMode.DropOldest` - for a bid ticker, only the latest price matters, so dropping stale updates is correct. - `BoundedChannelFullMode.Wait` with `TryWrite` - `TryWrite` returns `false` when full; treat that as "client cannot keep up" and disconnect it. - An **unbounded** channel hides the problem until a stuck client has queued gigabytes. ## Serialise once, send many The broadcaster should turn each bid into bytes **once** (for example `JsonSerializer.SerializeToUtf8Bytes(bid)`) and put the same `byte[]` into every outbox. Serialising per connection multiplies CPU and allocations by the number of bidders, and the payload is identical for all of them anyway. Because nobody mutates the array after it is queued, sharing it across send loops is safe. Per-user data (a "you are the highest bidder" flag) is better sent as a separate, small message to that one outbox than mixed into the broadcast. ## Detecting the end A connection ends through several doors, and all of them must lead to the same cleanup: - the client sends a close (receive loop sees `WebSocketMessageType.Close`); - the connection drops (pending `ReceiveAsync` or `SendAsync` throws `WebSocketException`); - `KeepAliveTimeout` aborts an unresponsive client; - `HttpContext.RequestAborted` fires, for example on server shutdown. Put the cleanup in a `finally` around the awaited loops so every path runs it. ## Scale limits This works within **one process**. With several instances behind a load balancer, a bid accepted on instance A must reach bidders connected to instance B, which needs a backplane (a message broker or pub/sub) feeding each instance's broadcaster. That plumbing, plus groups and reconnection, is exactly what SignalR provides; owning it yourself is the price of a raw protocol.
- Why Task.WhenAny rather than Task.WhenAll over the two loops?Either loop ending means the connection is over: the receive loop returns on the client's close or throws on a drop, and the send loop ends when its socket fails. With `WhenAll`, a closed client would leave the send loop waiting on an empty channel forever and the request would never finish. `WhenAny` lets the `finally` run as soon as one side ends; it then completes the channel so the other loop exits too.
- How would this design change when the app runs on three instances?Each instance only knows its own sockets, so a bid accepted on one instance must be published to the others. You add a pub/sub backplane: the bid service publishes to it, and every instance subscribes and feeds its local broadcaster. Sticky sessions are not required for raw WebSockets because a socket stays on the instance that accepted it, but the fan-out must cross instances.
- Loop over all sockets and await SendAsync on each in turn.
- Call SendAsync from the broadcaster and the handler at the same time; WebSocket is thread-safe.
- Use an unbounded channel so no bid is ever dropped.
- Return from the handler after registering the socket; the registry keeps it alive.
- A static List<WebSocket> works across several app instances.