Java 21 • Spring Boot 3 • Microservices
Java 21, Spring Boot 3 & Microservices Interview Questions & Answers (2026)
Master the exact Core Java, JVM internals, Spring Boot 3, Hibernate N+1, Spring Security JWT, Kafka Outbox, and LLD/HLD questions asked by Indian Service MNCs (TCS Digital/Prime, Infosys SP), Product Startups & GCCs.
Freshers Core Java & JVM Q1. How does HashMap work internally in Java 8+ and why should keys be immutable?
HashMap stores entries in an array of Node<K,V> buckets indexed via (n - 1) & hash(key). When collisions occur, entries chain into a linked list; once a bucket reaches TREEIFY_THRESHOLD (8) and table capacity >= 64, it converts into a Red-Black Tree for O(log n) worst-case lookup instead of O(n). Keys must be immutable (like String or Integer) so their hashCode() never mutates after insertion — otherwise get(key) looks in the wrong bucket and causes silent memory leaks.
Freshers Java 21 Concurrency Q2. What are Java 21 Virtual Threads and when do they outperform Platform Threads?
Virtual Threads (Project Loom) are lightweight user-mode threads managed by the JVM rather than the OS, multiplexed onto a small ForkJoinPool of carrier threads. When a virtual thread hits blocking I/O (JDBC, HTTP client, socket read), the JVM unmounts it from the carrier thread so thousands of concurrent I/O-bound requests scale with minimal RAM (~few KB per stack vs ~1 MB OS stack). Avoid synchronized pinning inside I/O paths (prefer ReentrantLock in Java 21) and do not use them to speed up CPU-bound loops.
Freshers Spring Boot Core Q3. What does @SpringBootApplication do internally and how does Auto-Configuration work?
@SpringBootApplication combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. Auto-configuration scans META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports across classpath jars and evaluates @ConditionalOnClass, @ConditionalOnMissingBean, and @ConditionalOnProperty rules — registering defaults (like DataSource, Jackson, Tomcat) only when you have not defined custom beans.
Freshers Spring IoC Q4. Why is Constructor Injection strongly preferred over @Autowired Field Injection in Spring Boot?
Constructor injection enables final immutable dependencies, fails fast at startup if a required bean is missing, immediately exposes circular dependencies instead of hiding them, and makes plain JUnit 5 + Mockito unit tests work without booting a Spring ApplicationContext or using reflection.
Freshers REST & Validation Q5. How do you implement standardized global exception handling in Spring Boot 3?
Use @RestControllerAdvice with @ExceptionHandler methods returning RFC 7807 ProblemDetail payloads (natively supported in Spring 6 / Boot 3). Map domain exceptions (e.g., ResourceNotFoundException → 404, MethodArgumentNotValidException → 400 with field errors) consistently without leaking stack traces to clients.
Experienced Spring Transactions Q6. Why does @Transactional silently fail on self-invocation or private methods, and how do you fix it?
Spring implements @Transactional via AOP dynamic proxies (CGLIB/JDK). Calling this.innerMethod() from inside the same bean bypasses the proxy completely, so no transaction interceptor runs; private methods cannot be overridden by CGLIB proxies either. Fix by moving the transactional method into a separate collaborating Spring bean (preferred) or injecting the proxy / using TransactionTemplate programmatically.
Experienced Hibernate & JPA Q7. What is the Hibernate N+1 Select problem and how do you eliminate it in production?
Fetching N parent entities (1 query) and then lazily accessing a child collection on each triggers N extra SQL queries, collapsing DB latency. Fix it using JPQL JOIN FETCH, @EntityGraph(attributePaths = ...), DTO constructor projections for read-only views, or @BatchSize for paginated parent queries (avoiding in-memory pagination warnings caused by JOIN FETCH + Pageable).
Experienced Spring Security & JWT Q8. How do you design stateless JWT authentication with secure token revocation and refresh rotation?
Keep access tokens short-lived (5–15 minutes) verified statelessly via Spring Security OncePerRequestFilter. Issue long-lived opaque or hashed refresh tokens stored in an HttpOnly, Secure, SameSite cookie and persisted in DB/Redis with a token family ID. On refresh, rotate and invalidate the old token; if a previously used refresh token is replayed, revoke the entire token family immediately to stop session hijacking.
Experienced PostgreSQL & Locking Q9. When would you use Optimistic Locking (@Version) vs Pessimistic Locking (SELECT ... FOR UPDATE SKIP LOCKED)?
Use Optimistic Locking (@Version) for low-to-medium contention updates (like profile or order edits) so reads never block and concurrent writes throw OptimisticLockException for safe retry. Use Pessimistic Locking (FOR UPDATE) for high-contention financial balances, and FOR UPDATE SKIP LOCKED for multi-worker job queues or inventory/seat claim pools so concurrent workers never stall waiting on locked rows.
Experienced Microservices Resilience Q10. How does Resilience4j Circuit Breaker work with Retries, Bulkheads, and Timeouts?
Resilience4j tracks failure/slow-call rates in a sliding window and transitions CLOSED → OPEN (failing fast to protect thread pools) → HALF_OPEN (testing recovery probes). Always order decorators carefully: apply TimeLimiter/Timeout per attempt, Retry ONLY on idempotent transient faults with jittered exponential backoff, Bulkhead to isolate downstream pools, and CircuitBreaker outside to shed load during sustained outages.
System Design Distributed Transactions Q11. How do you guarantee atomic database updates and Kafka event publishing without 2PC (Dual-Write Problem)?
Implement the Transactional Outbox Pattern: within the same local ACID PostgreSQL transaction that writes the domain order row, insert an event record into an outbox_events table. A relay worker (or Debezium CDC reading Postgres WAL) publishes unpublished outbox rows to Kafka at-least-once, while downstream consumers enforce idempotency using a unique processed_event_id table.
System Design Caching & Scale Q12. How do you prevent Cache Stampede (Thundering Herd) and Cache Penetration in Redis + Spring Boot?
For Cache Penetration (repeated lookups for non-existent IDs), cache short-TTL negative placeholders or front with a Redis Bloom Filter. For Cache Stampede (hot key expiring under heavy traffic), use single-flight per-key locking (Redisson/Lua mutex), probabilistic early refresh, or staggered jittered TTLs so only one backend request rebuilds the cache while others serve stale or wait briefly.
System Design API Idempotency Q13. How do you design an idempotent payment/checkout REST API in Spring Boot?
Require clients to generate a UUID Idempotency-Key header per checkout intent. Persist (idempotency_key, request_hash, status, response_body) with a UNIQUE constraint. On retries, return the cached response if completed, return 409 Conflict if the payload hash differs or request is still in-flight, and execute the charge + outbox write inside a single transaction.
System Design Java LLD Machine Coding Q14. How would you design a BookMyShow seat-locking engine preventing double booking under flash-sale traffic?
Model Show, Screen, Seat, ShowSeat (status: AVAILABLE, LOCKED, BOOKED, lock_expires_at, version), and Booking. On hold request, acquire a Redis Lua distributed lock or execute an atomic PostgreSQL conditional UPDATE (WHERE status = AVAILABLE OR lock_expires_at < NOW()) with a 7-minute TTL. Confirm booking inside a DB transaction only if the lock token matches and is unexpired, backed by a payment webhook idempotency guard.
System Design Observability & Performance Q15. A Spring Boot microservice P99 latency spiked from 120ms to 3.5s in production. How do you diagnose it?
Start with Prometheus/Grafana RED metrics (Rate, Errors, Duration) + OpenTelemetry distributed traces to isolate whether delay is in GC pauses, HikariCP connection pool exhaustion, slow SQL (pg_stat_statements + EXPLAIN ANALYZE), downstream HTTP waits, or thread starvation. Capture a low-overhead Java Flight Recorder (JFR) flamegraph and thread dump to confirm lock contention before scaling.
Freshers Java 21 Modern Syntax Q16. How do Java 21 Sealed Classes, Records, and Pattern Matching for switch improve domain modeling?
Records eliminate boilerplate for immutable DTOs/value objects. Sealed interfaces restrict exactly which subtypes can implement a contract, allowing Pattern Matching switch expressions to enforce compile-time exhaustiveness without fragile default branches — ideal for modeling payment outcomes or API responses.
Java 21 Sealed Interface + Record + Exhaustive Switchjava
public sealed interface PaymentResult permits PaymentResult.Paid, PaymentResult.Failed {
record Paid(String txnId, long amountPaise) implements PaymentResult {}
record Failed(String code, boolean retryable) implements PaymentResult {}
}
String describe(PaymentResult result) {
return switch (result) {
case PaymentResult.Paid(var id, var paise) -> "Settled " + id + " (" + paise + "p)";
case PaymentResult.Failed(var code, var retry) -> "Failed " + code + " retry=" + retry;
};
}
Freshers Java 21 Virtual Threads Q17. Show how to enable Java 21 Virtual Threads cleanly in Spring Boot 3 and avoid carrier thread pinning.
Set spring.threads.virtual.enabled=true in Spring Boot 3.2+ so Tomcat and @Async run on virtual threads. Replace synchronized blocks wrapping blocking I/O calls with ReentrantLock so the JVM unmounts virtual threads cleanly instead of pinning the underlying carrier OS thread.
Spring Boot 3 Virtual Threads + ReentrantLock (Zero Pinning)java
// application.yml: spring.threads.virtual.enabled: true
private final ReentrantLock lock = new ReentrantLock();
public String fetchRemoteQuota(String userId) {
lock.lock();
try {
return restClient.get().uri("/quota/{id}", userId).retrieve().body(String.class);
} finally {
lock.unlock();
}
}
Freshers Java Streams Pitfalls Q18. Why can parallelStream() degrade latency in a Spring Boot REST controller?
parallelStream() shares the single global ForkJoinPool.commonPool() across the entire JVM. Running blocking DB/HTTP work or small collections inside parallelStream() starves other concurrent requests sharing that pool and adds thread-splitting overhead. Use parallelStream() only for large, pure CPU-bound workloads on dedicated executors.
Experienced Hibernate & JPA Q19. Show how to fix Hibernate N+1 on a paginated Spring Data JPA endpoint without triggering in-memory pagination.
Never pair collection JOIN FETCH directly with Pageable (Hibernate logs HHH90003004 and loads all rows into RAM). Instead, query paginated parent IDs first, then fetch the entities + children in a second query using WHERE o.id IN (:ids) with JOIN FETCH.
Two-Step Paginated JOIN FETCH (Zero N+1 & Zero OOM)java
@Query("SELECT o.id FROM Order o WHERE o.status = :status ORDER BY o.createdAt DESC")
Page<Long> findOrderIds(@Param("status") OrderStatus status, Pageable pageable);
@Query("SELECT DISTINCT o FROM Order o LEFT JOIN FETCH o.items WHERE o.id IN :ids")
List<Order> findWithItemsByIds(@Param("ids") List<Long> ids);
Experienced Spring Boot 3 Errors Q20. Show a production @RestControllerAdvice handler returning RFC 7807 ProblemDetail in Spring Boot 3.
Spring 6 / Boot 3 natively implements RFC 7807 ProblemDetail (application/problem+json). Centralizing domain and validation exceptions inside @RestControllerAdvice ensures consistent status codes, trace IDs, and zero accidental stack-trace leaks.
Spring Boot 3 RFC 7807 ProblemDetail Handlerjava
@RestControllerAdvice
public class GlobalApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
ProblemDetail handleNotFound(OrderNotFoundException ex) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
pd.setTitle("Order Resource Not Found");
pd.setProperty("errorCode", "ORD_404");
return pd;
}
}
Experienced Spring Data Projections Q21. When should you use Spring Data Interface/Record DTO Projections instead of returning JPA Entities?
Returning JPA Entities triggers dirty-checking memory snapshots, accidental lazy-loading serialization loops, and over-fetching unused columns. For read-heavy endpoints, use JPQL constructor expressions into Java Records with @Transactional(readOnly = true) to bypass Hibernate persistence context overhead.
Experienced Kafka Consumer Engineering Q22. How does Kafka guarantee message ordering per entity and how do you avoid consumer rebalance storms?
Kafka guarantees strict ordering ONLY within a single partition — publish events using a deterministic partition key (like orderId or accountId). Prevent rebalance storms by using CooperativeStickyAssignor, keeping poll processing shorter than max.poll.interval.ms, and isolating slow downstream I/O via Dead Letter Topics (DLT).
System Design PostgreSQL & Locking Q23. Show the SQL query behind a lock-free concurrent job/seat worker claim using FOR UPDATE SKIP LOCKED.
FOR UPDATE SKIP LOCKED lets multiple Spring Boot worker pods claim distinct rows concurrently without blocking each other on row locks — turning PostgreSQL into an ACID-safe task queue or inventory claim table.
PostgreSQL Atomic Batch Claim with SKIP LOCKEDsql
WITH next_jobs AS (
SELECT id FROM outbox_events
WHERE status = 'PENDING'
ORDER BY created_at ASC
LIMIT 20
FOR UPDATE SKIP LOCKED
)
UPDATE outbox_events
SET status = 'PROCESSING', locked_at = NOW()
WHERE id IN (SELECT id FROM next_jobs)
RETURNING id, aggregate_id, payload;
System Design Saga Pattern Q24. Compare Saga Choreography vs Saga Orchestration across Spring Boot Microservices.
Choreography lets each service react to Kafka domain events independently — simple for 2–3 steps, but cyclic dependencies and distributed debugging become painful at scale. Orchestration uses a central coordinator (like Temporal or a dedicated Saga state machine) to invoke steps and trigger compensating rollback transactions cleanly across complex payment/fulfillment workflows.
System Design JVM Container Tuning Q25. How do you containerize and size JVM memory safely for Spring Boot 3 in Docker/Kubernetes?
Use multi-stage Docker builds with layered JARs (`jarmode=layertools`) and distroless/Alpine JRE images. Configure `-XX:MaxRAMPercentage=75.0` (leaving 25% headroom for Metaspace, thread stacks, DirectByteBuffers, and OS page cache) and use ZGC or G1GC based on latency vs throughput targets to prevent Kubernetes OOMKills.
Production Layered Spring Boot 3 JVM Containerdockerfile
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=builder /app/dependencies/ ./
COPY --from=builder /app/application/ ./
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75.0", "-XX:+UseG1GC", "org.springframework.boot.loader.launch.JarLauncher"]