Top 40 Spring Boot REST Interview Questions | Must-Prepare before interview.

Top 40 Spring Boot REST Interview Questions | Must-Prepare before interview Work through these 40 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. @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

  10. 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

  11. 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

  12. 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

  13. 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

  14. 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

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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

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

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

    Full answer

  24. 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

  25. SecurityFilterChain vs deprecated WebSecurityConfigurerAdapter?

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

    Full answer

  26. 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

  27. 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

  28. 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

  29. 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

  30. 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

  31. 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

  32. 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

  33. 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

  34. 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

  35. 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

  36. 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

  37. 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

  38. 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

  39. 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

  40. 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

Spring Boot REST Interview Questions and Answers · Top 50 Spring Boot REST Interview Questions and Answers (2026 Edition) · 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