Top 50 Spring Boot REST Interview Questions and Answers (2026 Edition)

Top 50 Spring Boot REST Interview Questions and Answers (2026 Edition) Work through these 50 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.

  1. Describe the Spring Bean lifecycle.

    Container instantiates the bean, injects dependencies, runs BeanPostProcessors, then @PostConstruct or InitializingBean. Singleton lives for context lifetime; prototype creates...

    Full answer

  2. What is the N+1 query problem and how do you fix it?

    Loading 100 orders then accessing each order's items triggers 101 queries. Fix with JOIN FETCH in JPQL, @EntityGraph on repository method, or a DTO query selecting only...

    Full answer

  3. What is dependency injection and why does Spring use it?

    DI supplies collaborators from outside the class — typically via constructor. Problem solved: tight coupling to concrete classes, hard unit tests, scattered object...

    Full answer

  4. How does @Transactional work?

    Spring creates a proxy around @Transactional beans. Calling createOrder() from another bean starts a transaction on the thread-bound EntityManager; commit on success, rollback...

    Full answer

  5. @RestController vs @Controller?

    @Controller is for traditional MVC — return "user/list" view name. @RestController adds @ResponseBody so return types become JSON/XML body — standard for REST APIs. Use...

    Full answer

  6. How do you handle exceptions globally in Spring?

    Create @RestControllerAdvice with @ExceptionHandler(MethodArgumentNotValidException.class) returning 400 + field map, NotFoundException → 404, generic Exception → 500 without...

    Full answer

  7. How would you design a rate-limited REST API?

    API gateway or filter applies token bucket per API key — Redis stores tokens with TTL. Exceeding limit returns 429 + Retry-After. Different tiers per plan. Log rejections for...

    Full answer

  8. What is the difference between JPA and Hibernate?

    JPA is the API contract; Hibernate is the engine under Spring Boot by default. You write @Entity per JPA spec; Hibernate handles SQL generation. Spring Data JpaRepository adds...

    Full answer

  9. How does Stream API parallel stream work?

    parallelStream() splits work across common pool threads. Good for CPU-heavy map on large in-memory collections. Bad for small lists, IO inside stream, or ordered stateful...

    Full answer

  10. How do you test Spring Boot applications?

    Unit test services with Mockito — no Spring. @WebMvcTest + MockMvc for controller contract. @DataJpaTest for repository queries. @SpringBootTest + Testcontainers for critical...

    Full answer

  11. How do you version REST APIs?

    We use /api/v1/users for clarity. Non-breaking: add optional JSON fields. Breaking: launch v2 path, maintain v1 for 6 months with Deprecation header. Spring maps...

    Full answer

  12. Explain sealed classes and their purpose in Java 17+.

    sealed interface Shape permits Circle, Rectangle limits who implements Shape. Compiler verifies switch (Shape s) covers all cases — no default needed. Use for domain variants...

    Full answer

  13. Explain structured concurrency and why it matters.

    In a request handler, open StructuredTaskScope, fork fetchUser and fetchOrders, join both — if orders fail, user fetch cancelled automatically. Safer than manual Future...

    Full answer

  14. How do Spring Boot Actuator health probes work with Kubernetes?

    Enable probes, configure K8s readinessProbe on /actuator/health/readiness, liveness on /actuator/health/liveness. Custom HealthIndicator for critical deps on readiness group...

    Full answer

  15. What is ProblemDetail (RFC 7807) in Spring 6 error handling?

    @ExceptionHandler(NotFoundException.class) ProblemDetail handle(NotFoundException ex) { return ProblemDetail.forStatusAndDetail(NOT_FOUND, ex.getMessage()); } — consistent 404...

    Full answer

  16. springdoc-openapi vs legacy springfox — what should new projects use?

    Add springdoc-openapi-starter-webmvc-ui dependency. Annotate with @Operation, @Schema on DTOs. Disable in prod via springdoc.api-docs.enabled=false or secure endpoint. Generate...

    Full answer

  17. How does Micrometer Tracing replace Spring Cloud Sleuth?

    Dependencies: micrometer-tracing-bridge-otel, opentelemetry-exporter-otlp. Traces propagate Authorization-safe headers across RestClient/WebClient calls. Correlate logs with...

    Full answer

  18. Best practices for Spring Data pagination with Pageable?

    Controller: @PageableDefault(size=20, sort="createdAt", direction=DESC) Pageable p. Cap size at 100. Admin reports: keyset pagination on id > lastId for deep pages — OFFSET...

    Full answer

  19. How configure Spring Security OAuth2 Resource Server for JWT?

    Configure issuer-uri pointing to IdP. SecurityFilterChain: authorizeHttpRequests(auth ->...

    Full answer

  20. How configure CORS correctly in Spring Security 6?

    CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(List.of("https://app.example.com")); config.setAllowedMethods(List.of("GET","POST"));...

    Full answer

  21. SecurityFilterChain vs deprecated WebSecurityConfigurerAdapter?

    @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()).authorizeHttpRequests(auth ->...

    Full answer

  22. What are idempotency keys and how implement them in REST APIs?

    Client sends Idempotency-Key: uuid on POST /payments. Server Redis SETNX key, process, store response JSON. Retry with same key returns 201 + original body without double...

    Full answer

  23. What is the Backend-for-Frontend (BFF) pattern?

    Mobile BFF /mobile/home aggregates user profile + feed + notifications in one round trip. Web BFF different field selection. BFF handles OAuth BFF cookie pattern. Domain...

    Full answer

  24. Kubernetes liveness vs readiness vs startup probes?

    deployment.yaml: startupProbe HTTP /actuator/health with failureThreshold*period covering 60s startup. readinessProbe /actuator/health/readiness includes DB. livenessProbe...

    Full answer

  25. A REST API is slow only in production, not locally. How do you debug it?

    Enable Micrometer timers and Hibernate statistics or datasource-proxy in staging with prod-like data. Check Hikari `connections-active`, JVM GC pauses, and Feign/RestClient...

    Full answer

  26. Your API works fine but returns 401 randomly. What could cause this?

    Random 401 often means token expiry mid-session, refresh not implemented, or some pods misconfigured with different signing keys. Check JWT `exp`, gateway header stripping, and...

    Full answer

  27. How do you handle API failures when calling another microservice?

    Use Resilience4j with Spring Boot 3: timeout, circuit breaker, bulkhead. Never retry POST payments without idempotency key. ```java @CircuitBreaker(name = "billing",...

    Full answer

  28. How do you implement retry logic for failed REST calls?

    ```java @Retry(name = "inventory", fallbackMethod = "inventoryFallback") public StockLevel fetchStock(String sku) { return restClient.get().uri("/stock/{sku}",...

    Full answer

  29. How do you handle versioning of REST APIs without breaking clients?

    Prefer non-breaking changes: add optional JSON fields. Breaking changes → new path `/api/v2`. ```java @RestController @RequestMapping("/api/v1/users") public class...

    Full answer

  30. What happens if an exception occurs inside a filter or interceptor?

    Exceptions in `Filter` bypass `@ControllerAdvice` unless handled. Filters run before MVC. ```java @Override protected void doFilterInternal(HttpServletRequest req,...

    Full answer

  31. What are common mistakes freshers make in Spring Boot projects?

    ```java // ❌ Wrong @RestController public class OrderController { @PostMapping("/orders") public Order create(@RequestBody Order o) { return orderRepository.save(o); // DB in...

    Full answer

  32. API returns correct data but response time is inconsistent. Why?

    Tail latency often from stop-the-world GC, connection pool contention, or cold cache. Monitor p99 separately from mean. ```yaml spring.datasource.hikari.maximum-pool-size: 10...

    Full answer

  33. How do you trace a request across multiple microservices?

    Inject trace context at edge; log `traceId` in every service. ```java log.info("traceId={} orderId={}", MDC.get("traceId"), orderId); ``` Spring Boot 3:...

    Full answer

  34. One API intermittently times out, no errors in logs. How do you debug?

    No app log may mean thread blocked waiting on external IO. Enable Feign/logger + trace. Check LB/proxy timeouts vs client timeouts. ```yaml feign: client: config: default:...

    Full answer

  35. A config change requires restart. How do you avoid it?

    ```java @RefreshScope @Configuration public class FeatureConfig { @Value("${feature.newCheckout:false}") private boolean newCheckout; } ``` Trigger refresh via...

    Full answer

  36. Requests work via curl but fail from frontend. Why?

    Browsers enforce CORS; curl does not. Configure allowed origins and methods. ```java @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration c = new...

    Full answer

  37. Why is storing a JWT in localStorage a problem, and what do you do instead with Spring Security?

    I prefer BFF: Vite proxies /api, Spring sets httpOnly cookie, React never sees the JWT. If I must use a bearer token, I keep access token in memory and refresh via cookie. I...

    Full answer

  38. How do you design a multi-step form that submits to a Spring API without losing field errors?

    RHF + zod per step. On 400 I map violations[] to setError. Business 409 goes to a form-level message. I disable submit with isSubmitting and the idempotency header. I do not...

    Full answer

  39. A table of 10,000 rows janks on scroll. What do you change first?

    I first ask if the API can page or cursor. If the UX needs a long scroll, I virtualize, give each row a stable id, and keep cell renderers pure. I profile with React DevTools —...

    Full answer

  40. What makes a good custom hook vs a bad one that hides too much?

    I extract useAccess, useCheckoutCoupon, useDebouncedValue — each has one job. Page-specific orchestration stays in the page. I pass api as an argument or import a thin api.ts I...

    Full answer

  41. When do you use ref, forwardRef, and useImperativeHandle?

    After RHF errors, I ref the first field and focus(). Video players expose play() via useImperativeHandle. I do not put “isOpen” in a ref — that belongs in state. On React 19 I...

    Full answer

  42. How do you test a React page that talks to Spring without testing implementation details?

    render(<QuestionPage />), mock GET /api/questions/q152, click Unlock, expect the paywall or the answer. I query by role “button”, name /Production Access/i. I do not read...

    Full answer

  43. How do you pair a Vite React app with a Spring Boot API in production — CORS, cookies, and errors?

    Locally I proxy. In prod nginx/CloudFront serve the SPA and forward /api to Spring — same origin. api.ts throws a typed ApiError from ProblemDetail. 401 sends the user to...

    Full answer

  44. What does hybrid post-quantum TLS in JDK 27 change for a Spring Boot service, and what does it not change?

    If we terminate TLS in the JVM, 27 can negotiate hybrid ML-KEM without a code change — I capture handshake size and CPU. If the edge terminates TLS, I upgrade the ingress...

    Full answer

  45. Which JDK 27 APIs still need --enable-preview, and how do LazyConstant and compact headers differ as upgrade stories?

    I upgrade the image for G1, headers, and TLS. Preview stays off unless a spike uses LazyConstant or STS and every plugin/container flag matches. If async-profiler or APM...

    Full answer

  46. What does Spring Boot do versus what LangChain4j does in the same Java service?

    Boot is the host. LangChain4j is how that host talks to models. I keep REST, JWT, and JPA on Spring. I inject ChatLanguageModel from a langchain4j-*-spring-boot-starter and...

    Full answer

  47. What is AiServices, and why is it better than calling chat.completions() from a controller?

    AiServices is a typed facade over ChatLanguageModel. I declare TicketAssistant with @SystemMessage and @UserMessage, register it as a singleton @Bean, and the controller never...

    Full answer

  48. How do you switch LangChain4j from OpenAI to Bedrock, Gemini, or Ollama without rewriting call sites?

    Call sites stay on TicketAssistant. I change the starter and langchain4j.*.chat-model properties under a profile. Locally I point at Ollama; prod uses Bedrock with IAM, not a...

    Full answer

  49. How do you keep model keys, timeouts, and startup failure out of the request path?

    Env var or IAM. Startup fails closed if the secret is missing. I set a read timeout on the LangChain4j HTTP client the same way I would on RestClient. I log latency and token...

    Full answer

  50. How does Spring Boot auto-configuration work?

    @SpringBootApplication enables @EnableAutoConfiguration, which loads candidate configs from starters. Each auto-config uses @ConditionalOn* to register beans only when...

    Full answer

Spring Boot REST Interview Questions and Answers · Top 40 Spring Boot REST Interview Questions | Must-Prepare before interview. · Spring Boot REST Interview Questions Every Fresher Must Know · Spring Boot REST Interview Questions for 2–3 Years

All interview question lists · Interview guides · Home · Support the platform