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

    Database Optimization

    Orders APIs almost always slow down at the database first — missing indexes, N+1 selects, huge pages, chatty flushes.

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

    Introduction

    Orders APIs almost always slow down at the database first — missing indexes, N+1 selects, huge pages, chatty flushes. Optimization is measurement plus a short list of high-impact fixes, not premature micro-tuning.

    Start with indexes on FK and filter columns (user_id, status, created_at). Kill N+1 with join fetch or @EntityGraph. Batch inserts with hibernate.jdbc.batch_size. Page and project so list endpoints never load full aggregates.

    On PostgreSQL, EXPLAIN (ANALYZE, BUFFERS) and pg_stat_statements tell you what is slow. Hibernate statistics or p6spy in development count statements per request. Track p95/p99 latency, not averages that hide checkout spikes.

    Cache hot read-only summaries in Redis only after the query plan is sane — caches multiply complexity when the SQL is still wrong.

    Purpose of this lesson

    Apply the highest-ROI database optimizations for TechLearningPRO Orders: indexes, N+1 elimination, batching, pagination/projections, and measurement.

    Understanding the topic

    Fix the query shape before buying bigger hardware.

    • Indexes: FKs, WHERE columns, composites for common filters.
    • N+1: join fetch / entity graphs on hot detail paths.
    • Batching: JDBC batch size for line-item inserts.
    • Lean reads: pagination + DTO projections.
    • Measure: EXPLAIN, statement counts, p95/p99.

    Step-by-step explanation

    1. Enable SQL logging; hit order detail and count selects.
    2. Add join fetch if items cause N+1; re-count.
    3. Ensure Flyway indexes match filter patterns; EXPLAIN a slow list query.
    4. Set hibernate.jdbc.batch_size and bulk-insert items in one transaction.

    Informative example

    N+1 fix + batch config for Orders.

    sql
    // Before: 1 select orders + N select items
    // After:
    @Query("select o from Order o join fetch o.items where o.id = :id")
    Optional<Order> findWithItems(@Param("id") Long id);
    # application.yml
    spring:
    jpa:
    properties:
    hibernate.jdbc.batch_size: 50
    hibernate.order_inserts: true
    hibernate.order_updates: true
    -- Postgres
    EXPLAIN (ANALYZE, BUFFERS)
    SELECT * FROM orders WHERE user_id = 17 AND status = 'PENDING'
    ORDER BY created_at DESC
    LIMIT 20;

    Output

    Index Scan using ix_orders_user_status ...
    Execution Time: 0.4 ms

    Real-world use

    During a course launch, TechLearningPRO order-detail p95 jumps. Statement logging shows 1+N item queries. One join fetch and a composite index on (user_id, status, created_at) restores checkout and account pages without scaling the cluster.

    Security implications

    Performance bugs can become availability attacks.

    • Unauthenticated endpoints that trigger heavy queries are DoS vectors.
    • Cap page sizes and expensive report queries behind authz.
    • Do not expose raw EXPLAIN or schema details to clients.

    Best practices

    • Measure with EXPLAIN before and after each change.
    • Keep open-in-view false so N+1 cannot hide in JSON rendering.
    • Review slow-query logs weekly during growth phases.

    Common mistakes

    • Adding Redis before fixing N+1.
    • Indexing every column 'just in case' and slowing writes.
    • Tuning JVM heap when EXPLAIN shows sequential scans.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat usually causes N+1 in JPA apps?+

    Answer

    Lazy collections accessed in a loop (or during serialization) without join fetch/entity graph, producing one query per parent row.
    2IntermediateQuestionWhy index foreign keys?+

    Answer

    Joins and ON DELETE/lookup patterns filter on FK columns; without indexes Postgres may sequential-scan child tables.
    3IntermediateQuestionWhat does hibernate.jdbc.batch_size help with?+

    Answer

    It groups insert/update statements so multi-row writes (order lines) use fewer network round trips.

    Hands-on exercise

    Lab. Create an order with 10 items. Load detail without fetch (count SQL). Add join fetch and recount. Run EXPLAIN on a filtered list before/after adding a composite index.

    Summary

    Database optimization keeps Orders fast as data grows. Next: structure persistence behind a clear repository pattern.

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