OkHttpClient: Enhancing Network Performance

Vairavan Srinivasan
3 min readAug 26, 2023
OkHttp Call

The remarkable abstractions provided by Square’s networking library, OkHttp, tend to overshadow the optimizations it brings, often escaping the notice of application developers. It uses the standard TCP handshake based connection for new requests and offers a default connection pool of 5 connections (each active for 5 minutes) to reuse previously setup TCP connection for subsequent requests.

class ConnectionPool internal constructor(
internal val delegate: RealConnectionPool
) {

constructor(
maxIdleConnections: Int,
keepAliveDuration: Long,
timeUnit: TimeUnit
) : this(RealConnectionPool(
taskRunner = TaskRunner.INSTANCE,
maxIdleConnections = maxIdleConnections,
keepAliveDuration = keepAliveDuration,
timeUnit = timeUnit
))

constructor() : this(5, 5, TimeUnit.MINUTES)

...
}

Under the hood

How does a connection pool enhance network performance? This can be verified using a OkHttp call specific EventListener.

private class OkHttpEventListenerFactory: EventListener.Factory {
override fun create(call: Call): EventListener {
return object: EventListener() {

override fun callStart(call: Call) {
Log.d("OkHttp", "CallStart")
}

override fun callEnd(call: Call) {…

--

--