Build a Minimal HTTP/1.1 Server from Scratch
System DesignModel answerLast updated
Implement a bare-metal HTTP server using only the standard library: request parsing, routing, static files, concurrency, timeouts, and graceful shutdown.
The Task
Build a working HTTP/1.1 server in your language of choice using only the standard library — no frameworks, no third-party HTTP helpers.
Your server must satisfy all of the following requirements.
Configuration
- The listening port is configurable (e.g. via a command-line flag or environment variable).
Protocol
- Parse raw HTTP/1.1 requests: request line, headers, and optional body.
- Support the
GETandPOSTmethods; respond with405 Method Not Allowedfor anything else on handled routes.
Routing
GET /health→200 OKwith a plain-text or JSON body indicating the server is alive.POST /echo→200 OKwith the request body mirrored back verbatim, with the originalContent-Typepreserved.- Any unrecognised path →
404 Not Found. - Malformed requests that cannot be parsed →
400 Bad Request.
Static file serving
- Serve files from a configurable root directory under a prefix such as
/static/. - Set the
Content-Typeheader based on file extension (e.g..html,.css,.js,.png,.json). - Reject path-traversal attempts (e.g.
../../etc/passwd) with400or403.
Concurrency
- Handle multiple simultaneous connections without blocking.
Reliability
- Enforce per-connection read/write timeouts so a slow client cannot hold a goroutine/thread indefinitely.
- On
SIGINT/SIGTERM, stop accepting new connections and allow in-flight requests to finish before exiting (graceful shutdown).
Observability
- Emit a structured log line for every request: timestamp, method, path, status code, and response duration.
Testing
- Include unit tests for at least: request parsing, routing logic, the path-traversal guard, and the echo handler.
Deliverable
Provide the full source code and a short README section with instructions to build and run the server locally. The reviewer should be able to clone, run, and curl all endpoints in under two minutes.
What the interviewer is looking for
- Correct, self-contained HTTP parsing (you understand what a raw request looks like).
- Clean separation of concerns: listener, parser, router, handler, logger.
- Concrete concurrency model — explain why you chose it, not just that you used it.
- Edge cases handled explicitly: empty body on POST, unknown MIME type, file not found, path traversal.
- Tests that target logic, not just happy-path integration.
- Operational thinking: timeouts, shutdown, structured logs.
Hints
Hint 1
Start by sketching the lifecycle of a single request — accept socket → read bytes → parse → route → handle → write response → close. Implementing each stage as a discrete function keeps the code testable and easy to reason about.
Hint 2
For path traversal, clean the requested path with your standard library's path-normalisation function (e.g. filepath.Clean in Go, os.path.realpath in Python) and then verify the result still starts with the configured static root before opening any file.
Hint 3
Graceful shutdown is a two-step operation: first stop the listener so no new connections arrive, then wait for active handlers to finish. A WaitGroup (or equivalent) around your handler goroutines/threads is the simplest correct implementation.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach and Design
The core challenge is implementing what frameworks hide from you: raw byte parsing, connection lifecycle management, and the operational concerns (timeouts, shutdown) that make a server production-worthy. The interviewer is checking whether you understand HTTP at the protocol level, not whether you can call http.ListenAndServe.
Architecture
Split the server into five layers:
- Listener loop — accepts TCP connections and dispatches each to a handler goroutine/thread.
- Parser — reads the raw byte stream and produces a structured request object (
method,path,headers,body). - Router — matches the parsed request to a handler function or returns
404/405. - Handlers —
/health,/echo, static files, error responses. - Logger — wraps the response writer to capture status code and duration, then emits one structured line per request.
Keeping these as separate, independently testable units is the single biggest quality signal for the interviewer.
HTTP Parsing
A raw HTTP/1.1 request looks like:
POST /echo HTTP/1.1\r\n
Host: localhost:8080\r\n
Content-Type: text/plain\r\n
Content-Length: 12\r\n
\r\n
hello world!
Parse it in three passes:
- Read the request line (first
\r\n-terminated line) and split into method, path, version. - Read headers line by line until the blank line (
\r\n\r\n). - If
Content-Lengthis present, read exactly that many bytes as the body. Never read more — this prevents a slow-loris style read from hanging.
Return 400 immediately on any malformed line (missing space, no HTTP/1.1 token, negative Content-Length).
Routing
A simple map from (method, path) to handler covers the two fixed endpoints cleanly. Check the static prefix with a string prefix match before falling through to the 404 handler.
/health GET → healthHandler
/echo POST → echoHandler
/static/{...} GET → staticHandler
* * → 404 or 405
The 405 logic: if the path is known but the method is wrong, return 405 with an Allow header. If the path is entirely unknown, return 404.
Static Files and Path Traversal
import os
def safe_open(root: str, requested: str):
# Normalise and resolve to absolute path
candidate = os.path.realpath(os.path.join(root, requested.lstrip("/")))
if not candidate.startswith(os.path.realpath(root) + os.sep):
raise PermissionError("path traversal detected")
return open(candidate, "rb")
The key is resolving symlinks before the prefix check. Skipping realpath and only using string manipulation (.. removal) is a common mistake that can be bypassed with symlinks or URL-encoded characters.
MIME type: maintain a small static dict of extensions to content types. If the extension is unrecognised, default to application/octet-stream.
Concurrency
In Go, spawn a goroutine per connection — the runtime scheduler handles thousands efficiently. In Python, use threading.Thread per connection or asyncio. In Java, a virtual thread (Java 21) or a cached thread pool.
Explain your choice: goroutines are cheap (~2 KB stack, grown on demand), making one-per-connection straightforward. Thread pools in Python/Java need a bounded size to avoid resource exhaustion under load.
Timeouts
Wrap the connection with a deadline before handing it to the parser:
conn.SetDeadline(time.Now().Add(30 * time.Second))
Reset the deadline after the headers are read if you want a separate, longer body-read timeout. A missing timeout is the most commonly cited production bug in homegrown servers.
Graceful Shutdown
// On SIGTERM:
listener.Close() // stop new accepts
wg.Wait() // drain in-flight handlers
Use a WaitGroup: Add(1) before spawning each handler goroutine, Done() at the end of the handler. The main goroutine blocks on wg.Wait() after closing the listener. Add a hard deadline (e.g. 10 s) with a context so a stuck handler doesn't prevent exit.
Structured Logging
Wrap the response writer to intercept the status code before it's sent:
type loggingWriter struct {
http.ResponseWriter
status int
start time.Time
}
// On WriteHeader: capture status, compute duration, emit JSON log line
Fields to log: ts, method, path, status, duration_ms, optionally bytes_sent and remote_addr.
Testing Strategy
| Test | What to assert |
|---|---|
TestParseRequest | Valid request → correct struct; missing \r\n\r\n → error |
TestRouterDispatch | /health GET → 200; /health POST → 405; /unknown → 404 |
TestPathTraversal | ../../etc/passwd → 400/403; normal path → file served |
TestEchoHandler | Body round-trips; Content-Type is preserved |
Integration tests can spin up the server on a random port, issue real curl or HTTP client requests, and assert status codes — these are valuable but should be a second tier, not a substitute for the unit tests above.
Common Mistakes
- Reading the body without checking
Content-Length— blocks forever on a client that never closes the connection. - String-only path traversal checks — bypassed by symlinks or
%2e%2eencoding. - No timeout on the connection — one slow client can exhaust all threads.
- Closing the listener but not waiting for handlers — results in truncated responses on shutdown.
- Returning
404when the path is known but method is wrong — correct behaviour is405with anAllowheader.