Top 50 System Design Interview Questions and Answers (2026 Edition)
Top 50 System Design 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.
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...
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...
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...
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...
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...
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...
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...
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...
How do CompletableFuture and virtual threads compare for concurrency?
Use virtual threads when business logic is naturally blocking — call DB, call HTTP, return. Use CompletableFuture when composing multiple independent async results with...
What are weak references and WeakHashMap use cases?
Attach metadata to objects without extending their lifetime — canonical mapping while object lives. When key GCs, entry drops. Do not rely on timing. For API response caching...
What is Hibernate second-level cache and when enable it?
Enable for ProductCategory, Currency — READ_ONLY, rarely changed. spring.jpa.properties.hibernate.cache.use_second_level_cache=true with Caffeine region factory. Avoid on...
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...
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...
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...
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 —...
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...
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...
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 application memory usage keeps increasing over time. What do you suspect?
Suspect memory leak if heap used grows after GC without traffic drop. Capture heap dump on OOM (`-XX:+HeapDumpOnOutOfMemoryError`), compare dominator tree. Common in Spring:...
You deployed a new version but users still hit the old behavior. Why?
Check K8s rollout status — old ReplicaSet still receiving traffic. Bust cache on static assets; API GET with `Cache-Control`. Confirm image tag in running pod matches CI build....
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...
You enabled caching but performance did not improve. Why?
Measure hits/misses. Wrong key expression caches per wrong granularity. ```java @Cacheable(value = "users", key = "#id") public User findById(Long id) { return...
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...
What is Anthropic prompt caching in LangChain4j 1.22.0, and when is it worth turning on?
I put the interviewer persona, tool JSON, and the static policy appendix in the cached system prefix. The user question and this-request RAG chunks stay dynamic. If the prefix...
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...
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" ```...
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...
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...
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...
System Design Interview Questions and Answers · Top 40 System Design Interview Questions | Must-Prepare before interview. · System Design Interview Questions Every Fresher Must Know · System Design Interview Questions for 2–3 Years
All interview question lists · Interview guides · Home · Support the platform