Workbench / Volume 3 Exercises: The Backend
V3·44
Backend Fundamentals
Exercises for Volume 3, chapter 44: what every backend does and the same service in different frameworks; request and response; routing; middleware and filters; dependency injection; serialisation; validation; business logic and layering; persistence; configuration; error handling; logging; and lifecycle concerns (thread models, timeouts, graceful shutdown). 10 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. The code is Java 21, using the JDK's HttpServer and HttpClient and Jackson 2.21. Every quoted output is real. Five results catch experienced developers:
- P1. A context registered for
/ordersalso answered/ordersXYZand/orders/../adminwith 200. The JDK server matches by string prefix and doesn't normalise the path. - P3. With unknown properties ignored, a client that sent
"refunded": true, "paise": 1got both fields bound, which is mass assignment. - P3.
qty: 2.9andpaise: 4050.75were silently truncated to 2 and 4050."3"as a string was coerced to 3. - P3. Duplicate JSON keys were accepted, and the last one won (
dosa), unless strict duplicate detection was on. - P5. A customer name containing a newline forged a second log line:
INFO payment refunded order=999 amount=₹5000.
The chapter's lab already measured these, and the exercises build on them rather than repeat them:
- 8 threads against 200 against virtual threads for 100 ms database calls: p50 2,514 ms, 279 ms and 223 ms;
- an outbound call with no timeout, still waiting after 5 s;
stop(0)breaking an in-flight request, whilestop(5)let it finish.
Coverage map.
| Chapter component | Exercises |
|---|---|
| what every backend does; frameworks compared | T1, P9 |
| request and response | T2, P1 |
| routing | T2, P1 |
| middleware and filters | T3, P2 |
| dependency injection | T4, P6 |
| serialisation | T5, P3 |
| validation | T6, P4 |
| business logic and layering | T7, P6 |
| persistence (overview) | T7 |
| configuration | T8, P7 |
| error handling | T9, P4 |
| logging | T10, P5 |
| thread model, timeouts, graceful shutdown | T1, P8 |
Theory
T1. What every backend does, and its lifecycle
- List the responsibilities of a backend service and map each to a TiffinBox order service component: - accept connections; - parse requests; - route; - authenticate and authorise; - validate; - run business logic; - persist; - call other services; - serialise responses; - handle errors; - log, metric and trace; - configure; - start and stop safely.
- The thread model and the lab's numbers. With 8 threads, p50 was 2,514 ms for 100 ms calls; with 200, 279 ms; with virtual threads, 223 ms. Apply Little's law (ch38's T1). Explain why a pool of 200 "fixes" this load but fails when a dependency slows to 2 s, and what actually bounds concurrency safely (the connection pool, bulkheads: ch52).
- Lifecycle covers startup (configuration, connections, warm-up, readiness), running, and shutdown. The lab:
stop(0)gave the client aConnectException, whilestop(5)returned after 1,710 ms and the client got 200. Write the graceful-shutdown sequence for a Kubernetes deployment, and explain why timeouts (the lab's call "still waiting after 5002 ms") are part of lifecycle design.
T2. Request, response and routing
- Describe what a handler receives and produces. The request has a method, path, query, headers (case-insensitive), a body with a content type and charset, and remote address and TLS information (behind proxies:
X-Forwarded-*,Forwarded). The response has a status, headers and a body, possibly streamed. Which parts must be validated, and which may be trusted? - Routing. P1's JDK
HttpServercontext/ordersmatched/orders/42,/ordersXYZand/orders/../admin, all with 200. Explain prefix matching against segment matching, path normalisation (..,//,%2e%2e, trailing slashes), and why mismatched normalisation between a proxy and the application causes security bugs (path-based authorisation bypass). How do Spring MVC and frameworks in other languages behave? - Design TiffinBox's routes for orders, cancellation and the kitchen's queue, with path parameters and query parameters (filtering, pagination). Explain method semantics (safe, idempotent: ch45),
405against404, andHEAD/OPTIONS.
T3. Middleware and filters
- Middleware runs around every request: logging, request ids, authentication, CORS, compression, rate limiting, error mapping, metrics and transactions. P2's filter chain ran
logging-before, thenauth, which rejected the request with 401, thenlogging-after. Explain how the chain order changes behaviour (should rejected requests be logged? measured?), and the "onion" model. - Give the right order for TiffinBox's filters and justify it: - request id; - access log and metrics; - exception mapping; - rate limiting; - authentication; - authorisation; - body size limits; - CORS; - compression.
- Compare middleware mechanisms: Servlet
Filters andHandlerInterceptors (Spring MVC), WebFluxWebFilters, Express and Koa middleware, Gohttp.Handlerwrappers, and AOP aspects. What belongs in middleware, and what belongs in the domain?
T4. Dependency injection
- Explain dependency injection as "objects receive their collaborators instead of creating them". Compare: - constructor injection (explicit, immutable, testable); - setter and field injection; - service locators; - static singletons.
Show TiffinBox's CheckoutService with constructor-injected OrderRepository, PaymentGateway, PricingRules and Clock.
2. Manual DI (a main that wires objects: "pure DI") against containers (Spring, Guice, Dagger, Micronaut). What does a container add (lifecycle, scopes, proxies for transactions, configuration binding, auto-configuration), and what does it cost (startup, magic, runtime errors instead of compile errors)?
3. Scopes and lifecycles: singleton, request, prototype; why request-scoped state in singletons is a bug (ch38's ThreadLocals); and circular dependencies, and why constructor injection exposes them.
T5. Serialisation
- P3's Jackson results:
- a plain
ObjectMapperrejected an unknown field (UnrecognizedPropertyException: Unrecognized field "coupon"); - with that check disabled (as Spring Boot does by default), a client-suppliedrefunded: trueandpaise: 1were bound (mass assignment); - floats were truncated into ints (qty 2.9became 2,paise 4050.75became 4050) untilACCEPT_FLOAT_AS_INTwas disabled ("Cannot coerce Floating-point value (2.9) tointvalue"); - the string"3"became 3; - a missing record component became0ornull; - an out-of-range number was rejected; - duplicate keys meant the last one won (dosa) unless strict detection was enabled ("Duplicate field 'dish'").
For each, give the security or correctness risk and the configuration or design fix.
2. Design request and response DTOs separate from domain objects and entities. Cover records with only client-settable fields, explicit mapping, @JsonProperty naming, versioning-friendly additions, and why returning JPA entities as JSON is dangerous (lazy loading, leaking fields, cycles: ch34's T6).
3. Serialisation of money, time and ids:
- P3 serialised 0.1 + 0.2 as 0.30000000000000004 and a Date as 0;
- ids above 2⁵³ lose precision in JavaScript (ch33's T3).
Write TiffinBox's JSON conventions, covering ISO-8601 timestamps with offsets, paise as integers (or strings for big values), and enums as stable lowercase strings.
T6. Validation
- Distinguish the layers of validation:
- syntactic (parsing: JSON shape, types; P3's rejections);
- structural (required fields, ranges, formats: Bean Validation
@NotBlank,@Size,@Pattern,@Positive); - semantic and business (the dish exists and is available, the kitchen is open, the coupon is valid: domain rules); - authorisation-dependent (the customer owns this cart).
Where does each live, and what HTTP status does each failure produce (400, 422, 403/404, 409)?
2. Validate at the boundary and enforce invariants in the domain. Why do both exist, and how do you avoid duplicating rules (constraints on DTOs for shape, domain constructors for invariants: ch33's P7 compact constructors)? Return all errors at once (ch36's Validation, Volume 2 ch20's form errors).
3. Input limits as validation: body size (P1 read 50 MB with no limit), array lengths, string lengths, nesting depth (ch37's P6), number of query parameters (ch35's P7), and file uploads. Where do you configure each in a Spring Boot service?
T7. Business logic, layering and persistence
- Explain the common layerings: - controller → service → repository (classic); - hexagonal (ports and adapters); - clean or onion; - vertical slices (feature folders).
What does each optimise for? Where does TiffinBox's checkout logic live (ch37's functional core and imperative shell)? 2. Anaemic domain model against rich domain model (ch34's T1), transaction-script services against aggregates. When is a "simple CRUD" service fine with thin layers, and when does it need a real domain model? 3. Persistence at the boundary: repository interfaces in the application layer, implementations in adapters, transactions at the use-case level, mapping between entities and domain objects (or using entities as the domain model, a pragmatic trade-off). Preview ch49's N+1 and batching results.
T8. Configuration
- Classify configuration: - build-time (dependencies, profiles in the build: avoid); - deploy-time (environment variables, config files, Kubernetes ConfigMaps); - runtime-dynamic (feature flags, rate limits: Volume 2 ch31); - secrets (database passwords, API keys).
Where does each belong, and why must one artifact run in every environment (twelve-factor)?
2. Explain precedence (command line > system properties > environment variables > profile files > application.yml > defaults, in Spring Boot: ch47) and typed, validated configuration (@ConfigurationProperties records with @Validated: fail fast at startup, ch40's P2 lesson).
3. Secrets: never in Git or images; environment variables against mounted files against secret managers (Vault, AWS Secrets Manager, Kubernetes Secrets with encryption); rotation; and not logging them (T10). How does TiffinBox rotate the payment gateway's API key without downtime?
T9. Error handling
- Design TiffinBox's error model:
- a domain error taxonomy (validation, not found, conflict, forbidden, dependency unavailable, internal);
- mapping to HTTP status codes;
- RFC 9457 problem details (
type,title,status,detail,instance, plus extensions:code,errors,traceId); - one translation point (@RestControllerAdvice). - What must never appear in error responses? Stack traces, SQL, internal hostnames, exception class names, other customers' data. How does a default error page leak them, and how do you test that it doesn't?
- Errors from dependencies. Translate a payment gateway timeout (the lab's 500 ms timeout failing after 553 ms) into a response:
-
503withRetry-Afterfor transient failures; -502or504where appropriate; - an idempotency-safe retry contract for the client (ch45); - never a generic 500 with an unknown outcome for a payment ("did I pay?").
T10. Logging
- Structured logging: JSON logs with stable fields (timestamp, level, logger, message,
traceId,requestId,orderId,kitchenId, duration, outcome), MDC for request context, and log levels by purpose. Why are structured logs better than formatted strings for search and alerting (ch52)? - Log injection. P5: a customer name containing
\nproduced a forged log lineINFO payment refunded order=999 amount=₹5000. Sanitising\r\nproduced one line. Explain the risks (forged audit entries, broken parsers, terminal escape sequences) and the fixes (structured JSON encoding, which escapes newlines; sanitisation for plain-text logs). - Write what to log and what never to log: - log: request summaries, decisions, state transitions, dependency failures with context; - never: passwords, tokens, full card numbers, OTPs, personal data beyond necessity (DPDP Act in India, GDPR).
Cover retention, sampling for high-volume debug logs, the cost of logging (ch41's P3), and audit logs as a separate stream.
Programming exercises
P1. Routing, normalisation and a minimal router
With the JDK HttpServer, register /orders and request /orders/42, /ordersXYZ and /orders/../admin. Observe the matches. Then write a small segment-based router supporting GET /orders/{id}, POST /orders and POST /orders/{id}/cancellation, which:
- normalises the path once (rejecting .., // and encoded dots with 400);
- returns 404 for unknown paths and 405 with Allow for wrong methods.
Test it with a table of paths.
P2. Middleware order
Build a filter chain with: - a request id; - an access log; - exception mapping; - a body size limit; - authentication; - a handler.
Show the order of execution for a successful request, an unauthenticated request (P2's logging-before, auth, logging-after), an oversized body, and a handler exception. Then move authentication before logging and show what's lost.
P3. Serialisation pitfalls and safe DTOs
Reproduce P3's Jackson behaviours:
- unknown fields;
- mass assignment;
- float truncation;
- string coercion;
- missing fields;
- out-of-range numbers;
- duplicate keys;
- float and Date serialisation.
Then configure an ObjectMapper for TiffinBox's public API (strict duplicates, no float-to-int, java.time as ISO, StreamReadConstraints), and write the request and response records for "place order" so clients can't set prices or flags.
P4. Validation and problem details
Implement "place order" validation in three layers:
- structural on DTOs (Bean Validation, or hand-written checks if Hibernate Validator isn't available);
- value types (Quantity, DishId);
- business rules (dish available, kitchen open in Asia/Kolkata, coupon valid).
Accumulate the errors and return RFC 9457 problems with field paths and codes. Write tests for each failure, and a test asserting that no 4xx or 5xx body contains stack traces or SQL.
P5. Structured logging and log injection
Log a customer name containing \n with plain-text concatenation, and show the forged line. Fix it:
- by sanitising;
- by switching to JSON logs with MDC (requestId, orderId), with Logback and an encoder if available, or a small JSON formatter.
Mask the phone number and Authorization header. Write a test that fails if a log line contains a raw token.
P6. Dependency injection by hand and with a container
Wire CheckoutService (repository, payment gateway, pricing rules, clock) manually in a Main composition root. Write tests with fakes and no container. Then wire the same graph with Spring's AnnotationConfigApplicationContext (Spring 7 jars are available here). Show:
- constructor injection;
- a startup failure for a missing bean;
- a startup failure for a circular dependency;
- the request-scope bug: a singleton holding the current cart.
P7. Configuration: precedence, typing and secrets
Build typed configuration for the payment client (base URL, timeout, maximum concurrency, API key) from defaults, a file, environment variables and system properties, with precedence and validation at startup. Show: - an invalid value failing fast with a clear message; - the API key masked in the startup log; - a key-file watcher that reloads a rotated key without a restart.
P8. Timeouts, thread pools and graceful shutdown
Reproduce the lab's three results:
- 8 threads against 200 against virtual threads for 100 ms calls;
- the hanging dependency with and without a timeout;
- stop(0) against stop(5).
Then: - add a per-dependency semaphore (20) and a 300 ms request deadline propagated to the outbound call (the remaining budget); - implement SIGTERM handling (a shutdown hook) that marks the service unready, waits for in-flight requests and exits.
P9. The same endpoint in four stacks
Implement GET /orders/{id} (lookup, 404 problem, JSON) in:
- the JDK HttpServer (P1's router);
- Spring MVC (with the Spring 7 jars available here: spring-webmvc, spring-boot-webmvc, Tomcat);
- Go's net/http with 1.22 patterns;
- Node with Express or Fastify (Volume 2).
Compare the lines of code, startup time, how routing and errors are expressed, and how each handles /ordersXYZ and /orders/../x.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–44)
C1. The TiffinBox order service skeleton
Build the order service with: - vertical-slice packages; - a hexagonal core (ch37's functional core); - constructor injection; - typed configuration; - a middleware chain (P2); - strict JSON (P3); - layered validation (P4); - RFC 9457 problems; - structured logs with request ids (P5); - timeouts, semaphores and deadlines on dependencies (P8); - graceful shutdown.
Use the JDK HttpServer or Spring 7 jars. Provide the place order, get order and cancel order endpoints, with an in-memory repository and a fake payment gateway, plus a test suite.
Combines: Volume 2's frontend API expectations (ch19, ch20), ch33–ch37's domain code, ch38's concurrency limits, ch43's module structure, and this chapter.
C2. Error and logging contract shared with the frontend
Define the shared error contract between the order service and the Volume 2 frontend:
- a JSON Schema for problem details;
- the error codes catalogue;
- field paths matching the form fields;
- traceId shown in the UI for support;
- localisation of messages (en, hi, te) done on the frontend from codes.
Generate TypeScript types from the schema, and write contract tests on both sides with shared fixtures.
Combines: Volume 2's forms and error handling (ch20, ch21) and TypeScript types (ch16), ch33's localisation concerns, and this chapter's error and logging design.
C3. Framework comparison spike
Implement the C1 endpoints in Spring Boot (MVC with virtual threads), Go (net/http plus database/sql), and Node (Fastify) with the same contract tests (C2), the same load test (ch41's C1 at a fixed arrival rate), and the same failure injection (a slow payment gateway). Compare the lines of code, startup, p99, memory, behaviour under the slow dependency, and developer experience, and write the recommendation for TiffinBox's next service.
Combines: ch33's language comparison, ch38's concurrency models, ch40's runtimes, ch41's measurement method, and this chapter.
What the chapter leaves out
API gateways, BFFs and service meshes
In production, requests often pass through an edge proxy or API gateway (TLS termination, routing, authentication, rate limiting), a BFF (backend-for-frontend, shaping data per client: Volume 2), and a service mesh (mTLS, retries, traffic shifting between services). Each layer duplicates middleware concerns, so decide where each one lives (rate limits at the edge, business authorisation in the service) and keep path normalisation consistent (T2).
Idempotency, concurrency control and HTTP semantics
Handlers that change state must cope with retries (clients, proxies and meshes all retry) and concurrent updates. Idempotency keys, ETags with If-Match for optimistic concurrency, and correct method semantics are chapter 45's subject, but every backend needs them from the first endpoint that charges money.
Background work and the request path
Not everything belongs in the request: sending SMS, generating invoices, recalculating analytics. Moving work to queues (ch51) keeps latency low and failures isolated, but it introduces eventual consistency and new failure modes (lost messages, duplicates). The outbox pattern links database changes to messages reliably.
Health checks and readiness semantics
Liveness ("restart me if I'm wedged"), readiness ("send me traffic") and startup probes have different meanings. A readiness check that depends on the database can take every instance out of rotation during a brief database blip, a cascading failure. Design probes deliberately (ch47's actuator, ch52).
Internationalisation on the backend
Backends generate localised content too: SMS, emails, PDFs, error messages for clients that don't localise. They need locale negotiation (Accept-Language), message bundles, number and date formatting per locale (ch33's Indian grouping), time zones (Asia/Kolkata against UTC storage), and Unicode-safe truncation (ch33's C3). Decide which layer localises what, and keep codes stable (C2).
Senior exercises
S1. The backend service standard
Write TiffinBox's backend service standard on one page: - the structure (slices plus a hexagonal core); - DI (constructor injection); - DTOs (separate, strict Jackson configuration); - validation layers; - the error contract (RFC 9457 plus codes); - logging (JSON, MDC, the never-log list); - configuration (typed, validated, no build-time environments; secrets from a manager); - timeouts and deadlines on every outbound call; - graceful shutdown settings; - input limits; - the path-handling rules.
Tie each to an output from this chapter.
S2. Review a new service's pull request
A new "kitchen payouts" service PR has:
- controllers returning JPA entities;
- @Autowired field injection everywhere;
- a GlobalExceptionHandler that returns e.getMessage() with status 500 for everything;
- log lines like log.info("payout " + payout), where Payout.toString includes the bank account number;
- RestTemplate calls with no timeouts;
- configuration read with System.getenv inside service methods;
- server.shutdown left at a custom value of immediate.
Write the review.
S3. Decide where business rules live in a growing service
The order service's checkout rules are spread across: - a Spring Cloud Gateway filter (minimum order value); - a controller (kitchen open hours); - a JPA entity listener (stock decrement); - a database trigger (loyalty points); - the frontend (the delivery fee shown).
The rules disagree in edge cases. Decide where each rule should live, plan the consolidation, and define how to prevent drift.
S4. Teach "the edges of a request" with five outputs
Prepare a 20-minute session using:
- P1's /ordersXYZ and /orders/../admin matching;
- P3's mass assignment and float truncation;
- P5's forged log line;
- the lab's 8-thread pool p50 of 2,514 ms;
- the lab's stop(0) failure.
For each, take a prediction, reveal, explain, and give the rule.
S5. Write the production-readiness checklist and review process
Design TiffinBox's production-readiness review (PRR) for new backend services. Cover: - the checklist (this chapter's concerns plus observability, security, data and runbooks); - the evidence required for each item (tests, dashboards, configuration); - who reviews; - how long it takes; - how to keep it from becoming bureaucracy.
Apply it to the payouts service from S2.