The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S9 · V1·09

An HTTP Server by Hand

Volume 1, chapter 09. TiffinBox gets a network face: a small HTTP/1.1 server written on plain sockets, one virtual thread per connection, serving menu search, idempotent order placement backed by stage 8's durable log, order lookup and each kitchen's next ticket. The parser is strict and bounded (bare line feeds, duplicate lengths, chunked bodies and slow clients are refused), idempotency survives restarts, and twenty simultaneous duplicate requests create one order. A restart test catches a time precision the log was silently losing, and a load test finds that the client, not the server, was the bottleneck.

6 parts · ~8 min to read
Updated Suggest a correction

Stage 9: an HTTP server by hand

The brief

What you'll build. A new server/ module, depending on core:

  • HttpRequest.read(in): a strict, bounded HTTP/1.1 request parser (request line, headers, Content-Length body), with a BadRequest exception carrying the status to answer with;
  • Server: accepts connections on a platform thread, serves each on a virtual thread, keeps connections alive, and enforces an idle timeout, a deadline for receiving a request's head, and a connection limit;
  • routes:
  • GET /health;
  • GET /menu/search?q=&limit= (stage 3's Menu, swapped atomically when it changes);
  • POST /orders with X-Customer-Id and Idempotency-Key headers (stage 5's keys; durable via stage 8's log before answering 201; a retry gets 200 with the same order);
  • GET /orders/{id};
  • GET /kitchens/{id}/next (stage 3's KitchenQueue, now behind a lock);
  • ServerTest: 6 end-to-end tests, including restart, concurrent duplicates, malformed requests and a slow client;
  • Load9: throughput and latency for searches (kept-alive and new connections) and order placement.

Why a real company needs this. Every framework (Tomcat, Netty, Spring) does what this stage does by hand: parse untrusted bytes into requests, decide how long to wait, limit concurrency, and map failures to status codes. When a production incident involves 400s from a proxy, connections reset by a load balancer or a slowloris attack, knowing what the server underneath does is what lets you diagnose it. Volume 3 replaces this server with Spring Boot; this stage is how you'll know what Spring is doing for you.

Why now. Chapter 09 covers TCP connections, HTTP's framing, timeouts and the fallacies of distributed computing. Earlier stages left promises for exactly this stage: menu search on every keystroke, the Idempotency-Key contract, a thread-safe kitchen queue, and swapping an immutable menu while readers keep reading.

What you'll have at the end.

  • server/ with its own build and 6 tests; core gains a test (39 in total);
  • load-test numbers for three ways of calling the server;
  • ADR-0011: the HTTP contract (statuses, limits, idempotency) and what the hand-written server deliberately doesn't support.

Theory to own

  1. Framing. How does an HTTP/1.1 server know where a request's body ends? What goes wrong if two components in a chain disagree about it? (Chapter: "Sockets: putting it together"; Companion, theoretical gap 3.)
  2. Timeouts. Name three different things a server must time out: before a request starts, while its head is arriving, and while a handler runs. Which does setSoTimeout cover, and which does it miss? (Chapter: "Timeouts and the network fallacies".)
  3. Idempotency on the wire. Two identical "place order" requests arrive at the same moment on different connections. What must the server guarantee, and what answer does each get? (Stage 5; Companion, theoretical gap 2.)
  4. Publishing a new menu. Menus change while searches run. How can a reader get either the old menu or the new one, never a mix, without locking? (Chapter 08: "Shared memory between threads"; stage 3.)
  5. Virtual threads and locks. On JDK 21, why should a lock held while blocking be a ReentrantLock rather than synchronized? (Companion to chapter 08, Gaps 1.)

Build it

Step 1: a strict, bounded parser

Write HttpRequest.read(InputStream):

  • read CRLF-terminated ASCII lines, rejecting bare LF, control characters, non-ASCII bytes and lines over 8 KB;
  • request line: exactly three parts; method of capital letters; target starting with /; version exactly HTTP/1.1 (else 505);
  • headers: at most 100 and 16 KB in total (else 431); Name: value with no space before the colon; duplicate Content-Length or Host rejected; Host required;
  • Transfer-Encoding rejected with 501;
  • body by Content-Length: digits only, at most 64 KB (else 413), read fully;
  • query parameters URL-decoded, with malformed encodings rejected.

Return null on a clean end of stream before the first byte (a kept-alive client closing).

Checkpoint. It compiles, and every rejection carries a status code.

Step 2: connections, virtual threads and timeouts

Write Server:

  • bind a ServerSocket to the loopback address (port 0 in tests picks a free port);
  • an acceptor platform thread loops on accept(); if more than maxConnections are open, it answers 503 and closes; otherwise it hands the socket to a virtual-thread-per-task executor;
  • each connection loop: set the socket's read timeout to the idle limit; for each request, wrap the stream in a DeadlineInputStream that fails once the head deadline has passed; parse; route; write the response with Content-Length; keep the connection unless the client asked to close;
  • on BadRequest, answer with its status and close: after a framing error, nobody knows where the next request starts.

Make the limits a record, Limits(idle, headDeadline, maxConnections), with defaults of 5 s, 10 s and 2,000, so tests can use shorter ones.

Checkpoint. A client that sends a request head one byte every 100 ms is disconnected after the head deadline (0.8 s in the test), without a response.

Step 3: routes, and the shared state they touch

Implement the routes, with these concurrency choices:

  • menu: an AtomicReference<Menu>; search calls menu.get() once per request; replaceMenu sets a new one;
  • orders: a ConcurrentHashMap<String, Order> for lookups;
  • kitchen queues: a HashMap<String, KitchenQueue> guarded by one ReentrantLock;
  • JSON: hand-written in a small Json class, escaping strings, with money as integer paise.

Checkpoint. GET /menu/search?q=mas&limit=5 returns exactly [{"id":"d1","name":"Masala dosa","pricePaise":8950},{"id":"d3","name":"Paneer masala","pricePaise":18000}], and limit=500 returns 400.

Step 4: idempotent, durable order placement

POST /orders with headers X-Customer-Id and Idempotency-Key, and a body of kitchen k7 followed by dishId quantity lines:

  1. build the stage 5 key from the two headers (400 if either is missing);
  2. claim the key with byKey.putIfAbsent(key, new CompletableFuture<>()); if another request already claimed it, wait for that future and answer 200 with its order;
  3. otherwise validate and build the order (400 for unknown dishes or bad lines, releasing the key so a corrected request can use it), append it to the OrderLog with the key and wait for durability, add it to the kitchen's queue, complete the future, and answer 201 with a Location header.

On startup, rebuild orders and keys from log.recovered(), and continue order ids after the highest recovered one.

Checkpoint. A retry returns 200 and the same body; 20 concurrent identical requests produce one order and one 201; after closing and reopening the server and log, the order exists, a retry still returns it, and the next order is o2.

Step 5: end-to-end tests, and a bug only a restart could find

Write ServerTest with java.net.http.HttpClient for well-formed requests and raw sockets for malformed ones: health and search; idempotent placement; concurrent duplicates; restart; strict parsing (bare LF, chunked, duplicate Content-Length, a 70,000-byte body, HTTP/1.0, a space before a colon, no Host); and the slow client.

Checkpoint. All 6 server tests pass.

Step 6: load test

Write Load9.java that starts the server with a 200-dish menu and measures, for 5 seconds each with 64 concurrent virtual-thread clients:

  1. GET /menu/search through java.net.http.HttpClient (which keeps connections alive);
  2. the same with a minimal raw-socket client keeping one connection per worker;
  3. the same with the raw client opening a new connection per request (Connection: close);
  4. POST /orders through HttpClient, each with a fresh idempotency key.

Report requests per second, p50 and p99, and errors.

Checkpoint. You can say which component limited each number.

Senior and architect lens

1. A server is a set of limits. Every number in Limits and HttpRequest (idle 5 s, head deadline 10 s, 2,000 connections, 8 KB lines, 100 headers, 64 KB bodies, limit ≤ 50) is a decision about how much of the machine one client may consume. Frameworks have the same numbers with different defaults; part of running one well is knowing them (the JDK's own HTTP server allows requests to take forever by default, the Companion's walkthrough).

2. ADR-0011: the HTTP contract. Write it with these points:

  • Statuses: 201 for a new order with Location; 200 for a retried idempotent request with the original body; 400 for invalid input (the key is released); 404, 413, 431, 501 (no chunked bodies), 503 (connection limit), 505 (HTTP/1.1 only).
  • Idempotency: Idempotency-Key plus X-Customer-Id are required on POST /orders; keys never expire yet (revisit with Volume 3's database and a retention period).
  • Durability: 201 means the order is in the fsynced log.
  • Limits: the table above, as part of the contract clients can rely on.
  • Not supported, on purpose: TLS (terminated by a proxy in front; Volume 7), HTTP/2, chunked bodies, compression, authentication (Volume 3 and 7).
  • Revisit when: Volume 3 moves to Spring Boot. The contract must survive the move; the server code doesn't.

3. Reject ambiguity at the edge. Strict parsing looks unfriendly, but every lenient rule is a place where this server and a proxy in front of it might disagree, which is how request smuggling works. Being precise and failing loudly is the modern reading of the robustness principle (the Companion's theoretical gap 3).

4. Restart tests find the bugs unit tests can't. The precision bug lived in the gap between "what's in memory" and "what's on disk", and only appeared when the process went through both. Any system with a persistent form of its data needs a test that writes, restarts, reads and compares, byte for byte.

5. Measure the measurer. The first load-test number was half the server's real capacity, because the client was the bottleneck. Checking the load generator's CPU, and comparing two clients, is a habit that prevents a lot of wrong conclusions about "slow servers".

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
a browser frontend calling the API no CORS headers, no TLS, no auth Volume 2 (the frontend) and Volume 3 (Spring Security)
discounts on orders total() has no pricing rules stage 10 (rules language)
more than one server instance the log and the idempotency map live in one process Volume 3 (database), Volume 5 (replication)
kitchens updating orders no endpoint applies stage 5's transitions stage 11 (the release adds the kitchen endpoints)
idempotency keys kept forever memory grows with every order Volume 3 (expiring keys in the database)

Evidence

  • server/ builds with its own build.sh; it prints tests: 6 passed, and core prints tests: 39 passed.
  • The failing restart test output and both fixes are in the README.
  • curl -v transcripts of a 201, a retried 200, a 400 and a 413 are in the README.
  • Your Load9 output is in the README, with one sentence on what limited each line.
  • A slowloris-style client is cut off by the head deadline (the test passes; note the time it took).
  • ADR-0011 is committed.

Carry forward

  • The HTTP contract in ADR-0011 is what Volume 2's frontend calls and what Volume 3's Spring service must keep: same paths, statuses, headers and JSON.
  • The strict parser's rules become Volume 3's validation and the rules of any gateway in front of TiffinBox.
  • "201 means durable" carries into every later storage choice.
  • Times are created at the precision they're stored (milliseconds), everywhere in TiffinBox.