Top 40 Distributed Systems Interview Questions | Must-Prepare before interview.

Top 40 Distributed Systems 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. 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

  2. A database connection pool is getting exhausted. How do you identify and solve it?

    Enable `spring.datasource.hikari.leak-detection-threshold`. Watch `hikaricp.connections.active` and threads blocked waiting. Fix leaks with try-with-resources; avoid long...

    Full answer

  3. How do you implement rate limiting for APIs?

    Apply at API Gateway; in-app use Redis-backed limiter for cluster-wide counts. ```java @RateLimiter(name = "apiLimiter") @GetMapping("/users") public List<User> users() {...

    Full answer

  4. What is circuit breaker pattern?

    When payment service errors exceed 50% in 10s window, breaker opens — return fallback immediately for 30s. Half-open lets one request through to test recovery. Pair with...

    Full answer

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

  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. When and why use CQRS (Command Query Responsibility Segregation)?

    E-commerce: write Order aggregate to PostgreSQL; project OrderSummaryView to Elasticsearch for search/filter dashboard. Accept projection lag. Not for simple User CRUD. Combine...

    Full answer

  8. Load shedding and backpressure in microservices?

    Tomcat max queue + reject policy returns 503 with Retry-After. WebClient timeout + circuit breaker stops calling slow dependency. Kafka consumer pause partitions when...

    Full answer

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

  10. Redis caching patterns: cache-aside vs write-through?

    @Cacheable("users") on findById — Redis cache-aside via Spring Data Redis. Update user: @CacheEvict. TTL 15m + jitter. Hot product page: lock on miss with Redisson. Do not...

    Full answer

  11. Your service needs zero downtime deployment. How do you achieve it?

    K8s rolling update + readiness probe ensures traffic only hits healthy pods. ```yaml readinessProbe: httpGet: path: /actuator/health/readiness port: 8080 initialDelaySeconds:...

    Full answer

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

  13. Your Spring Boot app fails only when deployed in Docker. Why?

    Container `-Xmx256m` with 256Mi limit causes OOMKilled. Missing `DB_HOST` defaults to localhost inside container. ```dockerfile ENV JAVA_OPTS="-XX:MaxRAMPercentage=75.0" ```...

    Full answer

  14. Autoscaling enabled but error rate increases. Why?

    New pods accept traffic before JVM/Caffeine warm. HPA adds API pods but Postgres max connections fixed. ```yaml readinessProbe: initialDelaySeconds: 30 ``` Scale connection...

    Full answer

  15. Explain the difference between == and .equals() in Java.

    For primitives, == compares values. For objects, == asks if two references point to the same instance. equals() compares content when overridden — String overrides it for...

    Full answer

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

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

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

  19. HashMap vs ConcurrentHashMap — when and why?

    HashMap for single-threaded or external synchronization. ConcurrentHashMap for shared concurrent maps — finer-grained locking than Hashtable. Cannot store null keys/values in...

    Full answer

  20. What is the difference between ArrayList and LinkedList?

    ArrayList: dynamic array, great for get(i) and iteration, amortized append. LinkedList: node chain, costly random access, only wins for frequent insert/remove in middle with...

    Full answer

  21. Explain immutability and why String is immutable.

    Immutable objects cannot change after build — thread-safe without synchronization. String immutability allows intern pool, caching hashCode, and security when used as...

    Full answer

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

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

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

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

  26. What is the difference between Comparable and Comparator?

    Comparable built into the type — Employee implements compareTo by id. Comparator external — sort by name or salary without changing Employee. Use...

    Full answer

  27. volatile vs synchronized — when to use each?

    volatile for single-writer flags (shutdown, initialized) where no read-modify-write. synchronized or java.util.concurrent locks when multiple threads update shared state. For...

    Full answer

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

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

  30. Explain garbage collection basics in the JVM.

    New objects allocate in Eden; minor GC copies survivors to survivor spaces, then old gen. When old gen fills, major/full GC runs — longer pauses. Tune -Xmx, choose G1 for...

    Full answer

  31. What is Optional and when should you use it?

    Use Optional as return type when absence is expected — findById returns Optional<User>. Chain with map/flatMap/orElseThrow. Do not use for fields, method parameters, or Jackson...

    Full answer

  32. Difference between @Component, @Service, @Repository?

    All register as singleton beans via component scan. Choose by layer for readability: @Repository on DAOs (plus SQLException translation), @Service on business logic, @Component...

    Full answer

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

  34. Explain CAP theorem in the context of microservices.

    When a network split isolates nodes, you cannot have both perfect consistency and every node answering. Example: order service during partition — either reject writes (CP) or...

    Full answer

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

  36. Explain microservices vs monolith trade-offs.

    Start monolith until team or scale pain justifies split. Microservices enable independent deploy and tech diversity but add network failures, observability burden, and data...

    Full answer

  37. Saga pattern — choreography vs orchestration?

    Order saga: reserve inventory → charge payment → ship. Failure at payment triggers release inventory compensation. Orchestration clearer for complex flows with visibility....

    Full answer

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

  39. When accept eventual consistency and how communicate it to clients?

    Checkout returns 202 Accepted with orderId — poll or webhook when confirmed. Inventory display may lag seconds — show "approximate stock." Payment ledger uses strong...

    Full answer

  40. Database sharding strategies for high-scale Java services?

    Shard by tenant_id mod 32 — RoutingDataSource lookup. User-scoped queries single shard. Global admin reports from CQRS read replica or Elasticsearch. Plan shard key early —...

    Full answer

Distributed Systems Interview Questions and Answers · Top 50 Distributed Systems Interview Questions and Answers (2026 Edition) · Distributed Systems Interview Questions Every Fresher Must Know · Distributed Systems Interview Questions for 2–3 Years

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