Kayavak

Kayavak / Work backwards

Work backwards

Every request took 48 milliseconds on localhost

Fifty requests to a server on the same machine took 48 ms each, until one socket option made them take 3.

The result

In Volume 3's API lab, 50 sequential GET requests to a small Java server on the same machine took 2,395 ms: 48 ms per request, with no network in between. Turning on one option on the server's sockets brought the total to 166 ms, about 3 ms per request (the lab).

Localhost round trips take microseconds. Something is waiting on purpose.

Work back from it

First question: the delay is nearly the same on every request. What does a constant delay suggest?

A timer, not a workload. Work that's slow varies with load and size; a fixed wait close to a round number usually means something is waiting for a timeout to expire.

Step 1: how did this server send its responses?

In two small writes: the headers, then the body. That detail is the clue.

Step 2: what does TCP do with a small write while earlier data is still unacknowledged?

With Nagle's algorithm on (the default), the sender holds back small segments while it has unacknowledged data in flight, so it can combine them into fuller ones (sequence numbers and acknowledgements). So the body waits for the headers to be acknowledged.

Step 3: why doesn't the acknowledgement come straight back?

The client uses delayed ACKs: it waits up to about 40 ms (Linux's timer) hoping to send its acknowledgement along with data of its own. But it has nothing to send until it has the whole response. Each side waits for the other until the timer fires.

The root cause

Nagle's algorithm on the sender and delayed acknowledgements on the receiver wait for each other, adding a timer's worth of delay to every response written in small pieces. TCP_NODELAY turns Nagle off for that socket; production servers such as Tomcat, Netty and Jetty set it by default.

What follows from it

Recall

Which two TCP behaviours combine into the 40 ms stall?

Nagle's algorithm (holding small writes while data is unacknowledged) and delayed ACKs (holding the acknowledgement hoping to piggyback it).

What fixed it in the lab?

Setting TCP_NODELAY on the server's sockets.