In ASP.NET Core 10's WebSocketOptions, what do KeepAliveInterval and KeepAliveTimeout default to, and how does KeepAliveTimeout change dead-client detection?
answer
- a heartbeat versus a heartbeat with a deadline
- KeepAliveInterval = 2 minutes
- KeepAliveTimeout = Timeout.InfiniteTimeSpan
- pong-only versus ping-and-wait
- per socket via WebSocketAcceptContext
basics
~10 sKeepAliveInterval defaults to two minutes and KeepAliveTimeout to Timeout.InfiniteTimeSpan (off). With only the interval, the server sends one-way heartbeats; setting KeepAliveTimeout makes it ping and abort the socket if no pong arrives in time.
solid answer
~40 s`WebSocketOptions.KeepAliveInterval` defaults to two minutes and `KeepAliveTimeout` to `Timeout.InfiniteTimeSpan`, which disables it (`TimeSpan.Zero` does too). With the timeout off, the interval drives an unsolicited heartbeat that keeps idle connections alive through proxies but never detects a dead client, so a silently vanished bidder can hold a socket for hours. Set `KeepAliveTimeout` (new in ASP.NET Core 9) and the server sends a ping after each quiet interval and aborts the socket if the pong does not arrive in time; the pending `ReceiveAsync` then throws. Two caveats: pongs are only processed while a `ReceiveAsync` is outstanding, so a send-only loop gets false aborts, and you can override both values per socket through `WebSocketAcceptContext`. `ReceiveBufferSize` on the options is obsolete and does nothing.
code
csharp · 18 linesapp.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromSeconds(20), // below the load balancer's idle timeout
KeepAliveTimeout = TimeSpan.FromSeconds(15) // abort if no pong within 15 s
});
app.Map("/bids", async (HttpContext context) =>
{
if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = 400; return; }
// Per-socket override: viewers on a slow kiosk network get more slack.
using var socket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext
{
KeepAliveTimeout = TimeSpan.FromSeconds(30)
});
await BidFeed.RunAsync(socket, context.RequestAborted); // keeps a ReceiveAsync pending
});go deeper
Recall the two defaults: a two-minute KeepAliveInterval and an infinite (disabled) KeepAliveTimeout.
Explain the difference between a one-way heartbeat and ping-with-timeout, and how WebSocketAcceptContext overrides the middleware values for one socket.
Size the interval against proxy idle timeouts, know that pongs are only processed with a receive pending, and treat timeout aborts as a normal disconnect path.
Balance detection speed against per-connection traffic and wake-ups at scale, and decide which endpoints deserve aggressive dead-peer detection.
## The options object `WebSocketOptions` (namespace `Microsoft.AspNetCore.Builder`) configures `WebSocketMiddleware`. You pass it to `app.UseWebSockets(options)` or configure it with `builder.Services.AddWebSockets(o => ...)`. Its constructor sets the defaults, and in ASP.NET Core 10 they are: | Property | Default | Meaning | |---|---|---| | `KeepAliveInterval` | `TimeSpan.FromMinutes(2)` | how often the server sends a keep-alive frame | | `KeepAliveTimeout` | `Timeout.InfiniteTimeSpan` | how long to wait for a pong after a ping; infinite or zero means disabled | | `AllowedOrigins` | empty list | which `Origin` values may open a socket; empty allows all | | `ReceiveBufferSize` | marked `[Obsolete]` | "Setting this property has no effect" | `KeepAliveTimeout` rejects negative values with `ArgumentOutOfRangeException` (except `Timeout.InfiniteTimeSpan` itself). ## Two keep-alive strategies The middleware hands both values to `WebSocket.CreateFromStream` through `WebSocketCreationOptions`, and the runtime picks a strategy: - **Interval only (the default).** The server sends an unsolicited heartbeat every `KeepAliveInterval`. It stops idle-timeout proxies and load balancers from cutting a quiet connection. It does **not** check that anyone is listening: nothing is expected back. - **Interval plus timeout.** When `KeepAliveTimeout` is a positive value, the server sends a ping once the connection has been quiet for `KeepAliveInterval` and waits up to `KeepAliveTimeout` for the matching pong. No pong in time means the client is deemed dead: the socket is **aborted**, and the outstanding `ReceiveAsync` throws. The difference matters for an auction feed. A bidder whose laptop lid closes never sends a close message. With the default settings, the server keeps that socket and keeps writing bids into it until TCP itself gives up, which can take a long time. With a timeout of, say, 15 seconds, the dead socket is detected within one interval plus 15 seconds. ## The pending-receive trap The runtime only processes incoming frames, pongs included, **while a `ReceiveAsync` is pending**. A handler that accepts a socket and only ever sends (a pure push feed) never reads the pongs, so with a timeout configured it will abort perfectly healthy connections. The fix is to keep a receive loop running alongside the send side even when clients send nothing, which also catches the client's close message. ## Global versus per socket Options on the middleware apply to every accepted socket. A specific endpoint can override them through the accept context: - `WebSocketAcceptContext.KeepAliveInterval` (nullable; `null` keeps the middleware value) - `WebSocketAcceptContext.KeepAliveTimeout` (nullable; `null` keeps the middleware value) So an internal admin socket can keep the defaults while public bidder sockets get a tight timeout. ## Diagnosing keep-alive problems | Symptom | Likely cause | |---|---| | idle sockets cut after exactly the same number of seconds | `KeepAliveInterval` is longer than a proxy's or load balancer's idle timeout | | healthy, quiet clients aborted at regular intervals | `KeepAliveTimeout` set but no `ReceiveAsync` pending to process pongs | | memory and connection counts creep up overnight | `KeepAliveTimeout` left at its infinite default, so vanished clients are never reaped | | a burst of aborts after a deploy | a shorter timeout combined with clients on slow or congested networks | Log the exception type from the receive loop, and you can tell a timeout abort from a client close in production dashboards. ## Choosing values 1. Keep `KeepAliveInterval` below the idle timeout of every proxy and load balancer in the path, or quiet connections will be cut. 2. Set `KeepAliveTimeout` when you hold per-connection state worth reclaiming (subscriptions, memory, a seat count). 3. Remember the cost: each interval adds a small frame per connection, which matters at tens of thousands of sockets. 4. Treat the abort exception from `ReceiveAsync` as a normal disconnect path, not an error.
- What does a client see when the server aborts its socket for a missed pong?The connection simply ends without a close handshake, so a browser client gets a close event with an abnormal-closure status rather than one the server chose. On the server, the pending `ReceiveAsync` throws, so the handler's catch block runs, the socket is disposed and the request completes. Any per-connection cleanup belongs in that path.
- Why not just set KeepAliveInterval very low, like one second?A low interval only makes the heartbeat more frequent; with `KeepAliveTimeout` off it still never detects a dead client. With the timeout on, one-second pings across thousands of sockets add constant traffic and wake-ups for little gain. Pick an interval just under the shortest proxy idle timeout and a timeout that matches how quickly you need to reclaim state.
- KeepAliveInterval alone detects and closes dead clients.
- KeepAliveTimeout defaults to 30 seconds, so dead sockets are already reaped.
- Set WebSocketOptions.ReceiveBufferSize to tune memory per connection.
- A push-only socket needs no ReceiveAsync once KeepAliveTimeout is set.
- Keep-alive values can only be set globally on the middleware.
Assumes ASP.NET Core 10; WebSocketOptions.KeepAliveTimeout and WebSocketAcceptContext.KeepAliveTimeout were added in ASP.NET Core 9, and earlier versions had only the one-way KeepAliveInterval heartbeat.