Web and REST APIs series: 1. The web and HTTP · 2. REST API design and Spring Boot
Senior interviews go beyond “GET reads, POST creates”: is it safe to retry a POST, why might PATCH not be idempotent, what does HTTP/2 change, why does Postman work when the browser reports a CORS error? This post answers those questions, from the Internet and HTTPS to methods, status codes, HTTP versions, timeouts and CORS. Part 2 builds on it to design REST APIs and set up a Spring Boot project.
The running example in both parts is the course’s pet project: an online-course (E-Learning) platform (teachers, courses, chapters, lessons, learners who enrol, rate courses and track progress); its schema is in SQL exercises on the E-Learning database. The hotel booking system in the Backend practice series is the instructor’s worked example of analysing requirements and designing an API, not the pet project I build.
1. How the Internet works
Key idea: the Internet is a network of networks, and every machine has an IP address. When you type a URL, the browser asks DNS for the IP, opens TCP, does the TLS handshake, and only then sends the HTTP request.
sequenceDiagram
participant B as Browser
participant D as DNS resolver
participant S as Server (example.com)
B->>D: What is the IP of example.com?
D-->>B: 93.184.215.14
B->>S: TCP handshake (SYN, SYN-ACK, ACK) on port 443
B->>S: TLS handshake (agree on keys, check the certificate)
B->>S: HTTP request: GET /courses
S-->>B: HTTP response: 200 OK + body
- An IP address identifies a machine (strictly, a network interface), like a street address.
- DNS turns a domain name into an IP. Answers are cached in the browser, the OS and the ISP’s resolver according to their TTL (how long a cached answer lives).
- IP routes packets across many routers. It guarantees neither delivery nor ordering.
- TCP sits on top of IP and gives a reliable connection: sequence numbers, retransmission, flow control. A port picks the application that gets the data (80 HTTP, 443 HTTPS, 8080 common in development).
- HTTP is an application-layer protocol over TCP (HTTP/1.1, HTTP/2) or QUIC/UDP (HTTP/3).
Clients and servers. The client initiates the request (a browser, a phone app, another service). The server runs continuously, waiting for requests and answering them, at a stable address. “Client/server” is a role in one conversation: when service A calls service B, A is the client, even though A is a server to the browser.
The two meanings of “server”, kinds of server and the layer model
Each server offers a kind of service over its own protocol: a web server serves websites and APIs over HTTP(S), a mail server accepts and relays email over SMTP (mail is read with IMAP/POP3), a DNS server answers name lookups. Every machine has its own IP (say your PC is 104.28.254.74, the mail server 172.33.17.88, the web server 138.98.66.90), and they all reach each other through chains of routers, which is what the Internet is. A client machine comes and goes; a server needs a static IP or a domain name.
“Server” means two things, and interviews mix them up: the machine (physical, a VM or a container) and the server process listening on a port, such as the Tomcat embedded in a Spring Boot app listening on 8080. One machine can run several server processes (web on 443, the database on 3306).
A simplified layer model:
| Layer | Example protocols | Responsibility |
|---|---|---|
| Application | HTTP, DNS, SMTP | What the data means |
| Transport | TCP, UDP, QUIC | Process-to-process delivery, reliable or not |
| Network | IP | Routing between machines |
| Link | Ethernet, Wi-Fi | Moving frames within one physical network |
2. How the web works
Key idea: a client (usually a browser) sends an HTTP request and the server sends back an HTTP response: either a ready-made HTML page, or just JSON data.
2.1. The traditional web model (server-side rendering)
Key idea: every navigation makes the server render fresh HTML (JSP, Thymeleaf, PHP…). It’s simple and SEO-friendly, but the server owns the UI too, so it’s hard to share with a mobile app.
Three kinds of files, like a house:
- HTML: structure and content (the frame and walls).
- CSS: presentation, colours, fonts, layout (paint and furniture).
- JavaScript: behaviour and interactivity (the wiring and plumbing that make the house work).
On the Spring side, a request goes through DispatcherServlet to a controller, and a ViewResolver turns the view name into an HTML page: see the Spring MVC post.
2.2. The Web API model
Key idea: the server returns data only (usually JSON) and the client draws the UI: an SPA (React, Vue), a mobile app or another service. One backend serves many kinds of clients at once; the course and this post focus on this model.
flowchart LR
W[Web SPA] -->|JSON over HTTP| API[Backend API]
M[Mobile app] -->|JSON over HTTP| API
P[Partner service] -->|JSON over HTTP| API
API --> DB[(Database)]
2.3. HTTP and HTTPS
Key idea: HTTP isn’t encrypted, so anyone on the path (café Wi-Fi, a proxy) can read and tamper with it. HTTPS is HTTP over TLS, which gives confidentiality, integrity and server authentication.
HTTP (HyperText Transfer Protocol) is a request/response protocol, textual in HTTP/1.1 and framed binary in HTTP/2 and HTTP/3. TLS adds:
- Confidentiality: the content is encrypted with a symmetric session key.
- Integrity: any modification in transit is detected.
- Server authentication: a certificate signed by a CA (an authority the browser trusts) proves you’re really talking to
example.com.
The TLS 1.3 handshake in a nutshell:
sequenceDiagram
participant C as Client
participant S as Server
C->>S: ClientHello (supported ciphers, key share)
S-->>C: ServerHello (key share) + Certificate + Finished
Note over C: Verify the certificate chain up to a trusted root CA, derive session keys
C->>S: Finished + encrypted HTTP request
Session keys come from an ephemeral key exchange (ECDHE), which gives forward secrecy: even if the server’s private key leaks later, old sessions can’t be decrypted. Asymmetric crypto is used only in the handshake; the data is encrypted symmetrically (AES-GCM, ChaCha20) because that’s far faster.
In real systems, TLS is usually terminated (decrypted) at the load balancer or ingress (Nginx, ALB). Behind it is plain HTTP on the private network, or mTLS if you need zero trust. The app learns the original request was HTTPS from the X-Forwarded-Proto header (Spring Boot: server.forward-headers-strategy=framework).
2.4. HTTP methods and their semantics
Key idea: each method has two properties worth knowing by heart: safe (doesn’t change server state) and idempotent (once or N times, same final state). Idempotency decides whether a retry is safe.
| Method | Used for | Safe | Idempotent | Body |
|---|---|---|---|---|
| GET | Read a resource | Yes | Yes | Shouldn’t |
| HEAD | Like GET, headers only | Yes | Yes | No |
| OPTIONS | Ask what the server supports (CORS preflight) | Yes | Yes | No |
| POST | Create, or any action that fits no other method | No | No | Yes |
| PUT | Replace a whole resource (or create it at a known URL) | No | Yes | Yes |
| PATCH | Partial update | No | Not guaranteed | Yes |
| DELETE | Remove a resource | No | Yes | Usually no |
CRUD ↔ HTTP method table and actions outside CRUD
Which method maps to which CRUD operation. This is a REST convention, not an HTTP rule:
| CRUD operation | HTTP method | Example |
|---|---|---|
| Create | POST (to the collection) |
POST /api/v1/courses |
| Read | GET |
GET /api/v1/courses/12 |
| Update | PUT (full replace) or PATCH (partial) |
PATCH /api/v1/courses/12 |
| Delete | DELETE |
DELETE /api/v1/courses/12 |
The slide maps Update to PUT only, but in practice most edits are PATCHes. Actions that don’t fit CRUD (cancelling an order, marking a lesson as done) are usually a POST to a sub-resource, such as POST /orders/145/cancel (see part 2).
- PUT is idempotent because sending the same full representation any number of times leaves that representation in place. PATCH depends:
{"age": 30}is idempotent,{"op": "increment", "path": "/balance", "value": 10}isn’t. - Why it matters: the network can time out after the server has done the work, and then clients, proxies or HTTP libraries retry. Retrying GET/PUT/DELETE is safe; retrying a POST (create an order, transfer money) can create duplicates.
- The common fix: an Idempotency-Key. The client generates a UUID per operation; the server stores the result under that key and replays it when the key shows up again.
A compact Idempotency-Key endpoint in Spring:
@PostMapping("/v1/orders")
public ResponseEntity<OrderResponse> create(
@RequestHeader("Idempotency-Key") String key,
@Valid @RequestBody CreateOrderRequest request) {
// createOnce: if the key exists, return the stored result; otherwise create the order
// and store the key in the same transaction. A UNIQUE constraint on the key column
// stops two concurrent requests from both getting through.
OrderResponse response = orderService.createOnce(key, request);
return ResponseEntity
.created(URI.create("/v1/orders/" + response.id()))
.body(response);
}
2.5. HTTP status codes
Key idea: five classes: 1xx informational, 2xx success, 3xx redirection, 4xx client error, 5xx server error. Monitoring, retries and caches all rely on them.
| Code | Meaning | When to use it |
|---|---|---|
| 200 OK | Success with a body | GET, a PUT/PATCH that returns the resource |
| 201 Created | Resource created | POST (or a PUT that creates); add a Location header |
| 204 No Content | Success, no body | DELETE, a PUT that returns nothing |
| 400 Bad Request | Malformed or invalid request | Broken JSON, missing field |
| 401 Unauthorized | Not authenticated | Missing or invalid token |
| 403 Forbidden | We know who you are, but you’re not allowed | A regular user calling an admin API |
| 404 Not Found | No such resource | Unknown id |
| 409 Conflict | State conflict | Email already taken, version mismatch |
| 429 Too Many Requests | Rate limited | Send Retry-After |
| 500 Internal Server Error | Something unexpected | A bug, an unhandled exception |
| 503 Service Unavailable | Temporarily unable to serve | Overload, maintenance; send Retry-After |
“401 Unauthorized” is a historical misnomer; it really means unauthenticated. Authorization failures are 403.
The other codes: 202, 301/308, 304, 405, 422, 502, 504
| Code | Meaning | When to use it |
|---|---|---|
| 202 Accepted | Received, will be processed later | Asynchronous jobs |
| 301 / 308 | Permanent redirect | URL moved; 308 keeps the method |
| 304 Not Modified | Use your cached copy | Conditional GET with an ETag |
| 405 Method Not Allowed | Method not supported on this URL | DELETE /orders when only GET/POST exist |
| 422 Unprocessable Content | Valid syntax, breaks a business rule | End date before start date |
| 502 Bad Gateway | The gateway got a bad response from upstream | Nginx talking to a crashed app |
| 504 Gateway Timeout | Upstream didn’t answer in time | The app took too long |
2.6. HTTP/1.1, HTTP/2, HTTP/3 and connections
Key idea: HTTP/2 multiplexes many requests over one connection, and HTTP/3 moves to QUIC so a lost packet doesn’t stall every stream. For backend code, what matters most is sharing the HTTP client and always setting timeouts.
| HTTP/1.1 | HTTP/2 | HTTP/3 | |
|---|---|---|---|
| Format | Text | Binary frames | Binary frames |
| Transport | TCP | TCP (browsers only speak HTTP/2 over TLS) | QUIC over UDP, with TLS 1.3 built into QUIC |
| Parallel requests | One request at a time per connection; browsers open about 6 connections per host | Multiplexing: many streams over one connection | Multiplexing with independent streams |
| Head-of-line blocking | At the HTTP layer: a request waits for the one before it | Gone at the HTTP layer but still there at TCP: one lost packet stalls every stream | Gone: a lost packet only delays its own stream |
| Headers | Repeated verbatim on every request | HPACK compression | QPACK compression |
| Connection setup | TCP + TLS 1.3: about 2 RTTs | Same as HTTP/1.1 | 1 RTT, 0-RTT on resumption |
Head-of-line blocking: one stuck packet at the front makes everything behind it wait, like a stalled car in a single-lane road. RTT: one round trip.
Reuse connections. Opening TCP + TLS costs a few round trips plus CPU for the handshake, so every HTTP client has a connection pool (open connections kept for reuse). Create your client (the JDK HttpClient, RestClient, WebClient) once and share it, for example as a bean. Building one per request throws the pool away and pays for a handshake every time.
// Build once and share across the application: the client keeps its own connection pool
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2) // falls back to HTTP/1.1 if the server can't do 2
.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 the response
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.version() + " " + response.statusCode()); // HTTP_2 200
Keep-alive, TIME_WAIT, HTTP/2 between services and HTTP/3
- Keep-alive. HTTP/1.1 already keeps the connection open after the response, and client pools build on that. Building a new client per request can also exhaust ephemeral ports because too many connections sit in
TIME_WAIT. Measured cost of a new connection (DNS + TCP + TLS 1.3, about 166 ms versus 52 ms when reused) and which side holds TIME_WAIT are in Networking for backend engineers. - HTTP/2 between services. gRPC runs on HTTP/2, so it gets multiplexing and streaming. Tomcat in Spring Boot enables HTTP/2 with
server.http2.enabled=true, but if TLS is terminated at the load balancer, the LB-to-app hop is often still HTTP/1.1, and that’s fine. Choosing REST or gRPC between backends, and why HTTP/2 server push is effectively dead, is in the synchronous communication post. - HTTP/3 usually lives at the CDN or load balancer in front. The Java application behind it rarely speaks QUIC itself.
In Spring, the timeouts go on the RestClient’s request factory:
@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();
}
Choosing timeouts, safe retries (backoff, jitter, idempotency keys), circuit breakers and bulkheads are covered in Timeouts, retries and circuit breakers.
2.7. CORS: why Postman works and the browser doesn’t
Key idea: browsers enforce the same-origin policy: a script from one origin can’t read responses from another. CORS (Cross-Origin Resource Sharing) is how the server tells the browser which origins are allowed. Postman and curl aren’t browsers, so they ignore it completely.
An origin = scheme + host + port. https://app.example.com and https://api.example.com are two different origins.
- A “simple” request (GET, or POST with a form content type and no custom headers) goes out straight away with an
Originheader. Without a matchingAccess-Control-Allow-Origin, the browser won’t let JavaScript read the response, even though the request reached the server and was processed. - Everything else (PUT, PATCH, DELETE,
Content-Type: application/json, anAuthorizationheader…) triggers a preflightOPTIONSrequest first, and the real request goes out only once that is allowed.
sequenceDiagram
participant B as Browser (app.example.com)
participant A as API (api.example.com)
B->>A: OPTIONS /api/v1/orders/7 (Origin, Access-Control-Request-Method: PATCH)
A-->>B: 204 + Access-Control-Allow-Origin: https://app.example.com, Allow-Methods, Allow-Headers, Max-Age
B->>A: PATCH /api/v1/orders/7 (Origin, Authorization)
A-->>B: 200 + Access-Control-Allow-Origin: https://app.example.com
Configuring CORS in Spring MVC and Spring Security
@Configuration
class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com") // list them explicitly, no "*"
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.allowedHeaders("Authorization", "Content-Type", "Idempotency-Key")
.allowCredentials(true)
.maxAge(3600); // browsers cache the preflight result for an hour
}
}
With Spring Security you also need http.cors(Customizer.withDefaults()). Otherwise the security filter, which runs before Spring MVC, rejects the preflight (it has no token) with a 401/403, and the browser reports a “CORS error” even though the configuration above is right.
How the server authenticates instead (session cookies with the right flags, or JWTs with refresh tokens) is in Authentication: session cookies and JWT. CORS doesn’t stop CSRF either, because the browser still sends the request with its cookies and only blocks the script from reading the response; CSRF, XSS and a Spring Security 6 baseline are in Web attacks and the OWASP Top 10.
Further reading: Part 2: REST API design and Spring Boot uses these semantics to design URLs, pagination and an error format. After that, Advanced REST API design goes deeper: a strict definition of safe and idempotent, URLs behind an API gateway, and cursor pagination and safe sorting at scale.
Remember
- Walk through what happens between typing a URL and getting the response (DNS, TCP, TLS, HTTP).
- Explain safe vs idempotent, why PATCH isn’t guaranteed to be idempotent, and how to retry a POST without duplicates.
- Pick the right status code for 401/403 and 400/409/422, and know which codes are worth retrying.
- Explain why an HTTP client must be shared and always have timeouts, and how one slow dependency takes a whole service down.
- Explain why Postman works while the browser reports a CORS error, and why CORS doesn’t replace authentication.
Interview questions
Junior
What’s the difference between HTTP and HTTPS?
HTTPS is HTTP over TLS: encrypted, tamper-evident, and the server is authenticated.
TLS authenticates the server with a CA-signed certificate. Plain HTTP is sent in clear text, so anyone on the path can read or change it. By default HTTP uses port 80 and HTTPS uses 443.
How do PUT and PATCH differ?
PUT replaces the whole resource and is idempotent; PATCH changes only what you send and isn’t guaranteed to be idempotent.
With PUT, any field left out is cleared or reset. Whether a PATCH is idempotent depends on the operation: setting a value is, incrementing isn’t.
What’s the difference between 401 and 403?
401 means not authenticated; 403 means authenticated but not allowed.
401: the token is missing, wrong or expired, and the client should log in again. 403: the server knows who you are but you can’t access the resource; logging in again won’t help.
How do 4xx and 5xx differ, and which ones should a client retry?
4xx means the client got it wrong, so the same request fails again; 5xx means the server failed, and 502/503/504 are often transient, so they can be retried.
- 4xx (bad request, missing authentication, no permission, state conflict): don’t retry, except 429 (wait for
Retry-After) and 408. - 502, 503, 504: retry with exponential backoff, jitter and a cap on attempts. A 500 caused by a bug rarely goes away on retry.
- Automatic retries are only safe for idempotent methods or requests carrying an Idempotency-Key.
What is the difference between a client and a server? Is a “server” the machine or the program?
The client initiates requests, the server runs continuously to wait for and answer them; “server” can mean either the machine or the process.
The machine is physical, a VM or a container; the process is a program listening on a port, like an embedded Tomcat on 8080. Client/server is a role in one conversation: a service is a server to the browser and a client when it calls the database or another service.
Mid
What do safe and idempotent mean? Give examples.
Safe means it doesn’t change server state (GET, HEAD, OPTIONS); idempotent means once or many times leaves the same final state (all safe methods plus PUT and DELETE).
POST is not idempotent. Responses may differ (a second DELETE returns 404) and the method is still idempotent, because we judge by server state.
How can a client retry a “create order” POST without creating duplicates?
Use an Idempotency-Key: the client sends a UUID per operation, and when the server sees the key again it returns the stored result.
The server stores the key and the result in the same transaction that creates the order, with a unique constraint on the key to block concurrent duplicates. Keys expire after a while (say 24 hours).
What does HTTP/2 improve over HTTP/1.1, and what extra problem does HTTP/3 solve?
HTTP/2 multiplexes many streams over one connection and compresses headers; HTTP/3 moves to QUIC so a lost packet doesn’t stall every stream.
- HTTP/2: binary frames and multiplexing, so requests no longer queue behind each other at the HTTP layer, plus HPACK header compression. But it still runs on TCP: one lost packet stalls every stream on the connection (head-of-line blocking at the TCP layer).
- HTTP/3: QUIC over UDP, where each stream is delivered independently, so a lost packet only delays its own stream. TLS 1.3 is built into QUIC, giving a 1-RTT handshake, 0-RTT on resumption, and connections that survive a network change (Wi-Fi to 4G).
What is CORS? Why does Postman reach the API while the browser shows a CORS error?
CORS is how a server lets other origins read its responses, relaxing the browser’s same-origin policy. Postman and curl aren’t browsers, so the policy doesn’t apply to them.
A script from origin A can read a response from origin B only if B returns an Access-Control-Allow-Origin header that allows A. For non-simple requests (JSON bodies, PUT/PATCH/DELETE, an Authorization header) the browser sends a preflight OPTIONS first. The proper fix is server-side CORS configuration with an explicit list of origins (and enabling CORS in Spring Security so the preflight isn’t blocked), not disabling checks on the client. CORS is not a replacement for authentication.
Senior
What changes for the application when TLS is terminated at the load balancer?
The app receives plain HTTP, so it relies on forwarded headers to know the original request, and the LB-to-app hop is no longer encrypted.
- Use
X-Forwarded-Proto/For/Host(orForwarded) to learn the original scheme and client IP and to build correct redirects and links; trust those headers only from known proxies. - For sensitive data or compliance, re-encrypt or use mTLS in a service mesh.
- Certificate rotation is centralised at the LB.
A slow third-party API takes your whole service down. Why, and how do you guard against it?
Every request calling the slow dependency holds a thread; without a timeout the thread pool drains and every other endpoint dies too. Guard with timeouts, controlled retries, a circuit breaker and bulkheads.
Tomcat has 200 threads by default; one dependency’s failure cascades into the whole system. Guards:
- Connect and read timeouts on every outbound call.
- Bounded retries with backoff, only for idempotent operations.
- A circuit breaker (Resilience4j) to fail fast while the dependency is down.
- A bulkhead (a dedicated pool or semaphore per dependency) so one dependency can’t eat all resources.
- A fallback or an early 503; per-dependency latency and error-rate metrics so you see the degradation coming.
Useful phrases for interviews
- “The key property here is idempotency: if the client retries after a timeout, we don’t want to charge the customer twice.”
- “I’d return a 409 Conflict rather than a 400, because the request is well-formed but clashes with the current state.”
- “We terminate TLS at the load balancer and rely on forwarded headers to reconstruct the original scheme.”
- “4xx means the client has to change the request; 5xx may be transient, so that’s where retries with backoff make sense.”
- “HTTP/2 removes head-of-line blocking at the HTTP layer, but TCP still has it; HTTP/3 fixes that by moving to QUIC.”
- “CORS is enforced by the browser, so it protects users, not the API; we still authenticate every request on the server.”
- “We create the HTTP client once and share it, so connections are reused instead of paying for a TLS handshake on every call.”
- “No outbound call goes out without a timeout; otherwise one slow dependency can exhaust our thread pool.”
Notes based on the Fundamentals of Backend course (Ronin Engineer), rewritten in my own words.