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

    Optimization Strategies

    A condensed, repeatable optimisation playbook used at scale: measure first, attack the top constraint, remeasure.

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

    Introduction

    A condensed, repeatable optimisation playbook used at scale: measure first, attack the top constraint, remeasure. For TechLearningPRO Orders on Spring Boot 3 / Java 21, the usual winners are eliminating N+1 queries, fixing indexes, caching hot reads, shrinking JSON, and moving slow work to queues — not rewriting business logic in assembly.

    Virtual threads help I/O fan-out when the stack is ready; they do not fix missing indexes. CDN and gzip help cacheable catalog responses; they do not fix a saturated Hikari pool.

    This lesson turns Ops metrics into a disciplined Orders performance loop.

    Purpose of this lesson

    Apply a measure-first optimisation playbook to Orders: DB chatter, cache, replicas, queues, payloads, and Java 21 virtual threads.

    Understanding the topic

    Attack constraints in priority order.

    • Measure first — Micrometer timers, EXPLAIN, traces; never tune blind.
    • DB chatter — kill N+1; add indexes; use projections.
    • Cache carefully — Redis with TTL and explicit invalidation.
    • Read scale — replicas / materialised views for reporting.
    • Async — queues for email, webhooks, heavy reports.
    • Slim payloads — DTOs, sparse fields, compression.
    • Java 21 — virtual threads for blocking I/O fan-out.
    • Edge — CDN for cacheable public responses.

    Step-by-step explanation

    1. Baseline p50/p99 for POST /api/orders and GET /api/orders/{id} under load.
    2. Inspect top SQL and Hibernate stats; fix N+1 and missing indexes first.
    3. Add Redis for hot SKU reads with TTL; verify stampede protection.
    4. Only then enable virtual threads / push slow side-effects to Kafka and remeasure.

    Informative example

    High-leverage Orders knobs.

    java
    # application.yml — Boot 3 / Java 21
    spring:
    threads:
    virtual:
    enabled: true
    datasource:
    hikari:
    maximum-pool-size: 20
    connection-timeout: 3000
    jpa:
    open-in-view: false
    cache:
    type: redis
    // Kill N+1 on order detail
    public interface OrderRepository extends JpaRepository<OrderEntity, Long> {
    @EntityGraph(attributePaths = "lines")
    Optional<OrderEntity> findWithLinesById(Long id);
    }
    @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 doubled traffic. CPU was fine; checkout p99 was 4s. Traces showed per-line selects and a missing index on orders.customer_id. One @EntityGraph, one index, and Redis for SKU lookups cut p99 under 400ms — classic playbook, no rewrite.

    Security implications

    Perf changes must not weaken isolation.

    • Never disable auth filters 'for speed'.
    • Cache keys must include tenant when data is private.
    • Keep DB and Redis credentials in env placeholders — not in sample YAML committed as real values.

    Best practices

    • Define SLOs; stop when they are met.
    • Paginate every list endpoint.
    • Set timeouts on every outbound HTTP client.

    Common mistakes

    • Tuning JVM flags before fixing SQL and pools.
    • Caching without TTL and serving stale prices.
    • Leaving open-in-view=true so lazy loads hold connections during JSON render.

    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.
    2IntermediateQuestionWhen do virtual threads help Orders?+

    Answer

    When the workload is I/O-bound and the stack is virtual-thread friendly; they do not replace indexes or caching.
    3IntermediateQuestionWhy is open-in-view dangerous under load?+

    Answer

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

    Hands-on exercise

    Lab. Introduce an intentional N+1 on order detail. Capture query count + p95, fix with @EntityGraph, add a Redis SKU cache, and write a one-page before/after report with Micrometer screenshots.

    Summary

    Optimisation on Orders is evidence-driven. Next: raise the security bar to enterprise practices regulators expect.

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