Mobile Development 15 min read

HTTP Connection Reuse Optimization in OkHttp:原理与实践

The article explains how reusing HTTP connections with OkHttp—by leveraging persistent HTTP/1.1, multiplexed HTTP/2, and pre‑established sockets—dramatically cuts latency, details the underlying ConnectInterceptor and ConnectionPool implementation, and recommends enlarging the pool and adjusting keep‑alive settings to suit multi‑domain, high‑concurrency apps.

vivo Internet Technology
vivo Internet Technology
vivo Internet Technology
HTTP Connection Reuse Optimization in OkHttp:原理与实践

This article explains how HTTP connection reuse improves network loading speed and provides detailed implementation guidance using OkHttp.

Background: When making network requests, understanding the underlying connection mechanism helps optimize network loading performance. This article focuses on HTTP connection reuse principles and optimization details.

Connection Reuse Mechanism: A typical network request involves: DNS resolution (1 RTT), TCP 3-way handshake (2 RTT), TLS handshake for HTTPS (2 RTT), sending request, receiving response, and TCP 4-way handshake to close connection. Connection reuse eliminates steps 2-4, significantly reducing latency. The first request takes 175ms, while subsequent requests to the same host take only 39ms.

HTTP Version Evolution: HTTP/1.0 requires a new TCP connection for each request. HTTP/1.1 introduces persistent connections by default, allowing connection reuse. HTTP/2 further improves with binary framing and multiplexed connections over a single TCP connection.

Pre-connection Implementation: Network frameworks like OkHttp support HTTP/1.1 and HTTP/2 connection reuse. Developers can pre-establish connections during app splash screen for critical pages. A simple HEAD request can pre-warm connections, potentially improving first request speed by 40%.

OkHttp Source Code Analysis: Connection establishment happens in ConnectInterceptor. RealConnection is managed by StreamAllocation, which finds available connections from ConnectionPool. The pool defaults to 5 idle connections, each evicted after 5 minutes.

Key code in ConnectInterceptor:

public final class ConnectInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
RealInterceptorChain realChain = (RealInterceptorChain) chain;
Request request = realChain.request();
StreamAllocation streamAllocation = realChain.streamAllocation();
boolean doExtensiveHealthChecks = !request.method().equals("GET");
HttpCodec httpCodec = streamAllocation.newStream(client, chain, doExtensiveHealthChecks);
RealConnection connection = streamAllocation.connection();
return realChain.proceed(request, streamAllocation, httpCodec, connection);
}
}

ConnectionPool manages connection reuse:

public final class ConnectionPool {
private final Deque<RealConnection> connections = new ArrayDeque<>();
public ConnectionPool() {
this(5, 5, TimeUnit.MINUTES);
}
void acquire(Address address, StreamAllocation streamAllocation, @Nullable Route route) {
for (RealConnection connection : connections) {
if (connection.isEligible(address, route)) {
streamAllocation.acquire(connection, true);
return;
}
}
}
}

RealConnection.isEligible() determines if a connection can be reused based on: allocation limit, address non-host fields matching, host matching, or HTTP/2 connection coalescing requirements.

Problem & Solution: The default ConnectionPool (max 5 connections) was insufficient for the complex game center app with multiple domains. Pre-established connections were evicted when the pool filled with other requests. Solution: Increase ConnectionPool size and keep-alive duration when building OkHttpClient.

Q&A:

1. How to determine pool size? Consider maximum concurrent requests and total domain count. Or test by navigating through the app and checking ConnectionPool size.

2. Memory impact? Testing with max 50 connections and 52 concurrent requests showed ~22.5 idle connections remaining, consuming ~97KB (4.3KB per connection).

3. Server impact? Servers control connection lifecycle. If server timeout is too short, connections may be closed by server, requiring re-establishment.

4. Server pressure? Pre-connection increases requests; evaluate based on business needs and server capacity.

5. Maximizing pre-connection effect? Coordinate with server timeout settings based on average user navigation time to detail pages.

ConnectionPoolPerformance Tuningnetwork optimizationHTTP/2OkHttpHTTP connection reuseMobile development
vivo Internet Technology
Written by

vivo Internet Technology

Sharing practical vivo Internet technology insights and salon events, plus the latest industry news and hot conferences.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.