CapstoneVol. 19 · Part XIX
0 / 0

Trails / Capstone

CP·211C

The Backend Layer

TiffinBox's API built to the capstone's list: current Java and Spring Boot, a layered modular structure, REST resources with problem details, idempotency keys and concurrency control, validation at the edge and invariants in the domain, transaction boundaries that don't hold locks across network calls, authorization checked per object, async workers and scheduled jobs, resilience patterns on every outbound call, structured logs and OpenTelemetry; with a lab in Java that hangs a dependency and compares no timeouts, timeouts, a circuit breaker and virtual threads.

22 topics · ~13 min read · 16-question quiz
Updated Suggest a correction

Start here: what the backend must guarantee

The backend is where TiffinBox's rules live: a skip only counts before the kitchen's cut-off, money moves exactly once, a kitchen sees only its own orders, an assistant action runs only as the signed-in user. The frontend can be bypassed; the backend can't. So the capstone's backend list is about guarantees:

Requirement Guarantee it provides
Java + Spring Boot a mature runtime and framework with production features (health, metrics, security) built in
REST a uniform, cacheable, well-understood contract
validation bad input stops at the door with a clear error
transactional services a business operation happens completely or not at all
authorization every request is checked against who's asking and what they're touching
async workers slow or optional work doesn't make users wait
resilience a failing dependency degrades one feature, not the whole service
structured logging + OpenTelemetry you can find out what happened to any request

One slow dependency, measured

The lab ran a small Java HTTP service with two endpoints: /healthy (no dependencies) and /quote (calls a pricing service). Then the pricing service started hanging for 5 seconds per call while 100 clients kept asking for quotes, and 10 other clients used /healthy:

How /quote calls the dependency /healthy while pricing hangs /quote
fixed pool of 50 threads, no timeout unavailable (every request timed out) 5.2 s per request
same pool, 200 ms timeout + fallback 48 req/s, p50 201 ms fallback after ~0.4 s
timeout + circuit breaker 4,330 req/s, p50 2.2 ms instant fallback
virtual threads, no timeout 43,565 req/s, p50 0.2 ms still 5.1 s per request

(With no problem at all, /healthy served about 30,000 requests per second at p50 0.27 ms.)

A hung dependency with no timeout took down an endpoint that doesn't even use it, because both shared the same 50 threads. Timeouts limited the damage; a circuit breaker removed it. Virtual threads stopped the thread exhaustion, but users of /quote still waited 5 seconds: cheap threads don't make a slow dependency fast.

How deep to go

Volume 17 defines six mastery levels. For the backend layer:

Level What you can do
L1 Name each requirement and the guarantee it gives
L2 Build the modules, endpoints and tests with Spring Boot
L3 Explain transactions, isolation, locking, thread models and how Spring's proxies apply them
L4 Debug lost updates, deadlocks, pool exhaustion, slow endpoints and memory leaks
L5 Design module boundaries, consistency, resilience and API contracts, and defend them
L6 Run it: profiling in production, safe upgrades (Java and Spring versions), capacity planning

Volume 3 (chapters 33–54) teaches each topic in depth; this chapter is the build guide.

Runtime and framework

  • Java. The roadmap's baseline is Java 27 (released September 2026). Deploy on what your organisation supports; many teams run the JDK 25 LTS in production and test against the latest release in CI, so upgrades are routine rather than heroic. Since JDK 24, virtual threads no longer pin their carrier inside synchronized blocks (JEP 491), which removes the problem Volume 17's JDK 21 lab measured.
  • Spring Boot 4.x (4.1 at the time of writing) on Spring Framework 7. Its production features (Actuator health and metrics, structured logging, observability, graceful shutdown) do much of this chapter for you if you turn them on.
  • Build with Gradle or Maven, with a dependency lock or BOM, reproducible builds, and a container image built by the pipeline (chapter 211G).

Code structure

Inside each module (Subscriptions shown):

Text
subscriptions/
  api/            public interface other modules may call (SubscriptionsApi, DTOs, events)
  web/            controllers: HTTP → commands; problem details for errors
  application/    use cases: SkipDay, Subscribe; transaction boundaries live here
  domain/         Subscription, Schedule, rules (cut-off), no Spring imports
  persistence/    repositories, JPA entities or jOOQ/JDBC queries

Controllers are thin: parse, validate, call one use case, map the result. Use cases are where transactions start and end. The domain has no framework code, so its rules are fast to unit-test.

REST API design

Volume 3, chapter 45 covers the details; the capstone decisions:

  • Resources and verbs: POST /subscriptions, POST /subscriptions/{id}/skips with { "date": "2026-11-10" }, GET /kitchens/{id}/orders?date=…. Actions that aren't natural resources become sub-resources (/refunds), not verbs in paths.
  • Errors as problem details (RFC 9457): { "type": ".../cut-off-passed", "title": "Too late to skip", "status": 409, "detail": "Kitchen 12's cut-off for 2026-11-10 was 10:30 IST", "instance": "/subscriptions/88/skips" }. The frontend switches on type, never on message text.
  • Idempotency keys on every non-idempotent POST that matters (payments, subscriptions, refunds, skips): the Idempotency-Key header, stored with the response in the same transaction (chapter 212B's lab shows the difference: 600 charges for 200 orders without keys, 200 with).
  • Concurrency control: resources carry a version; GET returns an ETag; updates require If-Match, and a mismatch returns 412 Precondition Failed instead of silently overwriting someone else's change.
  • Pagination by keyset (?after=<last id>) for lists that grow, not offset.
  • Versioning: evolve additively (new optional fields); breaking changes get a new media type or path version and a deprecation period, enforced by contract tests against contracts/openapi.yaml.

Validation

  • At the edge: Bean Validation annotations on request DTOs (@NotNull, @Size, @FutureOrPresent), with failures mapped to a 400 problem listing each invalid field.
  • In the domain: rules that need state ("this date is after the cut-off", "a cancelled subscription can't be skipped") live in domain methods that throw domain exceptions, mapped to 409 or 422.
  • In the database: NOT NULL, foreign keys, CHECK (amount_paise > 0), UNIQUE (subscription_id, date) for skips. These catch what code misses, including concurrent requests.

Transactions

  • Boundaries at the use case (@Transactional on the application service method). Remember Spring applies it through a proxy: calls from inside the same class bypass it.
  • No remote calls inside a transaction. Call the payment provider first with an idempotency key, then record the result in a transaction; or record the intent and let a worker do the call (outbox).
  • Concurrency for the cut-off: the skip must be recorded only if the cut-off hasn't passed and the order for that day isn't already sent to the kitchen. Either lock the subscription row (SELECT … FOR UPDATE) during the check-and-insert, or make it a single conditional statement that the database evaluates atomically. Test it with concurrent requests (Volume 18, Phase 3).
  • Isolation: READ COMMITTED is PostgreSQL's default and fine for most use cases when combined with row locks or conditional updates; use SERIALIZABLE (with retry on serialization failures) for the few rules that span many rows, such as "a kitchen's daily capacity can't be exceeded".
  • Events in the same transaction: the outbox row is inserted with the business change.

Authorization

  • Coarse rules with method security: @PreAuthorize("hasRole('KITCHEN_STAFF')") on the kitchen dashboard's use cases.
  • Object-level rules in queries: findOrdersForKitchen(kitchenId, staffUserId) joins through the staff membership table, so a user can't see another kitchen's orders by changing an ID (Volume 18, Phase 10's audit). Return 404 for objects the caller may not see.
  • The assistant acts as the user: its tools call the same use cases with the user's identity and permissions, never with a service account.
  • Tests that prove it: for each endpoint, a test that another user (and another kitchen) is refused. Make the test fail if a check is removed.

Async workers and scheduled jobs

  • Event consumers (notifications, search indexing, assistant ingestion) run in the workers deployment, consume from Kafka, and are idempotent: they record processed event IDs or use upserts (chapter 211E).
  • Scheduled jobs (generate tomorrow's orders at the cut-off, send reminders) run with a distributed lock (ShedLock on a database table) so that three replicas don't generate orders three times, and are themselves idempotent (generating orders for a date twice creates nothing new thanks to UNIQUE (subscription_id, date)).
  • Threads: use virtual threads for blocking I/O-heavy work (spring.threads.virtual.enabled=true), but keep explicit limits on what they call: a virtual thread per request means a slow dependency can accumulate tens of thousands of waiting requests unless you cap concurrency per dependency.

Resilience

Every outbound call (payment provider, model provider, email service, even Redis) gets:

Pattern Setting for TiffinBox Why
timeout connect 200–500 ms; response based on the dependency's p99 (e.g. payments 3 s, Redis 50–200 ms) bound the wait
retry only idempotent or keyed calls; 2–3 attempts; exponential backoff with jitter; retry budget transient failures; no storms
circuit breaker open after a failure-rate threshold over a window; half-open probes stop hammering a failing dependency; fail fast
bulkhead separate concurrency limits per dependency one slow dependency can't take all threads (the lab)
fallback cached menu, "price unavailable", queue for later degrade a feature, not the service
rate limit / load shedding per user and global; return 429/503 with Retry-After survive spikes (chapter 212A)

Resilience4j implements these for Spring. Two traps: client libraries have their own defaults (chapter 212A's lab found the Redis client retrying with back-off for 4.4 s when Redis was down), and retries multiply: three layers each retrying three times turn one failure into 27 calls.

Structured logging

  • Log as JSON (Spring Boot's structured logging: logging.structured.format.console=ecs or logstash), one event per line.
  • Every line carries trace_id, span_id, the request route, and identifiers that help (order ID, kitchen ID), never secrets, tokens, or raw personal data (mask phone numbers and emails).
  • Log events, not narration: "skip recorded" with fields, at INFO; expected business refusals (cut-off passed) at INFO with a reason, not ERROR; ERROR only for things someone should look at.

OpenTelemetry

  • Instrument with the OpenTelemetry Java agent or Spring's Micrometer Observation with an OTLP exporter; either gives HTTP, JDBC, Kafka and HTTP-client spans automatically.
  • Propagate context across HTTP (traceparent) and Kafka (message headers), so a skip's trace continues into the notification worker.
  • Add business attributes to spans (kitchen ID, order ID, idempotency-key hit or miss) and a few custom spans for important steps.
  • Metrics from the same instrumentation: request rate, errors and duration per route (RED), pool usage, consumer lag, breaker state.

Done when

  • All use cases implemented with unit tests for domain rules and integration tests (Testcontainers) for persistence and transactions.
  • Concurrency tests prove no double skips, no double charges, and no lost updates.
  • Authorization tests prove no cross-user or cross-kitchen access for every endpoint.
  • Every outbound call has a timeout, a bulkhead and a breaker or fallback; a hung dependency affects only its own feature (rerun the lab's scenario against the real service).
  • Logs are JSON with trace IDs and no personal data; traces flow from the browser through the API into workers.

Common traps

  • Remote calls inside transactions.
  • Self-invocation bypassing @Transactional or @PreAuthorize proxies.
  • Unbounded concurrency (virtual threads or reactive) toward a slow dependency.
  • Retrying non-idempotent calls.
  • Business errors logged as ERROR, drowning real ones.

Lab: a hung dependency in Java

Setup. OpenJDK 21 on the lab machine (2 CPUs). One Java program (the JDK's built-in com.sun.net.httpserver, no frameworks, since the lab machine can't download Spring) runs two servers:

  • pricing on port 9302: every call sleeps 5 s (a hung dependency), served by virtual threads so it never runs out of capacity itself.
  • the service on port 9301: /healthy returns immediately; /quote calls pricing through java.net.http.HttpClient and returns a fallback ("price unavailable") with 503 on failure.

Four modes of the service:

  1. none: a fixed pool of 50 platform threads, no timeout.
  2. timeout: same pool, 200 ms request timeout.
  3. breaker: timeout plus a minimal circuit breaker (opens for 10 s after 5 consecutive failures).
  4. virtual: a virtual thread per request, no timeout.

Load: wrk with 100 connections on /quote for 20 s; after 5 s, a second wrk with 10 connections on /healthy for 10 s (2 s client timeout). Everything ran on the same 2 CPUs.

A detour first: 44 ms per request

The first baseline gave /healthy only 227 requests per second at a constant p50 of 44 ms with no dependency involved. That's the classic Nagle plus delayed-ACK interaction: the JDK's simple HTTP server writes the response in several small pieces on a kept-alive connection, Nagle's algorithm holds back the last small piece until the previous one is acknowledged, and the client delays its ACK by ~40 ms. Starting the JVM with -Dsun.net.httpserver.nodelay=true (setting TCP_NODELAY) gave 29,976 requests per second at p50 0.27 ms. All results below use it. Remember the signature: a constant ~40 ms floor on every request.

Results

Mode /healthy (while pricing hangs) /quote
none 0 successful: all 10 connections timed out at 2 s 7.5 req/s, each ~5.15 s
timeout (200 ms) 48 req/s, p50 201 ms, p99 323 ms 247 req/s, all fallbacks, ~0.4 s each
breaker 4,330 req/s, p50 2.2 ms, p99 82 ms 39,372 req/s, instant fallbacks (avg 5 ms)
virtual threads, no timeout 43,565 req/s, p50 0.2 ms, p99 11.5 ms 15 req/s, each ~5.1 s

What it shows

  • No timeout: total failure of an unrelated endpoint. 100 quote requests filled all 50 threads, each stuck for 5 s, and /healthy requests queued behind them until the client gave up.
  • A timeout limits but doesn't isolate. Each quote still held a thread for 200 ms, and with 100 concurrent quote callers the 50 threads stayed busy: /healthy waited ~200 ms in the queue. The fix is a bulkhead: a separate, smaller limit for calls to pricing.
  • A circuit breaker isolates. After five failures it stopped calling pricing for 10 s, so quote requests returned in microseconds and threads were free. (/healthy didn't reach the 30,000/s baseline only because the 39,000/s of fast quote fallbacks competed for the same 2 CPUs.)
  • Virtual threads remove thread exhaustion, not slowness. /healthy was unaffected, but every quote user waited 5 s, and with more clients the waiting requests (each holding memory and a socket) would keep growing. Virtual threads still need timeouts and concurrency limits on dependencies.

Try it yourself

  1. Add a bulkhead (a Semaphore of 10 permits around the pricing call) to the timeout mode and rerun: does /healthy recover without a breaker?
  2. Make pricing fail fast (return 500 immediately) instead of hanging: which modes now behave the same, and why?
  3. Raise /quote load to 2,000 connections in virtual mode and watch the heap and open sockets grow.
  4. Rebuild the service with Spring Boot and Resilience4j on a machine with Maven access, and compare.

Revision sheet: the backend layer

Key ideas

  • Modules with api / web / application / domain / persistence; transactions start in use cases.
  • REST with problem details, idempotency keys, ETag/If-Match, keyset pagination, additive evolution.
  • Validation at three levels: edge (shape), domain (rules), database (invariants).
  • No remote calls in transactions; lock or conditional statements for check-then-act; outbox for events.
  • Authorization coarse by role, fine in queries; the assistant acts as the user.
  • Every outbound call: timeout, bulkhead, breaker or fallback; retries only when safe, with jitter and budgets.
  • JSON logs with trace IDs and no personal data; OpenTelemetry across HTTP and Kafka.

Numbers to remember

  • Lab: no timeout → /healthy 0 successes; timeout → 48/s at 201 ms; breaker → 4,330/s at 2.2 ms; virtual threads → /healthy fine, /quote still 5 s.
  • Nagle + delayed ACK ≈ 40 ms floor per request; TCP_NODELAY fixed it (227/s → 29,976/s).
  • 3 layers × 3 retries = up to 27 calls for one failure.

Pitfalls

  • Remote calls in transactions; proxy self-invocation; unbounded concurrency; retrying non-idempotent calls; business refusals logged as errors.

Glossary

  • Problem details: RFC 9457 error format.
  • Idempotency key: client-chosen ID making retries of one request safe.
  • Bulkhead: isolated resource pool per dependency.
  • Circuit breaker: stops calls to a failing dependency for a while.
  • JEP 491: removed virtual-thread pinning inside synchronized (JDK 24).