J
J
J. Snow2016-12-07 11:57:44
Performance evaluation
J. Snow, 2016-12-07 11:57:44

Why doesn't OkHttp reuse connections?

I'm using OkHttp 3.5.0 to test a web application under load. With it, I send thousands of requests to the same address.
The OkHttp docs say that it uses connection pooling to optimize performance. However, if we look netstat, we will see thousands of connections there in the TIME_WAIT state:

TCP    127.0.0.1:80           127.0.0.1:51752        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51753        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51754        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51755        TIME_WAIT
TCP    127.0.0.1:80           127.0.0.1:51756        TIME_WAIT
...

That is, connections are closed for some reason and are not reused.
Connection: keep-alivedoes not affect in any way.
And after several thousand requests, everything starts to fall. can't get a free port:
SocketException: No buffer space available (maximum connections reached?)

Client code (Kotlin):
val client = OkHttpClient.Builder()
        .connectionPool(ConnectionPool(5, 1, TimeUnit.MINUTES))
        .build()

val request = Request.Builder().url("http://192.168.0.50").build()

while (true) {
    val response = client.newCall(request).execute()
    response.close()
}

If you write response.body().string()instead of response.close(), then it SocketExceptionwill stop being thrown away, everything will seem to work, but thousands of TIME_WAIT connections will still be created, and performance will sag a lot.
Where is the joint? Why doesn't OkHttp reuse connections?
PS: That being said, Apache HttpClient works well (it has a dedicated pool PoolingHttpClientConnectionManager). But I want to figure out what's wrong with OkHttp.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question