SteelReed

Search

Search posts, questions…

5. Spring Boot

Where one HTTP request travels: DNS, TLS, methods, status codes, HTTP/2, HTTP/3 and CORS

Follow one request through DNS, TCP and TLS to HTTP to see why retrying a POST creates duplicate orders, why a missing timeout takes a service down, how to pick status codes, HTTP/2 or HTTP/3, and why Postman works while the browser reports a CORS error; plus how to review an AI-written HTTP client.

17 Nov 20269 min readMid

–

1. The problem

A mobile app sends POST /v1/orders for 1,250,000 VND. The server saves the order, then 4G drops and the app resends: the customer has two orders. The same week the payment service hangs for 40 seconds; the client has no timeout, so all 200 Tomcat threads get stuck.

2. Key idea

A request goes through DNS, TCP (or QUIC) and TLS before it reaches HTTP. Any hop can fail. With no response, the client doesn't know whether the server did the work. Every outbound call needs three answers: is resending safe, whose fault is the error, how long do I wait at most.

2.1 Which methods can be resent?

Safe: doesn't change server state. Idempotent: calling once or N times leaves the same final state.

Method Safe Idempotent
GET, HEAD, OPTIONS Yes Yes
PUT, DELETE No Yes
POST No No
PATCH No Not guaranteed
  • A second DELETE that returns 404 is still idempotent.
  • Retrying a POST is only safe with an Idempotency-Key header and a UNIQUE constraint on the key column.
  • GET must never have side effects: crawlers call GET whenever they like.

2.2 What does the status code say?

  • 4xx: the client fixes the request, no retry. 401 not authenticated, 403 not allowed, 409 conflict.
  • 429: rate limited, retry after the Retry-After header.
  • 502, 503, 504: temporary failure, retry with backoff.
  • Don't return 200 with {"success": false}: monitoring and retries rely on the status code.

2.3 What do I use when?

Technique Use when Don't use when
Retry with backoff GET, PUT, DELETE; 502/503/504, 429, connection errors POST, PATCH without an Idempotency-Key
Idempotency-Key + UNIQUE creating orders, moving money GET, PUT are already idempotent
HTTP/2 (many requests on one connection) many parallel requests to one host, gRPC the LB → app hop is fine on HTTP/1.1
HTTP/3 (QUIC over UDP) mobile clients, lossy networks; usually enabled at the CDN internal services
CORS configuration a browser on another origin calls the API as a replacement for authentication

CORS is how the server tells the browser which origins may read the response. Postman and curl aren't browsers, so they ignore it.

3. In Java

One shared client, always with two timeouts.

JAVA
// Build once (a bean) and share it: the client keeps a connection pool
HttpClient client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)      // falls back to HTTP/1.1 if the server can't do it
        .connectTimeout(Duration.ofSeconds(2))   // max time to open a connection
        .build();
 
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
        .timeout(Duration.ofSeconds(5))          // max time to wait for a response; unset means forever
        .GET()
        .build();
 
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.version() + " " + response.statusCode());   // HTTP_2 200

Spring: use RestClient; RestTemplate is deprecated since Spring Framework 7.1. Other languages: Go needs http.Client{Timeout: ...} because the default has none; Node.js uses AbortSignal.timeout(...).

Default timeouts, connection pools and TLS
  • HttpURLConnection and SimpleClientHttpRequestFactory default to a connect timeout and read timeout of 0, meaning wait forever.
  • A new client per request throws away the connection pool, pays DNS + TCP + TLS every time, and can exhaust ephemeral ports with connections stuck in TIME_WAIT.
  • HTTP/2 removes blocking at the HTTP layer, but one lost TCP packet stalls every stream (head-of-line blocking); HTTP/3 runs on QUIC, so only that stream slows down.
  • TLS is usually terminated (decrypted) at the load balancer; the app learns the original request was HTTPS from X-Forwarded-Proto. Enable only TLS 1.2 and 1.3.
JAVA
@Bean
RestClient paymentClient(RestClient.Builder builder) {
    var factory = new SimpleClientHttpRequestFactory();
    factory.setConnectTimeout(Duration.ofSeconds(2));
    factory.setReadTimeout(Duration.ofSeconds(5));
    return builder.baseUrl("https://payments.internal").requestFactory(factory).build();
}
CORS: preflight and Spring configuration
  • Origin = scheme + host + port: https://app.example.com and https://api.example.com are two origins.
  • For JSON, PUT/PATCH/DELETE or an Authorization header, the browser sends a preflight OPTIONS first and only sends the real request if allowed.
  • List origins explicitly. * doesn't work with credentials; reflecting any Origin lets any malicious page read the logged-in user's data.
  • With Spring Security, also enable http.cors(Customizer.withDefaults()). Otherwise the security filter rejects the preflight (no token) with 401/403 and the browser still reports a "CORS error".
JAVA
registry.addMapping("/api/**")
        .allowedOrigins("https://app.example.com")
        .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
        .allowedHeaders("Authorization", "Content-Type", "Idempotency-Key")
        .allowCredentials(true)
        .maxAge(3600);   // the browser caches the preflight result for 1 hour

4. Working with AI

Hand to AI: generating a client from OpenAPI, WireMock tests for timeouts and 503.

Check in AI-written code:

  • The client is a shared bean, not created inside a method.
  • There is a connect timeout and a read timeout: search for setReadTimeout, .timeout(.
  • Only idempotent methods or requests with an Idempotency-Key are retried; no retry on 4xx (except 408, 429).
  • The Idempotency-Key has a UNIQUE constraint, not just findByKey then save.
  • CORS lists explicit origins, no * and no reflected Origin.

5. Exercises

Exercise 1: Review an Idempotency-Key that "prevents duplicates"

The AI wrote in the PR: "duplicates prevented with an Idempotency-Key". Find the bug, name a test that proves it, fix it.

JAVA
@Transactional
public OrderResponse createOnce(String key, CreateOrderRequest req) {
    return keys.findByKey(key)
            .map(k -> k.response())
            .orElseGet(() -> {
                OrderResponse r = orders.create(req);
                keys.save(new IdempotencyRecord(key, r));
                return r;
            });
}
Solution to Exercise 1

This is check-then-act: two requests with the same key arriving in parallel both see findByKey empty and both create an order. @Transactional at READ COMMITTED doesn't stop it.

Test: two threads call createOnce("k1", req) behind a CountDownLatch on a real DB (Testcontainers), then count orders: 2.

Fix: a UNIQUE constraint on key; INSERT the key record first (status IN_PROGRESS), then create the order, in the same transaction. The second request violates UNIQUE, catches it and reads back the result, or returns 409 if the first one isn't done yet.

Exercise 2: Read an incident

p99 of /checkout goes from 300 ms to 30 s; tomcat.threads.busy is 200/200. Thread dump: 190 threads parked in SocketInputStream.read, all calling payments.internal. Diagnose it, say what you do in the next 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: the payment service hangs; the client has no read timeout, so each request holds a Tomcat thread until all 200 are gone.
  • 15 minutes: switch payments off with a feature flag or fail /checkout fast with 503; a restart won't help while payments still hang. Tell the payments team.
  • Root fix: a read timeout based on the SLA (say 5 s), a circuit breaker and a separate pool for payments, an alert on tomcat.threads.busy. See Timeouts, retries and circuit breakers.

Summary

  • A timeout doesn't tell you whether the server did the work; only retry what is idempotent.
  • Retrying a POST is safe with an Idempotency-Key + UNIQUE constraint.
  • 4xx: fix the request; 502/503/504: retry with backoff.
  • Share one HTTP client and always set a connect timeout and a read timeout.
  • CORS is enforced by the browser and doesn't replace authentication.

Next: Part 2: REST API design and Spring Boot.

Practice interview questions on this topic

All Web & REST API questions →

Loading comments…