Top 40 Kafka Interview Questions | Must-Prepare before interview.
Top 40 Kafka 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.
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 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....
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...
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...
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 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 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...
Compare BlockingQueue implementations for producer-consumer workloads.
For order processing, use ArrayBlockingQueue with capacity matching SLA — slow consumer blocks producer instead of OOM. ThreadPoolExecutor with SynchronousQueue +...
What is Spring Boot Docker Compose dev services support?
Add compose.yaml with postgres and redis services. Include spring-boot-docker-compose on runtimeOnly. Boot starts Postgres, sets JDBC URL — zero local install. CI uses...
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...
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...
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...
How do you handle long-running background jobs in Spring Boot?
Do not block HTTP threads. Use `@Async` with named executor or message-driven workers. ```java @EnableAsync @Configuration public class AsyncConfig { @Bean Executor...
Why does Context re-render every consumer, and how do you keep RBAC/theme from stalling the tree?
AuthProvider holds user with useMemo. Permission checks go through can(permission) from a hook that reads a stable access object. Theme is a separate provider. High-frequency...
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...
Kafka Interview Questions and Answers · Top 50 Kafka Interview Questions and Answers (2026 Edition) · Kafka Interview Questions Every Fresher Must Know · Kafka Interview Questions for 2–3 Years
All interview question lists · Interview guides · Home · Support the platform