Database Optimization
Orders APIs almost always slow down at the database first — missing indexes, N+1 selects, huge pages, chatty flushes.
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
- Enable SQL logging; hit order detail and count selects.
- Add join fetch if items cause N+1; re-count.
- Ensure Flyway indexes match filter patterns;
EXPLAINa slow list query. - Set
hibernate.jdbc.batch_sizeand bulk-insert items in one transaction.
Informative example
N+1 fix + batch config for Orders.
// 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.ymlspring:jpa:properties:hibernate.jdbc.batch_size: 50hibernate.order_inserts: truehibernate.order_updates: true-- PostgresEXPLAIN (ANALYZE, BUFFERS)SELECT * FROM orders WHERE user_id = 17 AND status = 'PENDING'ORDER BY created_at DESCLIMIT 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
EXPLAINshows sequential scans.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat usually causes N+1 in JPA apps?+
Answer
2IntermediateQuestionWhy index foreign keys?+
Answer
3IntermediateQuestionWhat does hibernate.jdbc.batch_size help with?+
Answer
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.