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

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

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

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

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

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

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

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

    Full answer

  7. SecurityFilterChain vs deprecated WebSecurityConfigurerAdapter?

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

    Full answer

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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