Skip to content

TCP Fast Open implementation? #1476

Open

Description

@icylogic

Proposal: TCP Fast Open

TCP Fast Open is an extension for TCP to speed up the handshaking process in successive TCP connections. This feature has been available for OSX and Linux for years and was implemented on Windows by Anniversary Update. Users could check by netsh

>netsh int tcp show global
Querying active state...

TCP Global Parameters
----------------------------------------------
...
TCP Fast Open                       : enabled

but dotnet has not implemented this for System.Net yet.

Rational and Usage

This new API is important and powerful because when it is used with TLS False Start, we are down to 1-RTT from original 3-RTT for a successive TCP+TLS (HTTPS) connection, and furthermore, 0-RTT could be achieved by combining TFO and TLS 1.3.

And it's easy to use: programmers only need to add a few lines to set an socket option and provide a buffer filled with data to send. Here's the usage:

var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var e = new SocketAsyncEventArgs();
s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.FastOpen, true);
e.SetBuffer(buffer, offset, length); 
s.ConnectAsync(e);

Note that buffer[offset] ~ buffer[offset+length-1] might be (partially) sent together with SYN. It's up to the OS how to send.

A typical usage is the TLS handshake. In successive connections, the client could send a SYN with TLS Client Hello.

Please check the "Original Proposal" for details.

Proposed API

namespace System.Net.Sockets
{
    // Defines socket option names for the <see cref='System.Net.Sockets.Socket'/> class.
    public enum SocketOptionName
    {
        // ...

        #region SocketOptionLevel.Tcp
        // ...
        FastOpen = 15
        #endregion

    }
}

This enum value is 15 for Windows according to ws2ipdef.h.

Problems & Extra works

  • Implementation
    In fact, adding just one line like the code above in SocketOptionName.cs would work for Windows.
    However, it might not work for Unix. Since dotnet simply pass the socket option to native API on Windows while the Unix Pal would check the value. For more information about the difference please check the relevant issue dotnet/corefx#14237 . To make this work for Unix we may need to modify this part

  • Compatibility
    According to MSDN, this option is available since Windows 10, 1607. Maybe we should generate a warning if this option is set on the older Windows platform

  • Other System.Net API
    For API using sockets in its code such as WebClient or HttpClient, it could take advantage of this feature, especially for "https://" scheme.

Original Proposal

TCP Fast Open on Windows

Windows has introduced TCP Fast Open in the Anniversary Update serveral months ago. (Announcing: New Transport Advancements in the Anniversary Update for Windows 10 and Windows Server 2016)

TFO is one full Round Trip Time (RTT) faster than the standard TCP setup which requires a three way-handshake. This leads to latency savings and is very relevant to short web transfers over the Internet where the average latency is on the order of 40 msec.

Native API for TCP Fast Open

This feature could be turned on using native Windows Socket 2 API: IPPROTO_TCP Socket Options. But it has not been implemented in dotnet (SocketOptionName.cs).

dotnet API relating to TCP Fast Open

According to the Native API Documentation, in addition to passing a new enum value to the method setSocketOption which then calls the native setsockopt, we need to set up the buffer including the data to send during the initial connection:

Note that to make use of fast opens, you should use ConnectEx to make the initial connection, and specify data in that function's lpSendBuffer parameter to be transferred during the handshake process. Some of the data in lpSendBuffer will be transferred under the Fast Open protocol.

The native method ConnectEx is called by DoOperationConnect which is called by socket.ConnectAsync on Windows. And the buffer could be set as a property of SocketAsyncEventArgs.

//TFO is defined as 15 in ws2ipdef.h
socket.SetSocketOption(SocketOptionLevel.Tcp, (SocketOptionName)15, true);  
e.SetBuffer(buffer, start, length);  //e is a SocketAsyncEventArgs
socket.ConnectAsync(e);

dotnet implementation

The most straightforward way to implement this feature is to add a new value to the SocketOptionName enum. But it enables this feature only on Windows. In this issue https://github.com/dotnet/corefx/issues/14237, it seems that members are interested in introducing a new cross-platform API for TCP options.

It would be nice if the Public API contained all of the possible socket options across Windows, Linux, and Darwin.

PS. TCP Fast Open is natively supported on Linux and OSX. Here's how to use it on Linux: TCP Fast Open: expediting web services

More about TCP Fast Open:

Activity

  1. geoffkizer commented on Mar 1, 2017

    @geoffkizer
    Contributor

    I agree, we should do this.

  2. karelz commented on Mar 4, 2017

    @karelz
    Member

    Next step: We need formal API proposal

  3. icylogic commented on Mar 4, 2017

    @icylogic
    Author

    Glad you are interested in this API. I could follow the guideline to file a formal proposal so we can discuss details. Do I need to open a new issue like "Proposal: TCP Fast Open" or edit this issue?

  4. karelz commented on Mar 4, 2017

    @karelz
    Member

    Just edit this one. I often keep the original text in "Original Proposal" section or "Details" as GH doesn't version issue text.
    Ping the issue whenever you update top post, summarizing the changes - it is easier to keep track of what happened.

  5. icylogic commented on Mar 4, 2017

    @icylogic
    Author

    Added a proposal including a short introduction, an example and some problems while leaving the original text unchanged in the section "Original Proposal"

  6. karelz commented on Mar 4, 2017

    @karelz
    Member

    Sounds great, thank you!

    Re: Compatibility: What happens when you pass the flag on lower Windows version or Linux/OSX version which does not support it? Is it no op? Or failure?

    @geoffkizer @davidsh @CIPop @Priya91 any concerns/thumbs up? If I get 2 thumbs up, I can mark it as ready for API review on Tue.

  7. geoffkizer commented on Mar 4, 2017

    @geoffkizer
    Contributor

    I don't think we prevent you from passing arbitrary ints to SetSocketOption. So something like this should work today:

    s.SetSocketOption(SocketOptionLevel.Tcp, (SocketOptionName)15, true);

  8. icylogic commented on Mar 4, 2017

    @icylogic
    Author

    @geoffkizer Yes, it does work for Windows as I stated in the original proposal. So for Windows after Win10 1607, adding one line to the enum to formalize this API is enough. I'm just not sure what will happen for Unix and Windows before 1607.

  9. geoffkizer commented on Mar 4, 2017

    @geoffkizer
    Contributor

    My point is that we don't need to make any product change for users to do this today.

    It might be nice to add the SocketOptionName for this, but that raises the question of whether and how we want to expose OS-specific socket options in SocketOptionName.

  10. icylogic commented on Mar 4, 2017

    @icylogic
    Author

    OK, if we don't make any change, we can still use this feature on recent Windows. For programmers developing on other platforms which natively support TFO, they may need to wait for this issue https://github.com/dotnet/corefx/issues/14237#issuecomment-266035007 to be solved to use these socket options. It seems that corefx team is interested in introducing a new set of API.
    Another issue is about other System.Net API, like WebClient or SslStream, which provide TLS connections and could obviously use this feature. If we don't want make any change to these API using this unexposed feature today, we could wait for TLS 1.3 to come out and make changes together.

  11. geoffkizer commented on Mar 4, 2017

    @geoffkizer
    Contributor

    I think we could certainly consider other APIs, e.g. some sort of way to enable this in a platform-neutral way.

    I'm reacting to the "Proposed API" above, which proposes to add a Windows-specific enum value for FastOpen. My point is that this is a convenience, not a necessity, since you can achieve the desired functionality by just passing (SocketOptionName)15.

  12. icylogic commented on Mar 4, 2017

    @icylogic
    Author

    That makes sense. It's just the most direct way came to me but actually not a good way.
    Maybe we could expose some other APIs that does not take a platform-specific value and translate it in the PAL(Platform Adaptation Layer) like this

  13. stephentoub commented on Mar 7, 2017

    @stephentoub
    Member

    I think we should do two things:

    • Add the enum value and appropriately implement it on both Windows and Unix. I'm not sure why the enum value is described as being specific to Windiws... on Unix we'd translate it in the PAL into the right platform value as we do with all other options.
    • Add the ability to pass option names in a platform-specific way so that we have a workaround available in the future for other such options. While on Windows it would work to just cast the number to the enum, on Unix we go through a translation layer, so we'd either misinterpret the value if it had an existing match in the enum, or we'd throw for it if the value wasn't known, neither of which is right. We've had a discussion of this in another issue, but I'm on my phone and can't easily find it at the moment. Basically you want the ability to say "pass this exact value to the OS, don't try to interpret/translate it", and leave it up to the app to do the platform detection and determine the right value to use.
  14. geoffkizer commented on Mar 7, 2017

    @geoffkizer
    Contributor

    Add the enum value and appropriately implement it on both Windows and Unix. I'm not sure why the enum value is described as being specific to Windiws... on Unix we'd translate it in the PAL into the right platform value as we do with all other options.

    Is this something we want to continue to do, though? I realize we did this for compat initially, but it seems like we could get into trouble here. Would we be better off adding a "bool FastOpen" property on Socket, not unlike NoDelay?

    +1 to having a way to do platform-specific options names.

  15. 36 remaining items

  16. antonfirsov commented on Nov 20, 2023

    @antonfirsov
    Contributor

    MSG_FASTOPEN is not cross-platform, so I would prefer looking for alternatives to the SocketFlag. For example, we could set MSG_FASTOPEN transparently, or use TCP_FASTOPEN_CONNECT (needs Linux 4.11+).

    Someone needs to go and prototype this feature, ideally including it's usage by higher layers of the stack as #1476 (comment) recommends.

  17. ScotMac commented on Nov 30, 2023

    @ScotMac

    OK, so the MSG_FASTOPEN also works for the sendto? But only on certain platforms? Can you provide the details please?

  18. ScotMac commented on Jan 11, 2024

    @ScotMac

    Can someone point me to how to use .NET to turn on TFO and send TFO data? Preferably in a platform independent manner. Is there some other issue that handles this?

  19. ScotMac commented on Jan 22, 2024

    @ScotMac

    @deeprobin is anything wrong with the usage proposed by the OP? The underlying Unix PAL (platform abstraction layer) could use a sendto syscall instead of connect in a transparent manner when TcpFastOpen is set and there is a buffer available on SocketAsyncEventArgs.

    Using the managed SendTo / ReceiveFrom API-s directly comes with a big performance penalty today (see #30797), I wouldn't recommend it.

    This seems to be a problem. ie, I don't believe you did the implementation the OP asked for, and the pass-thru implementation appears to have a big performance problem. Please look into doing the original proposal, where you handle the C native calls for sendto vs connect underneath the covers.

  20. ScotMac commented on Jan 23, 2024

    @ScotMac

    OK, this is what i am doing, as a pass-thru to the C native API for SendTo (SetSockOpt does NOT appear to be needed):

    m_client.Client.SendTo(Encoding.ASCII.GetBytes(m_conOption.ConnectData), 0, m_conOption.ConnectData.Length,
    (System.Net.Sockets.SocketFlags) 0x20000000, new IPEndPoint(addr, m_portNo));

    Is this the right approach?

  21. ScotMac commented on Jan 24, 2024

    @ScotMac

    It appears that the "pass-thru" for the SendTo() is not supported (like it IS for the SetSockOpt(). When i try it, I get the following error:

    SE : System.Net.Sockets.SocketException (95): Operation not supported
    at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
    at System.Net.Sockets.Socket.SendTo(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, EndPoint remoteEP)
    at OracleInternal.Network.TcpTransportAdapter.ConnectIterate()

  22. ScotMac commented on Jan 24, 2024

    @ScotMac

    And from this issue:

    #28706

    It appears that Send/SendTo are validating the flags, so no PASS-THRU flag is going to work.

  23. antonfirsov commented on Mar 27, 2024

    @antonfirsov
    Contributor

    While in #99490 we are planning to introduce this feature so customers can use it on their own risk, we must issue an important warning about its reliability:

    A non trivial percentage of middleboxes (routers, firewalls, proxies) in the open web will drop SYN packets containing TFO cookies. According to this article, the ratio was 5% in 2019. This could lead to software bugs and failures that are very difficult to diagnose.

    We consulted with the Windows networking team, and they confirmed that this concern is valid. It has prevented them from utilizing TFO as an enabled-by-default optimization in higher-level Windows components.

    In practice, TFO is only reliable in controlled networking environments. This means that if an organization wants to optimize their solutions with TFO, they need full control over each firewall, router, and proxy on the network path between the client and the server. They need the rights and expertise to configure these middleboxes and they need to be committed to maintain the configuration. In my understanding this essentially excludes most cloud scenarios.

    Also note that on Windows there is an aggressive TFO fallback mechanism that completely disables TFO globally until next restart when it detects problems with it. In my experiments I was never able to see a TFO cookie on a Windows system without first disabling this mechanism using netsh int tcp set global fastopenfallback=disabled. I assume there is a strong reason for the presence of this mechanism, and there is a risk that disabling it for one software may break other software on the same machine.

  24. antonfirsov commented on Mar 27, 2024

    @antonfirsov
    Contributor

    @ScotMac considering the problems described above, do you still find TFO useful for your scenario?

  25. karelz commented on Apr 9, 2024

    @karelz
    Member

    @ScotMac ping?

  26. wfurt commented on Apr 9, 2024

    @wfurt
    Member

    Note that the linked #99490 brings back the idea @icylogic originally mentioned

    var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    var e = new SocketAsyncEventArgs();
    s.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.FastOpen, true);
    e.SetBuffer(buffer, offset, length); 
    s.ConnectAsync(e);

    This fragment will now work across all platforms. On top of it, it adds the approved FastOpen enum. When used in combination AND when TFO is actually enabled at OS level AND the TCP stack has proper cookies, part (or all of the provided) data will go it together with initial SYN. Otherwise it would just go out when TCP is established.

    We don't plan to add more API at the moment but one can write simple extension. Perhaps something like

    internal static void Connect(this Socket socket, EndPoint ep, Memory<byte> buffer, int timeout)
    {
        var re = new ManualResetEventSlim();
        var saea = new SocketAsyncEventArgs();
        saea.SetBuffer(buffer);
        saea.RemoteEndPoint = ep;
        saea.Completed += (_, __) => re.Set();
        if (!socket.ConnectAsync(saea))
        {
            re.Wait(timeout);
        }
    }
  27. ScotMac commented on Apr 9, 2024

    @ScotMac

    We are discussing it internally. Thanks for the ping.

  28. ScotMac commented on Apr 15, 2024

    @ScotMac

    Based on the fact that we will have a good number of people using this within the cloud (not the public internet), we believe that 5% will not apply to us. And for a good number of those customers, the client will be on Linux.

    So, yes, please continue w/ the implementation.

  29. ScotMac commented on Jun 26, 2024

    @ScotMac

    @wfurt Hi Tomas, did your implementation make it into .NET 9 Preview 5? Is the new enum, specified here (SocketOptionName.FastOpen) implemented for your solution?

  30. wfurt commented on Jun 26, 2024

    @wfurt
    Member

    no, it was submitted after the cutoff. It should be part of preview 6 - around Jul 9 . If you want to proceed on testing you can grab daily build: https://github.com/dotnet/sdk/blob/main/documentation/package-table.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Net.Socketsos-windowstenet-performance

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions