Skip to content

Commit

Permalink
Enable TCP_NODELAY for all synchronous sockets.
Browse files Browse the repository at this point in the history
The widely documented poor interaction between the Nagle algorithm and
TCP's delayed ACK feature, when making short successive writes, leads to
unnecessary delays (around 50ms on Linux). This happens in httpcore
whenever a POST request is made, since the headers and body are sent as
two separate calls.

The TCP_NODELAY can be enabled to disable Nagle's algorithm, and
therefore avoid this delay.

The option is already enabled by default for all asyncio and Trio
sockets. It is also enabled by CPython's http.client module (which
urllib and requests use) and by many high-level HTTP libraries found in
other languages, including libcurl, Java's Netty, Rust's reqwest and
Go's standard library, to name a few.
  • Loading branch information
plietar committed Jan 12, 2023
1 parent 7eb2022 commit 3d7fad4
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions httpcore/backends/sync.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import errno
import socket
import ssl
import sys
Expand Down Expand Up @@ -94,6 +95,14 @@ def connect_tcp(
sock = socket.create_connection(
address, timeout, source_address=source_address
)

# Might fail in OSs that don't implement TCP_NODELAY
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except OSError as e:
if e.errno != errno.ENOPROTOOPT:
raise

return SyncStream(sock)

def connect_unix_socket(
Expand Down

0 comments on commit 3d7fad4

Please sign in to comment.