Unexpected read timeout while request is still being sent
Have been running into this a lot lately with Retrofit 1.9.0 and OkHttp 2.5.0. While doing a PUT/POST request with a large request body, a "SocketException: socket is closed" is thrown from the native socket implementation. This seems to happen after a time determined by the configured OkHttp read timeout setting.
I would have expected the read timeout setting to mean the maximum time that is allowed to pass between the client having sent the entire request and the server sending the first response byte, or between response bytes sent by the server. Instead it appears that the read timeout starts immediately and can be triggered while the client is still actively sending the request, at which point the server should not really have been expected to send a single byte yet.
Setting a huge read timeout (globally or for each request) is an ugly hack that does avoid the problem, but obviously that results in unexpectedly long timeouts in cases where the request was small and the server actually takes a long time to respond.
I think it actually behaves the way you want it to. Is it possible something else is interfering? Nothing is better than a cold hard test case.
@swankjesse Here's a test case that seems to always trigger a timeout:
@Test public void unexpectedRequestTimeout() throws Exception {
final MockWebServer server = new MockWebServer();
server.setBodyLimit(0);
server.enqueue(new MockResponse().setBody("done.").throttleBody(1024, 100, TimeUnit.MILLISECONDS));
final OkHttpClient client = new OkHttpClient();
client.setReadTimeout(10, TimeUnit.SECONDS);
client.setWriteTimeout(10, TimeUnit.SECONDS);
final byte[] buffer = new byte[1024 * 1024];
final RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), buffer);
final Request request = new Request.Builder().post(requestBody).url(server.url("/")).build();
client.newCall(request).execute();
server.takeRequest();
}
There's definitely something weird going on here, though. I'm not sure anymore if it is the read timeout or the write timeout that gets triggered - the stack trace seems to randomly point to either one. Increasing one of the timeouts while keeping the other one at 10 seconds also seems to result in it sometimes working and sometimes not.
I also tested this against a real server by throttling my connections to ~10KB/s and sending a large request with read and write timeouts set to 10 seconds, then watched the packets flow in tcpdump. Sometime after 10 seconds, with the request still in progress and very much active, the socket would just throw the timeout exception and close itself.
Hey, not sure if this will help, but thought I'd note my observations. Running the provided test case on a Windows 10 host with OkHttp 2.7.0, I see the following:
- A SocketTimeoutException that consistently happens during the socket.write() call. I added a logging statement to RequestBody which signals when the write() completes, and it is never emitted.
- Looking at the packets with WireShark, I can see the request never completes. In addition, I'm seeing some "TCP Window Full" entries
- If I change the buffer to
new byte[1024 * 200], then the write completes almost instantly, I see my log statement, and then I receive an exception during the socket.read() consistently - Looking at the packets with WireShark, it recognizes the HTTP POST, but just barely before the SocketTimeoutException is thrown
If I'm interpreting things correctly, in the first scenario the socket.write() call blocks for longer than 10 seconds, which triggers a timeout within OkHttp and it closes the socket. This seems right.
In the second scenario, the socket.write() call appears to complete. Even though it returns, I'm still seeing packets flowing in WireShark. I think this means the OS is still in the middle of sending the data. Because it completed, it then enters the socket.read() call which blocks and eventually times out. Again, this seems right.
Thanks for running the test and confirming the behaviour @dave-r12.
Not entirely sure what you mean by "this seems right" - the behaviour that you observed is definitely not what I would expect from the library. The timeouts should not be triggered while packets are still actively flowing.
The packets are flowing, but far away from the application layer and OkHttp. The problem is that there isn't backpressure to cause the writes to block. You'll likely see that if you increase the upload size or decrease the host network’s buffer size.
The real problem is that the host network’s buffer makes MockWebServers read throttle ineffective. The writer can write nearly instantly, but it takes longer than the timeout for the MockWebServer tonrespond to the write.
You could imagine that this buffer & throttling could be occurring on any routing equipment between client and server in a real world deployment. You have a router that accepts the entire request immediately, but trickles those bytes up to the origin webserver.
What would you have OkHttp do in that situation? Remember that although packets are flowing, OkHttp doesn't know that.
I see. I suppose there is not much that can be done about the read timeouts.
That only leaves the write timeout problem then. To reproduce it more reliably, increase both the throttling speed and the request body size in the previous test case. For example 1MB/s throttling, 20MB body, 10 seconds write timeout.
Like @dave-r12 noted, it seems to be triggered by the AsyncTimeout's watchdog thread closing the socket after the socket.write() call blocks for 10 seconds. Is there a way to avoid that, other than calculating the write timeout from the body size or trying to hack OkHttp to use chunked encoding?
(Chunked encoding shouldn't make a difference.)
You're right, it's not so much about chunked encoding as it is about doing the socket.write() in smaller parts. Test cases (first one fails, second one passes):
@Test public void largeBodyOnePart() throws Exception {
final MockWebServer server = new MockWebServer();
server.setBodyLimit(0);
server.enqueue(new MockResponse().setBody("done.").throttleBody(1024 * 1024, 1000, TimeUnit.MILLISECONDS));
final OkHttpClient client = new OkHttpClient();
client.setReadTimeout(10, TimeUnit.SECONDS);
client.setWriteTimeout(10, TimeUnit.SECONDS);
final byte[] buffer = new byte[16 * 1024 * 1024];
final RequestBody requestBody = new RequestBody() {
public MediaType contentType() {
return MediaType.parse("application/octet-stream");
}
public long contentLength() {
return buffer.length;
}
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer, 0, buffer.length);
}
};
final Request request = new Request.Builder().post(requestBody).url(server.url("/")).build();
client.newCall(request).execute();
server.takeRequest();
}
@Test public void largeBodyTwoParts() throws Exception {
final MockWebServer server = new MockWebServer();
server.setBodyLimit(0);
server.enqueue(new MockResponse().setBody("done.").throttleBody(1024 * 1024, 1000, TimeUnit.MILLISECONDS));
final OkHttpClient client = new OkHttpClient();
client.setReadTimeout(10, TimeUnit.SECONDS);
client.setWriteTimeout(10, TimeUnit.SECONDS);
final byte[] buffer = new byte[16 * 1024 * 1024];
final RequestBody requestBody = new RequestBody() {
public MediaType contentType() {
return MediaType.parse("application/octet-stream");
}
public long contentLength() {
return buffer.length;
}
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer, 0, buffer.length / 2);
sink.write(buffer, buffer.length / 2, buffer.length / 2);
}
};
final Request request = new Request.Builder().post(requestBody).url(server.url("/")).build();
client.newCall(request).execute();
server.takeRequest();
}
No obvious action for us to take here?
Is the behaviour in the last two test cases expected? Since I'm using Retrofit I can't actually use the solution that makes the latter test case pass by writing into the sink in chunks.
It would be nice if OkHttp wrote the request body in reasonably-sized chunks so that the timeout actually worked as a timeout, not as a deadline. Being able to disable the watchdog timeout but keep the socket timeout might also work around the problem, but I could not figure out how to do that either.
Chunking the request body isn’t going to make a difference here.
So why does it seem to make a difference in my test case above? Am I doing something else differently?
It’s not a behavior you can rely upon. It’s likely not failing as a side effect of how segments are being flushed, but this is definitely not a reliable fix.
...In this case it looks like inconsistency in MockWebServer.throttledTransfer(). It throttles within each chunk, but not across chunks. This is a bad emulation of how throttled transferring will work in practice.
Yes, I did notice that behaviour with the throttling, which is why I have used 1000 or even 100 as the throttling interval. That should not be the difference here.
Why is flushing parts of the request an unreliable fix? It does not rely on any undefined socket/buffer behaviour, the timeout code that the hack bypasses is all in ~~OkHttp~~ Okio.
When sink.write() is called a timer is added to the watchdog thread's handler, which then manually triggers a socket timeout if socket.write() blocks longer than the defined write timeout. Writing in two parts cancels the timer after the first part has been written into the socket (either on the wire or in a buffer) and restarts it when sink.write is called again. Writing in even more parts would make the timeout behave like I would expect it to. There could be some overhead from the timer being restarted too often, so unless it is possible to disable or fix the watchdog behaviour some other way a sensible write chunk size would be needed.
The relevant Okio code seems to be here: https://github.com/square/okio/blob/master/okio/src/main/java/okio/AsyncTimeout.java#L155 The actual socket timeout exception that gets thrown is caused by this: https://github.com/square/okio/blob/master/okio/src/main/java/okio/Okio.java#L221
So the argument is that with a 1 second timeout, it’s dumb that we hold true to that 1 second, whether we’re writing 5 bytes or 5,000 ? I buy that.
That sounds like a deadline to me.
From Okio documentation (http://square.github.io/okio/1.x/okio/okio/Timeout.html): Timeouts specify the maximum time to wait for a single operation to complete. Timeouts are typically used to detect problems like network partitions. For example, if a remote peer doesn't return any data for ten seconds, we may assume that the peer is unavailable.
I think that is also how pretty much all socket timeout settings behave, i.e. it gets triggered if not a single byte is received/written in the timeout period.
I suppose another solution could be having the ability to completely disable the Okio sink timeout and just relying on SO_TIMEOUT, which should behave the way I described. But currently there is only a single write timeout setting that sets them both.