BE·44
Backend Fundamentals
The anatomy of every backend service, independent of framework: the request/response cycle, routing, middleware and filters, dependency injection, serialisation, validation, business logic and layering, persistence, configuration, error handling and logging. One small orders service is built side by side in Spring Boot, Go's net/http, Rust's Axum, ASP.NET Core, FastAPI, NestJS and Elixir's Phoenix, so the shared concepts stand out from the framework details.
Start here: from one file to a structured service
What changes when a backend grows
The menu API at the start of this volume did everything inside one handle method: routing, parsing, validation, business rules, storage, errors. That's fine at 80 lines and unworkable at 80,000. Every backend framework (Spring, ASP.NET Core, Express, Django, FastAPI, Gin, Axum, Phoenix) organises the same responsibilities in the same way, so it's worth seeing them separated by hand first:
| Concern | Where it lives | Knows about HTTP? |
|---|---|---|
| Routing, parsing requests, choosing status codes | Controller (handler) | Yes |
| Business rules and validation | Service | No |
| Storing and loading data | Repository | No |
| Request ids, logging, timing, auth, error mapping | Middleware (filters, interceptors) | Yes, generically |
| Ports, limits, credentials | Configuration, from the environment | No |
| Creating objects and connecting them | Wiring (dependency injection) | No |
The order service
// repository: the only code that knows how orders are stored
interface OrderRepository { Order save(String dish, int qty, long total); Optional<Order> find(long id); }
// service: business rules, no HTTP in sight
Order place(String dish, Integer qty) {
var errors = new LinkedHashMap<String, String>();
if (dish == null || dish.isBlank()) errors.put("dish", "is required");
else if (!menu.containsKey(dish)) errors.put("dish", "is not on the menu");
if (qty == null) errors.put("qty", "is required");
else if (qty < 1 || qty > maxQty) errors.put("qty", "must be between 1 and " + maxQty);
if (!errors.isEmpty()) throw new ValidationException(errors);
return repo.save(dish, qty, (long) menu.get(dish) * qty);
}
// controller: HTTP in, HTTP out
if (method.equals("POST") && path.equals("/orders")) {
String body = new String(ex.getRequestBody().readNBytes(10_000), UTF_8); // never read unbounded input
Order o = service.place(str(body, "dish"), num(body, "qty"));
ex.getResponseHeaders().add("Location", "/orders/" + o.id());
send(ex, 201, "application/json", o.toJson());
}
// wiring, with configuration from the environment
int maxQty = Integer.parseInt(System.getenv().getOrDefault("MAX_QTY", "20"));
var service = new OrderService(new InMemoryOrderRepository(), Map.of("Masala dosa", 9000, "Filter coffee", 3000), maxQty);
server.createContext("/orders", new OrderController(service)::handle).getFilters().add(new Observe());
The service can be tested without a server (call place and check the result or exception), and the in-memory repository can be swapped for a PostgreSQL one (chapter 49) without touching the service. That's the point of layering: each part can change, and be tested, alone.
Using it
$ PORT=8091 MAX_QTY=10 java OrderApi.java
$ curl -i -X POST localhost:8091/orders -d '{"dish":"Masala dosa","qty":2}'
HTTP/1.1 201 Created
X-request-id: 96d8473d
Location: /orders/1001
{"id":1001,"dish":"Masala dosa","qty":2,"total":18000}
$ curl -X POST localhost:8091/orders -d '{"dish":"Pizza","qty":50}'
{"type":"about:blank","title":"Invalid order","status":422,"detail":"the order has invalid fields",
"errors":{"dish":"is not on the menu","qty":"must be between 1 and 10"}}
$ curl localhost:8091/orders/42
{"type":"about:blank","title":"Not Found","status":404,"detail":"order 42 not found"}
$ curl localhost:8091/health
{"status":"UP"}
Four habits are visible. Validation reports every problem at once, keyed by field, so a form can show them all. Errors use one consistent format, Problem Details (RFC 9457, application/problem+json), which Spring, ASP.NET Core and others produce natively. Unexpected exceptions become a generic 500 whose details go to the log, never to the client (stack traces leak internals; Volume 10). And there's a cheap health endpoint for load balancers and Kubernetes to check.
Middleware: the same code around every request
public void doFilter(HttpExchange ex, Chain chain) throws IOException {
String rid = Optional.ofNullable(ex.getRequestHeaders().getFirst("X-Request-Id")).orElse(newId());
ex.getResponseHeaders().add("X-Request-Id", rid);
long t = System.nanoTime();
try { chain.doFilter(ex); } // the controller runs here
catch (ValidationException e) { send 422 problem }
catch (NotFoundException e) { send 404 problem }
catch (RuntimeException e) { log details with rid; send 500 problem }
finally { log one JSON line: rid, method, path, status, ms }
}
{"ts":"2026-10-29T14:19:24.682Z","level":"INFO","rid":"96d8473d","method":"POST","path":"/orders","status":201,"ms":72.2}
{"ts":"2026-10-29T14:19:24.695Z","level":"INFO","rid":"abc123","method":"GET","path":"/orders/1001","status":200,"ms":1.9}
{"ts":"2026-10-29T14:19:24.705Z","level":"INFO","rid":"32b6a78d","method":"POST","path":"/orders","status":422,"ms":2.5}
A filter wraps the handler, so concerns that apply to every request are written once. A request id (reused if the caller sent one, as abc123 was) appears in the response and every log line, so a user's complaint, a log search and a trace across services (Volume 9) can be joined. Logs are structured (one JSON object per line) so log tools can filter by field. Note the first request's 72 ms: that's warm-up (chapter 40), not the business logic.
Configuration and lifecycle
Settings that differ between environments (ports, limits, database URLs, secrets) come from environment variables or config files, never from code, so one build runs everywhere (the twelve-factor app principle). And a server must stop gracefully: when the platform sends SIGTERM during a deploy, stop accepting new requests and let in-flight ones finish. The shutdown hook here calls server.stop(5); the lab shows what stop(0) does to a request in flight.
How deep to go in backend fundamentals
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain the request path through controller, service, repository and middleware |
| L2 | Build a layered service with validation, consistent errors, logging, config and health checks |
| L3 | Compare how Spring, ASP.NET Core, Express, FastAPI, Gin, Axum and Phoenix structure the same concerns; explain threading models and request lifecycles |
| L4 | Diagnose pool exhaustion, missing timeouts, unbounded inputs and ungraceful shutdowns |
| L5 | Set service templates and conventions (error format, logging fields, config, health) for a team |
| L6 | Standardise backend platforms across many teams and services |
The shape of a backend
What every backend does
Strip away frameworks and every HTTP backend does the same things for each request:
- Accept a connection and parse HTTP (the server: Tomcat, Netty, Go's
net/http, Hyper, Kestrel, Uvicorn, Cowboy/Bandit). - Run cross-cutting middleware: tracing, logging, authentication, CORS, compression, rate limiting.
- Route the request (method + path) to a handler.
- Deserialise and validate input: path variables, query parameters, headers, body.
- Execute business logic, which reads and writes persistent state.
- Map the outcome, success or error, to an HTTP status and response body.
- Serialise the response and write it out.
- Log, measure and trace throughout.
At startup, the application loads configuration and wires dependencies (repositories into services into controllers). The rest of this chapter takes each concern in turn and shows how frameworks in different languages express it.
The same service in seven frameworks
The running example is a tiny orders API: GET /orders/{id} and POST /orders, with validation, a 404 for missing orders, and a repository.
// Spring Boot (Java 25, Spring Boot 4)
@SpringBootApplication
public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
record CreateOrder(@NotBlank String customerId, @NotEmpty List<@Valid Line> lines) {
record Line(@NotBlank String sku, @Positive int qty) {}
}
record OrderDto(String id, String customerId, String status, List<CreateOrder.Line> lines) {}
@RestController
@RequestMapping("/orders")
class OrderController {
private final OrderService service;
OrderController(OrderService service) { this.service = service; } // constructor injection
@GetMapping("/{id}")
OrderDto get(@PathVariable String id) { return service.find(id); } // throws OrderNotFound → 404
@PostMapping
ResponseEntity<OrderDto> create(@Valid @RequestBody CreateOrder cmd, UriComponentsBuilder uri) {
var created = service.create(cmd);
return ResponseEntity.created(uri.path("/orders/{id}").build(created.id())).body(created);
}
}
@ResponseStatus(HttpStatus.NOT_FOUND)
class OrderNotFound extends RuntimeException { OrderNotFound(String id) { super("order " + id + " not found"); } }
// Go 1.22+ standard library: method + path patterns in ServeMux; no framework needed
type CreateOrder struct {
CustomerID string `json:"customerId"`
Lines []Line `json:"lines"`
}
type Line struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
type Server struct{ svc *OrderService } // dependencies are struct fields, wired in main()
func (s *Server) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", s.getOrder)
mux.HandleFunc("POST /orders", s.createOrder)
return withLogging(withRecover(mux)) // middleware = handler wrappers
}
func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
o, err := s.svc.Find(r.Context(), r.PathValue("id"))
if errors.Is(err, ErrNotFound) {
writeProblem(w, http.StatusNotFound, "order not found")
return
}
if err != nil {
writeProblem(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, http.StatusOK, o)
}
func (s *Server) createOrder(w http.ResponseWriter, r *http.Request) {
var cmd CreateOrder
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)) // cap body size
dec.DisallowUnknownFields()
if err := dec.Decode(&cmd); err != nil {
writeProblem(w, http.StatusBadRequest, "malformed JSON")
return
}
if errs := cmd.Validate(); len(errs) > 0 {
writeValidationProblem(w, errs)
return
}
o, err := s.svc.Create(r.Context(), cmd)
if err != nil {
writeProblem(w, http.StatusInternalServerError, "internal error")
return
}
w.Header().Set("Location", "/orders/"+o.ID)
writeJSON(w, http.StatusCreated, o)
}
func main() {
db := mustOpenDB(os.Getenv("DATABASE_URL"))
srv := &Server{svc: NewOrderService(NewPgOrderRepo(db))}
log.Fatal(http.ListenAndServe(":8080", srv.routes()))
}
// Rust: Axum on Tokio; extractors parse input, State carries dependencies
#[derive(Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
struct CreateOrder {
#[validate(length(min = 1))] customer_id: String,
#[validate(length(min = 1), nested)] lines: Vec<Line>,
}
#[derive(Deserialize, Serialize, Validate, Clone)]
struct Line { #[validate(length(min = 1))] sku: String, #[validate(range(min = 1))] qty: u32 }
#[derive(Clone)]
struct AppState { svc: Arc<OrderService> }
async fn get_order(State(st): State<AppState>, Path(id): Path<String>) -> Result<Json<OrderDto>, ApiError> {
let order = st.svc.find(&id).await?; // ApiError: IntoResponse maps NotFound → 404
Ok(Json(order))
}
async fn create_order(State(st): State<AppState>, Json(cmd): Json<CreateOrder>)
-> Result<(StatusCode, [(header::HeaderName, String); 1], Json<OrderDto>), ApiError> {
cmd.validate()?; // validator crate → 422 via From impl
let o = st.svc.create(cmd).await?;
Ok((StatusCode::CREATED, [(header::LOCATION, format!("/orders/{}", o.id))], Json(o)))
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let pool = PgPoolOptions::new().max_connections(20).connect(&std::env::var("DATABASE_URL")?).await?;
let state = AppState { svc: Arc::new(OrderService::new(PgOrderRepo::new(pool))) };
let app = Router::new()
.route("/orders/{id}", get(get_order))
.route("/orders", post(create_order))
.layer(TraceLayer::new_for_http()) // tower middleware
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
axum::serve(listener, app).await?;
Ok(())
}
// ASP.NET Core minimal APIs (.NET 10)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IOrderRepository, PgOrderRepository>(); // built-in DI container
builder.Services.AddScoped<OrderService>();
builder.Services.AddProblemDetails();
builder.Services.AddValidation(); // .NET 10 minimal-API validation
var app = builder.Build();
app.MapGet("/orders/{id}", async (string id, OrderService svc) =>
await svc.FindAsync(id) is { } o ? Results.Ok(o) : Results.NotFound());
app.MapPost("/orders", async (CreateOrder cmd, OrderService svc) =>
{
var o = await svc.CreateAsync(cmd);
return Results.Created($"/orders/{o.Id}", o);
});
app.Run();
public record CreateOrder([Required] string CustomerId, [MinLength(1)] List<Line> Lines);
public record Line([Required] string Sku, [Range(1, int.MaxValue)] int Qty);
# FastAPI (Python): type hints drive parsing, validation (Pydantic) and OpenAPI docs
app = FastAPI()
class Line(BaseModel):
sku: str = Field(min_length=1)
qty: int = Field(gt=0)
class CreateOrder(BaseModel):
customer_id: str = Field(min_length=1, alias="customerId")
lines: list[Line] = Field(min_length=1)
def get_service(db: AsyncSession = Depends(get_db)) -> OrderService: # DI via Depends
return OrderService(PgOrderRepo(db))
@app.get("/orders/{order_id}", response_model=OrderDto)
async def get_order(order_id: str, svc: OrderService = Depends(get_service)):
order = await svc.find(order_id)
if order is None:
raise HTTPException(status_code=404, detail="order not found")
return order
@app.post("/orders", status_code=201, response_model=OrderDto)
async def create_order(cmd: CreateOrder, response: Response, svc: OrderService = Depends(get_service)):
order = await svc.create(cmd) # invalid body → automatic 422 with field errors
response.headers["Location"] = f"/orders/{order.id}"
return order
// NestJS (TypeScript on Node): Angular-style modules, decorators and DI
export class LineDto { @IsString() @IsNotEmpty() sku!: string; @IsInt() @Min(1) qty!: number; }
export class CreateOrderDto {
@IsString() @IsNotEmpty() customerId!: string;
@ValidateNested({ each: true }) @Type(() => LineDto) @ArrayMinSize(1) lines!: LineDto[];
}
@Controller("orders")
export class OrdersController {
constructor(private readonly orders: OrdersService) {} // injected
@Get(":id")
async get(@Param("id") id: string) {
const o = await this.orders.find(id);
if (!o) throw new NotFoundException("order not found");
return o;
}
@Post()
@HttpCode(201)
create(@Body() dto: CreateOrderDto) { return this.orders.create(dto); } // global ValidationPipe → 400
}
@Module({ controllers: [OrdersController], providers: [OrdersService, PgOrderRepo] })
export class OrdersModule {}
# Phoenix (Elixir): router → pipeline of plugs → controller; Ecto changesets validate
# router.ex
scope "/", ShopWeb do
pipe_through :api # a plug pipeline (middleware)
get "/orders/:id", OrderController, :show
post "/orders", OrderController, :create
end
# order_controller.ex
defmodule ShopWeb.OrderController do
use ShopWeb, :controller
action_fallback ShopWeb.FallbackController # maps {:error, …} tuples to responses
def show(conn, %{"id" => id}) do
with {:ok, order} <- Orders.fetch(id) do # {:error, :not_found} → fallback renders 404
render(conn, :show, order: order)
end
end
def create(conn, params) do
with {:ok, order} <- Orders.create(params) do # {:error, %Ecto.Changeset{}} → 422 with errors
conn |> put_status(:created) |> put_resp_header("location", ~p"/orders/#{order.id}") |> render(:show, order: order)
end
end
end
The same concepts appear in every tab: routes, extraction and validation of input, injected dependencies, error-to-status mapping, and serialisation. The differences are how much is implicit:
- Spring and NestJS: annotations plus a container wire everything; behaviour comes from conventions.
- Go: everything explicit, standard library only, more lines.
- Axum: explicit but type-driven; extractors are types.
- FastAPI: type hints drive the behaviour.
- Phoenix: plug pipelines and pattern-matched result tuples.
Request handling
Request and response
HTTP (Vol. 1 ch. 9, Vol. 2 ch. 19) is a request/response protocol: method, target (path + query), headers and an optional body in, status, headers and an optional body out. Framework abstractions over it:
| Framework | Request | Response |
|---|---|---|
| Servlet API (under Spring MVC) | HttpServletRequest (mutable, stream-based) |
HttpServletResponse |
| Spring MVC | Method parameters bound via annotations (@PathVariable, @RequestParam, @RequestHeader, @RequestBody) |
Return value + ResponseEntity<T> |
| Spring WebFlux | ServerHttpRequest / ServerRequest (functional) |
Mono<ServerResponse> |
| Go | *http.Request (with Context()) |
http.ResponseWriter (write headers, then body) |
| Axum / Hyper | Request<Body> and typed extractors |
Anything implementing IntoResponse |
| ASP.NET Core | HttpContext.Request, parameter binding |
IResult / Results.* |
| FastAPI (Starlette) | Typed function parameters, Request |
Return value + response_model, or Response |
| Phoenix | %Plug.Conn{}: one immutable struct carrying request and response, transformed by each plug |
The same conn with status, headers and body set |
Important request-level concerns every framework must handle:
- Body limits (to resist DoS): Spring
server.tomcat.max-swallow-sizeandspring.servlet.multipart.max-*, Gohttp.MaxBytesReader, AxumDefaultBodyLimit, and Nginxclient_max_body_sizein front. - Timeouts: read, header and write timeouts at the server (Go's
http.Server{ReadHeaderTimeout: …}, which is essential against Slowloris), and request deadlines propagated to downstream calls (Gocontext, Java virtual-thread interrupts, Rust future cancellation). - Streaming large responses instead of buffering them (Spring
StreamingResponseBody, Go writing toResponseWriterincrementally, AxumBody::from_stream). - Request-scoped context: the authenticated user, trace ID and locale. Java uses
ThreadLocal/ScopedValue, SpringRequestContextHolderandSecurityContextHolder. Go passescontext.Contextexplicitly. Axum uses request extensions, ASP.NETHttpContext.Items, and Phoenixconn.assigns.
Routing
Routing maps (method, path) to a handler, extracting path parameters. Implementation strategies range from linear regex matching (old frameworks) to radix trees/tries (httprouter, Gin, Axum's matchit, Fastify's find-my-way) with O(path length) lookups.
| Framework | Declaration |
|---|---|
| Spring MVC | Annotations: @GetMapping("/orders/{id}"). PathPattern matching (since Boot 2.6), class-level prefixes, produces/consumes/params/headers conditions |
| Spring WebFlux.fn / WebMvc.fn | Functional: route(GET("/orders/{id}"), handler::get) |
| Go stdlib (1.22+) | mux.HandleFunc("GET /orders/{id}", h). Wildcards {name}, {rest...}, and the most specific pattern wins. Chi, Gin, Echo and Fiber offer groups and middleware per group |
| Axum | Router::new().route("/orders/{id}", get(h).delete(d)), nested routers, merge |
| ASP.NET Core | MapGet (minimal APIs), attribute routing on controllers, route constraints ({id:int}) |
| FastAPI | Decorators @app.get("/orders/{order_id}"); APIRouter with prefixes |
| NestJS | @Controller("orders") + @Get(":id") |
| Phoenix | A router DSL with scope, pipe_through, resources "/orders", OrderController (REST conventions) |
Concerns that matter:
- Trailing slashes: Spring Boot 3 stopped matching
/orders/to/ordersby default. - Route conflicts and precedence: specific beats wildcard.
- Method not allowed (405, with an
Allowheader) versus not found (404). - Versioned prefixes (chapter 45).
- Generated OpenAPI documentation from routes: springdoc-openapi, FastAPI (built in), NestJS Swagger, ASP.NET OpenAPI (built in since .NET 9), utoipa (Rust), huma or ogen (Go).
Middleware and filters
Middleware wraps request handling to add cross-cutting behaviour before and after the handler. Structurally it's function composition, an onion: each layer can inspect or modify the request, call the next layer (or short-circuit, for example rejecting unauthenticated requests), then inspect or modify the response.
// Servlet filter (Spring registers @Component filters automatically, ordered by @Order)
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
class RequestIdFilter extends OncePerRequestFilter { // guaranteed once per request, even with forwards
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String id = Optional.ofNullable(req.getHeader("X-Request-ID")).orElseGet(() -> UUID.randomUUID().toString());
MDC.put("requestId", id);
res.setHeader("X-Request-ID", id);
long start = System.nanoTime();
try {
chain.doFilter(req, res); // → next filter → DispatcherServlet → controller
} finally {
log.info("{} {} → {} in {} ms", req.getMethod(), req.getRequestURI(), res.getStatus(),
(System.nanoTime() - start) / 1_000_000);
MDC.remove("requestId");
}
}
}
// Spring also has HandlerInterceptor (around controller methods, knows the handler) and
// @ControllerAdvice (around exceptions and bodies), covered in chapter 48.
// Go: middleware is func(http.Handler) http.Handler
func withLogging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &statusRecorder{ResponseWriter: w, status: 200}
next.ServeHTTP(rw, r)
slog.Info("request", "method", r.Method, "path", r.URL.Path, "status", rw.status,
"dur_ms", time.Since(start).Milliseconds())
})
}
func withRecover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
slog.Error("panic", "err", v, "stack", string(debug.Stack()))
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
// Compose: handler := withLogging(withRecover(withAuth(mux))): the outermost runs first
// Rust: tower Layers/Services; axum::middleware::from_fn for ad-hoc middleware
async fn require_api_key(req: Request, next: Next) -> Result<Response, StatusCode> {
match req.headers().get("x-api-key").and_then(|v| v.to_str().ok()) {
Some(k) if valid(k) => Ok(next.run(req).await),
_ => Err(StatusCode::UNAUTHORIZED), // short-circuit
}
}
let app = Router::new()
.route("/orders/{id}", get(get_order))
.layer(middleware::from_fn(require_api_key))
.layer(TimeoutLayer::new(Duration::from_secs(10))) // tower-http: timeout, CORS, compression, trace…
.layer(TraceLayer::new_for_http());
// Order: layers added LATER wrap earlier ones (the last .layer is outermost).
// ASP.NET Core: an explicit pipeline where order matters
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.Use(async (ctx, next) => { // inline middleware
var sw = Stopwatch.StartNew();
await next(ctx);
app.Logger.LogInformation("{Path} {Status} {Ms}ms", ctx.Request.Path, ctx.Response.StatusCode, sw.ElapsedMilliseconds);
});
# FastAPI/Starlette middleware
@app.middleware("http")
async def timing(request: Request, call_next):
start = time.perf_counter()
response = await call_next(request)
response.headers["Server-Timing"] = f"app;dur={(time.perf_counter() - start) * 1000:.1f}"
return response
# Phoenix: plugs are functions conn -> conn; a pipeline is a list of plugs
pipeline :api do
plug :accepts, ["json"]
plug ShopWeb.Plugs.RequestId
plug ShopWeb.Plugs.Authenticate # can halt(conn) to short-circuit
end
Ordering matters. Tracing and request IDs go outermost (so everything is covered), then exception handling, then CORS (so preflight OPTIONS requests get answers before authentication rejects them), authentication, authorisation, rate limiting, and finally the handler. A mis-ordered pipeline produces bugs like "CORS errors only when the token is expired", where an auth failure response lacks CORS headers.
Dependency injection
Dependency injection (DI): a component receives its collaborators instead of creating them. OrderService takes an OrderRepository in its constructor rather than calling new PgOrderRepository(...). The benefits:
- Testability: inject a fake or in-memory repository.
- Configurability: choose implementations per environment.
- Explicit dependencies: the constructor signature documents what a component needs.
- Lifecycle management: someone creates and shares one connection pool and closes it on shutdown.
DI is the pattern. A DI container is one way to do it. The spectrum:
| Approach | Languages and frameworks | How |
|---|---|---|
Manual wiring in main ("pure DI") |
Go (idiomatic), Rust, Zig, small services in any language | main() constructs everything in order and passes it down. Compile-time checked, explicit, no magic |
| Compile-time code generation | Google Wire (Go), Dagger (Java/Android), Micronaut and Quarkus (build-time DI for Java), Avaje Inject | Wiring code is generated from annotations or provider functions: no reflection, errors at build time |
| Runtime reflective container | Spring, Jakarta CDI, Guice, ASP.NET Core's built-in container, NestJS, Angular, FastAPI Depends |
The container scans and reads metadata, builds a graph and instantiates beans, managing scopes and lifecycles. Very flexible (AOP proxies, conditional beans); errors at startup; reflection costs startup time (Spring AOT mitigates this, chapter 47) |
| Functional / parameter passing | Haskell (Reader monad, records of functions), Elixir (module arguments, config), Scala ZIO layers | Dependencies are values passed down or resolved through effect systems |
// Go: wiring is just code in main(): readable top to bottom
func main() {
cfg := config.MustLoad()
db := postgres.MustOpen(cfg.DatabaseURL)
defer db.Close()
repo := orders.NewPgRepo(db)
payments := paymentsclient.New(cfg.PaymentsURL, &http.Client{Timeout: 3 * time.Second})
svc := orders.NewService(repo, payments, clock.Real{})
srv := api.NewServer(svc)
run(srv, cfg.Port)
}
Spring's container is covered in depth in chapter 46. Whatever the mechanism, the principles are the same: constructor injection (dependencies are final and required), depend on interfaces at boundaries (repositories, external clients, clocks), avoid service locators (ApplicationContext.getBean() scattered through code), and keep the object graph acyclic.
Serialisation
Serialisation converts in-memory objects to a wire format (JSON, Protobuf, Avro, XML, MessagePack, CBOR), and deserialisation converts back. In HTTP APIs, JSON dominates. For internal RPC and events, binary schema-based formats (Protobuf with gRPC, Avro with Kafka) are common (chapter 45, Vol. 5).
| Language | De facto JSON library | Mechanism |
|---|---|---|
| Java | Jackson (Spring's default; Jackson 3 arrived with Spring Boot 4), Gson, JSON-B (Yasson), Moshi (Kotlin/Android) | Reflection + annotations, with optional bytecode generation (Afterburner/Blackbird) |
| Kotlin | kotlinx.serialization | A compiler plugin generates serialisers (multiplatform, no reflection) |
| Go | encoding/json (struct tags + reflection); encoding/json/v2 (an experiment in 1.25 under GOEXPERIMENT=jsonv2); sonic, easyjson for speed |
Reflection |
| Rust | serde + serde_json | Derive macros generate code at compile time: very fast and type-safe |
| C# | System.Text.Json (with source generators for AOT), Newtonsoft.Json | Reflection or source generation |
| Python | json + Pydantic (validation + serialisation, a Rust core in v2), orjson, msgspec |
Runtime type introspection |
| TS/Node | JSON.parse/stringify + validation libraries (Zod, class-validator) |
Runtime |
| Elixir | Jason | Protocols (Jason.Encoder) |
| C/C++ | cJSON, nlohmann/json, simdjson (GB/s parsing), RapidJSON, Glaze (reflection-based) | Manual or macro/template-based |
Serialisation pitfalls that cause real incidents:
- Exposing internal models: serialising JPA entities directly leaks fields (password hashes), triggers lazy-loading during serialisation (N+1 queries or
LazyInitializationException, chapter 49), and couples the API contract to the database schema. Use DTOs (records) at the API boundary. - Unknown properties: fail (strict) or ignore (tolerant)? For inbound requests in public APIs, ignoring unknown fields supports forward compatibility (chapter 45). Jackson ignores them in Spring Boot by default via
FAIL_ON_UNKNOWN_PROPERTIES=false. Strictness catches client typos. - Number precision: JavaScript clients lose precision on integers above 2⁵³. Serialise 64-bit IDs as strings, and money as strings or integer minor units, never as floats.
- Dates and times: use ISO-8601 with offsets (
2026-10-24T10:08:00+05:30) or UTCInstants. Never serialisejava.util.Dateas epoch milliseconds by accident (configureWRITE_DATES_AS_TIMESTAMPS=false). Time zones belong in the data, not inferred from the server's default zone. - Nulls versus absent:
{"coupon": null}(explicitly clear) versus{}(don't touch) matter for PATCH semantics. Java and Go lose the distinction by default (Go's*string, Java'sJsonNullableorOptionalwrappers can model it). - Polymorphism and deserialisation security: Jackson's default typing (
enableDefaultTyping,@JsonTypeInfo(use = CLASS)) lets attackers choose classes to instantiate, giving remote code execution gadget chains. Java's native serialisation (ObjectInputStream) has the same issue. Use explicit type names with an allow-list (@JsonTypeInfo(use = NAME)+@JsonSubTypes), or sealed types. - Performance: serialisation is often the top CPU and allocation consumer in API services (chapter 41). Prefer streaming, avoid intermediate trees, and reuse
ObjectMapper(thread-safe once configured; creating one per request is expensive).
Validation
Validate at the boundary, before business logic sees the data. There are layers of validation:
- Syntactic: is it well-formed JSON with the right types? (Deserialisation does this.)
- Field constraints: required, length, range, pattern, email, positive, collection size.
- Cross-field:
end > start,password == confirmation. - Business rules: "customer exists", "SKU is in stock", "order not already paid". These need state and belong in the domain or service layer, not in annotations.
// Jakarta Bean Validation (Hibernate Validator): declarative constraints, triggered by @Valid
public record CreateOrder(
@NotBlank String customerId,
@NotEmpty @Size(max = 100) List<@Valid Line> lines,
@Email String notifyEmail,
@FutureOrPresent LocalDate deliverBy) {
public record Line(@NotBlank @Pattern(regexp = "[A-Z0-9-]{3,32}") String sku, @Positive @Max(999) int qty) {}
@AssertTrue(message = "at most one line per SKU") // cross-field via a method
boolean isUniqueSkus() { return lines == null || lines.stream().map(Line::sku).distinct().count() == lines.size(); }
}
// Spring: @Valid on @RequestBody → MethodArgumentNotValidException → 400 with field errors.
// @Validated on a class + constraints on method parameters → method-level validation (via AOP proxy).
Return validation failures as structured errors that clients can map to form fields. Use RFC 9457 Problem Details with an errors extension (chapter 45). Status code: 400 Bad Request for malformed input, and 422 Unprocessable Content for well-formed but semantically invalid input (FastAPI and Phoenix use 422; Spring uses 400 by default; either is defensible if you're consistent).
Rust's type system enables "parse, don't validate" (Alexis King): convert unvalidated input into types that can only hold valid values (Email, NonEmptyVec<Line>, Quantity(NonZeroU32)), so downstream code never re-checks. The same works in Java with records that validate in their compact constructors (chapter 34), and in TypeScript with Zod schemas that produce typed values.
Behind the handler
Business logic and layering
Where does the logic live? The classic layered architecture:
controller / handler — HTTP concerns only: parse, validate, call the service, map the result to HTTP
↓
service / application — use cases: orchestrate the domain, transactions, authorisation decisions, calls to other systems
↓
domain — entities, value objects, business rules (ideally framework-free and pure)
↓
repository / adapters — persistence and external integrations behind interfaces
Rules of thumb:
- Controllers stay thin. No business rules, and no repository calls that bypass services.
- Transactions at the service layer (
@Transactionalon service methods, chapter 49): one use case, one transaction. - The domain doesn't depend on the web or database frameworks. Hexagonal architecture (ports and adapters) and clean architecture formalise this: the domain defines ports (interfaces such as
OrderRepositoryandPaymentGateway), and adapters implement them (JPA, REST clients). Vol. 13 covers these in depth. - Package by feature (
orders/,payments/,catalog/, each with its own controller, service and repository) usually scales better than package by layer (controllers/,services/,repositories/). Spring Modulith can enforce module boundaries within a monolith.
The paradigm view: Go codebases typically organise by feature packages with small interfaces defined by consumers. Elixir/Phoenix uses contexts (Shop.Orders, Shop.Payments) as the public API of each domain area, with controllers calling only context functions. Rust services often use a domain module with pure types and functions, and infra modules for adapters. FastAPI projects use routers + services + repositories. The vocabulary changes, but the boundaries are the same.
Persistence
The persistence layer turns domain operations into durable state changes. The main styles:
| Style | Java | Others |
|---|---|---|
| Raw driver / SQL | JDBC, Spring JdbcClient |
Go database/sql + pgx; Rust sqlx (SQL checked against the DB schema at compile time); Python psycopg; Elixir Postgrex |
| Query builders / type-safe SQL | jOOQ (generated from the schema) | Go sqlc (generates Go from SQL), Rust Diesel/SeaQuery, Kysely (TS), Ecto.Query |
| ORM / data mapper | JPA/Hibernate, Spring Data JPA | EF Core (C#), SQLAlchemy (Python), Prisma/TypeORM/Drizzle (TS), GORM/ent (Go), SeaORM (Rust), Ecto (Elixir, explicitly not an ORM: no lazy loading, no identity map) |
| Document / KV / other | Spring Data MongoDB/Redis/Cassandra | Native drivers |
Chapter 49 covers Spring Data and JPA in depth, and Vol. 4 covers databases themselves. Fundamentals that apply to every style:
- Connection pooling: database connections are expensive to establish (TCP + TLS + auth + session setup), so pools reuse them (HikariCP; Go's
sql.DBis itself a pool; sqlxPgPool; Npgsql's pool). Size pools for the database's capacity, not the app's thread count. - Transactions: atomic units of work with clear boundaries.
- Parameterised queries, always: never concatenate input into SQL (SQL injection, Part X).
- Migrations: versioned schema changes in code (Flyway, Liquibase, golang-migrate, sqlx migrate, EF migrations, Alembic, Ecto migrations), applied by CI/CD.
- Timeouts on queries and on acquiring connections from the pool.
Configuration
Configuration varies between environments (URLs, credentials, pool sizes, feature flags) and must stay out of the code. The Twelve-Factor App principle: store config in the environment, with strict separation of config from code, and the same build artifact promoted through environments.
Configuration sources, from lowest to highest precedence (Spring Boot's order is similar to most frameworks): defaults in code → packaged config files (application.yml) → profile- or environment-specific files → environment variables → command-line arguments → external config services or secret managers.
# Spring Boot: application.yml + typed binding (chapter 47)
shop:
payments:
base-url: https://payments.internal
timeout: 3s
max-retries: 2
spring:
datasource:
url: ${DATABASE_URL} # resolved from the environment
@ConfigurationProperties(prefix = "shop.payments")
@Validated
public record PaymentsProperties(@NotNull URI baseUrl, @NotNull Duration timeout, @Min(0) int maxRetries) {}
// Override via env: SHOP_PAYMENTS_TIMEOUT=5s (relaxed binding)
// Go: explicit env parsing (often with a small library like caarlos0/env or kelseyhightower/envconfig)
type Config struct {
DatabaseURL string `env:"DATABASE_URL,required"`
PaymentsURL string `env:"PAYMENTS_URL,required"`
PaymentsTimeout time.Duration `env:"PAYMENTS_TIMEOUT" envDefault:"3s"`
Port int `env:"PORT" envDefault:"8080"`
}
func MustLoad() Config {
var c Config
if err := env.Parse(&c); err != nil { log.Fatalf("config: %v", err) } // fail fast at startup
return c
}
// Rust: the figment or config crates, plus serde; or envy for env-only
#[derive(Deserialize)]
struct Config { database_url: String, payments_url: Url, #[serde(with = "humantime_serde", default = "default_timeout")] payments_timeout: Duration }
let cfg: Config = Figment::new().merge(Toml::file("config.toml")).merge(Env::prefixed("SHOP_")).extract()?;
# Python: pydantic-settings validates env vars into typed settings
class Settings(BaseSettings):
database_url: PostgresDsn
payments_url: HttpUrl
payments_timeout: float = 3.0
model_config = SettingsConfigDict(env_prefix="SHOP_", env_file=".env")
settings = Settings() # raises at startup if invalid
# Elixir: config/runtime.exs runs at boot (releases), reading the environment
config :shop, Shop.Repo,
url: System.fetch_env!("DATABASE_URL"),
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10")
Principles:
- Typed and validated at startup ("fail fast"): a wrong URL should stop the deployment, not cause errors an hour later.
- Secrets aren't config files: inject them from a secret manager (Vault, AWS Secrets Manager, Kubernetes Secrets with encryption, Part X). Never commit them, and never log them.
- Sensible defaults for everything except environment-specific values.
- Dynamic config and feature flags for things that change without a deploy (chapter 31's runtime config, LaunchDarkly/Unleash/OpenFeature).
Error handling
A backend must map every failure to an appropriate response consistently, and never leak internals (stack traces, SQL, class names) to clients:
| Failure | Status | Notes |
|---|---|---|
| Malformed request, validation failure | 400 / 422 | Field-level details |
| Not authenticated | 401 + WW-Authenticate |
|
| Authenticated but not allowed | 403 (or 404 to hide existence) | |
| Resource not found | 404 | |
| Conflict (version mismatch, duplicate, invalid state transition) | 409 / 412 | Optimistic locking (chapter 49), conditional requests (chapter 45) |
| Rate limited | 429 + Retry-After |
|
| Downstream failure / timeout | 502 / 503 / 504 | Possibly with Retry-After |
| Bug | 500 | Logged with full detail server-side; a generic message plus a correlation ID for the client |
Mechanisms differ by language (chapter 33): Spring maps exceptions with @ControllerAdvice/@ExceptionHandler to ProblemDetail (chapter 48). Go handlers check errors.Is/errors.As and write responses, often via a helper that converts domain errors to HTTP errors. Axum converts typed Result errors through IntoResponse. ASP.NET Core has exception handlers plus IProblemDetailsService. FastAPI has HTTPException and exception handlers. Phoenix uses action_fallback with pattern-matched error tuples.
The cross-language design rule: domain code raises domain errors (OrderNotFound, InsufficientStock, PaymentDeclined), and one boundary component maps them to HTTP. Then domain logic is reusable from a message consumer or CLI, and the HTTP mapping is consistent.
Logging
Logs are the narrative of what happened. Modern practice (Vol. 6 goes deeper):
- Structured logs (JSON lines with fields) rather than free text, so logs are queryable:
{"ts":"…","level":"INFO","msg":"order created","orderId":"o-42","customerId":"c-7","traceId":"4bf9…"}. - Levels: ERROR (needs attention), WARN (unexpected but handled), INFO (business events, lifecycle), DEBUG (diagnostics, off in production by default), TRACE.
- Context propagation: request ID and trace ID in every line (MDC in Java,
slogwith context in Go,tracingspans in Rust,ILoggerscopes in .NET,structlogcontextvars in Python, Logger metadata in Elixir). - Don't log secrets or PII (passwords, tokens, card numbers, often emails). Redact by default.
- Log once: handle or rethrow, not both (avoid duplicate stack traces at every layer).
- Performance: parameterised messages (chapter 41), asynchronous appenders, sampling for high-volume debug logs.
| Language | API (facade) | Implementation |
|---|---|---|
| Java | SLF4J (2.x fluent API), System.Logger |
Logback (Spring Boot's default), Log4j 2. Spring Boot 3.4+ has built-in structured logging (logging.structured.format.console=ecs / logstash / gelf) |
| Go | log/slog (standard since 1.21) |
JSON/text handlers, zap, zerolog |
| Rust | tracing (spans + events), log facade |
tracing-subscriber (JSON, OpenTelemetry layer) |
| C# | ILogger<T> (Microsoft.Extensions.Logging) |
Console, Serilog, OpenTelemetry |
| Python | logging (stdlib), structlog |
JSON formatters |
| Node | pino, winston | — |
| Elixir | Logger (with metadata) |
Console, JSON formatters |
// SLF4J 2 fluent API with key-values (rendered as JSON fields by structured encoders)
log.atInfo().setMessage("order created").addKeyValue("orderId", o.id()).addKeyValue("lines", o.lines().size()).log();
slog.InfoContext(ctx, "order created", "orderId", o.ID, "lines", len(o.Lines))
#[tracing::instrument(skip(self, cmd), fields(customer = %cmd.customer_id))] // a span with fields for this call
async fn create(&self, cmd: CreateOrder) -> Result<Order, Error> {
let o = self.repo.insert(&cmd).await?;
tracing::info!(order_id = %o.id, lines = o.lines.len(), "order created");
Ok(o)
}
Lab: three ways a healthy backend falls over
A JDK HttpServer with three endpoints, driven by a Java HttpClient load generator on the same 2-core machine (JDK 21, server started with -Dsun.net.httpserver.nodelay=true; chapter 45's lab shows why). With client and server sharing two cores, totals vary by about 30% between runs; the ratios don't. Each experiment is a configuration choice that looks harmless until traffic arrives.
Experiment 1: the request-handling pool
An endpoint that spends 100 ms waiting on "the database", hit by 400 concurrent requests, with three server executors:
s.createContext("/slow-db", e -> { sleep(100); send(e, 200, "ok"); });
s.setExecutor(Executors.newFixedThreadPool(8)); // or 200, or a virtual thread per request
fixed pool of 8 threads: total 5106 ms | 78 req/s | p50 2514 ms | p99 4863 ms
fixed pool of 200 threads: total 481 ms | 832 req/s | p50 279 ms | p99 345 ms
virtual thread per request: total 318 ms | 1258 req/s | p50 223 ms | p99 305 ms
With 8 threads, at most 8 requests wait on the database at once; everyone else queues, so the median user waited 2.5 s for a 100 ms operation and the slowest waited 5 s. Little's law predicts it exactly: throughput = concurrency ÷ latency = 8 ÷ 0.1 s = 80 requests per second. Raising the pool to 200 helped by the same law (two rounds of 200); a virtual thread per request removed the limit altogether, and the remaining time is the load generator and server sharing two cores. This is the most common production failure mode for thread-per-request servers (Tomcat's default pool is 200 threads): a downstream dependency slows from 10 ms to 500 ms, the pool fills, and the service stops responding even to requests that don't touch that dependency. Removing the thread limit moves the bottleneck rather than removing it: the 20-connection database pool (chapter 49) or the database itself becomes the limit, which is why chapter 52 adds bulkheads and load shedding.
Experiment 2: timeouts
client.send(HttpRequest.newBuilder(URI.create(".../hang")).timeout(Duration.ofMillis(500)).build(), …);
client.sendAsync(HttpRequest.newBuilder(URI.create(".../hang")).build(), …); // no timeout
call to a hanging service with a 500 ms timeout: failed fast after 553 ms (request timed out)
same call with no timeout: still waiting after 5002 ms (the default timeout is infinite)
Java's HttpClient, most JDBC drivers, and many HTTP libraries in every language default to no timeout (or a very long one). One hung dependency then holds a thread, a connection and the caller's request indefinitely, and the problem in experiment 1 cascades upstream. Set a connect timeout and a request timeout on every outbound call, sized from the dependency's normal latency and your own deadline (if your API promises 1 s, a downstream call can't be allowed 5 s), and propagate deadlines between services (gRPC does this natively). Chapter 52 builds retries, circuit breakers and fallbacks on top.
Experiment 3: graceful shutdown
A 2-second request is in flight when the server is told to stop:
stop(0) with a 2 s request in flight: stop returned after 2 ms, client got ConnectException: null
stop(5) with a 2 s request in flight: stop returned after 1710 ms, client got 200 "report ready"
stop(0) closed the connection under the client: a failed request during every deploy, for every instance, which users see as random errors. stop(5) stopped accepting new connections and waited (up to 5 s) for the exchange to finish. Graceful shutdown in production has three parts: the platform marks the instance unready so the load balancer stops sending traffic (Kubernetes readiness, Volume 6), the server drains in-flight work within a grace period shorter than the platform's kill timeout (Kubernetes' default terminationGracePeriodSeconds is 30), and background consumers stop taking new messages. Spring Boot enables this with server.shutdown=graceful (the default since Boot 3.4).
Try it yourself
- Repeat experiment 1 with 1,000 requests and a
Semaphore(20)inside the handler to model a 20-connection database pool. What's the throughput now with virtual threads, and does it match Little's law? - Add a 50 ms queue time measurement to the
Observefilter of Start here (time from accept to handler start). How would you expose it as a metric? - Send a 50 MB body to an endpoint that uses
readAllBytes()while watching heap usage withjcmd <pid> GC.heap_info, then change it toreadNByteswith a 413 response. - Write experiment 1's server in Go (
net/http, a goroutine per request) and in Node (setTimeoutin the handler). How do they compare with the virtual-thread version, and why?
Revision sheet: backend fundamentals
Key ideas
- Shape: listener → middleware chain → router → controller → service → repository → database/other services; the same in Spring, ASP.NET Core, Express/Fastify, Django/FastAPI, Gin/Echo, Axum, Phoenix.
- Request handling models: thread per request (now virtual threads), event loop (Node, Netty/WebFlux, Vert.x), goroutines, BEAM processes, async/await runtimes (Tokio, .NET).
- Middleware: request ids, logging, timing, authentication, CORS, compression, rate limiting, error mapping; ordering matters.
- Dependency injection: wire objects from the outside; constructors; scopes.
- Serialisation and validation: JSON mapping (Jackson), bean validation, all errors at once, size limits, unknown-field policy.
- Layering: thin controllers, services with rules and transactions, repositories hiding storage; hexagonal/ports-and-adapters as the generalisation (Volume 13).
- Configuration: environment variables and profiles, secrets from a vault, validated at startup.
- Errors: domain exceptions mapped centrally to status codes; Problem Details (RFC 9457); never leak internals; log with request ids.
- Lifecycle: health (liveness, readiness), graceful shutdown, startup checks.
Numbers to remember
- Lab: 8 threads × 100 ms waits = 78 req/s (Little's law); a virtual thread per request served 400 concurrent requests in about 320 ms; no timeout means waiting forever;
stop(0)failed an in-flight request,stop(5)completed it. - Tomcat's default max threads: 200. Kubernetes' default termination grace period: 30 s.
Pitfalls
- Business logic in controllers; HTTP types in services.
- Unbounded request bodies, lists and page sizes.
- No timeouts on outbound calls; pools sized without Little's law.
- Different error shapes per endpoint; stack traces in responses.
- Logs without request ids or structure; logging secrets or personal data.
- Hard shutdowns during deploys.
Glossary
- Controller/handler: maps HTTP requests to application calls.
- Service: application logic and rules.
- Repository: storage abstraction for one kind of entity.
- Middleware/filter: code wrapped around every request.
- Problem Details: the RFC 9457 error format.
- Graceful shutdown: stop accepting work, finish in-flight work, then exit.