Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 63

    Performance Optimization

    Optimisation order matters: measure, then change.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Capture baseline p50/p99 for POST /api/orders under a realistic load test.
    2. Inspect top SQL and N+1 patterns; add indexes or entity graphs.
    3. Tune Hikari and outbound timeouts; remeasure.
    4. Only then consider caching or virtual-thread executors for I/O fan-out.

    Informative example

    High-leverage Orders knobs (YAML + entity graph).

    java
    # application.yml
    spring:
    datasource:
    hikari:
    maximum-pool-size: 20
    connection-timeout: 3000
    threads:
    virtual:
    enabled: true
    jpa:
    open-in-view: false
    // Avoid N+1 when loading order lines
    public 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=true and 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.

    3 questions
    1BeginnerQuestionWhere should you look first for Spring Boot slowness?+

    Answer

    Database queries, N+1, and connection pool wait — not micro-optimising CPU in services.
    2IntermediateQuestionHow do virtual threads help Orders?+

    Answer

    They make blocking I/O concurrency cheaper on Java 21, improving throughput for call-heavy use cases when the stack is virtual-thread friendly.
    3IntermediateQuestionWhy is open-in-view dangerous under load?+

    Answer

    Lazy loads during view rendering hold DB connections longer and amplify N+1, crushing the pool.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.