Learning SequenceVol. 18 · Part XVIII
0 / 0

Trails / Learning Sequence

LS·199

Phase 3 — Spring Production Backend

The third phase: Spring Core, Spring Boot, web, validation, data access with JPA, transactions, security, testing and observability, ending with a production-style business application; the order and why, an entry check, step-by-step exit checks mapped to Volumes 3, 9 and 11, the project with milestones and definitions of done, traps, a time budget, and a lab measuring the data-integrity bugs every business application must prevent.

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

Start here: Phase 3 in one page

Phase 2 showed what a backend does by hand. Phase 3 learns the framework most Java teams use to do it at scale: Spring. The goal isn't to memorise annotations; it's to know what each one does underneath (a proxy, a transaction, a filter chain, a connection pool), so you can build a production-style application and debug it when it misbehaves.

The sequence

Text
Spring Core → Spring Boot → Web → Validation → Data/JPA → Transactions → Security → Testing → Observability

Core (dependency injection, beans, proxies) explains everything else. Boot adds auto-configuration and packaging. Web, validation and data access form the request path. Transactions protect data across that path. Security wraps it. Testing proves it. Observability lets you see it in production.

Why "production-style" matters

A demo app handles one user clicking once. A production app handles many users clicking at the same moment, retrying when the network hiccups, and sometimes double-clicking. The lab showed what that does to data, using PostgreSQL directly with the same patterns Spring and JPA generate:

Pattern 8 users × 50 "add one credit" requests Spring/JPA equivalent
load, change, save 56 of 400 credits recorded repo.findById → setCredits → save
atomic update 400 @Modifying @Query("update … set c = c + 1")
row lock 400 @Lock(PESSIMISTIC_WRITE)
version column 400 (after 2,121 retries) @Version + retry

And a double-submitted order created two orders until an idempotency key with a unique constraint made it one. These bugs pass every single-user test and appear on the first busy day.

How deep to go in Phase 3

Volume 17 defines six mastery levels; Phase 3's exit targets are:

Topic Exit level What that means here
Spring Core and Boot L3 explain DI, bean lifecycle, proxies, auto-configuration
web and validation L2–L3 build REST APIs with validation, error mapping and content negotiation
data access and JPA L3 entities, repositories, fetch strategies, N+1, projections
transactions L3 propagation, isolation, rollback rules, locking
security L2 authentication, authorisation, OAuth2 resource server basics
testing L2–L3 unit, slice and integration tests with real databases
observability L2 Actuator, metrics, structured logs, traces

The sequence, step by step

Step Learn Read Exit check
1 DI, beans, scopes, proxies, AOP Vol. 3, ch. 46 explain and reproduce the self-invocation trap
2 Boot, starters, auto-configuration, profiles Vol. 3, ch. 47 find why a bean was (or wasn't) auto-configured
3 MVC (and WebFlux awareness), validation, error handling Vol. 3, ch. 48 consistent problem-details errors for every failure
4 JDBC, JPA, Hibernate, Spring Data Vol. 3, ch. 49 find and fix an N+1 with logs
5 transactions and locking Vol. 3, ch. 49; Vol. 4, ch. 59 prove lost updates and their fix with a concurrent test
6 Spring Security, OAuth2/OIDC Vol. 3, ch. 50 protect endpoints by role and by resource owner
7 async work, messaging, resilience, caching Vol. 3, ch. 51–53 a retry with back-off and an idempotent consumer
8 testing Vol. 3, ch. 54; Vol. 11, ch. 115–116 integration tests against a real PostgreSQL
9 observability Vol. 9, ch. 97–101 metrics and traces for every endpoint

Entry check

Phase 2's exit criteria: idiomatic Java, collections and generics, threads and executors, HTTP API design, and a framework-free service you built.

The phase project: a production-style business application

Goal. A Spring Boot application for a real-feeling domain (TiffinBox subscriptions, skips, payments, kitchen orders) with the qualities production demands.

Milestones. Domain model and API design → persistence with migrations (Flyway or Liquibase) → validation and problem-details errors → transactions with the right locking per use case → idempotency keys for payments and orders → authentication and per-owner authorisation → background jobs (reminders) → integration tests with Testcontainers → Actuator health, metrics and tracing → a load test with concurrency.

Done when. A concurrent test proves no lost updates or duplicate orders; authorisation tests prove users can't read others' data; integration tests run against PostgreSQL in CI; dashboards show request rate, errors and latency per endpoint; a README explains each transaction and locking choice.

Stretch. Add an outbox for events (Phase 8 preview) or a second module enforced by ArchUnit or Spring Modulith.

Common traps

  • Annotation-driven development without knowing the proxy, transaction or filter underneath.
  • Load-change-save on shared counters and balances.
  • Open-session-in-view and lazy loading producing N+1 queries.
  • Testing only with H2 while production runs PostgreSQL.
  • Security by URL patterns only, missing per-object authorisation.

Exit criteria

  • [ ] The project meets its "done when" list, including concurrency and authorisation tests.
  • [ ] I can explain what @Transactional, @Async, @Cacheable and @PreAuthorize do through proxies, and their self-invocation limits.
  • [ ] I can choose optimistic or pessimistic locking for a use case and defend it.
  • [ ] I can find an N+1 problem from SQL logs and fix it.
  • [ ] I scored at least 80% on 40 questions from Volume 3's chapters 46–54 quizzes, twice.

Time budget

Volume 3's chapters 46–54 (about 75,000 words) plus the testing and observability chapters named above (about 35,000) are about 8 hours of reading; with practice, about 32 hours, plus 3–4 weeks for the project: about 2.5 months at 8 hours a week.

Lab: the data-integrity bugs every business app must prevent

Setup. PostgreSQL 16 on the lab machine, driven from Python with psycopg 3. Substitute, stated plainly: the lab machine has no Maven Central access, so Spring can't be downloaded; the experiments use the exact SQL patterns that Spring Data JPA generates for each approach (shown in the table), which is where these bugs live. 8 threads each send 50 "add one credit to the wallet" requests (400 in total), each in its own transaction, with 1 ms of "business logic" between reading and writing.

Experiment 1: concurrent updates to one row

Approach SQL pattern Spring equivalent Credits recorded (expected 400) Time Retries
load, change, save SELECT credits … UPDATE … SET credits = ? findById → setCredits → save 56 0.17 s —
atomic update UPDATE … SET credits = credits + 1 @Modifying @Query 400 0.15 s —
pessimistic lock SELECT … FOR UPDATE then update @Lock(PESSIMISTIC_WRITE) 400 0.70 s —
optimistic lock UPDATE … WHERE id = ? AND version = ?, retry if 0 rows @Version + retry 400 1.27 s 2,121

The default ORM pattern lost 86% of updates, with no error, no exception and no log line: just wrong balances. The atomic update was fastest and correct but only works when the change can be expressed in SQL. The row lock serialised the requests (4.7× slower than atomic, still correct). Optimistic locking was correct but, on one hot row with 8 writers, failed and retried 2,121 times; it shines when conflicts are rare (user edits a profile), not on counters.

Experiment 2: the double-submitted order

Two identical "create order" requests arrive at the same moment (a double click, or a client retrying after a timeout):

Protection Orders created
none 2
idempotency key column with a UNIQUE constraint; the second insert fails and returns the first result 1

A check in code ("does an order with this key exist?") would race exactly like Experiment 1; the database's unique constraint is atomic. In Spring, map the resulting DataIntegrityViolationException to "return the original response".

Try it yourself

  1. Rerun Experiment 1 at isolation level REPEATABLE READ with load-change-save: what does PostgreSQL do now?
  2. Lower contention (8 threads over 100 wallet rows) and compare optimistic retries.
  3. In a Spring Boot project of your own, write a test with an ExecutorService that reproduces Experiment 1 against Testcontainers PostgreSQL.
  4. Implement the idempotency-key flow end to end: store the response with the key, return it on replay, expire keys after 24 hours.

Revision sheet: Phase 3, Spring production backend

Key ideas

  • Sequence: Core → Boot → Web → Validation → Data/JPA → Transactions → Security → Testing → Observability.
  • Know the mechanism behind each annotation: proxies (transactions, caching, async, security), filter chains, auto-configuration conditions.
  • Production-style means concurrency-safe: atomic updates, locks or versions, idempotency keys, per-owner authorisation.
  • Test against the real database; observe every endpoint.

Numbers to remember

  • Lab: load-change-save recorded 56 of 400 updates; atomic, locked and versioned approaches all 400.
  • Lab: optimistic locking on one hot row needed 2,121 retries for 400 updates.
  • Budget: ~32 study hours + 3–4 project weeks ≈ 2.5 months at 8 h/week.

Pitfalls

  • Lost updates from load-change-save.
  • Self-invocation bypassing proxies.
  • N+1 queries from lazy loading.
  • H2-only tests.
  • URL-only security without object-level checks.

Glossary

  • Proxy: a wrapper object adding behaviour around method calls.
  • Lost update: a write overwritten by a concurrent write based on stale data.
  • Optimistic / pessimistic locking: detect conflicts at write time / prevent them with locks.
  • Problem details: RFC 9457 standard JSON error format.
  • Testcontainers: a library running real dependencies in containers for tests.