System Design Part 1 Measurement basics

The Journey of an HTTP Request: Timing Every Leg from DNS, TCP, and TLS Through the Load Balancer to the Database

Bill.Lin 11 min read

System Design series Part 1-1 | Previous: How to Think About System Design | Next: Latency, Throughput, and p99 | Series map

Scenario and problem

A customer in the US reports: “The order page takes over a second to open.” You open your APM: the server time for GET /orders is only 150 ms, and the database query takes 5 ms. Where did the missing second go?

1.25 seconds to open the order page from US West11 / 11
1.25 seconds to open the order page from US WestUS West browserDNSServer (Taiwan)Resolve the domainIP addressSYNSYN-ACKTLS ClientHelloCert and key exchangeGET /ordersServer processing 150 msFirst byte: 650 msTwo more APIs in sequence300 ms each, 1,250 ms total
  1. The first connection has to start with a DNS lookup, about 50 ms this time.
  2. Only with the IP can the connection start.
  3. The TCP three-way handshake. One round trip (RTT) from US West to Taiwan is about 150 ms, and the handshake spends one RTT first.
  4. The connection is up, but HTTPS still needs a TLS handshake before any data can be sent.
  5. The TLS 1.3 handshake costs another RTT, another 150 ms.
  6. About 350 ms have passed by now, and not a single byte of order data has been sent.
  7. The request is finally sent.
  8. The 150 ms in the APM is only this part, and the database query is just 5 ms of it.
  9. DNS 50 + TCP 150 + TLS 150 + request round trip 150 + server 150 = 650 ms, and the server is only 23% of it.
  10. The frontend then calls two APIs in sequence, each one waiting for the previous one's result. The connection is already open, but each still costs one RTT plus 150 ms on the server.
  11. 650 + 2 × 300 = 1,250 ms, which is where "over a second" comes from. Even if you optimize the server down to 50 ms, the total only drops to 950 ms.

The answer: server processing time is only one leg of the whole journey. Before you optimize a single line of code, find out which stop the time is spent at.

The simplest model and its blind spots

The most intuitive model has three stops: “Client → Server → DB”. It misses many places where time goes:

  • Finding the server: the domain name has to be turned into an IP through DNS first
  • Opening the connection: the TCP three-way handshake, plus the TLS key exchange and certificate verification
  • Queueing: the Load Balancer, Tomcat’s thread pool, and HikariCP’s connection pool all make you wait when they are full
  • Transfer: a large response is limited by bandwidth and TCP congestion control

Worse, server-side metrics run from “Tomcat starts handling the request” to “the response is written”, so connection setup and network transfer time are not in them at all. That is why the server looks fast while users feel it is slow.

Core mechanism: every stop a request makes

sequenceDiagram
    participant C as Client
    participant D as DNS Resolver
    participant L as Load Balancer
    participant A as Spring Boot
    participant P as HikariCP
    participant M as MySQL
    C->>D: Look up api.example.com
    D-->>C: IP (with TTL)
    C->>L: TCP SYN
    L-->>C: SYN-ACK
    C->>L: ACK + TLS ClientHello
    L-->>C: ServerHello + certificate + Finished
    C->>L: TLS Finished + GET /orders
    L->>A: Forward (LB and backend usually share an existing connection)
    A->>P: Get a DB connection
    P-->>A: Connection
    A->>M: SELECT ...
    M-->>A: rows
    A-->>L: 200 OK + JSON
    L-->>C: 200 OK + JSON

Here is the cost of each stop (RTT is the time it takes a packet to make a round trip):

Stage First request Reusing a connection Notes
DNS lookup 0 (cache hit) to tens of ms or more 0 Depends on where the resolver is and on the TTL
TCP handshake 1 RTT 0 SYN → SYN-ACK → ACK
TLS handshake 1 RTT for TLS 1.3, 2 RTT for TLS 1.2 0 Plus the CPU cost of verifying the certificate
Sending the request until the first byte arrives 1 RTT + server processing time Same This is TTFB (Time To First Byte)
Downloading the response body Depends on size and bandwidth Faster A new connection goes through TCP slow start, so its transfer rate ramps up gradually
Queueing in Tomcat 0 and up, varies Same When every thread is busy, requests wait in the accept queue
Getting a DB connection 0 to connection-timeout Same Waits when the pool is exhausted
Running the SQL About 1 ms for a primary-key lookup Same Slow queries are another story

Orders of magnitude for RTT (real values depend on the route and the carrier): under 1 ms within the same data center; about 30–40 ms from Taipei to Tokyo; about 130–160 ms from Taipei to US West.

Use this table to work through the opening scenario. A user in US West connects to a data center in Taiwan, with an RTT of 150 ms, on a first request:

text
DNS 50 + TCP 150 + TLS 150 + request round trip 150 + server 150 = 650 ms before the first byte arrives

The server is only 23% of that. If the frontend then has to call two APIs in sequence, each waiting for the previous one’s result (the connection is already open, so each = 1 RTT + 150 ms on the server):

text
650 + 2 × (150 + 150) = 1,250 ms

That is where the “over a second” comes from. Optimize the server from 150 ms to 50 ms and the total only drops to 950 ms. Cross-region latency is bound by the speed of light, and optimizing code cannot win it back. You can do only two things: make fewer round trips, or move the endpoint closer.

Comparing options: ways to cut round trips

Technique What it saves Cost / prerequisite
Connection reuse (keep-alive, connection pools) The TCP + TLS handshake on every request You have to handle idle connections that the other side has closed
HTTP/2 multiplexing Many requests run on one connection at the same time, with no extra connections Still a single TCP connection underneath, so one lost packet stalls every stream (head-of-line blocking at the TCP layer)
HTTP/3 (QUIC) The transport and crypto handshakes are combined; a lost packet affects only one stream; supports 0-RTT resumption Runs over UDP, which corporate firewalls may block; 0-RTT data can be replayed, so use it only for idempotent requests
TLS session resumption TLS 1.2 goes from 2 RTT to 1 RTT; with TLS 1.3 it saves the cost of sending and verifying the certificate TLS 1.3 still needs 1 RTT unless you use 0-RTT
Terminating TLS at the edge (CDN, a nearby LB) The handshake completes at a node close to the user, so the RTT is shorter The edge-to-origin connections must be kept open and reused, or you only move the latency somewhere else
Combining or parallelizing API calls Fewer round trips spent waiting in sequence More complex API design (BFF, batch APIs, GraphQL)
A longer DNS TTL Fewer DNS lookups During failover, the old IP stays cached longer

In Java

1. Break the time down with curl

bash
curl -o /dev/null -s \
  -w 'dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n' \
  https://api.example.com/orders

Sample output (numbers made up for illustration, not a measurement):

text
dns=0.048 tcp=0.198 tls=0.349 ttfb=0.652 total=0.655

These numbers are cumulative seconds from the start to the end of each stage, so subtract them to get the time of each stage:

Stage Calculation Time
DNS time_namelookup 48 ms
TCP handshake time_connect - time_namelookup 150 ms
TLS handshake time_appconnect - time_connect 151 ms
Waiting for the response time_starttransfer - time_appconnect 303 ms (1 RTT + server processing)
Downloading the body time_total - time_starttransfer 3 ms

2. Java HttpClient: one client for the whole application

java
public final class OrderApiClient {

    // HttpClient has an internal connection pool; TCP and TLS connections are reused only when you share one instance
    private static final HttpClient CLIENT = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(2))
            .build();

    public String fetchOrders(URI uri) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder(uri)
                .timeout(Duration.ofSeconds(3))   // upper bound on waiting for the response; throws HttpTimeoutException when exceeded
                .GET()
                .build();
        return CLIENT.send(request, HttpResponse.BodyHandlers.ofString()).body();
    }
}

To see the effect of connection reuse for yourself, run this program (JDK 11 or later; java ConnectionReuseDemo.java runs it directly):

java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ConnectionReuseDemo {

    public static void main(String[] args) throws Exception {
        URI uri = URI.create(args.length > 0 ? args[0] : "https://example.com/");
        HttpClient client = HttpClient.newHttpClient(); // the same client sends three requests in a row

        for (int i = 1; i <= 3; i++) {
            long start = System.nanoTime();
            HttpResponse<Void> res = client.send(
                    HttpRequest.newBuilder(uri).build(),
                    HttpResponse.BodyHandlers.discarding());
            long ms = (System.nanoTime() - start) / 1_000_000;
            System.out.printf("Request %d: HTTP %d, %d ms%n", i, res.statusCode(), ms);
        }
    }
}

Request 1 is noticeably slower than requests 2 and 3: it includes DNS, the TCP and TLS handshakes, and the cost of the JVM loading the TLS classes for the first time. From request 2 on, only the request’s round trip and the server processing time remain.

3. Server side: log the processing time of every request

yaml
server:
  tomcat:
    basedir: /var/app/tomcat
    accesslog:
      enabled: true
      pattern: '%t %a "%r" %s %b %D'

%D is the time Tomcat spent processing the request (in microseconds since Tomcat 10). It does not include DNS, the handshakes, or network transfer, so subtract it from the total time measured on the client and you know whether the time went to the network or the server.

You also need to watch queueing inside the server: HikariCP exports hikaricp.connections.acquire (time spent waiting to get a connection) and hikaricp.connections.pending (the number of threads currently waiting) through Micrometer. For how to size the connection pool, see HikariCP tuning.

4. The JVM’s DNS cache

The JVM caches DNS results, controlled by the security property networkaddress.cache.ttl. When no SecurityManager is installed, the specification only says the caching period is up to the implementation; OpenJDK uses 30 seconds. Failed lookups are controlled by networkaddress.cache.negative.ttl, which defaults to 10 seconds.

java
// Set this before the first DNS lookup; you can also edit $JAVA_HOME/conf/security/java.security
java.security.Security.setProperty("networkaddress.cache.ttl", "30");

Note that it is a security property, not a system property: -Dnetworkaddress.cache.ttl=30 has no effect.

Pitfalls and gotchas

  • Creating a new client for every call: every request redoes the TCP + TLS handshake, and opening lots of connections also leaves a pile of TIME_WAIT sockets behind. Share the connection factories underneath HttpClient and RestClient
  • A keep-alive idle time longer than the LB’s: the client thinks the connection is still usable, but the LB closed it long ago, so sending a request gets a Connection reset. The rule is that the client’s idle timeout must be shorter than the server’s and the LB’s (for example, the AWS ALB idle timeout defaults to 60 seconds, so set the client to 30–50 seconds)
  • Only looking at server-side latency: server metrics cannot see the handshakes, the time spent queued in the accept queue, or network transfer. Measure what users experience from the client side (Real User Monitoring or synthetic monitoring)
  • Thinking a short DNS TTL means fast failover: the resolvers in between, the operating system, and the JVM all have their own caches and may not honor your TTL. Shift traffic with the LB, not with DNS alone
  • Large responses without compression: a few hundred KB of JSON costs several extra RTTs over a cross-region connection. Spring Boot can turn on gzip with server.compression.enabled=true
  • Finding out only when Tomcat’s threads are exhausted: time spent queued in the accept queue does not count toward the application’s latency metric, so monitor metrics such as tomcat.threads.busy separately (Spring Boot only exports them with server.tomcat.mbeanregistry.enabled=true)

When you need this level of detail

  • You need it: users and servers in different regions, many users on mobile networks, a client-side p99 that does not match the server side, deciding whether to add a CDN or deploy to multiple regions
  • You mostly do not: microservices calling each other within the same data center, where the RTT is under 1 ms and connections are already reused. There the bottleneck is almost always inside the server: queueing, connection pools, slow queries, which the next post covers
  • When to re-evaluate: entering overseas markets, or a change in frontend architecture (for example moving from server-side rendering to an SPA, which means more API calls)

References

Comments