Top 50 REST API Interview Questions and Answers (2026 Edition)

Top 50 REST API 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. 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

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

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

    Full answer

  3. SecurityFilterChain vs deprecated WebSecurityConfigurerAdapter?

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

    Full answer

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

  5. Explain the transactional outbox pattern.

    OrderService @Transactional saves Order and OutboxEvent(type=ORDER_CREATED, payload=json). OutboxProcessor @Scheduled polls FOR UPDATE SKIP LOCKED, sends to Kafka, updates...

    Full answer

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

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

  8. Kafka consumer groups, offsets, and delivery semantics?

    @KafkaListener with AckMode.MANUAL — ack after DB save. Consumer group order-service scales to partition count max. Idempotency key in message header dedup table. Monitor...

    Full answer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  31. How do @Tool methods turn a Spring bean into a LangChain4j agent?

    I put @Tool on TicketService methods that already enforce auth. AiServices.builder(Assistant.class).tools(ticketService).build(). The model can search or draft; it cannot...

    Full answer

  32. How do you stop a LangChain4j agent loop from running forever, and who owns the workflow?

    I set maxSequentialToolsInvocations to a small number — three or four for triage. Writes take an idempotency key. Approve is not a @Tool. Automating a business process with AI...

    Full answer

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

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

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

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

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

  38. Explain JWT authentication flow in Spring Security.

    POST /login with credentials → auth provider validates → issue JWT with exp/sub/roles. Subsequent requests include Bearer token. JwtAuthenticationFilter runs before...

    Full answer

  39. What are Spring Boot starters?

    spring-boot-starter-web brings spring-webmvc, Tomcat, Jackson with tested versions and enables WebMvcAutoConfiguration. You declare one starter instead of 10 coordinates....

    Full answer

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

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

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

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

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

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

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

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

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

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

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

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

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