Volume 3 Companion: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Companion: The Backend

V3·44

Backend Fundamentals

Companion to Volume 3, chapter 44: how a backend's lifecycle, its request path, how it's built and how it's run connect; new angles (a restaurant closing for the night, a log as a ledger written by a clerk who can fall behind, a request id as a ticket stub); what the chapter simplifies, measured on the build's stage 45: a graceful shutdown that waited 5 seconds for a connection that wasn't doing anything (and made the test suite five times slower), an asynchronous access log that cost a fifth of the throughput in its first design and saved half of it against a slow log shipper in its second, a request id kept in a ThreadLocal that went missing or named the wrong request once work moved to another thread, and an error log whose stack trace pointed at the waiting thread instead of the failure; the theory behind them (persistent connections, bounded queues, context propagation); how Logback's AsyncAppender decides what to drop, from its source; four debugging drills; interview questions with how to approach each.

6 sections · ~13 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 44 covers what every backend does: its lifecycle (startup, serving, readiness, graceful shutdown), the request path (request and response, routing, middleware and filters), building it (dependency injection, serialisation, validation, business logic and layering, persistence) and running it (configuration, error handling, logging), across frameworks and languages.

lifecycle the request path building it running it startup config, connections, warm-up serving threads, timeouts readiness take traffic or not graceful shutdown drain, then exit request and response methods, status, headers routing paths to handlers middleware, filters an onion, in order request context id, user, deadline dependency injection wiring, scopes serialisation DTOs, not entities validation at the edge logic and layering where rules live configuration precedence, secrets error handling problem details logging structured, levelled what operators need find one request then signals before matched by wrapped in sets wires then guards shapes recorded in serve builds on: ch38 concurrency · ch41 performance · goes on: ch45 HTTP APIs · ch46–48 Spring · ch52 resilience · Vol 6 observability exercises: P1–P9 routing, middleware order, serialisation, validation, logging, DI, configuration, shutdown, four stacks; C1–C3
Concept map of chapter 44, backend fundamentals: what every backend does (its lifecycle: start, serve, shut down), the request path (request and response, routing, middleware and filters), building the service (dependency injection, serialisation, validation, business logic and layering, persistence), and running it (configuration, error handling, logging), with links such as middleware order being semantics and a request id tying a user's report to the logs.

The links worth remembering:

  • Every request crosses the same edges. Parse, route, wrap in middleware, validate, run the logic, serialise, log. A problem at an edge (a missing timeout, a wrong order of filters) affects every endpoint at once.
  • A service is judged at its start and its end, too. Startup, readiness and shutdown are where deploys turn into user-visible errors.
  • Operators need to find one request. A request id that reaches the user, the access log and the error log is what turns "it failed for me" into a line of code.

Explain it differently

1. Graceful shutdown is a restaurant closing for the night. You lock the door to new guests and let the ones eating finish. You don't wait for the couple who finished an hour ago and are just sitting there: you ask them to leave. A server that waits for idle keep-alive connections is waiting for the couple (Gaps 1).

2. An asynchronous log is a ledger written by a clerk. Cashiers hand slips to the clerk instead of writing the ledger themselves, so the queue at the till keeps moving. If the clerk falls behind, either the cashiers wait (blocking) or some slips go in the bin (dropping). And if the slips are passed through one narrow window, the cashiers queue at the window instead (Gaps 2).

3. A request id is a ticket stub. The customer keeps half, the kitchen keeps half. When the customer complains, the stub finds the order. A stub kept in the cashier's pocket (a ThreadLocal) isn't there when the order is handed to the kitchen next door (Gaps 3).

4. A wrapped exception is a note saying "the delivery didn't arrive". It tells you where someone was waiting, not where the van broke down. The cause is the van (Gaps 4).

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from OpenJDK 21.0.12 on 2 cores and the build's stage 45 (exp/45), unless stated.

1. Graceful shutdown can wait for connections that aren't doing anything. The lab's graceful shutdown waits for a request in flight. HTTP/1.1 connections stay open between requests (browsers, proxies and HTTP clients keep them for reuse), and TiffinBox's handler for such a connection was blocked reading the next request. Time from SIGTERM to exit:

Terminal
nothing connected                  exit after SIGTERM: 40, 33, 41 ms
one idle keep-alive connection     exit after SIGTERM: 5,055, 5,040, 5,040 ms
one event stream                   exit after SIGTERM: 21, 35, 32 ms

One idle connection held the shutdown for the full idle timeout (5 s), with no request in flight. With an idle timeout of 60 s (common behind a load balancer), every instance would take a minute to stop, or be killed by the orchestrator first. Stage 45 keeps the set of connections waiting for their next request and closes them in close():

Terminal
one idle keep-alive connection     exit after SIGTERM: 336, 347, 345 ms

The same wait was hiding in the tests. Each test's server was closed while the test's HttpClient still held an idle connection, so each close() waited out the test idle timeout of 2 s. The server's build, mostly its 53 tests, took 63 seconds without the change and 12 seconds with it. Closing an idle connection is safe: HTTP clients retry idempotent requests on a connection the server closed, and a request that was mid-flight isn't idle.

2. An asynchronous log helps only against a slow destination, and it can cost more than it saves. The chapter recommends asynchronous appenders. Requests per second for GET /menu from 64 keep-alive connections, three runs each (median), with no access log, a println per request on the request's thread, and an asynchronous log. The first design used an ArrayBlockingQueue, as many logging libraries do:

Terminal
stdout to a file  access log off     median  15201 requests/s  (runs: 15201 15054 15455)
stdout to a file  access log direct  median  14935 requests/s  (runs: 14935 13912 15355)
stdout to a file  access log async   median  11889 requests/s  (runs: 11889 10585 13371)
stdout to a pipe  access log off     median  16258 requests/s  (runs: 16258 15250 17229)
stdout to a pipe  access log direct  median   7037 requests/s  (runs: 7037 6996 7088)
stdout to a pipe  access log async   median  14590 requests/s  (runs: 13998 14914 14590)

To a file, the plain println cost about 2%, and the asynchronous log cost 22%: every request thread and the writer took the queue's one lock, and the writer competed for two cores. To a pipe read at about 1 MB/s (a slow log shipper or container runtime), println halved the throughput, because every request waited for the pipe; the asynchronous log kept 90% of it and dropped 16,000 to 20,000 lines in each run. With a lock-free queue and a size counter, stage 45's version:

Terminal
stdout to a file  access log async   median  14326 requests/s  (runs: 14326 12955 15053)
stdout to a pipe  access log async   median  14813 requests/s  (runs: 14604 14813 15808)

No visible cost to a file, and the slow pipe no longer slows requests. The drops remain, and are now written into the log itself ({"kind":"log","dropped":…}). Whether to block or drop is a decision about the destination, and should be measured against the one production has.

3. A request id in a ThreadLocal doesn't follow the work. The chapter's logging section puts the request id in the MDC, which is a ThreadLocal. Three requests, each handing work to another thread:

Terminal
request r1: same thread r1 | supplyAsync null | shared pool null | InheritableThreadLocal, pool made by r1 r1 | passed as a value r1
request r2: same thread r2 | supplyAsync null | shared pool null | InheritableThreadLocal, pool made by r1 r1 | passed as a value r2
request r3: same thread r3 | supplyAsync null | shared pool null | InheritableThreadLocal, pool made by r1 r1 | passed as a value r3

On CompletableFuture.supplyAsync and on a shared pool, the id is simply gone: log lines from that work can't be found. With an InheritableThreadLocal, a pool thread copies the value when the thread is created, so a pool made during request r1 reports r1 for every later request: wrong, which is worse than missing. Passing the id as a value always worked. TiffinBox passes it explicitly from the connection handler. Libraries wrap executors to copy the MDC (Spring's TaskDecorator, Micrometer's context propagation), and Java's ScopedValue (final in JDK 25) binds a value for a call and the threads a structured task scope starts.

4. A wrapped exception's stack trace starts where someone waited, not where it failed. The order log's append fails, and the request thread sees it through a CompletableFuture. Logged as caught, the first lines of the stack, which are what error trackers group by and alerts show, are about waiting:

Terminal
java.util.concurrent.ExecutionException: java.lang.IllegalStateException: log is closed | 	at java.base/java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:396) | 	at java.base/java.util.concurrent.CompletableFuture.get(CompletableFuture.java:2096) | 	at in.tiffinbox.server.Server.place(Server.java:464) | ...

Stage 45 logs the cause of an ExecutionException or CompletionException:

Terminal
java.lang.IllegalStateException: log is closed | at in.tiffinbox.core.OrderLog.append(OrderLog.java:82) | at in.tiffinbox.server.Server.place(Server.java:467) | at in.tiffinbox.server.Server.placeOrder(Server.java:442) | ...

Before stage 45, the user saw internal error and the operator saw one line, 500: java.util.concurrent.ExecutionException: …, with no path and no stack. Now the user sees internal error; reference support-ticket-7 (their own X-Request-Id, or a generated one), and the error and access log lines carry the same id.

Common misconceptions

Misconception What's actually true Where it's shown
"Graceful shutdown waits for requests in flight." It may also wait for idle connections, unless it closes them. Gaps 1
"Slow tests are slow code." Here they were five times slower because of a shutdown wait. Gaps 1
"Asynchronous logging is always faster." Only against a slow destination; a contended queue can cost more than it saves. Gaps 2
"An async appender never loses logs." Full queues drop (or block); know which, and count it. Gaps 2, Code walkthrough
"The MDC follows the request." Not across threads; an inheritable one can name the wrong request. Gaps 3
"The top of the stack trace is where it failed." Not for wrapped exceptions from other threads. Gaps 4
"Middleware order doesn't matter." It decides what the request id, logging and error mapping can see. Exercises P2

Theoretical gaps: the ideas behind the chapter

1. Persistent connections and who may close them. HTTP/1.1 (RFC 9112, section 9) makes connections persistent by default; either side may close an idle one at any time, and clients must be ready to retry a request that was sent on a connection the server closed, if it's idempotent. A graceful server closes idle connections and finishes busy ones; a client library retries GET and keyed POSTs (TiffinBox's idempotency keys exist for exactly that).

2. A bounded queue chooses between backpressure and loss. When producers outrun a consumer, a bounded queue fills, and then either producers wait (backpressure, which slows the requests) or items are dropped (load shedding, which loses log lines). An unbounded queue postpones the choice to an OutOfMemoryError. Little's law says the queue's length is the arrival rate times the time each item waits; with a consumer slower than the arrival rate, no queue size is enough.

3. Context propagation: implicit or explicit. A request's context (id, user, deadline, trace) can travel implicitly (thread-locals and the MDC; Kotlin's coroutine context, implicit but carried by the runtime) or explicitly as parameters (Go's context.Context). Implicit context is convenient and breaks at every thread hop it doesn't know about (Gaps 3); OpenTelemetry's context API and ScopedValue with structured concurrency make the hops visible.

4. Errors have an identity. A user-visible error should carry an id that leads to exactly one log record with the cause and the stack, and the stack should start where it failed (Gaps 4). RFC 9457's problem details have an instance member for this.

Applying it

Code walkthrough

Gaps 2's choice between blocking and dropping is made for most Java services by Logback. From qos-ch/logback at v_1.5.12, logback-core/src/main/java/ch/qos/logback/core/AsyncAppenderBase.java and logback-classic/.../AsyncAppender.java.

The queue and its defaults

Java
    public static final int DEFAULT_QUEUE_SIZE = 256;
    int queueSize = DEFAULT_QUEUE_SIZE;
    ...
    int discardingThreshold = UNDEFINED;
    boolean neverBlock = false;
Java
        blockingQueue = new ArrayBlockingQueue<E>(queueSize);

        if (discardingThreshold == UNDEFINED)
            discardingThreshold = queueSize / 5;

An ArrayBlockingQueue of 256 events: one lock shared by every logging thread and the worker, the design that cost 22% in Gaps 2 at 64 connections. 256 events is a fraction of a second of access logging at TiffinBox's rates.

What happens when it fills

Java
    @Override
    protected void append(E eventObject) {
        if (isQueueBelowDiscardingThreshold() && isDiscardable(eventObject)) {
            return;
        }
        preprocess(eventObject);
        put(eventObject);
    }

    public boolean isQueueBelowDiscardingThreshold() {
        return (blockingQueue.remainingCapacity() < discardingThreshold);
    }

    private void put(E eventObject) {
        if (neverBlock) {
            blockingQueue.offer(eventObject);
        } else {
            putUninterruptibly(eventObject);
        }
    }

And in logback-classic:

Java
    protected boolean isDiscardable(ILoggingEvent event) {
        Level level = event.getLevel();
        return level.toInt() <= Level.INFO_INT;
    }

When less than a fifth of the queue is free, events at INFO and below are thrown away, silently: nothing counts them. WARN and ERROR are kept by blocking the logging thread until there is room (put), unless neverBlock is set, in which case offer drops them too, also silently. So by default, under a slow destination, the access log (usually INFO) disappears without a trace, and the moment errors spike, requests start waiting on the log.

Debugging drills

D1. Deploys take a minute per instance

A rolling deploy of 20 instances takes 20 minutes. Each instance stops accepting requests within a second of SIGTERM but exits only after about 60 s, and some are killed by Kubernetes.

D2. The service gets slower when the logging pipeline has a bad day

Latency p99 rises from 40 ms to 2 s whenever the log shipper on the nodes falls behind; CPU is low. Thread dumps show many threads in PrintStream.println or ch.qos.logback.core.AsyncAppenderBase.put.

D3. Log lines with the wrong request id

Support finds that the logs for a customer's failed checkout contain lines from a different customer's request, all with the same request id, and only from the payment step, which runs on an executor.

D4. Every error in the tracker looks the same

The error tracker groups 3,000 errors from the last week into one issue: ExecutionException at CompletableFuture.reportGet. The underlying causes turn out to be four different bugs.

Career-oriented

Interview prep

Mid-level 1: what a filter can and can't see

Question. "We added a filter that logs the response status, but for some errors it logs 200. Why?"

How to get there. Where the filter sits relative to the error mapping, and when the status is decided.

Mid-level 2: a request id end to end

Question. "How would you make sure a user's support ticket leads to the right log lines?"

How to get there. Create, propagate, show, log.

Senior 1: zero-error deploys

Question. "During deploys, users see a burst of errors. How do you get to zero?"

How to get there. Follow one connection through the whole shutdown, from the load balancer's view.

Senior 2: logging under load

Question. "Our service logs 2 KB per request at 5,000 requests per second. Design its logging."

How to get there. Volume, cost, what may be lost, and who reads it.

Staff 1: a platform's service template

Question. "You're writing the template every new backend service at the company starts from. What does it guarantee, and how do you know it still does a year later?"

How to get there. The edges every service shares, and tests for each.

Staff 2: framework or library

Question. "A team wants to write a new service without a framework, using the JDK's HTTP server and a few libraries. Do you approve?"

How to get there. What a framework provides at the edges, and what the team would rebuild.