Skip to content

Commit

Permalink
Merge pull request #303 from talex5/nodelay
Browse files Browse the repository at this point in the history
Set TCP_NODELAY to avoid Nagle's algorithm
  • Loading branch information
talex5 authored Nov 30, 2024
2 parents f8177be + e5eec6e commit 574768a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
2 changes: 1 addition & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ API changes:

Performance and bug fixes:

- Add buffering of outgoing messages (@talex5 #287).
- Add buffering of outgoing messages (@talex5 #287 #303).
Sending each message in its own TCP packet isn't very efficient, and also interacts very badly with Nagle's algorithm.
See <https://roscidus.com/blog/blog/2024/07/22/performance/> for details.

Expand Down
17 changes: 13 additions & 4 deletions unix/network.ml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ let close x =
try Eio.Net.close x
with Eio.Io (Eio.Net.E Connection_reset _, _) -> ()

let try_set_nodelay socket =
try Unix.setsockopt socket Unix.TCP_NODELAY true
with Unix.Unix_error ((EINVAL | EOPNOTSUPP), _, _) -> () (* Probably a Unix-domain socket *)

let connect net ~sw ~secret_key (addr, auth) =
let eio_addr =
match addr with
Expand All @@ -87,17 +91,22 @@ let connect net ~sw ~secret_key (addr, auth) =
begin match addr with
| `Unix _ -> ()
| `TCP _ ->
let socket = Eio_unix.Resource.fd_opt socket |> Option.get in
Eio_unix.Fd.use_exn "keep-alive" socket @@ fun socket ->
Unix.setsockopt socket Unix.SO_KEEPALIVE true;
Keepalive.try_set_idle socket 60
Eio_unix.Resource.fd_opt socket
|> Option.iter (fun socket ->
Eio_unix.Fd.use_exn "keep-alive" socket @@ fun socket ->
Unix.setsockopt socket Unix.SO_KEEPALIVE true;
try_set_nodelay socket;
Keepalive.try_set_idle socket 60
)
end;
Tls_wrapper.connect_as_client socket secret_key auth
| exception ex ->
Fiber.check ();
error "@[<v2>Network connection for %a failed:@,%a@]" Location.pp addr Fmt.exn ex

let accept_connection ~secret_key flow =
Eio_unix.Resource.fd_opt flow
|> Option.iter (fun fd -> Eio_unix.Fd.use_exn "TCP_NODELAY" fd try_set_nodelay);
Tls_wrapper.connect_as_server flow secret_key

let v t = (t :> [`Generic] Eio.Net.ty r)

0 comments on commit 574768a

Please sign in to comment.