The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S45 · V3·44

Find One Request

Volume 3, chapter 44. A TiffinBox user who got an error saw "internal error", and the operator got one line on stderr with no path, no request and a stack trace that pointed at the wrong thread. The server kept no access log. Its graceful shutdown waited 5 seconds for any idle keep-alive connection, and the same wait made its test suite five times slower. This stage gives every request an id (the caller's, if it's safe, else a new one) that appears in the response, the access log and the error log; writes JSON access and error lines through an asynchronous log whose first design cost 22% of throughput and whose second cost nothing visible; logs the cause of a wrapped exception; and closes idle connections on shutdown: 5,040 ms to 340 ms, and the server's tests from 63 seconds to 12.

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

Stage 45: find one request

The brief

What you'll build.

  • Request ids: X-Request-Id from the caller if it's 1 to 64 characters of letters, digits, -, _ or ., else a new random base-36 id; returned on every response (event streams too).
  • AccessLog: OFF, direct (a println per line, for comparison) and async (a lock-free bounded queue and one writer thread that prints in batches, drops when full and writes {"kind":"log","dropped":N} into the log as it happens). Main uses async on stdout.
  • Access and error lines: {"kind":"access","t":…,"id":…,"method":…,"path":…,"status":…,"bytes":…,"us":…} for every request (the path without its query string); {"kind":"error",…,"error":…,"stack":…} for every 500, which tells the user internal error; reference <id>.
  • The cause, not the wrapper: an ExecutionException or CompletionException is logged as its cause.
  • Shutdown that doesn't wait for idle connections: the server keeps the set of connections waiting for their next request and closes them in close(); after close() starts, a finished request gets Connection: close.
  • Tests: everyResponseCarriesARequestIdAndASafeCallerIdIsKept, aFailureInsideTheServerGivesTheUserAReferenceAndTheLogTheStack, closeDoesNotWaitForAnIdleKeepAliveConnection, and AccessLogTest.
  • Release check: the access log has a line for the retried order and no drops.
  • Measurements in exp/45: shutdown.py, CloseIdle.java, Five00.java, LogLoad.java and logload.sh, Context.java.

Why a real company needs this. "It failed for me at about 7" is most of what support gets. Without an id that the user can see and the logs contain, finding that request means guessing. Deploys that wait out idle connections are slow at best, and killed mid-request at worst.

Why now. Chapter 44 is backend fundamentals: lifecycle, the request path, middleware, error handling and logging. TiffinBox has had a request path since its first stages, but nothing that lets an operator find one request in it.

What you'll have at the end.

  • one id per request, from the user's screen to the log line with the stack;
  • an access log that doesn't slow requests when its destination is slow, and says when it drops;
  • a shutdown in a third of a second, and a test suite five times faster;
  • ADR-0047: how TiffinBox logs and stops.

Theory to own

  1. Persistent connections. Who may close an idle HTTP/1.1 connection, and what does the client do? (Companion, Gaps 1 and Theory 1.)
  2. Bounded queues. What must a log do when its destination is slower than the requests? (Companion, Gaps 2 and Theory 2; the chapter, "Logging".)
  3. Context propagation. Why does a ThreadLocal request id go missing, or go wrong? (Companion, Gaps 3 and Theory 3.)
  4. Error identity. What should a user see for a 500, and what should the log record? (Companion, Gaps 4 and Theory 4; the chapter, "Error handling".)

Build it

Step 1: what happens now

Write exp/45/Five00.java (a request whose order log was closed under it, sent with X-Request-Id: support-ticket-7) and exp/45/shutdown.py (time from SIGTERM to exit with nothing connected, one idle keep-alive connection, one event stream).

Checkpoint. exp/45/five00-wrapped.out and shutdown-before.out, with the stage 44 build.

Step 2: an id for every request

Add requestId, the header on every response, and the reference in the 500 body. Write the first two tests.

Checkpoint. five00-after.out shows X-Request-Id: support-ticket-7 and internal error; reference support-ticket-7.

Step 3: the access log

Write AccessLog and LogLoad.java: 64 keep-alive connections for 4 s after a 2 s warm-up, three runs per setting, stdout to a file and to a pipe read at about 1 MB/s. Try the asynchronous log first with an ArrayBlockingQueue, then with a ConcurrentLinkedQueue and a size counter.

Checkpoint. exp/45/logload-abq.out, logload.out; AccessLogTest.

Step 4: the cause, and the context

Log the cause of ExecutionException and CompletionException. Then write exp/45/Context.java: three requests, each reading a ThreadLocal id on its own thread, in supplyAsync, on a shared pool, through an InheritableThreadLocal on a pool created during the first request, and passed as a value.

Checkpoint. five00-after.out's stack starts java.lang.IllegalStateException: log is closed | at in.tiffinbox.core.OrderLog.append; exp/45/context.out.

Step 5: shutdown without waiting for idle connections

Keep idle (connections waiting for their next request), close them in close(), and stop keeping connections alive once closing. Write exp/45/CloseIdle.java and the test; check the test fails without the change.

Checkpoint. exp/45/closeidle.out, shutdown-after.out; the server's build time.

Senior and architect lens

1. The edges are shared code. Request ids, access logs, error mapping and shutdown live in one place (the connection handler) and are tested there, so every endpoint, present and future, has them.

2. ADR-0047: how TiffinBox logs and stops. Write it with these points:

  • Ids: the caller's if safe, else generated; in every response, access line and error line; passed as a value across threads.
  • Format: JSON lines on stdout: access per request (no query strings: they can carry personal data), error per 500 with the cause's stack, log when lines are dropped.
  • Delivery: asynchronous, bounded at 10,000 lines, dropping and counting when full; measured against a slow destination.
  • Users: a 500 says internal error; reference <id> and nothing else.
  • Shutdown: stop accepting, close idle connections, close streams, finish requests in flight, drain the log, then close the order log.

3. Measure your assumptions about speed, too. The asynchronous log was assumed to be faster and wasn't, until its queue was changed. The test suite's slowness was assumed to be the tests and wasn't.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
stdout piped into a container runtime that's slow dropped access lines (counted) Volume 9's stages (observability: shipping logs, metrics from counts)
no metrics: latency only in log lines dashboards built by parsing logs Volume 9's stages (observability: metrics and traces)
work on other threads (jobs) ids that must be passed along by hand stage 52 (async and jobs)
no readiness signal before shutdown a load balancer may still send requests stage 48 (Spring Boot: readiness and warm-up)

Evidence

  • exp/45/five00-wrapped.out, five00-after.out.
  • exp/45/shutdown-before.out, shutdown-after.out, closeidle.out.
  • exp/45/logload-abq.out, logload.out, AccessLog-abq.java.txt (the first design).
  • exp/45/context.out.
  • Core 52, server 53 and tbx 21 tests; golden master: 47 exchanges, identical; the release check passes, with access log: N lines, none dropped.
  • ADR-0047 is committed.

Carry forward

  • The request id, passed as a value into anything that runs later or elsewhere.
  • The access log, as the first place to look, and its drop count, as something to alert on.
  • A shutdown test for anything that holds connections or threads.