The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·00

Start Here: What a Backend Is

For readers who have never written server code: what a backend does, what happens to one request from arrival to response, the tools you need, a working HTTP API in one Java file explained line by line, how this volume is organised, and how to study it.

10 topics · ~11 min read · 10-question quiz
Updated Suggest a correction

Start here: how to use this volume

Two reading paths

This volume covers backend engineering: the programming languages servers are written in (with Java and the JVM in depth and Go, Rust, C#, Python, Node and others alongside), how servers handle requests, design APIs, store data, stay secure, do background work, survive failures, cache, and get tested. It's written for two kinds of reader:

  • If you're new to backend work (or to programming beyond Volume 1's basics), read this chapter first, then each chapter's Start here section in order. Each assumes only what earlier Start here sections taught. Run every example; the code is short on purpose.
  • If you already build services, skip this chapter. Start each chapter with its Revision sheet, take its quiz, and use How deep to go to choose which internals sections and lab experiments to read.

The first eleven chapters (33–43) are about the language and runtime: Java as the main thread, compared with other languages. The next eleven (44–54) are about building services: HTTP, APIs, Spring, persistence, security, messaging, resilience, caching and testing. The final chapter is a set of projects that build one service up through all of it.

Mastery levels

Every chapter uses the same six levels:

Level Name You can… Example for an HTTP endpoint
L1 Recognition define it and spot it "that's a POST handler returning 201"
L2 Working use it correctly write an endpoint with validation and correct status codes
L3 Internals explain why it works explain how the request reaches your method through the server's threads and filters
L4 Debugging diagnose failures find why requests hang under load (a thread pool exhausted by slow database calls)
L5 Design choose between approaches decide between synchronous REST, async messaging or gRPC for a feature
L6 Production run it at scale keep it fast, correct and secure for millions of requests and many teams

What a backend is

The part users never see

When you tap "Place order" in a food app, the screen you see is the frontend (Volume 2). The order itself is handled by the backend: programs running on servers that receive the request, check it, apply the business rules (is the restaurant open? is the item in stock? what's the total with tax?), store it in a database, perhaps notify the kitchen and the payment provider, and answer the app. Backends also run work nobody asks for directly: nightly reports, sending emails, cleaning up expired carts.

A backend's responsibilities, roughly in order of how often you'll touch them:

  1. Receive requests over the network (usually HTTP) and send responses.
  2. Validate input: never trust what clients send (Volume 2 chapter 13).
  3. Apply business logic: the rules that make the product what it is.
  4. Store and retrieve data in databases (Volume 4), caches and files.
  5. Authenticate and authorise: who is this, and are they allowed to do this?
  6. Talk to other systems: payment providers, other internal services, message queues.
  7. Stay up: handle failures, overload and bad input without falling over, and report what's happening (Volume 9).

One request, start to finish

clientapp/web backend process HTTPparse,route filtersauth,logging controllervalidate,map JSON servicebusinessrules repositorySQLqueries databasePostgreSQL POST /orders →← 201 Created + JSON
The journey of one request through a typical backend. Each layer has one job, and the request passes through all of them in both directions
  • The HTTP layer (a web server such as Tomcat, Jetty, Netty, or Go's net/http) reads bytes from the network, parses the HTTP request (Volume 2 chapter 19), and routes it by method and path to your code.
  • Filters (also called middleware or interceptors) run for every request: authentication, logging, rate limits, compression.
  • The controller (handler) converts the request into your program's types (JSON into objects), validates it, and calls the business logic.
  • The service layer holds the business rules and transactions.
  • The repository (data-access layer) talks to the database with SQL.
  • The response travels back through the same layers.

That layering isn't required, but almost every framework in every language (Spring, ASP.NET, Django, Rails, NestJS, Go's standard library with chi or gin) organises code this way, because it keeps HTTP details, business rules and SQL from tangling together.

Many requests at once

A backend serves many clients at the same time: a thousand people ordering lunch at 12:30. The server process accepts each connection and hands each request to a thread (Volume 1 chapter 8), or to an event loop, so that a slow request doesn't block the others. How a runtime does this (platform threads, virtual threads, goroutines, async/await, event loops) is one of the most important differences between backend platforms, and chapter 38 compares them all.

Because many copies of a backend usually run behind a load balancer, and any of them may restart at any moment, servers are designed to be stateless: anything that must survive between requests (users, orders, carts) lives in a database or cache, not in the server's memory.

Your first backend

Tools you need

Tool What it's for Choose
A JDK (Java Development Kit) compiling and running Java JDK 25 (the current long-term-support release) or 21; from Adoptium (Temurin), Oracle, Amazon Corretto or your package manager. Examples in this book were run on JDK 21 and 25.
An IDE writing and refactoring code IntelliJ IDEA (Community is free), VS Code with the Java extensions, or Eclipse
A build tool dependencies and builds Maven or Gradle (chapter 43); not needed for single-file programs
An HTTP client trying your API curl (already installed on most systems), HTTPie, Bruno or Postman
A database storing data PostgreSQL (chapter 49 and Volume 4), run locally or in a container
Docker (optional) running databases and other services locally Docker Desktop, Podman or Rancher Desktop

Check your JDK with java -version. Since JDK 11, java File.java compiles and runs a single source file in one step, which is how this chapter's example runs.

A menu API in one file

This complete program is a working HTTP API using only the JDK. It serves a list of dishes, a single dish, and lets clients add dishes:

Java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class MenuApi {
    record Dish(int id, String name, int pricePaise) {
        String toJson() { return "{\"id\":%d,\"name\":\"%s\",\"price\":%d}".formatted(id, name, pricePaise); }
    }

    // the "database": in memory for now (chapter 49 replaces it with PostgreSQL)
    static final Map<Integer, Dish> dishes = new ConcurrentHashMap<>();
    static final AtomicInteger nextId = new AtomicInteger(1);

    public static void main(String[] args) throws IOException {
        for (var d : List.of(new Dish(0, "Masala dosa", 9000), new Dish(0, "Idli (2)", 5000))) add(d.name(), d.pricePaise());

        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());   // one cheap thread per request (chapter 38)
        server.createContext("/dishes", MenuApi::handle);
        server.start();
        System.out.println("Menu API listening on http://localhost:8080/dishes");
    }

    static Dish add(String name, int price) {
        int id = nextId.getAndIncrement();
        Dish d = new Dish(id, name, price);
        dishes.put(id, d);
        return d;
    }

    static void handle(HttpExchange ex) throws IOException {
        String method = ex.getRequestMethod(), path = ex.getRequestURI().getPath();
        System.out.printf("%s %s on %s%n", method, path, Thread.currentThread());
        try {
            if (method.equals("GET") && path.equals("/dishes")) {
                String body = dishes.values().stream().map(Dish::toJson).reduce((a, b) -> a + "," + b).map(s -> "[" + s + "]").orElse("[]");
                send(ex, 200, body);
            } else if (method.equals("GET") && path.matches("/dishes/\\d+")) {
                Dish d = dishes.get(Integer.parseInt(path.substring(8)));
                if (d == null) send(ex, 404, "{\"error\":\"no such dish\"}"); else send(ex, 200, d.toJson());
            } else if (method.equals("POST") && path.equals("/dishes")) {
                String body = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
                var m = java.util.regex.Pattern.compile("\"name\"\\s*:\\s*\"([^\"]+)\".*\"price\"\\s*:\\s*(\\d+)").matcher(body);
                if (!m.find()) { send(ex, 400, "{\"error\":\"name and price are required\"}"); return; }
                Dish d = add(m.group(1), Integer.parseInt(m.group(2)));
                ex.getResponseHeaders().add("Location", "/dishes/" + d.id());
                send(ex, 201, d.toJson());
            } else {
                send(ex, 405, "{\"error\":\"method not allowed\"}");
            }
        } catch (RuntimeException e) {
            send(ex, 500, "{\"error\":\"internal error\"}");
        }
    }

    static void send(HttpExchange ex, int status, String json) throws IOException {
        byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
        ex.getResponseHeaders().add("Content-Type", "application/json");
        ex.sendResponseHeaders(status, bytes.length);
        try (var out = ex.getResponseBody()) { out.write(bytes); }
    }
}

Run it with java MenuApi.java, then try it from another terminal:

Text
$ curl localhost:8080/dishes
[{"id":1,"name":"Masala dosa","price":9000},{"id":2,"name":"Idli (2)","price":5000}]

$ curl -i -X POST localhost:8080/dishes -H 'Content-Type: application/json' -d '{"name":"Filter coffee","price":3000}'
HTTP/1.1 201 Created
Content-type: application/json
Location: /dishes/3

{"id":3,"name":"Filter coffee","price":3000}

$ curl localhost:8080/dishes/99                         → {"error":"no such dish"} 404
$ curl -X POST localhost:8080/dishes -d '{"name":"Vada"}'   → {"error":"name and price are required"} 400
$ curl -X DELETE localhost:8080/dishes/1                → {"error":"method not allowed"} 405

And the server's own log:

Text
Menu API listening on http://localhost:8080/dishes
GET /dishes on VirtualThread[#22]/runnable@ForkJoinPool-1-worker-1
POST /dishes on VirtualThread[#26]/runnable@ForkJoinPool-1-worker-1
GET /dishes/3 on VirtualThread[#28]/runnable@ForkJoinPool-1-worker-1
…

Read it against the request journey above:

  • HttpServer.create(...) and createContext("/dishes", …) are the HTTP layer: listen on port 8080 and route paths starting with /dishes to handle.
  • setExecutor(Executors.newVirtualThreadPerTaskExecutor()) gives each request its own thread; the log shows each request on a different virtual thread.
  • handle is the controller: it dispatches on method and path, validates the body, and chooses the status code (200, 201, 400, 404, 405, 500; Volume 2 chapter 19).
  • add is a tiny service, and the ConcurrentHashMap stands in for a repository and database. It's a concurrent map because many request threads use it at once (chapter 38 shows what goes wrong with a plain HashMap).
  • Prices are stored as integer paise, never as floating-point rupees (Volume 1 chapter 6).

Stop the server and start it again, and the filter coffee is gone: in-memory state dies with the process. Real backends keep data in a database (chapter 49), and use frameworks (Spring Boot, chapters 46–48) that replace the hand-written routing, JSON handling and validation here with tested, declarative equivalents. Knowing what this file does by hand is what makes those frameworks understandable rather than magic.

How to study backend engineering

A routine that works

  1. Read one topic of a Start here section.
  2. Run the example. Change one thing (a status code, a thread pool size, a query) and predict the effect before you run it again.
  3. Break it on purpose: send malformed JSON, a huge request, 1,000 concurrent requests, stop the database. Backends are judged by how they behave when things go wrong.
  4. Look inside: logs, thread dumps (jstack), the debugger, EXPLAIN on queries.
  5. Answer Check yourself without looking, take the quiz, and revisit a few days later.

Warm-up exercises

Before chapter 33, extend MenuApi:

  1. Add DELETE /dishes/{id} returning 204, or 404 if it doesn't exist.
  2. Reject prices that are zero, negative or above ₹10,000 with a 422 and a helpful error message.
  3. Add GET /dishes?maxPrice=6000 filtering by price.
  4. Log how long each request took, in milliseconds.
  5. Send 200 requests at once (seq 200 | xargs -P 50 -I{} curl -s -o /dev/null localhost:8080/dishes) and confirm every one succeeds.

Glossary

  • Backend / server: programs that receive requests over a network, apply business logic and store data.
  • Endpoint: one method-and-path combination an API supports (POST /dishes).
  • Handler / controller: the code that handles requests for an endpoint.
  • Middleware / filter: code that runs for every request around the handlers.
  • Stateless service: a server that keeps no client state in memory between requests.
  • Thread: an independent flow of execution inside a process; servers use them to handle requests concurrently.
  • Status code: the three-digit result of an HTTP request (200 OK, 404 Not Found…).
  • JDK / JVM: the Java Development Kit (compiler and tools) / the Java Virtual Machine that runs compiled Java (chapter 40).