Performance Optimization
Optimisation order matters: measure, then change.
Introduction
Optimisation order matters: measure, then change. For Spring Boot 3 Orders on Java 21, the 80/20 is almost always database access, then JSON/payload size, then pool and client timeouts — rarely CPU-bound business logic.
Use Micrometer timers and DB/EXPLAIN plans before rewriting services. Fix N+1 with @EntityGraph or join fetch, size HikariCP from load tests, cache hot catalog reads in Redis with TTL, and adopt virtual threads for I/O-bound fan-out where the stack is ready.
Performance work without budgets becomes endless. Define p99 latency and error-rate SLOs for checkout, then spend effort only on what moves those numbers.
This lesson turns monitoring data into a disciplined Orders performance practice.
Purpose of this lesson
Apply a measure-first performance loop to Orders: DB, pools, JSON, caches, and Java 21 virtual threads.
Understanding the topic
Attack the top constraint; ignore vanity micro-optimisations.
- Slow SQL: indexes, projections, batch writes.
- N+1: entity graphs / join fetch — not lazy surprises in JSON.
- Pools: Hikari and HTTP client pools sized from load tests.
- Cache: Redis for hot reads with explicit TTL and invalidation.
- Virtual threads: cheaper blocking I/O concurrency on Java 21.
Step-by-step explanation
- Capture baseline p50/p99 for
POST /api/ordersunder a realistic load test. - Inspect top SQL and N+1 patterns; add indexes or entity graphs.
- Tune Hikari and outbound timeouts; remeasure.
- Only then consider caching or virtual-thread executors for I/O fan-out.
Informative example
High-leverage Orders knobs (YAML + entity graph).
# application.ymlspring:datasource:hikari:maximum-pool-size: 20connection-timeout: 3000threads:virtual:enabled: truejpa:open-in-view: false// Avoid N+1 when loading order linespublic interface OrderRepository extends JpaRepository<OrderEntity, Long> {@EntityGraph(attributePaths = "lines")Optional<OrderEntity> findWithLinesById(Long id);}// Cache hot catalog reads@Cacheable(cacheNames = "sku", key = "#sku")public SkuView getSku(String sku) {return catalog.findBySku(sku).map(SkuView::from).orElseThrow(() -> new SkuNotFoundException(sku));}
Real-world use
TechLearningPRO Black Friday traffic doubled. CPU was fine; p99 checkout was 4s. Traces showed repeated line-item selects per order. One @EntityGraph and a missing index on orders.customer_id cut p99 under 400ms — no rewrite of the service layer.
Security implications
Perf changes can weaken isolation if careless.
- Do not disable auth filters 'for speed'.
- Cache keys must include tenant/user where data is private.
- Keep connection strings and cache passwords in env placeholders.
Best practices
- Profile with production-like data volumes.
- Paginate list endpoints; never return unbounded collections.
- Set timeouts on every outbound HTTP/gRPC client.
Common mistakes
- Tuning JVM flags before fixing N+1 and missing indexes.
- Leaving
open-in-view=trueand lazy-loading during JSON render under load. - Caching without TTL and serving stale prices.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhere should you look first for Spring Boot slowness?+
Answer
2IntermediateQuestionHow do virtual threads help Orders?+
Answer
3IntermediateQuestionWhy is open-in-view dangerous under load?+
Answer
Hands-on exercise
Lab. Introduce an intentional N+1 in order detail. Measure with a timer metric, fix with @EntityGraph, and compare query counts and p95 before/after.
Summary
Performance work on Orders is evidence-driven. Next: lock behaviour with unit tests so optimisations do not regress logic.