Top 50 Distributed Systems Interview Questions and Answers (2026 Edition)
Top 50 Distributed Systems 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.
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...
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...
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...
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....
How do you handle exceptions globally in Spring?
Create @RestControllerAdvice with @ExceptionHandler(MethodArgumentNotValidException.class) returning 400 + field map, NotFoundException → 404, generic Exception → 500 without...
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...
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...
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...
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...
Explain method overloading vs overriding.
Overload print(int) and print(String) in one class — compiler picks at compile time. Override toString in subclass — JVM calls subclass version via virtual method table....
What is CSRF and how does Spring Security handle it?
CSRF tricks logged-in user's browser to POST to your site. Spring stores CsrfToken and validates on mutating requests. For SPA with session cookies, expose token via...
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...
Bean scopes in Spring — singleton vs prototype?
Default singleton shares one instance — stateless services. Prototype for per-operation objects. Request/session scopes tie to web lifecycle with proxies. Prototype inside...
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...
What is an ExecutorService and why use it?
Instead of new Thread per task, submit Runnable to fixed pool sized to CPU/IO profile. Handle Future results and exceptions. On shutdown hook call shutdown() and...
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...
What are virtual threads in Java 21 and when should you use them?
Virtual threads excel when code blocks on IO — HTTP clients, JDBC, file reads — allowing one platform thread to serve thousands of concurrent requests. For CPU-heavy parallel...
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...
What is pattern matching for switch (Java 21)?
Instead of if (obj instanceof String s) { ... }, use switch (obj) { case String s when s.length() > 5 -> ...; case String s -> ...; case null -> ...; default -> ... }. Works...
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...
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...
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...
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....
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...
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...
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 —...
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...
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...
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() {...
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...
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...
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...
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...
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...
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...
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...
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:...
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:...
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" ```...
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...
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...
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...
Describe the Spring Bean lifecycle.
Container instantiates the bean, injects dependencies, runs BeanPostProcessors, then @PostConstruct or InitializingBean. Singleton lives for context lifetime; prototype creates...
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...
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...
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...
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...
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...
@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...
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...
Distributed Systems Interview Questions and Answers · Top 40 Distributed Systems Interview Questions | Must-Prepare before interview. · 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