runtime: Add WebSocketOptions.Timeout to ClientWebSocket

Edited by @CarnaViire

Justification

This API allows the users to identify and close idle WebSocket connections without having to rely on the TCP KeepAlive timeout, which can be way too big (e.g. ~15 min on Linux), and can be impossible or very hard to configure.

// see the original issue in the end of the post

API Proposal

namespace System.Net.WebSockets;

// used to create a base WebSocket (ManagedWebSocket) instance
public class WebSocketCreationOptions
{
    // existing
    //public TimeSpan KeepAliveInterval { get; set; } // default: infinite (off)

    // new
    public TimeSpan KeepAliveTimeout { get; set; } = Timeout.InfiniteTimeSpan;

    // ...
}

// used to configure a ClientWebSocket instance
public class ClientWebSocketOptions
{
    // existing
    //[UnsupportedOSPlatform("browser")]
    //public TimeSpan KeepAliveInterval { get; set; } // default: 30s

    // new
    [UnsupportedOSPlatform("browser")]
    public TimeSpan KeepAliveTimeout { get; set; } = Timeout.InfiniteTimeSpan;

    // ...
}

Usage

For ClientWebSocket:

var ws = new ClientWebSocket();
ws.Options.KeepAliveTimeout = TimeSpan.FromSeconds(10);
await ws.ConnectAsync(uri, cts.Token);

For ManagedWebSocket:

var options = new WebSocketCreationOptions()
{
    KeepAliveInterval = WebSocket.DefaultKeepAliveInterval,
    KeepAliveTimeout = TimeSpan.FromSeconds(10)
};
var ws = WebSocket.CreateFromStream(stream, options);

Notes on behavior

Timeout.InfiniteTimeSpan or TimeSpan.Zero would disable the timeout logic and fall back to the existing “unsolicited” Pong keep-alive (per understanding in https://github.com/dotnet/runtime/issues/35473#issuecomment-620726903 we cannot send Pings without waiting for the reply)

Any other positive timeout value would turn on Ping-Pong logic; we will be sending Pings instead of Pongs and track whether we’ve received Pongs in time; if not, the connection is treated as stale and aborted. The behavior and implementation should be similar to HTTP/2 KeepAlivePingTimeout.

Alternative Naming

We could name the new property KeepAlivePingTimeout. This will “break” it’s similarity to KeepAliveInterval, but it might help highlight that Pings, not Pongs, are being sent (if we care enough about this distinction).

namespace System.Net.WebSockets;

public class WebSocketCreationOptions
{
    //public TimeSpan KeepAliveInterval { get; set; } // existing
    public TimeSpan KeepAlivePingTimeout { get; set; } // new

    // ...
}

public class ClientWebSocketOptions
{
    //public TimeSpan KeepAliveInterval { get; set; } // existing
    public TimeSpan KeepAlivePingTimeout { get; set; } // new

    // ...
}

Existing API shape for other keep-alives

For comparison:

// HTTP/2 in runtime:
namespace System.Net.Http;
public class SocketsHttpHandler
{
    public TimeSpan KeepAlivePingDelay { get; set; } // default: infinite (off)
    public TimeSpan KeepAlivePingTimeout { get; set; } // default: 20s (N/A when delay=inf)
    public HttpKeepAlivePingPolicy KeepAlivePingPolicy { get; set; } // default: Always
    // ...
}

// HTTP/2 in Kestrel:
namespace Microsoft.AspNetCore.Server.Kestrel.Core;
public class Http2Limits
{
    public TimeSpan KeepAlivePingDelay { get; set; } // default: infinite (off)
    public TimeSpan KeepAlivePingTimeout { get; set; } // default: 20s (N/A when delay=inf)
    // ...
}

// Sockets in runtime:
namespace System.Net.Sockets;
public enum SocketOptionName
{
    TcpKeepAliveInterval, // between probe retries, if no answer received
    TcpKeepAliveRetryCount, // probe retries before deemed idle, if no answer received
    TcpKeepAliveTime, // before the first probe, after the last received byte
    // ...
}

Original issue by @bjornen77

I think that adding a WebSocketOptions.Timeout property would be a good thing.

Today, the ClientWebSocket is closed when the TCP Retransmission times out(if the connection to the server drops for some reason). This timeout seems to be different on Windows and Linux. By default, on Windows it takes about 21 seconds and on Linux it takes about 15 minutes before the WebSocket is closed. It would be good if we could have a separate Timeout setting, so that we get the same behavior regardless of the platform. And also that this could be configured by the application without having to modify the TCP Timeout settings in the OS… The websocket should still be disconnected if the OS TCP Timeout is reached.

The ClientWebSocket today only sends “Pong” to the server, and therefore it does not wait for a “Pong” response to arrive. I think that the ClientWebSocket shall send a “Ping” instead, and then verify that a “Pong” is received within the Timeout set. If not received, the connection shall be closed. Or at least it should expose the "received “Pong” message in the WebSocketReceiveResult.MessageType. It would be good if an received “Ping” message from a server is also exposed. Then the application could use these Ping/Pong message types to implement its own timeout logic.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 23
  • Comments: 39 (25 by maintainers)

Most upvoted comments

Strong +1 for this issue. This is an important feature for applications like games where detecting a broken connection quickly is important for user experience. The WebSocket API does not expose the ability to send ping or pong messages, so there isn’t even really a way to add this functionality in our applications without creating our own works-like ping/pong messages (which aren’t really ping/pong messages but regular websocket messages).

Just one point of clarification in the original issue — OP mentions that the current implementation only sends pong, rather than ping. I don’t think that’s true, from what I can see in ManagedWebSocket:518. I think the issue is simply that the implementation doesn’t wait for a pong in response to the ping.

The WebSocket RFC does not explicitly specify that clients should disconnect in the case a pong is not received in response to a ping within a certain timeframe. I think this would be a good thing to do though, as a user-configurable option. It should probably be default-off, so the change doesn’t impact any applications which are somehow depending on very long retry times. Just adding an extra WebSocketOptions for this as OP suggests is the right approach IMHO.

@Madguy93 it is currently planned for .NET 9, yes.

Thanks @pavelsavara! So, I guess, from the API perspective, we keep UnsupportedOSPlatform("browser") attribute on both the existing ClientWebSocketOptions.KeepAliveInterval and the new ClientWebSocketOptions.KeepAliveTimeout properties, correct?

And when implementing the respective API on Kestrel side, we would need to either add a test (if that’s possible in the infra) of Kestrel talking to a browser WS client, or at least verify it manually? cc @BrennanConroy

Triage: given that the customer ask is high, and it should be relatively easy to implement, optimistically putting it to 9.0.

WebSocketAcceptContext would likely need a new property, something like KeepAliveTimeout. I can help out if this feature gets added.

any estimate on which preview it would make?

Most possibly Preview 7, scheduled for the middle of August @chrsin

The proposal is exactly what’s needed for my company’s servers. With .NET 5-8, the replacement of the unidirectional Ping with a unidirectional Pong broke tens of thousands of clients that didn’t have a 3rd party implementation that could understand Pong frames as a heartbeat. The result was chaos, with disconnections about every minute or so.

I’ve been using this as the tracking issue, until there is something to do on the Kestrel side.

It is true that this could be implemented in another way too: the client initiates pings and waits for pongs, and at the same time, the server also initiates pings and waits for pongs.

Yes, I believe this would be the expected approach by RFC. If the server is on Kestrel, the timeout APIs will be introduced as a follow-up to this one (see https://github.com/dotnet/runtime/issues/48729#issuecomment-956579982), within the same release.

@BrennanConroy is there a tracking issue for this?

The proposed WebSocketCreationOptions.KeepAliveTimeout is exactly the “too long time” you mention – that will be tracked and applied from within the WebSocket, so it will get disconnected automatically in case of the response timing out. The pairing process will also become just a part of the internal implementation. You still won’t be able to send any arbitrary data in the PING frame, but given that its main purpose is for pairing with PONGs, I am not sure that the exact values should matter on the application level.

It’s unfortunate that we can’t implement this effectively because ManagedWebSocket.SendFrameAsync is private, preventing us from sending the PING frames ourselves in the application. Additionally, ClientWebSocket.ReceiveAsync doesn’t allow the reception of PONG frames in the application.

We’ll likely have to manually test with the browser. These kinds of tests aren’t great to add to automation since they by design would need to last 20+ seconds due to no APIs in the browser that let us influence the keep alive timeout.

Assuming we add good enough unit tests the one-off manual test should be fine.

There is no flag on the browser API for controlling it AFAIK.

There are notes on how to implement ping/pong in the server in the FF docs, which suggests that the browser itself may implement it.

But I don’t know, I never tested it and never looked at it with wireshark. We should test that, so that our server doesn’t break the browser as a client.

I would also like to see this implemented. Our setup is running a websoket server with lots of embedded devices as clients. We run a standardized protocol based on websocket and therefore cannot implement our own ping mechanism or use signalR. It’s important since if you run linux for your servers it will take about 15 min for it to detect a disconnect as the default TCP RTO setting in linux.

I’ve updated the root description with the API proposal

I guess SignalR uses its own pingpong, and is covering over for this flaw for most use cases? But I use it with vs-streamjsonrpc and ended up implementing my own pingpong, and used 99.9% time on that and the rest on actual work… My testing involved killing processes, pulling network cables, supending/resuming/killing VM’s, “pulling” network “cables” within VM’s etc. I easily got into situations with infinite hang (waited over night).

Triage: we are open to adding proper ping/pong sending. At the moment, there’s only this one issue asking for it so we’ll leave it to future.

Not so. Issue https://github.com/dotnet/aspnetcore/issues/24614 is already asking for the same (and duplicate https://github.com/dotnet/aspnetcore/issues/26117)