95 Microservices, Kafka & Redis Interview Questions and Answers for Java Backend Developers
This post answers 95 interview questions Java backend developers actually get asked about microservices, Kafka, and Redis — with a simple explanation first and a short worked example for each one. It is the first post in a series built from a 483-question Java backend interview question bank: this post covers sections 7–9 of the bank (microservices and distributed systems, Kafka and messaging, Redis and caching). The rest of the bank — Core Java, Spring Boot, Security & JPA, SQL & Database Engineering, system design, cloud, and more — follows in the same format.
How to use it. Each section is split by priority, exactly as the bank ranks them. Very High Priority questions are the ones to master first — they are the fundamentals interviewers return to again and again. High Priority questions cover practical implementation, troubleshooting, and trade-offs. Medium Priority questions add breadth for senior or company-specific rounds. If you are short on time, do the Very High questions in all three sections first; that is 37 questions and the core of the topic. If you want the microservices fundamentals in a shorter form first, the site's earlier Microservices Interview Questions for Java Developers covers the same ground in less depth.
A note on the examples: they are short and standard — a few lines of Java, a config snippet, or a concrete scenario — and they are meant to show the shape of an answer, not to be copied into production as-is. Where an example would be contrived, the answer says so and gives the rule instead. Nothing here was run against a live Kafka cluster or Redis server; the code is written to be read and reasoned about, the way you would reason about it in an interview.
7. Microservices Architecture & Distributed Systems
Very High Priority
230. What is the difference between monolithic and microservices architecture? What are the trade-offs?
A monolith is one deployable unit: the UI, business logic, and data access all live in a single codebase and usually share one database. Microservices split the system into small, independently deployable services, each owning its own data and communicating over the network, typically through HTTP or messaging. The trade-offs are real on both sides. A monolith is simpler to build, test, debug, and deploy, and in-process calls are fast and reliable. Microservices let teams deploy and scale parts independently and use different technologies per service, but they add network latency, distributed failure modes, eventual consistency, and heavy operational overhead — service discovery, observability, and deployment pipelines. As a rule of thumb, start with a modular monolith and split only when a part genuinely needs independent scaling or ownership.
Example: An online shop as a monolith ships one WAR file containing catalog, cart, and checkout. As microservices, catalog, cart, and checkout are three services with three databases; checkout calls the catalog service over HTTP instead of calling a Java method. The split buys independent checkout deploys, but a network call can now fail where a method call could not.
231. How do microservices communicate? Compare synchronous REST with asynchronous messaging.
Microservices communicate in two broad ways. Synchronous communication, usually REST over HTTP, means the caller waits for a reply: it is simple to reason about and fits request–response flows such as "get the price before showing the cart." Its cost is coupling — if the downstream service is slow or down, the caller blocks or fails. Asynchronous messaging, through a broker such as Kafka or RabbitMQ, means the sender publishes an event and moves on; consumers process it later. That decouples services in time, smooths traffic spikes, and keeps working when a consumer is briefly down, but it adds eventual consistency, harder debugging, and the need to handle duplicate or out-of-order delivery. A common rule of thumb is: use REST when you need an immediate answer, messaging when you need to notify or decouple.
Example: Placing an order calls the payment service synchronously (the user needs to know if payment succeeded), then publishes an OrderPlaced event that the shipping and email services consume asynchronously.
232. What is an API Gateway, and how is it different from a load balancer?
An API Gateway is a single entry point in front of your microservices. It routes requests to the right service, and it is also the natural place for cross-cutting concerns: authentication, rate limiting, request/response transformation, and aggregating calls. A load balancer, by contrast, distributes traffic across multiple instances of the same service so no single instance is overloaded; it usually works at the transport or HTTP level and knows nothing about your business logic. In practice the two often sit together: clients hit the gateway, the gateway routes to a service, and a load balancer spreads that traffic across that service's instances. Think of the gateway as the reception desk that knows which department you need, and the load balancer as the queue manager that spreads visitors evenly across the counters.
Example: A Spring Cloud Gateway route sends /orders/** to the order service and /users/** to the user service, applies a JWT check once at the gateway, and forwards each request to one of three healthy order-service instances behind a load balancer.
233. What is service discovery, and how do tools such as Eureka or Consul work?
Service discovery answers a simple problem: in a microservices system, service instances come and go — they scale up, crash, and get redeployed on new addresses — so callers cannot hard-code hostnames and ports. A service registry such as Eureka or Consul keeps a live directory of healthy instances. Each service registers itself on startup and sends periodic heartbeats; the registry removes instances that stop responding. Clients either ask the registry for an address before calling (client-side discovery, as with Eureka plus a load balancer) or call a fixed address that resolves through the registry (server-side discovery). Health checks keep stale entries out, so traffic only reaches live instances. Without discovery, every redeploy would mean updating configuration in every caller.
Example: The order service starts three instances, each registering with Eureka as ORDER-SERVICE. The payment service asks Eureka for ORDER-SERVICE, gets a list of healthy instances, and picks one to call.
234. What is the database-per-service pattern, and why should services not directly access another service's database?
Database-per-service means each microservice owns its data: it has its own database (or at least its own schema) and no other service reads or writes that data directly. Other services get data only through the owning service's API or through events it publishes. Direct database access breaks encapsulation: a schema change in one service silently breaks another, teams cannot deploy independently, and a slow query from a foreign service can take down the owner. It also makes ownership unclear — nobody can say which service is responsible for the correctness of a piece of data. The pattern trades easy joins for clean boundaries; cross-service questions are answered by API composition, replicated read models, or events rather than shared tables.
Example: The order service must never run SELECT against the inventory database. Instead it calls the inventory service's API, or consumes StockUpdated events to keep a local read copy of the stock it needs.
235. What is the Saga pattern? Compare orchestration and choreography.
A saga is a way to run a transaction across several microservices without a distributed transaction: it breaks the work into a sequence of local transactions, one per service, each with a compensating action that undoes it if a later step fails. For example, an order saga reserves stock, charges payment, then books shipping; if payment fails, a compensating action releases the reserved stock. In orchestration, a central coordinator (the orchestrator) tells each service what to do next and handles failures — this is easier to follow and debug, but the orchestrator becomes a central piece of logic. In choreography, there is no coordinator: each service reacts to events published by others, which is looser and more decoupled but harder to trace when something goes wrong. Orchestration suits complex flows with clear ordering; choreography suits simple event chains.
Example: An orchestrator runs: reserve stock → charge card → schedule delivery. If charging fails, the orchestrator calls the stock service's compensating action to release the reservation, leaving the system consistent.
The two styles look like this:
236. How do you handle distributed transactions and maintain consistency across services?
There is no free two-phase commit across independent microservices in practice — it blocks resources, couples services tightly, and fails badly under partial outages — so the standard approach is to design for eventual consistency using patterns instead of one atomic transaction. The most common are sagas, where each step has a compensating action, and the transactional outbox, where a service writes its database change and the event it must publish in the same local transaction, then a relay publishes the event reliably. Idempotent consumers make retries safe, and careful ordering of writes keeps the system converging. The honest answer in an interview is that you pick the consistency level the business needs: money movements get a saga with strong checks, while a "recently viewed" list can lag behind without harm.
Example: When an order is created, the order service saves the order and an outbox row in one database transaction; a relay then publishes OrderPlaced to Kafka. If publishing fails, the relay retries from the outbox — the event is never lost.
237. What is eventual consistency, and how do you design for it?
Eventual consistency means that after an update, different parts of the system may briefly disagree, but if no new updates arrive, all replicas converge to the same state. It is the price of availability and partition tolerance in distributed systems: a service keeps serving while an update is still propagating. Designing for it means accepting temporary staleness and planning for it. Read models are updated from events and may lag; the UI should show honest states ("processing" rather than pretending an order is confirmed); operations that must be strongly consistent, such as deducting money, are kept inside one service's boundary or protected by a saga; and retries and idempotency keys make duplicate deliveries harmless. The key interview point is knowing which data can be eventually consistent and which cannot.
Example: After a user changes their address in the profile service, the order service's cached copy may show the old address for a few seconds. Checkout reads the profile service directly when the address genuinely matters, and tolerates the lag everywhere else.
238. What is the Circuit Breaker pattern, and how does it prevent cascading failures?
A circuit breaker sits between a caller and a downstream service and stops calling it when it is clearly failing — just as an electrical breaker cuts power to prevent damage. It has three states. Closed: calls pass through normally while failures are counted. Open: after a threshold of failures, calls fail fast immediately without touching the downstream service, giving it time to recover and freeing the caller's threads. Half-open: after a wait, a few trial calls are allowed through; if they succeed the breaker closes, if they fail it opens again. Without a breaker, a slow downstream service makes every caller wait, exhausts its thread pool, and the failure cascades across the system. Libraries such as Resilience4j provide this out of the box in Spring Boot.
Example:
@CircuitBreaker(name = "inventory", fallbackMethod = "inventoryFallback")
public Stock checkStock(String sku) {
return inventoryClient.getStock(sku);
}
public Stock inventoryFallback(String sku, Throwable t) {
return Stock.unknown(sku); // fail fast, degrade gracefully
} 239. How do you implement retries, timeouts and fallback mechanisms safely?
Retries, timeouts, and fallbacks only help when they are bounded and deliberate. Every outbound call needs a timeout, or one slow downstream service can hold your threads hostage; set separate connect and read timeouts and keep them short enough that a retry is still useful. Retries should be limited (a small fixed number), use exponential backoff with jitter so all clients do not retry at the same instant, and apply only to transient failures — retrying a 400 validation error or a duplicate payment is harmful. Retries must be paired with idempotency, or a retried request can execute twice. A fallback is the plan for when retries give up: return cached data, a default, or a clear degraded response instead of an error page. Finally, combine retries with a circuit breaker so a dead service is not hammered by every client retrying at once.
Example: A payment call gets a 2-second read timeout and at most two retries with backoff for 5xx responses only, each retry carrying the same idempotency key; if all attempts fail, the fallback tells the user the payment status is unknown and to check their orders page rather than charging twice.
240. What is idempotency, and how do you implement it in REST APIs and distributed systems?
An operation is idempotent when doing it twice has the same effect as doing it once. That matters because networks are unreliable: a client that gets no response cannot know whether its request executed, so it retries — and a retried payment must not charge twice. In REST, GET, PUT, and DELETE are idempotent by design, while POST is not, which is why payment endpoints need extra protection. The standard implementation is an idempotency key: the client sends a unique key with the request, the server stores the key with the result of the first execution, and any repeat with the same key returns the stored result without re-executing. In messaging, consumers keep a record of processed message IDs and skip duplicates. Keys should expire after a sensible window so storage does not grow forever.
Example:
// POST /payments with header Idempotency-Key: 550e8400-...
// Server: if key exists in idempotency_keys, return stored response.
// Otherwise process payment, store (key, response) in one transaction,
// then return the response. A retry with the same key is a no-op. 241. How do you implement distributed tracing across multiple services?
Distributed tracing follows one request as it hops across services, so you can see where time is spent and where it fails. The mechanism is simple: when a request enters the system, a trace ID is generated (or taken from an incoming header) and passed along with every downstream call in a header, together with a span ID identifying each individual operation. Each service logs and reports its spans — start time, duration, and tags — to a collector such as Zipkin or Jaeger, which stitches them into one timeline. In Spring Boot this is usually done with Micrometer Tracing (the successor to Spring Cloud Sleuth), which propagates the trace context automatically through RestTemplate, WebClient, Feign, and messaging, as long as you use the instrumented clients. The trace ID also belongs in your logs, so a single ID connects logs and traces.
Example: A request to the gateway gets trace ID abc123. The gateway calls the order service with header traceparent carrying that ID; the order service's call to payment carries it onward. In Jaeger you search abc123 and see gateway → order (180 ms) → payment (1.4 s) — the bottleneck is obvious.
242. How do you implement centralized logging for microservices?
With dozens of services on many machines, logging to local files is useless — nobody can find anything. Centralized logging means every service ships its logs to one searchable store. Each log line should be structured (JSON is common) and carry the same fields: timestamp, service name, level, message, and the correlation or trace ID of the request. A typical pipeline is an agent such as Filebeat or Fluent Bit collecting logs, Logstash or a similar shipper parsing them, Elasticsearch storing them, and Kibana (the ELK stack) or Grafana Loki for searching and dashboards. Equally important is discipline: log at the right level, never log secrets or full payloads with personal data, and keep a consistent format across services so one query works everywhere.
Example: Every service logs JSON lines like {"ts":"2026-12-01T10:00:00Z","service":"order-service","traceId":"abc123","level":"ERROR","msg":"Payment failed"}. Searching traceId:abc123 in Kibana shows every log line for that one request across all services.
243. How do you handle a slow or unavailable downstream service without affecting the entire system?
The goal is to contain the failure so one bad dependency does not take down everything that calls it. The toolkit is a combination of patterns rather than one fix. Timeouts bound how long you wait, so threads are not held hostage. A circuit breaker stops calling a service that is clearly failing and fails fast instead. The bulkhead pattern isolates thread pools per dependency, so a slow payment service cannot starve the threads serving catalog requests. Fallbacks degrade gracefully — cached data, a default response, or a clear message — instead of a 500 error. And asynchronous paths, such as queuing non-critical work, keep the request path short. Monitoring and alerting complete the picture: you want to know a dependency is sick before users tell you. The interview point is to name several of these and explain how they combine.
Example: The product page calls the recommendation service with a 300 ms timeout on its own small thread pool, behind a circuit breaker. If recommendations are slow, the page still renders — just without the "you may also like" section.
244. How do you reduce latency when an API depends on multiple downstream services?
When one API fans out to several downstream services, the naive approach — calling them one after another — adds up every latency. The first fix is parallelism: fire independent calls concurrently, for example with CompletableFuture or reactive WebClient, so total time approaches the slowest call rather than the sum. Next, cut work: cache responses that change rarely, ask each service only for the fields you need, and avoid the N+1 pattern of one call per item. Then move work out of the request path — precompute or denormalize data into a read model, or return a fast partial response and fill in the rest asynchronously. Finally, check the network itself: keep connections alive and reuse them, co-locate chatty services, and make sure timeouts are tight so one slow dependency cannot dominate the total. Measure with distributed tracing before optimizing, so you fix the real bottleneck.
Example:
CompletableFuture<User> user = userService.get(id);
CompletableFuture<List<Order>> orders = orderService.list(id);
CompletableFuture<Cart> cart = cartService.get(id);
CompletableFuture.allOf(user, orders, cart).join();
// Three independent calls run concurrently; total time ~ the slowest one. High Priority
245. What are the advantages and disadvantages of microservices?
The advantages are about independence. Teams can deploy, scale, and change one service without coordinating a release of everything; a hot service scales on its own; different services can use different technologies; and a failure in one service can be contained instead of crashing the whole system. The disadvantages are the cost of distribution. Network calls replace method calls, so latency and partial failures appear everywhere; data consistency becomes eventual rather than transactional; testing, debugging, and tracing across services is harder; and the operational burden — deployment pipelines, monitoring, service discovery, configuration — grows steeply. Microservices also demand mature DevOps and strong team ownership. As a rule of thumb, they pay off for large systems with several teams and genuinely independent parts, and they are usually overkill for a small product built by one team.
Example: A streaming platform scales its video-transcoding service independently during a premiere while the billing service stays small — but the team now runs a gateway, a registry, tracing, and centralized logging just to keep that independence working.
246. What is Domain-Driven Design, and what is a bounded context?
Domain-Driven Design (DDD) is an approach to modelling software around the business domain rather than around tables or technical layers: developers and domain experts build a shared language, called the ubiquitous language, and the code uses the same terms the business uses. A bounded context is the boundary inside which one model and one meaning of a term apply. The classic example is "order": in the sales context an order is a cart being checked out, while in the shipping context an order is a parcel with a delivery address — same word, different model, and forcing one shared model creates confusion. Bounded contexts map neatly onto microservice boundaries: each service owns one context, its own model, and its own data, and contexts talk to each other through explicit interfaces or events.
Example: A "customer" in the billing context has payment methods and invoices; in the support context the same person has tickets and chat history. Two services, two models, linked only by a customer ID — not one giant shared Customer object.
247. What are entities and aggregates in DDD?
In DDD, an entity is a domain object defined by its identity rather than its attributes — a Customer remains the same customer even if their address changes, because their customer ID is what makes them who they are. A value object, by contrast, is defined purely by its attributes: two Money objects of the same amount and currency are interchangeable. An aggregate is a cluster of related entities and value objects treated as one unit for consistency, with a single entry point called the aggregate root. All changes go through the root, and the aggregate is saved as a whole, which keeps its internal rules — its invariants — intact. A common rule of thumb is to keep aggregates small: a large aggregate becomes a contention hotspot and a modelling headache.
Example: An Order is an aggregate root containing OrderLine entities and a shipping Address value object. You add a line through order.addLine(...), which can enforce "an order cannot exceed ten lines," and the whole order is persisted together.
248. What is decentralized data management and polyglot persistence?
Decentralized data management means there is no single central database owned by a central team: each microservice owns and manages its own data, choosing the storage that fits its needs. Polyglot persistence is the natural consequence — different services use different databases. A catalog service might use a document store for flexible product data, the order service a relational database for transactional integrity, the search service Elasticsearch for full-text search, and a session service Redis for fast key-value access. The benefit is that each workload gets the right tool; the cost is operational complexity — more database technologies to run, monitor, back up, and hire for — and no single place to run a cross-service join. Data is shared through APIs and events, not through shared tables.
Example: Product search reads from Elasticsearch, orders live in MySQL, and user sessions live in Redis. The search index is fed by events from the catalog service; no service queries another service's database.
249. What is the CAP theorem? Explain consistency and availability trade-offs.
The CAP theorem says a distributed data store can guarantee at most two of three properties when a network partition occurs: Consistency (every read sees the latest write), Availability (every request gets a response), and Partition tolerance (the system keeps working when nodes cannot talk to each other). Because partitions happen in real networks, partition tolerance is not really optional — so the practical choice is between consistency and availability during a partition. A CP system refuses or delays writes to stay consistent, while an AP system keeps accepting writes and reconciles later, accepting temporary inconsistency. Most real systems mix the two: strong consistency for money, availability with eventual consistency for a product catalog. A common misconception is that CAP forces a permanent choice; in reality you choose per operation and per failure mode.
Example: During a network split, a CP order service rejects new orders rather than risk double-selling the last item, while an AP "recently viewed" service keeps recording views on both sides and merges them when the partition heals.
250. What are the fallacies of distributed computing?
The fallacies of distributed computing are eight false assumptions that developers new to distributed systems tend to make: the network is reliable; latency is zero; bandwidth is infinite; the network is secure; topology does not change; there is one administrator; transport cost is zero; and the network is homogeneous. Every one of them is wrong in production. Networks fail and partition, calls take real time, bandwidth is finite and shared, the network is hostile, services move and scale constantly, many teams and providers are involved, serialization and calls cost CPU and money, and clients and services run on wildly different stacks. Good distributed design assumes the opposite of each fallacy: timeouts and retries for unreliable networks, caching and batching for latency and bandwidth, TLS and authentication for security, and service discovery for changing topology. In an interview, naming four or five with a one-line consequence each is usually enough.
Example: Assuming "latency is zero" leads to a checkout flow making twenty sequential service calls; assuming "the network is reliable" leads to code with no timeout that hangs forever when a downstream service stops responding.
251. What is the Bulkhead pattern?
The bulkhead pattern isolates failures by partitioning resources, named after the watertight compartments in a ship's hull: one flooded compartment does not sink the ship. In software this usually means giving each downstream dependency its own thread pool or connection pool, so a slow or failing dependency exhausts only its own pool and leaves the rest of the system healthy. It can also mean separate instances, queues, or rate limits per tenant or per workload. Without bulkheads, a single slow service consumes the one shared thread pool and every request — even those that never touch that service — starts timing out. Bulkheads are often combined with circuit breakers and timeouts: the breaker stops calling the sick service, the bulkhead makes sure the sickness cannot spread while the breaker is deciding.
Example: The checkout service uses a 20-thread pool for payment calls and a separate 20-thread pool for inventory calls. If the payment service hangs, only the payment pool fills up; catalog browsing on other threads keeps working.
252. What is the Outbox Pattern, and how does it prevent lost events?
The outbox pattern solves the dual-write problem: a service that updates its database and then publishes an event can crash in between, leaving the database changed but the event never sent — or send the event and then fail to save, publishing a lie. With the outbox, the service writes its business change and the outgoing event into the same database transaction, the event landing in an "outbox" table. A separate relay process then reads outbox rows and publishes them to the broker, marking each as sent. Because both writes are atomic, an event is never lost and never published without its database change. The relay retries failed publishes, and consumers must be idempotent because a relay can legitimately publish the same event twice. This is the standard reliable way to emit events from a service.
Example: Creating an order inserts the order row and an outbox row for OrderPlaced in one transaction. A relay polls the outbox table and publishes to Kafka; if the relay crashes mid-publish, it retries the unsent row on restart.
253. What is CQRS, and when should it be used?
CQRS — Command Query Responsibility Segregation — separates the model that handles writes (commands) from the model that serves reads (queries). Instead of one model doing both, writes go to a command side optimized for business rules and consistency, and reads come from a query side optimized for fast, denormalized views, kept in sync by events. It shines when read and write needs diverge sharply: complex validation on writes, but dashboards and search needing pre-joined, pre-aggregated data. It is not free — you now have two models, eventual consistency between them, and more moving parts — so it is overkill for ordinary CRUD, where one model serves both sides perfectly well. CQRS pairs naturally with event sourcing, but the two are independent ideas and either can be used alone.
Example: An e-commerce write side stores orders as normalized rows enforcing inventory rules; an event handler builds a read model of "orders with customer name, items, and totals" in one document, so the order-history page needs no joins at all.
254. What is Event Sourcing, and how does it differ from storing current state?
Event sourcing stores the history of what happened instead of the current state. Rather than updating a row to reflect the latest balance, you append immutable events — AccountOpened, MoneyDeposited, MoneyWithdrawn — to an event log, and the current state is derived by replaying those events. The differences are significant: you get a complete audit trail and can rebuild state at any past point, debug by replaying, and build new read models from history. The costs are also real: reading state requires replay or maintained snapshots, queries across aggregates are awkward, and changing old event shapes needs versioning or upcasting. Event sourcing fits domains where the history itself matters, such as banking, auditing, or collaboration; for simple CRUD it adds complexity with little payoff.
Example: A bank account's balance of 700 is not stored directly; it is the result of replaying Deposited 1000 then Withdrew 300. A dispute is settled by reading the event log, not by guessing from a single number.
255. What is API Composition?
API composition is the pattern of building one response by calling several services and combining their results, usually in an API gateway or a dedicated aggregator service (sometimes called a Backend for Frontend). The client makes one call — "give me the order details page" — and the composer fetches the order, the customer, and the shipment status from three services and merges them. It keeps clients simple and avoids chatty client-side fan-out, and a dedicated composer per client type can shape the response for a mobile app differently from a web app. The trade-offs are the usual ones for fan-out: the composer must call services in parallel to stay fast, handle partial failures gracefully (show the order even if shipment tracking is down), and avoid becoming a bottleneck or a place where business logic quietly accumulates.
Example: The mobile app calls GET /mobile/orders/42 once. The composer calls the order, customer, and shipping services concurrently, then returns one JSON object with order lines, buyer name, and delivery status combined.
256. What is the difference between synchronous and asynchronous error handling between services?
In synchronous communication, an error comes back immediately in the same request: the caller gets an HTTP status code and can decide on the spot — retry, fall back, or show the user an error. The challenge is translating errors meaningfully: a downstream 500 should not leak as your 500 without context, and a downstream timeout needs its own handling. In asynchronous communication, the sender has already moved on, so errors surface later and elsewhere: a consumer fails to process a message, and the failure must be handled by retries, a dead-letter queue, and alerting, because nobody is waiting for an answer. The design difference is about ownership: synchronous errors are handled by the caller in the moment, asynchronous errors are handled by the consumer's retry and dead-letter machinery, with observability doing the work of connecting the failure back to the original request.
Example: A REST call to the payment service returns 503, so checkout immediately shows "payment unavailable, try again." A failed OrderPlaced event, by contrast, is retried by the shipping consumer three times and then parked in a dead-letter topic for an engineer to inspect.
257. How should microservices handle HTTP status codes and propagate errors?
Services should use status codes with their standard meanings and keep error responses consistent, so callers can react without guessing. Use 400 for invalid input the client can fix, 401 for missing or bad authentication, 403 for authenticated but forbidden, 404 for a missing resource, 409 for a conflict such as a duplicate, 422 for a well-formed request that fails business validation, 429 when rate-limited, 500 for unexpected server failures, and 502/503/504 when a downstream dependency or gateway fails. Error bodies should carry a stable machine-readable code plus a human-readable message, and ideally a correlation ID — never stack traces or internal details. When calling downstream services, do not blindly forward their status: translate it, so a downstream 500 becomes a meaningful error from your service, and reserve 500 for your own genuine failures. Retries should only target retryable codes such as 429, 502, 503, and 504.
Example:
{
"code": "ORDER_NOT_FOUND",
"message": "No order exists with id 42",
"correlationId": "abc123"
} 258. What is Feign Client, and how does it work?
Feign is a declarative HTTP client from Spring Cloud: instead of writing boilerplate RestTemplate code, you declare a Java interface with annotations describing the remote calls, and Feign generates the implementation at runtime. It integrates with the Spring Cloud ecosystem, so it can resolve service names through a registry such as Eureka, apply client-side load balancing, and plug in resilience features such as circuit breakers. Under the hood it builds the HTTP request from your method signature — URL, path variables, headers, and body — executes it, and deserializes the response. It is a good fit for straightforward service-to-service REST calls where the interface-first style keeps clients readable, though for reactive or streaming workloads WebClient is usually the better choice.
Example:
@FeignClient(name = "inventory-service")
public interface InventoryClient {
@GetMapping("/inventory/{sku}")
Stock getStock(@PathVariable String sku);
}
// Calling inventoryClient.getStock("ABC") issues GET
// inventory-service/inventory/ABC, resolved via service discovery. 259. How do you manage configuration across multiple microservices?
Configuration spread across dozens of services quickly becomes unmanageable if each service carries its own copy: a changed database password or feature flag means editing and redeploying everything. The standard approach is externalized, centralized configuration — one source of truth, such as Spring Cloud Config Server, Consul, or environment variables injected by the deployment platform — with per-environment profiles (dev, staging, production) and per-service overrides. Secrets never live in plain config files; they come from a vault or the platform's secret store. Configuration should be reloadable where possible, so a changed flag does not force a restart, and every change should be versioned and auditable, so you can answer "what changed at 2 a.m.?" Finally, keep the rule that code never hard-codes environment-specific values; anything that differs between environments is configuration.
Example: All services read shared settings from a Config Server backed by Git: application-prod.yml holds the production database URL, while order-service-prod.yml overrides just the order service's pool size.
260. What is Spring Cloud Config Server?
Spring Cloud Config Server is a Spring Cloud service that centralizes configuration for all your microservices. It serves configuration files — typically stored in a Git repository, which gives you versioning, history, and review — over HTTP, and client services fetch their config at startup (and can refresh it later). Each client asks for its own application name and active profile, such as order-service with profile prod, and gets back the matching properties, with shared defaults layered underneath. Because config lives in Git, changes are auditable and reversible, and because clients pull config at startup, the same deployable artifact runs unchanged across environments. Sensitive values should be encrypted in the repository or supplied by a vault rather than stored in plain text.
Example:
# bootstrap.yml in the order service
spring:
application:
name: order-service
cloud:
config:
uri: http://config-server:8888
profile: prod
# Config Server then serves order-service-prod.yml from its Git repo. 261. What is the difference between a common library and a separately deployed service?
A common library is code shared by linking it into each service: every service gets its own copy at build time, calls run in-process, and there is no network hop. That makes it fast and simple, but every change requires rebuilding and redeploying every consumer, and version drift is a constant risk — five services can easily end up on three versions of the same library. A separately deployed service is shared at runtime over the network: one deployment serves everyone, and changes roll out in one place. The price is network latency, a new failure mode, and the need for versioned APIs and backward compatibility. As a rule of thumb, share stable, stateless utilities (validation, date handling) as libraries, and share stateful business capabilities (pricing, user identity) as services.
Example: A money-formatting helper belongs in a shared library; a pricing engine that applies live discounts belongs in a pricing service, because its rules change often and every service must see the same prices at the same time.
262. What is the difference between a multi-module repository and separate repositories?
A multi-module repository (a monorepo) keeps several services or modules in one version-control repository, often as Maven or Gradle modules sharing a build. It makes cross-service changes atomic — one commit can change a shared library and all its consumers — and keeps tooling and versioning consistent. The cost is scale: the repository grows large, builds get slower, and teams must coordinate around shared pipelines and access rules. Separate repositories (one per service) give each team full independence over its build, versioning, and deployment, which matches the microservices ownership model, but cross-cutting changes become multi-repo pull requests, and shared code needs its own versioned release process. Neither is universally right; the choice follows how independently the teams actually work.
Example: A monorepo lets one commit update a shared DTO module and the three services using it. With separate repos, the same change is a library release plus three service upgrades, each deployed on its own schedule.
263. What are the 12-factor app principles?
The 12-factor app is a methodology for building applications that deploy cleanly, especially as services. Its twelve principles are: one codebase tracked in version control with many deploys; explicitly declared and isolated dependencies; configuration stored in the environment, never in code; backing services (databases, queues) treated as attached resources; strictly separate build, release, and run stages; stateless processes that share nothing and persist state in backing services; binding to ports and exposing services via URLs; scaling out by running more processes; fast startup and graceful shutdown for disposability; keeping development and production as similar as possible; treating logs as event streams sent to a collector; and running admin tasks as one-off processes. In interviews, you rarely need all twelve verbatim — the most quoted are config in the environment, stateless processes, and logs as streams.
Example: A 12-factor order service reads its database URL from an environment variable, keeps no session state in memory, starts in seconds, and writes JSON logs to stdout for the platform to collect — the same artifact runs in dev, staging, and production.
264. How do you maintain backward compatibility when evolving APIs?
Backward compatibility means old clients keep working after you change an API, and it is maintained by additive change and discipline. Add new fields instead of renaming or removing old ones; make new fields optional with sensible defaults; never change the meaning or type of an existing field; and never remove an endpoint or a field without a deprecation period. When a breaking change is unavoidable, introduce a new version (usually in the URL, such as /v2/orders) and run both versions side by side until clients migrate. Consumer-driven contract tests help: they verify that the provider's responses still satisfy what each consumer actually uses. Finally, communicate — publish a changelog and a sunset date — because compatibility is a promise to clients, not just a technical property.
Example: Adding a discountCode field to the order response is safe; renaming totalAmount to total breaks every client. Ship the new field, mark the old one deprecated, and remove it only after clients confirm migration.
265. How do you secure service-to-service communication?
Services calling each other over a network cannot trust the network, so service-to-service security has several layers. Transport security comes first: mutual TLS (mTLS) encrypts traffic and lets each service prove its identity with a certificate, so a rogue process cannot impersonate a service. On top of that, calls carry a token — commonly a short-lived JWT or an OAuth 2.0 client-credentials token — so the receiving service can check what the caller is allowed to do, not just who it is. A service mesh such as Istio can provide both mTLS and policy enforcement without changing application code. Network segmentation adds defense in depth: services sit in private networks, only the gateway is public, and security groups or network policies limit which services can reach which. Finally, never pass a user's token blindly between services without considering its scope and lifetime.
Example: The order service calls the payment service over mTLS with a client-credentials token scoped to payments:charge. The payment service verifies the certificate and the token's scope before processing the charge.
266. What are horizontal and vertical scaling? When would you use each?
Vertical scaling (scaling up) means giving one machine more power — more CPU, memory, or faster disk. It is simple, needs no code changes, and suits stateful or single-instance workloads, but it has a hard ceiling: you eventually cannot buy a bigger machine, and one machine is still a single point of failure. Horizontal scaling (scaling out) means adding more instances of a service and spreading load across them, typically behind a load balancer. It has no practical ceiling and adds resilience, but it requires the service to be stateless (or to externalize its state), and it brings the distributed problems of load balancing, discovery, and data partitioning. As a rule of thumb, scale vertically for a quick fix or a database that cannot shard easily, and design services to scale horizontally from the start.
Example: A stateless catalog service scales horizontally from 3 to 30 instances during a sale. The primary database, which cannot simply be duplicated, is scaled vertically to a larger instance until read replicas or sharding become necessary.
267. What is load balancing, and what are common algorithms?
Load balancing distributes incoming traffic across multiple instances of a service so no single instance is overloaded and a failed instance stops receiving traffic. A load balancer continuously health-checks its targets and only routes to healthy ones. Common algorithms include round robin, which cycles through instances in order; weighted round robin, which sends more traffic to stronger instances; least connections, which picks the instance with the fewest active requests — a good fit when requests vary in cost; IP hash, which sends the same client to the same instance and is useful for session affinity; and least response time, which favors the fastest instance. Layer 4 balancers route on transport information such as IP and port, while Layer 7 balancers understand HTTP and can route on URL or headers. The right algorithm depends on whether your requests are uniform or varied in cost.
Example: Three order-service instances sit behind a Layer 7 load balancer using least connections, so a long-running checkout does not pile up on one instance while the others sit idle.
268. What is a reverse proxy, and how does it differ from a forward proxy?
A reverse proxy sits in front of servers and handles requests on their behalf: clients talk to the proxy, and the proxy forwards to the right backend service. It is the server side's proxy, used for load balancing, TLS termination, caching, and hiding internal topology — an API gateway and a load balancer are both commonly built on reverse proxies. A forward proxy sits in front of clients: it forwards the client's requests to the internet on the client's behalf, typically for access control, filtering, or anonymity inside a corporate network. The difference is whose interests the proxy serves: a reverse proxy protects and presents the servers, a forward proxy serves the clients. In an interview, one line captures it: with a forward proxy the client knows it is using a proxy, with a reverse proxy the client usually has no idea one is there.
Example: Nginx as a reverse proxy terminates TLS and forwards /api/orders to the order service. A corporate forward proxy, by contrast, is configured in employees' browsers so all their outbound web traffic passes through company filtering.
269. What is a CDN, and when does it help?
A content delivery network (CDN) is a globally distributed set of edge servers that cache content close to users, so a request is served from a nearby edge node instead of travelling to the origin server. It helps most with static or cacheable content — images, videos, JavaScript, stylesheets — and with geographically spread users, cutting latency and taking load off the origin. CDNs also commonly absorb traffic spikes and some denial-of-service attacks, and many offer TLS termination and edge computing. A CDN does not help much with personalized, uncacheable responses: an API returning "your orders" still has to reach the origin. Cache invalidation matters too — a stale image on the edge is a real bug — so content that changes often needs short TTLs or explicit purging.
Example: Product images are served from a CDN edge node near the shopper, so the page loads fast worldwide while the origin serves only the small dynamic API responses for prices and stock.
Medium Priority
270. What is leader election in distributed systems?
Leader election is the process by which a group of nodes agrees on one of them to act as the leader — the single node that coordinates work, such as assigning partitions or sequencing writes — while the others act as followers. It is needed because without a leader, nodes can make conflicting decisions, for example two nodes both believing they own the same task. Election usually runs through a coordination service such as ZooKeeper, etcd, or Consul, using a consensus algorithm such as Raft or Paxos: nodes campaign, a majority votes, and the winner takes a lease that expires if it stops sending heartbeats. If the leader fails, the remaining nodes detect the missing heartbeat and elect a new one. The key properties are that at most one leader exists at a time and that a new leader emerges automatically after a failure.
Example: In a Kafka cluster, one broker is elected controller and decides which broker leads each partition. If the controller broker crashes, the remaining brokers elect a new controller, which resumes assigning partition leaders.
271. What are heartbeat mechanisms and distributed coordination?
A heartbeat is a small periodic signal — "I am alive" — that a node sends to its peers or to a coordination service, proving it is still running and reachable. If heartbeats stop for a configured interval, the node is declared dead and its work is reassigned. Distributed coordination is the broader problem heartbeats serve: getting independent nodes to agree on shared state, such as who holds a lock, which node is the leader, or what the current configuration is. Tools such as ZooKeeper, etcd, and Consul provide the primitives — leader election, distributed locks, watches on configuration, and service registration — built on consensus algorithms that keep the coordination data itself consistent even when nodes fail. Heartbeats are the liveness detector; consensus is what makes the decisions trustworthy.
Example: Each service instance sends a heartbeat to Eureka every 30 seconds. If an instance misses several beats, Eureka removes it from the registry so no new traffic is routed to a dead instance.
272. What is a distributed file system?
A distributed file system spreads files across many machines while presenting them as one logical file system, so applications read and write files without caring which physical machine holds them. Files are typically split into blocks and replicated across several nodes, which gives both scale — total capacity grows by adding machines — and fault tolerance, since losing one node does not lose data. Examples include HDFS for big-data workloads, where large files are split into blocks processed in parallel, and cloud object stores such as Amazon S3, which offer a similar model through an API rather than a POSIX interface. The trade-offs are consistency and latency: writes may take time to replicate, network access is slower than a local disk, and strong POSIX semantics are hard to provide across a network, so many systems settle for simpler guarantees.
Example: A video platform stores uploaded videos in a distributed file system: a 2 GB file is split into blocks replicated on three different machines, so playback keeps working even if one machine fails.
273. What is full-text search, and when would you use Elasticsearch?
Full-text search finds documents by the words they contain, ranked by relevance, rather than by exact matches on structured columns. A database LIKE '%shoe%' scan cannot rank results, handle stemming ("running" matching "run"), or cope with typos — a search engine can. Elasticsearch is a distributed search engine built on Lucene: it breaks text into tokens, builds an inverted index mapping each term to the documents containing it, and answers queries with relevance scoring. You would use it when search is a product feature — product catalogs, document search, log search — or when you need faceted filtering and fuzzy matching at scale. It is not a replacement for a primary database: it favors search speed over transactional guarantees, and its data should be derived from a source of truth, usually fed by events.
Example: A shopper searching "wireless headphones" gets ranked results including "Bluetooth earphones" through tokenization and synonyms, with filters for brand and price — something a SQL LIKE query cannot do well.
274. How does Elasticsearch distribute data using shards and replicas?
Elasticsearch splits each index into shards — horizontal partitions of the documents — and spreads those shards across the nodes of a cluster, so indexing and search load are shared and the data set can exceed what one machine holds. Each shard has replicas: copies stored on different nodes. A primary shard handles writes, and its replicas serve reads and take over if the primary's node fails, giving both read scaling and fault tolerance. Routing decides which shard a document lands on, usually by hashing its ID. The practical consequences are that too many small shards waste memory and management overhead, while too few large shards limit parallelism and make recovery slow; and replica count trades read capacity and safety against storage cost. A single-node setup with no replicas is fine for development but loses data if that node dies.
Example: A product index with 5 primary shards and 1 replica per shard holds 10 shard copies across a 3-node cluster. If one node goes down, the replica copies on the surviving nodes keep every document searchable.
275. What are the fallacies of network reliability in a distributed environment?
This question overlaps with the fallacies of distributed computing, but with a focus on the network itself: the dangerous assumptions are that the network is reliable, that latency is zero, that bandwidth is infinite, and that the topology does not change. In practice, packets are lost, connections drop, partitions split the system, latency varies with load and distance, bandwidth is shared and finite, and services constantly move as instances scale and redeploy. Designing as if these were true produces systems that hang on a dead connection, time out under normal load spikes, or break when an IP address changes. The practical answer is to design for failure: every call gets a timeout, retries are bounded with backoff and jitter, requests are idempotent, health checks remove dead instances, and service discovery — not hard-coded addresses — tracks the moving topology.
Example: A service that assumes a stable network hard-codes a downstream IP and has no timeout. When that instance is redeployed to a new address, every call fails — and without a timeout, the caller's threads pile up until the caller itself stops responding.
276. What is the difference between data duplication and shared database access between services?
Data duplication means each service keeps its own copy of the data it needs, usually updated through events published by the owning service. The copies can go stale briefly, and storage is used twice, but services stay independent: they deploy separately, fail separately, and query their own copy fast without a network call. Shared database access means services read and write the same tables directly. It looks simpler — one query, always fresh data — but it couples services at the data layer: a schema change breaks other teams, a bad query from one service hurts all of them, and ownership of the data becomes unclear. Duplication is the standard microservices trade: accept eventual consistency and extra storage in exchange for real independence. Shared access is acceptable only for genuinely shared reference data that rarely changes, and even then it is usually better exposed through an API.
Example: The order service keeps a duplicated copy of product names and prices, updated from catalog events, so the order-history page needs no live call. It never reads the catalog database directly — that would couple the two services' schemas and deployments.
8. Kafka, Messaging & Event-Driven Architecture
Very High Priority
277. What is Apache Kafka, and how does its architecture work?
Apache Kafka is a distributed streaming platform that lets applications publish and consume streams of records, much like a commit log that many services can read from and write to. At its heart are brokers — the servers that store messages — organized into a cluster. Producers send records to topics, which are categories of messages such as "orders" or "payments". Each topic is split into partitions, and each partition is an ordered, append-only log of records stored on disk. Consumers read from partitions at their own pace, tracking their position with an offset. Brokers replicate each partition across several servers so that data survives a broker failure, and a controller broker manages leadership and partition assignment. Modern Kafka no longer needs ZooKeeper: the cluster's metadata is managed internally by a quorum of controller brokers (KRaft mode), which simplifies operations. Kafka keeps messages durably even after they are consumed, so a new consumer can replay history, and it is built for high throughput — thousands of messages per second across many partitions.
Example: An e-commerce order service publishes an order event, and three downstream services — payment, inventory, and notifications — each read it independently from the same topic.
Producer (Order Service) --> Topic: orders (3 partitions, replication factor 3)
|
+---------------------------+---------------------------+
| | |
Payment Service Inventory Service Notification Service
(consumer group A) (consumer group B) (consumer group C) 278. What is the difference between a topic, partition, offset and consumer group?
A topic is a named category or feed of messages, like a channel that producers publish to and consumers subscribe to. A partition is a subdivision of a topic: each topic is split into one or more partitions, and each partition is an ordered, append-only log stored on a broker. Records are assigned to a partition, usually by key, and the order of records is only guaranteed within a single partition, not across the whole topic. An offset is a sequential number that identifies the position of a record inside a partition — think of it as the record's index in that log. A consumer group is a set of consumers that cooperate to read a topic: Kafka assigns each partition to exactly one consumer in the group, so the work is split across the members, and each member tracks its own offsets. Two different consumer groups can read the same topic independently, each from its own position. So the topic is the feed, the partition is the ordered shard, the offset is the bookmark, and the consumer group is the team sharing the reading work.
Example: A topic payments with 4 partitions and a consumer group of 4 instances means each instance reads exactly one partition. If a fifth instance joins, it sits idle until a rebalance frees a partition.
Topic: payments
Partition 0: [offset 0, 1, 2, ...] --> Consumer A
Partition 1: [offset 0, 1, 2, ...] --> Consumer B
Partition 2: [offset 0, 1, 2, ...] --> Consumer C
Partition 3: [offset 0, 1, 2, ...] --> Consumer D 279. How do Kafka partitions and consumer groups provide parallelism?
Partitions are the unit of parallelism in Kafka. A single partition can only be read by one consumer within a group at a time, so the maximum number of consumers in a group that can actively process a topic equals the number of partitions. If a topic has 12 partitions and a consumer group has 12 instances, each instance reads one partition and the load is spread across all of them — processing 12 records in parallel instead of one at a time. Add more consumers than partitions and the extras stay idle, waiting for a rebalance. Partitions also parallelize the producer side: producers can write to different partitions concurrently, and because partitions live on different brokers, the storage and network load spreads across the cluster. The practical rule of thumb is to choose the partition count based on the throughput you need and the number of consumer instances you expect to run, since you cannot exceed the partition count for parallel consumption in one group. Picking too few partitions caps your throughput; picking far too many adds overhead in rebalances and broker metadata.
Example: A topic with 6 partitions and 3 consumers gives each consumer 2 partitions. Scaling the group to 6 consumers gives each one partition, roughly doubling parallel throughput.
Topic: events (6 partitions)
Group with 3 consumers: A gets p0, p1 | B gets p2, p3 | C gets p4, p5
Group with 6 consumers: A gets p0 | B gets p1 | C gets p2 | D gets p3 | E gets p4 | F gets p5 The shape looks like this:
280. How does Kafka maintain message ordering?
Kafka guarantees ordering only within a single partition, not across a topic. Records written to the same partition are appended in the order they arrive and are read back in that same order, because a partition is a simple append-only log with sequential offsets. To keep related messages in order, you give them the same key: the producer hashes the key and always routes records with that key to the same partition. So all events for one customer, one order, or one account stay ordered relative to each other. Messages with different keys may land in different partitions and can be processed out of order relative to each other — that is the trade-off for parallelism. A common mistake is assuming a whole topic is ordered; it is not, and ordering across partitions cannot be relied on. If strict global order matters for a use case, the usual approach is a single-partition topic, accepting that throughput is then limited to one consumer. Also note that retries can break ordering: if a producer retries a failed send, a later record may be written first. Enabling idempotent producers and limiting in-flight requests helps preserve order when retries are in play.
Example: Using the order ID as the key guarantees that "order created", "order paid", and "order shipped" for the same order are processed in sequence.
// Same key --> same partition --> order preserved
producer.send(new ProducerRecord<>("orders", "order-123", "ORDER_CREATED"));
producer.send(new ProducerRecord<>("orders", "order-123", "ORDER_PAID"));
producer.send(new ProducerRecord<>("orders", "order-123", "ORDER_SHIPPED")); 281. What happens when a Kafka consumer crashes or a consumer group rebalances?
When a consumer crashes, the group coordinator detects the failure — usually because the consumer stops sending heartbeats — and triggers a rebalance. During a rebalance, the group pauses consumption and reassigns the crashed consumer's partitions to the surviving members, so no partition is left unread for long. Each consumer's progress is tracked by committed offsets, which record how far it has read. After a rebalance, the new owner of a partition resumes from the last committed offset, not from where the crashed consumer had actually processed up to. That gap matters: if the crashed consumer processed some records but had not committed their offsets yet, those records are delivered again, so the new owner may process duplicates. Rebalances also happen when a consumer joins or leaves the group, or when a topic's partition count changes. Frequent rebalances hurt throughput because consumption pauses while partitions are reassigned, so common causes — consumers that are too slow to heartbeat, long processing times, or unstable deployments — are worth investigating. Modern group protocols reduce the pause by reassigning only the affected partitions instead of stopping the whole group.
Example: A consumer processes offsets 100–109 but commits only up to 100 before crashing. After rebalance, the new owner re-reads offsets 101–109, so those messages are processed twice unless the consumer is idempotent.
Consumer A crashes (last committed offset: 100, processed up to: 109)
Group coordinator detects missed heartbeats
Rebalance: partition reassigned from A to B
Consumer B resumes from committed offset 101
--> offsets 101-109 are delivered again (at-least-once) 282. How do you troubleshoot Kafka consumer lag?
Consumer lag is the gap between the latest offset in a partition and the offset the consumer group has committed — in other words, how far behind the consumer is. The first step is to measure it per partition, not just as a single number, because one slow partition can hide behind a healthy average. Tools such as the kafka-consumer-groups command-line tool, or a monitoring system like Prometheus with a Kafka exporter, show lag per topic, group, and partition. Next, find the cause. If lag grows steadily, the consumer is slower than the producer: check whether processing is slow (a heavy database call, a slow downstream API), whether the consumer is stuck retrying poison messages, or whether the group has fewer consumers than partitions so some partitions are unassigned. If lag spikes suddenly, look for a rebalance storm, a broker or network issue, or a burst of producer traffic. Fixes depend on the cause: scale out consumers up to the partition count, add partitions if consumers are maxed out, speed up processing (batch commits, async calls, parallel processing within a consumer), or fix the poison message blocking progress. Also check that the consumer is committing offsets regularly and that its poll interval and session timeout are tuned so it is not being kicked out of the group.
Example: A quick command shows which partitions are behind.
kafka-consumer-groups.sh --bootstrap-server localhost:9092 \
--group order-processor --describe
TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG
orders 0 12050 12050 0
orders 1 9840 11200 1360 <-- behind
orders 2 12010 12010 0 283. How do you handle message-processing failures and retries in Kafka?
When a consumer fails to process a message — a downstream service is down, the data is invalid, or a database call throws — the first question is whether the failure is transient or permanent. Transient failures are usually retried, while permanent failures should not be retried forever. A common pattern is to retry a few times with a delay between attempts, ideally with exponential backoff so a struggling downstream service is not hammered. In Kafka, the tricky part is that retrying usually blocks the partition: while one message is being retried, later messages in that partition wait behind it, which can grow lag and stall ordering. To avoid blocking, many teams use a retry topic: the failed message is published to a retry topic with a delay, and the consumer moves on. Spring Kafka supports this with non-blocking retries using @RetryableTopic, which creates retry topics automatically. If all retries are exhausted, the message goes to a dead-letter topic for inspection. Also decide what happens to the offset: committing it means the message will not be redelivered, while not committing it means it will be replayed — which is only safe if processing is idempotent. The golden rule is to never silently drop a failed message and never retry forever without a dead-letter escape hatch.
Example: Spring Kafka retries a failed message up to 3 times with backoff, then routes it to a dead-letter topic.
@RetryableTopic(attempts = "4", backoff = @Backoff(delay = 1000, multiplier = 2.0),
topicSuffixingStrategy = TopicSuffixingStrategy.SUFFIX_WITH_INDEX_VALUE)
@KafkaListener(topics = "orders", groupId = "order-processor")
public void handleOrder(OrderEvent event) {
orderService.process(event); // throws on transient failure --> retried
}
@DltHandler
public void handleDeadLetter(OrderEvent event) {
log.error("Giving up on order event after retries: {}", event);
// alert ops, persist for manual inspection
} 284. What is a Dead Letter Topic/Queue, and how should it be designed?
A Dead Letter Topic (DLT), also called a Dead Letter Queue (DLQ), is a separate topic where messages are sent after they have failed processing and exhausted all retries. Its purpose is to stop a poison message — one that will never succeed, such as a malformed payload — from blocking the main topic forever, while still keeping the message available for inspection instead of deleting it. A good DLT design starts with keeping the original message intact, including its key and headers, and adding metadata: how many times it was retried, which exception was thrown, when it failed, and which consumer group handled it. The DLT should have its own alerting, because messages landing there usually signal a bug or a data problem that needs a human. It should also have a replay path: a tool or process that can re-send fixed messages back to the main topic after the root cause is resolved. Retention matters too — keep DLT messages long enough for the team to investigate, which is often longer than the main topic's retention. Finally, avoid the trap of treating the DLT as a bin nobody watches: if nobody monitors it, failed orders or payments disappear silently, which is worse than a visible failure.
Example: A payment event with a missing amount fails validation three times, then lands in payments.DLT with headers recording the cause.
Original topic: payments
Retry topics: payments-retry-0, payments-retry-1, payments-retry-2
Dead letter: payments.DLT (headers: x-exception-message,
x-exception-class, x-original-topic,
x-original-partition, x-original-offset) 285. What are at-most-once, at-least-once and exactly-once delivery semantics?
These three terms describe the guarantee a messaging system makes about how many times a message is processed. At-most-once means a message is delivered zero or one times: the consumer commits its offset before processing, so if it crashes mid-processing, the message is lost — never processed, but never duplicated either. This suits data where occasional loss is acceptable, such as metrics. At-least-once means a message is delivered one or more times: the consumer processes first and commits the offset afterwards, so a crash between processing and committing causes redelivery and duplicates. This is the most common choice, because it never loses data, but the consumer must handle duplicates. Exactly-once means a message is processed exactly one time, with no loss and no duplicates. True exactly-once is hard in distributed systems; Kafka approximates it with idempotent producers and transactions, which let a producer write to a topic and commit offsets atomically, so a consumer using read_committed isolation only sees fully committed records. Even then, exactly-once usually holds only within Kafka itself — once the consumer writes to an external database, the guarantee depends on the consumer's own design, such as writing the record and its offset in a single transaction.
Example: A payment consumer uses at-least-once delivery plus an idempotency check: a payment with an ID already in the database is skipped, so a redelivery cannot charge the customer twice.
// At-least-once + idempotency key = effectively exactly-once
if (paymentRepository.existsById(event.getPaymentId())) {
return; // duplicate delivery, safe to skip
}
paymentRepository.save(new Payment(event));
consumer.commitSync(); // offset committed only after successful save 286. How do you prevent duplicate message processing? How do you build an idempotent consumer?
Duplicates are a fact of life with at-least-once delivery: a consumer can crash after processing a message but before committing its offset, and the message is then delivered again. An idempotent consumer is one that produces the same result whether it processes a message once or many times. The standard technique is to give every message a unique identifier — an event ID or a business key such as an order ID — and to record which IDs have already been processed. Before doing the work, the consumer checks whether that ID exists in a store (a database table, Redis, or a unique constraint); if it does, the message is skipped. The critical detail is atomicity: the check and the business write must happen in the same transaction, otherwise a crash between them can still produce a duplicate. A common implementation is to insert the processed event ID into a table with a unique constraint inside the same transaction as the business update — if the insert fails with a duplicate-key error, the message was already processed. Other approaches include making the operation itself naturally idempotent, such as setting a value rather than incrementing it, or using a unique constraint on the business entity itself. The idempotency record should also be cleaned up or retained for a sensible window, depending on how long redeliveries can plausibly occur.
Example: A unique constraint on the event ID makes duplicate processing fail safely inside the same transaction as the business write.
@Transactional
public void process(OrderEvent event) {
// Unique constraint on processed_events(event_id) rejects duplicates
processedEventRepository.save(new ProcessedEvent(event.getEventId()));
orderRepository.updateStatus(event.getOrderId(), event.getStatus());
// If the event was already processed, the insert throws
// and the whole transaction rolls back -- no double update.
} 287. What is the difference between Kafka and RabbitMQ, and when would you choose each?
Kafka and RabbitMQ are both message brokers, but they are designed for different jobs. Kafka is a distributed commit log: messages are stored durably in topics and partitions, consumers track their own offsets, and messages can be replayed long after they were consumed. It is built for high-throughput event streaming, event sourcing, and feeding many independent consumers from the same data. RabbitMQ is a traditional message broker built around queues and exchanges: a producer publishes to an exchange, which routes the message to queues, and once a consumer acknowledges a message it is removed — there is no replay. RabbitMQ is a strong fit for task distribution and work queues, where each message should be processed exactly once by one worker, and for complex routing rules such as topic-based or header-based routing. Kafka's strengths are throughput, durability, replay, and stream processing; its weaknesses are operational complexity and weaker per-message routing. RabbitMQ's strengths are flexible routing, lower latency for small volumes, and simpler semantics for job queues; its weakness is that it is not designed for replay or for very high throughput fan-out. A rough rule of thumb: choose Kafka when the event log itself is the asset, and RabbitMQ when the queue of pending work is the asset.
Example: Use Kafka for an order-events stream that payment, inventory, analytics, and auditing all read independently; use RabbitMQ for an email-sending work queue where each email is processed once by one worker.
Kafka: Producer --> Topic (durable log, replayable, many consumer groups)
RabbitMQ: Producer --> Exchange --> Queue --> Consumer (ack removes message) 288. What is a message broker, and how does it decouple microservices?
A message broker is middleware that receives messages from producers, holds them, and delivers them to consumers — services never talk to each other directly. This decoupling works in three ways. First, time decoupling: the producer does not need the consumer to be running when it sends a message; the broker stores it until the consumer is ready, so a temporary outage in one service does not break the other. Second, space decoupling: the producer only knows the broker and the topic or queue name, not the address, deployment, or even existence of the consumer, so services can be added, removed, or scaled independently. Third, synchronization decoupling: the producer sends the message and moves on instead of waiting for a response, which keeps it fast and prevents a slow downstream service from blocking it. The trade-offs are real: the system becomes eventually consistent rather than immediately consistent, debugging a flow that crosses several services is harder, and the broker itself becomes a piece of infrastructure that must be operated reliably. Still, for most event-driven microservices, a broker is what makes the services genuinely independent instead of just separately deployed.
Example: An order service publishes an "order placed" event to a broker and returns success immediately; the inventory service consumes it seconds later and decrements stock, without the order service ever knowing it exists.
Order Service --publish--> [ Broker: topic "orders" ] --consume--> Inventory Service
(no direct call, no shared database, no waiting) High Priority
289. What is Schema Registry, and why is it useful with Avro?
A Schema Registry is a central service that stores and versions the schemas of the messages flowing through Kafka, so producers and consumers agree on the structure of the data. It is most commonly used with Avro, a binary serialization format where the schema defines the fields, their types, and their defaults. When a producer sends an Avro message, it registers the schema (or reuses an existing one) and sends only a small schema ID with the payload instead of the full schema, which keeps messages compact. Consumers fetch the schema by ID and deserialize accordingly. The real value is compatibility: the registry can enforce rules such as backward compatibility, meaning a new schema can add optional fields but cannot remove or rename required ones, so old consumers keep working when producers evolve their events. Without a registry, teams usually end up with JSON payloads where a renamed field silently breaks a consumer, or with ad-hoc version fields nobody enforces. The registry turns schema evolution from a hope into a checked contract, and it also gives a single place to see every event type in the system.
Example: A producer registers schema v2 of OrderCreated that adds an optional discountCode field; the registry accepts it because it is backward compatible, and old consumers ignore the new field.
Producer: Avro schema v2 --register--> Schema Registry (id = 42)
Message sent as: [schema id 42][binary payload]
Consumer: reads id 42, fetches schema, deserializes
Compatibility rule: BACKWARD -- new schema must be readable by old consumers 290. What are Kafka retention and log-compaction policies?
Retention and log compaction are the two ways Kafka decides which messages to keep. Retention is time- or size-based: by default a topic keeps messages for a configured period (commonly seven days) or until the topic reaches a size limit, after which old segments are deleted. This suits event streams where only recent history matters, such as clickstreams or logs. Log compaction works differently: for each message key, Kafka keeps only the latest value and discards older values with the same key, while keeping at least one record per key forever (subject to a minimum retention for the compaction process itself). This turns a topic into a changelog of current state rather than a history — ideal for topics such as user profiles or product catalogs, where a consumer wants the latest value for every key and can rebuild the full state by reading the topic from the beginning. The two policies are set per topic with the cleanup.policy setting (delete, compact, or both), and they can be combined: compact the log and also delete records that have not been updated for a long time. Choosing wrong has consequences — deleting history a consumer still needs, or compacting a topic where every event matters and no key repeats.
Example: A user-profiles topic with compaction keeps only the newest profile per user ID, so a new consumer can rebuild the full current state; an orders topic with 7-day retention drops old events once the window passes.
# Delete policy: keep 7 days of history
cleanup.policy=delete
retention.ms=604800000
# Compact policy: keep only the latest value per key
cleanup.policy=compact
# user-1: v1, v2, v3 --> only v3 retained 291. What happens when a producer or broker fails?
When a producer fails, the main risk is lost or duplicated messages. If the producer crashes before receiving an acknowledgement, it does not know whether the broker wrote the record, so retrying can create a duplicate — enabling idempotent producers makes the broker deduplicate retries using a producer ID and sequence number, removing that risk for a single producer session. If the producer cannot reach any broker, messages stay in its local buffer until it times out, then the send fails and the application must decide what to do: retry, persist locally, or fail loudly. When a broker fails, the impact depends on replication. Each partition has a leader and followers; if a follower fails, nothing is lost and the leader keeps serving, but replication falls behind. If the leader fails, the controller elects one of the in-sync replicas as the new leader, and producers and consumers are redirected — usually within seconds. Data loss is possible only if the leader had acknowledged writes that had not yet been replicated, which is why the acks=all setting and a minimum number of in-sync replicas matter for durability. If too many replicas are lost for a partition, it becomes unavailable until a broker returns or an out-of-sync replica is allowed to take over, trading durability for availability.
Example: With acks=all and min.insync.replicas=2, a write is only acknowledged once two brokers hold it, so the loss of a single broker cannot lose an acknowledged message.
acks=all + min.insync.replicas=2 + replication.factor=3
Broker 1 (leader) fails
--> Controller elects Broker 2 (in-sync replica) as new leader
--> Producers/consumers redirected; no acknowledged data lost 292. What is the difference between producer acknowledgements and consumer offset commits?
Producer acknowledgements and consumer offset commits are two different promises at opposite ends of the pipeline, and confusing them is a common interview trap. A producer acknowledgement (acks) controls how the broker confirms a write: acks=0 means the producer does not wait for any confirmation, acks=1 means the leader has written the record, and acks=all means all in-sync replicas have written it. It answers the question "has this message been durably stored?" A consumer offset commit, by contrast, records how far a consumer has read: it writes the consumer group's position into Kafka's internal offsets topic, answering "how far have I processed?" The timing of the commit decides the delivery guarantee. Committing before processing gives at-most-once (a crash loses the message), while committing after processing gives at-least-once (a crash replays it). So acknowledgements protect against losing messages on the way in, and offset commits track progress on the way out — one governs durability, the other governs delivery semantics, and a system needs both configured correctly to be reliable.
Example: A producer with acks=all knows a payment event is safely replicated, while the consumer commits offset 500 only after the payment has been written to the database, so a crash before the commit replays the event instead of losing it.
Producer side: send() --> broker acks=all --> record durably stored
Consumer side: poll() --> process() --> commitSync(offset) --> progress recorded 293. How do you implement retry topics and dead-letter topics?
Retry topics and dead-letter topics are implemented as ordinary Kafka topics with a naming convention, plus logic that moves a failed message between them with increasing delays. The flow is: the consumer fails to process a message from the main topic, so instead of blocking the partition, it publishes the message to a first retry topic. A consumer on the retry topic waits for a delay — often implemented with a timestamp check or a delayed consumer — then tries again; if it fails, the message moves to the next retry topic with a longer delay, and so on. After the final retry topic is exhausted, the message is published to the dead-letter topic and an alert is raised. In Spring Kafka this is largely built in: the @RetryableTopic annotation creates the retry topics and the dead-letter topic automatically, applies exponential backoff between attempts, and routes exhausted messages to a method annotated with @DltHandler. When implementing it by hand, the important details are preserving the original message and its headers, recording the attempt count and failure reason in headers, making the delays increase so a struggling service is not hammered, and ensuring the retry consumer is idempotent — because a message can be retried after a partial success. The dead-letter topic should also have a replay mechanism so fixed messages can be returned to the main topic.
Example: Spring Kafka retry chain for an orders consumer.
@RetryableTopic(
attempts = "4",
backoff = @Backoff(delay = 1000, multiplier = 2.0, maxDelay = 10000),
autoCreateTopics = "true")
@KafkaListener(topics = "orders", groupId = "order-processor")
public void handle(OrderEvent event) {
orderService.process(event);
}
@DltHandler
public void deadLetter(OrderEvent event) {
alertingService.notify("Order event exhausted retries: " + event.getOrderId());
} 294. What is Event-Driven Architecture?
Event-Driven Architecture (EDA) is a design style in which services communicate by producing and consuming events — records that something happened — rather than calling each other directly. An event is a fact about the past, such as "order placed" or "payment failed", usually carrying the data a consumer needs. Producers publish events to a broker, and any interested service subscribes and reacts, without the producer knowing who is listening. This gives loose coupling and easy extensibility: adding a new feature often means adding a new consumer, not changing the producer. It also fits naturally with asynchronous processing, so slow work does not block the request path. The trade-offs are that the system becomes eventually consistent — a consumer may see an event seconds after it happened — and that debugging a business flow now spans multiple services and an event log, which demands good tracing and observability. Events should be designed as immutable facts with a stable schema, and teams usually distinguish between event notification (a lightweight "something changed, come and fetch it") and event-carried state transfer (the event carries all the data). A common mistake is treating events as commands ("do this") rather than facts ("this happened"), which couples the producer to the consumer's behavior.
Example: When a user registers, the auth service publishes UserRegistered; the email service sends a welcome email, the analytics service records a signup, and the CRM service creates a contact — none of them known to the auth service.
Auth Service --publish UserRegistered--> [ Event Broker ]
| | | |
| Email Service Analytics CRM Service
| (welcome mail) (signup) (contact)
+-- producer knows nothing about consumers --+ 295. What is the difference between a message queue and publish-subscribe messaging?
A message queue and publish-subscribe are two messaging patterns with different delivery rules. In a queue (point-to-point), a message is sent to a queue and delivered to exactly one consumer — once that consumer acknowledges it, the message is removed and no other consumer sees it. This is the pattern for distributing work: a pool of workers shares a queue of tasks, and each task is handled once by one worker. In publish-subscribe, a message is published to a topic and delivered to every subscriber — each consumer group gets its own copy, so many independent services can react to the same event. Kafka topics are a publish-subscribe model, while a RabbitMQ queue is a point-to-point model (though RabbitMQ can also do pub-sub through exchanges and multiple queues). The choice depends on the intent: if the message is a task to be done once, use a queue; if it is an event that several services need to know about, use publish-subscribe. A useful mental model is that a queue divides work, while a topic broadcasts information. Some systems combine them — a topic fans out to several queues, one per consumer group, each of which then distributes work among its workers.
Example: A queue distributes 1,000 image-resize jobs among 5 workers (each job done once); a topic broadcasts one OrderPlaced event to payment, inventory, and notification services (each gets a copy).
Queue (point-to-point): Producer --> [Queue] --> ONE of Worker A / B / C
Pub-Sub: Producer --> [Topic] --> Subscriber A AND B AND C 296. What is the transactional outbox pattern when publishing Kafka events?
The transactional outbox pattern solves the dual-write problem: when a service updates its database and also needs to publish an event to Kafka, doing both as separate steps can leave them inconsistent — the database commit can succeed while the publish fails, or vice versa. The outbox pattern fixes this by writing the event into an outbox table inside the same database transaction as the business change, so the two either commit together or roll back together. A separate relay process then reads new rows from the outbox table and publishes them to Kafka, marking each row as published afterwards. If the relay crashes mid-publish, it simply retries the unpublished rows on restart, and because consumers are idempotent, a duplicate publish is harmless. The pattern is usually implemented with a polling relay or with change-data-capture tools that tail the database transaction log. It is a common answer in interviews because it shows an understanding that distributed atomicity is usually achieved by making one local transaction the source of truth and letting everything else follow from it, rather than by trying to coordinate two systems in a single transaction.
Example: Creating an order and its outbox row commit together; a relay then publishes the event.
@Transactional
public void placeOrder(Order order) {
orderRepository.save(order); // business write
outboxRepository.save(new OutboxEvent(
"OrderPlaced", order.getId(), toJson(order))); // same transaction
}
// Relay: polls outbox table, publishes to Kafka, marks row published.
// Crash before publish? Row stays unpublished and is retried. 297. What is backpressure, and how can a consumer avoid being overwhelmed?
Backpressure is the problem of a producer sending data faster than a consumer can process it. Without any control, the consumer's memory fills up, its queues grow unboundedly, and eventually it crashes or starts failing — and a flood of messages can cascade into downstream services too. The goal is to make the consumer signal "slow down" rather than silently drown. Kafka helps naturally because consumers pull rather than being pushed: a consumer only fetches a batch when it is ready, and its max.poll.records setting caps how many records arrive per poll. Beyond that, common techniques include pausing consumption when a downstream dependency is struggling, processing in batches instead of one message at a time, scaling out consumers up to the partition count, and shedding load by routing non-critical messages to a separate topic for later processing. For HTTP-based consumers, rate limiting and returning retryable errors push the pressure back to the sender. The key insight for interviews is that backpressure is a design property of the whole pipeline, not a single setting: every stage should be able to slow its upstream, and the system should degrade gracefully — slower, not broken — when load spikes.
Example: A consumer that detects a slow database pauses its Kafka partitions until the database recovers, instead of fetching more records it cannot handle.
if (database.isSlow()) {
consumer.pause(consumer.assignment()); // stop fetching new records
} else {
consumer.resume(consumer.assignment()); // fetch again when healthy
}
// Kafka config: max.poll.records=100 limits each batch size 298. What are background workers, and when should work be processed asynchronously?
Background workers are processes that run outside the request-response path, picking up jobs from a queue or a topic and processing them on their own schedule. The user-facing request returns immediately while the heavy work happens later. Work belongs in the background when it is slow, when the user does not need the result right away, when it can be retried safely, or when it should survive a restart — examples include sending emails, generating reports, resizing images, syncing data to another system, and processing webhooks. Work should stay synchronous when the user needs the answer to proceed, such as validating a payment before confirming an order, or when the operation must be atomic with the request. A good background job is idempotent, carries all the data it needs (or a reference to it), has a timeout and a retry policy, and reports failures visibly instead of failing silently. Common implementations are worker threads in the application, a dedicated worker service consuming from Kafka or a queue, or a scheduled job. The interview point is the trade-off: asynchronous work improves responsiveness and resilience, but adds eventual consistency, operational complexity, and the need to tell the user the result later — for example with a status endpoint, a notification, or a webhook.
Example: A file-upload endpoint stores the file, enqueues a GenerateThumbnail job, and returns 202 Accepted immediately; a worker picks up the job and generates the thumbnail in the background.
POST /uploads --> store file, enqueue job, return 202 Accepted
Worker: consumes "thumbnail-jobs" queue
generates thumbnail, updates status to READY
Client: polls GET /uploads/{id} or receives a webhook when done Medium Priority
299. What is a webhook, and how do you verify its signature?
A webhook is an HTTP callback: instead of polling an API for changes, you register a URL with a provider, and the provider sends an HTTP POST to that URL whenever an event happens — a payment succeeds, a repository is updated, a shipment is delivered. It is a simple form of event-driven integration over plain HTTP. The risk is that anyone who discovers your endpoint URL can send fake events, so providers sign their webhooks: they compute a cryptographic signature (usually an HMAC) over the request body using a shared secret, and send it in a header. To verify, your endpoint recomputes the HMAC over the raw request body with the same secret and compares it to the header value using a constant-time comparison — comparing in constant time matters, because a naive string comparison can leak information about the correct value through timing. You must use the raw body bytes, not a re-serialized JSON object, because any whitespace change breaks the signature. Other checks worth doing are rejecting requests with stale timestamps (to limit replay attacks), verifying the event ID has not been seen before (idempotency), and responding quickly with a 2xx status so the provider does not retry. The secret itself should be stored securely, never hard-coded, and rotated if it is ever exposed.
Example: Verifying a Stripe-style HMAC signature in a Spring controller.
@PostMapping("/webhooks/payments")
public ResponseEntity<Void> handle(@RequestBody byte[] rawBody,
@RequestHeader("X-Signature") String signature) {
String expected = "sha256=" + hmacSha256Hex(webhookSecret, rawBody);
if (!MessageDigest.isEqual(expected.getBytes(), signature.getBytes())) {
return ResponseEntity.status(401).build(); // forged or tampered
}
processEvent(rawBody);
return ResponseEntity.ok().build();
} 300. How should webhook retries be implemented without duplicate side effects?
Webhook providers retry delivery when your endpoint returns an error or times out, and they may also deliver the same event twice if a response is lost — so your endpoint must be safe to receive the same event more than once. The core technique is idempotency keyed on the event ID: every webhook event carries a unique identifier, and your endpoint records each processed event ID in a database table with a unique constraint. When an event arrives, you check whether its ID has already been processed; if it has, you return 200 immediately without doing the work again. The check and the business write should happen in the same transaction, so a crash cannot leave a half-applied event. Your endpoint should also return a 2xx status as soon as the event is accepted and durably recorded — doing slow work synchronously risks a provider timeout and a duplicate delivery, so heavy processing usually goes to a background job after the event is stored. Providers typically retry with exponential backoff over hours or days, and some offer a dashboard to replay failed events manually. On your side, log every delivery with its event ID, and monitor for repeated failures, which usually indicate a bug rather than a transient problem.
Example: An event ID table with a unique constraint makes a duplicate delivery a no-op.
@Transactional
public void handlePaymentWebhook(String eventId, String payload) {
try {
processedWebhookRepository.save(new ProcessedWebhook(eventId));
} catch (DataIntegrityViolationException e) {
return; // event already processed -- duplicate delivery, safe to ignore
}
applyPayment(payload); // runs only once per eventId
} 301. What is jitter, and why should it be added to exponential backoff?
Jitter is a small random variation added to a retry delay, and it exists to stop the thundering herd problem. With plain exponential backoff, a failing service causes many clients to retry after 1 second, then 2, then 4, then 8 — and because they all started failing at the same moment, they all retry at the same moments, hitting the recovering service with synchronized waves of traffic that can knock it over again. Jitter breaks the synchronization by randomizing each delay: instead of every client waiting exactly 4 seconds, each waits somewhere between, say, 0 and 4 seconds, spreading the retries out. A common formula is to take the exponential delay and multiply it by a random factor, or to add a random value up to the delay itself ("full jitter"). The backoff still grows exponentially, so a persistently failing service is not hammered, but the load is smoothed instead of arriving in spikes. The same idea applies to scheduled jobs and cache expiry: adding jitter to a cron schedule or a TTL stops thousands of instances from waking up or expiring at the same instant. It is a small detail that interviewers like because it shows you have thought about what happens when many clients behave identically at scale.
Example: Full jitter spreads retries that would otherwise land in the same second.
// Without jitter: all clients retry at 1s, 2s, 4s, 8s -- synchronized waves
long delay = baseDelay * (1L << attempt);
// With full jitter: each client waits a random time up to the backoff cap
long delayWithJitter = ThreadLocalRandom.current().nextLong(0, delay + 1);
scheduler.schedule(retryTask, delayWithJitter, TimeUnit.MILLISECONDS); 302. How do you schedule background jobs in Spring Boot?
Spring Boot provides the @Scheduled annotation for running background jobs on a fixed schedule, backed by a task scheduler. You enable it with @EnableScheduling on a configuration class, then annotate a method with a schedule: fixedRate runs every N milliseconds regardless of how long the previous run took, fixedDelay waits N milliseconds after the previous run finishes, and a cron expression gives fine control such as "every night at 2 AM". The default scheduler is a single thread, so a long-running job can delay other scheduled jobs — for production use, configure a thread pool via a TaskScheduler bean. For a single instance this is enough, but in a multi-instance deployment every instance runs the job, which is wrong for work that must happen once — the usual fixes are a distributed lock (for example with ShedLock) or moving the job to a dedicated worker. For more demanding needs, teams use Quartz for persistent, clustered scheduling, or an external scheduler such as a Kubernetes CronJob. A well-written scheduled job is idempotent, logs its start and finish, guards against overlapping runs, and has alerting so a silently stopped job is noticed.
Example: A nightly cleanup job with a thread-pool scheduler and a cron expression.
@Configuration
@EnableScheduling
public class SchedulingConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5); // avoid the single-thread default
scheduler.setThreadNamePrefix("scheduled-");
return scheduler;
}
}
@Component
public class CleanupJob {
@Scheduled(cron = "0 0 2 * * *") // every day at 02:00
public void purgeExpiredSessions() {
sessionRepository.deleteExpiredBefore(Instant.now());
}
} 303. How do you implement graceful shutdown for message consumers?
Graceful shutdown means a consumer stops cleanly when the application is asked to terminate — finishing the message it is working on, committing its offset, and closing its connections, instead of dying mid-message and leaving work in an unknown state. In Spring Boot, the application context closes on a SIGTERM, and Spring Kafka's listener containers stop polling new records, wait for in-flight messages to finish (up to a configurable shutdown timeout), and then commit offsets and close the consumer. The key configuration points are the container's shutdown timeout, which bounds how long it waits for a message to finish, and the consumer's max.poll.interval.ms, which must be longer than the longest processing time so the consumer is not kicked out of the group while it finishes. For a hand-rolled consumer, the pattern is to catch the shutdown signal, call consumer.wakeup() from another thread to break out of the poll loop, finish and commit the current batch, and then close the consumer. Kubernetes helps by sending SIGTERM and waiting for a grace period before force-killing the pod, so the application's shutdown timeout should fit inside that grace period. The result is that a deployment or scale-down does not lose messages or leave duplicates beyond the normal at-least-once guarantee.
Example: A hand-rolled consumer that wakes up cleanly on shutdown.
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
consumer.wakeup(); // interrupts poll() in the main thread
}));
try {
while (running) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
process(records);
consumer.commitSync(); // commit before the next poll
}
} catch (WakeupException e) {
// expected on shutdown: finish up and exit
} finally {
consumer.close(); // leaves the group cleanly, triggers rebalance
} 9. Redis, Caching & Performance Patterns
Very High Priority
304. What is Redis, and why would you choose it over local in-memory caching or the default Spring Cache implementation?
Redis is an in-memory data store that runs as a separate server process and can be reached over the network, unlike a local cache that lives inside one application's JVM. It stores data in structures such as strings, hashes, lists, sets and sorted sets, and it is commonly used as a cache, a session store, a message broker building block and a place to hold counters or rate-limiting state. You would choose Redis when you run more than one application instance: a local cache in each instance holds different data, so one instance may serve a stale or missing value that another instance already cached. Redis gives every instance the same view, and it survives application restarts, so a redeploy does not wipe the cache. The default Spring Cache implementation is an abstraction, not a cache itself — it delegates to whatever provider is configured, and without one it falls back to a simple in-memory map. That is fine for a single-instance prototype, but Redis is the usual choice once you need a shared, durable cache across instances.
Example: A rule of thumb: one instance and data that can be rebuilt cheaply — a local cache is fine. Two or more instances, or a cache that must survive restarts — use a shared store such as Redis. A typical setup has the Spring Boot app connecting to a Redis server and using it behind the Spring Cache annotations, so the caching code does not change when the provider changes.
305. What is the difference between Redis and Spring Cache?
Redis and Spring Cache are different kinds of things, which is why they are often confused. Redis is a concrete technology: an in-memory data store server with its own protocol, data structures, persistence options and clustering. Spring Cache is an abstraction inside the Spring Framework: a set of annotations such as @Cacheable and @CacheEvict plus a CacheManager interface, and it does not store anything itself. It delegates to a provider — that provider can be a plain in-memory map, Caffeine, Ehcache or Redis. In other words, Redis is one possible engine behind Spring Cache, and Spring Cache is one possible way to use Redis from a Spring Boot application. You can also use Redis directly through a client such as Lettuce or Jedis without Spring Cache at all, which is common when you need Redis features that the cache abstraction does not expose, such as sorted sets for leaderboards or atomic increments for counters.
Example: With Spring Cache backed by Redis, annotating a method with @Cacheable("products") stores the result in Redis under a generated key. Switching the provider to Caffeine later means changing configuration, not the annotated methods — that is the abstraction doing its job.
306. How do you integrate Redis caching with Spring Boot?
You add the Spring Data Redis starter and the Spring Cache dependency, point the application at a running Redis server, and choose a cache manager that talks to Redis. Spring Boot auto-configures a RedisConnectionFactory from properties such as spring.data.redis.host and spring.data.redis.port, and enabling caching with @EnableCaching plus a RedisCacheManager bean makes the @Cacheable, @CachePut and @CacheEvict annotations store their entries in Redis instead of a local map. One detail worth getting right early is serialization: by default, keys and values may be serialized as Java binary data, which is unreadable from redis-cli and fragile across deployments. A common setup is to configure string keys and JSON values, so entries can be inspected and debugged from the command line. You should also set a default time-to-live on the cache manager, so entries expire rather than living forever.
Example:
# application.properties
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.cache.redis.time-to-live=600000
// Enable caching in a configuration class
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}
} 307. Explain Cache-Aside, Write-Through and Write-Behind strategies.
These are three patterns for how the application, the cache and the database interact on reads and writes. In cache-aside, also called lazy loading, the application owns the logic: on a read it checks the cache first and, on a miss, reads the database and then puts the result in the cache; on a write it updates the database and deletes or updates the cached entry. It is the most common pattern because the cache only holds data that is actually requested, but the first read after a write is always a miss. In write-through, the application writes only to the cache, and the cache writes synchronously to the database before the write is acknowledged. The cache and the database stay consistent, but every write pays the database latency. In write-behind, also called write-back, the application writes to the cache and the cache acknowledges immediately, then writes to the database asynchronously in the background. Writes are fast, but there is a window where the database does not yet have the data, so a cache crash in that window loses writes. As a rule of thumb, cache-aside is the default choice, write-through fits data where consistency matters more than write speed, and write-behind fits write-heavy workloads that can tolerate a small risk of loss.
Example: Cache-aside read in Java:
public Product getProduct(Long id) {
Product cached = redisTemplate.opsForValue().get("product:" + id);
if (cached != null) {
return cached;
}
Product product = productRepository.findById(id).orElseThrow();
redisTemplate.opsForValue().set("product:" + id, product, Duration.ofMinutes(10));
return product;
} 308. How do you keep Redis cache data consistent with MySQL?
Perfect consistency between a cache and a database is not achievable with a simple cache, because the cache and the database are two separate stores updated at different moments. The practical goal is to bound how long a stale value can be served. The standard approach is cache-aside with explicit invalidation: every write to MySQL deletes the affected cache keys, so the next read is a miss and reloads fresh data from the database. A time-to-live on each entry acts as a safety net, so even a missed invalidation only leaves stale data until the entry expires. You should delete the cache entry after the database write commits, not before, otherwise a concurrent read can reload the old value and re-cache it after your delete. If deletes can be missed — for example the application crashes between the database commit and the cache delete — a common recovery is a short TTL plus a background job that reconciles or re-deletes known-changed keys. For stronger guarantees, some teams publish a change event after the write and let a consumer invalidate the cache, which is more reliable than relying on the writing thread alone. A useful interview line: choose the strategy by asking how long a stale read is acceptable for that particular data.
Example: After updating a product price in MySQL, delete product:42 from Redis in the same service method, after the transaction commits. A product page may then show the old price for at most the TTL, typically minutes, which is acceptable for a catalog but not for a payment balance — that data should not be cached at all.
309. What is cache invalidation, and what strategies can be used?
Cache invalidation is removing or updating cached entries when the underlying data changes, so later reads do not serve outdated values. It is often called one of the hard problems in computer science because the cache and the source of truth are separate systems, and there is always a window where they disagree. The simplest strategy is time-based expiry: every entry carries a TTL, and stale data disappears on its own. It is easy and safe, but reads can be stale for up to the TTL. The second strategy is write-time invalidation: the code that updates the database also deletes the affected cache keys. This is precise, but it only works if every write path remembers to invalidate — one forgotten path leaves stale data indefinitely. A third strategy is event-driven invalidation: database changes publish events, and a consumer deletes or refreshes the matching cache entries, which centralizes the logic instead of scattering it across write paths. A fourth is versioning or key namespacing: the cache key includes a version number, and a write bumps the version, so old entries are simply never read again. In practice, most systems combine TTL as a safety net with write-time or event-driven invalidation for the main paths.
Example: A rule instead of a contrived code sample: invalidate by the same key the read path uses. If reads fetch product:42, the write path must delete exactly product:42 — and also any list keys such as products:category:7 that embed that product, or the list will keep showing the old value.
310. What is cache eviction? Explain LRU and LFU policies.
Cache eviction is the cache removing entries to make room when it runs out of memory. Redis has a maximum memory limit, and when it is reached, the configured eviction policy decides which entries go. Without a policy, Redis would simply reject new writes once full. LRU, least recently used, evicts the entries that have not been accessed for the longest time, on the assumption that data untouched for a while is unlikely to be needed soon. LFU, least frequently used, evicts the entries accessed least often overall, on the assumption that rarely requested data is less valuable than popular data. The difference shows up when a once-popular item goes cold: LRU will eventually evict it because it has not been touched recently, while LFU may keep it for a long time because its historical access count is high. Redis offers approximate versions of both, sampling a small set of keys rather than tracking exact order for every key, which keeps eviction cheap. The interview-ready summary: eviction is a memory-management policy, not an expiry mechanism — TTL expiry happens on a schedule, eviction happens when memory pressure forces a choice.
Example:
# Evict least recently used keys when memory is full
maxmemory-policy allkeys-lru
# Evict least frequently used keys instead
maxmemory-policy allkeys-lfu 311. What is a cache stampede, and how do you prevent it?
A cache stampede, also called a thundering herd, happens when a popular cached entry expires or is missing, and a large number of concurrent requests all miss the cache at the same time and all hit the database to reload the same data. The database, which the cache was protecting, suddenly receives hundreds or thousands of identical expensive queries, and the load spike can slow it down or take it down — which makes more requests time out and retry, feeding the problem. Prevention works on three fronts. First, spread out expiry times with a small random jitter on TTLs, so entries do not all expire in the same second. Second, let only one request rebuild the entry while the others wait or are served the stale value — this is request coalescing or locking, covered in question 318. Third, warm the cache proactively: refresh popular entries in the background before they expire, so they never go missing under load. A useful mental model: a stampede is not caused by high traffic alone, but by high traffic combined with a synchronized expiry.
Example: A rule instead of a contrived code sample: never let a TTL be the same for every entry. Setting a base TTL of 10 minutes plus a random 0–60 seconds per entry spreads expirations out, and that alone removes the most common stampede trigger — a mass expiry after a deploy that warmed the cache all at once.
312. What is the difference between a cache miss and a cache stampede?
A cache miss is a single, normal event: one request looks for a key, does not find it, and loads the data from the database. Misses are expected — every entry misses once when it is first loaded, and every expiry causes a miss. A cache stampede is a system-level failure mode: many requests miss the same key at the same time, and all of them independently hit the database for the same data, overwhelming it. The difference is one of scale and consequence: a miss costs one extra database query, while a stampede costs as many duplicate queries as there are concurrent requests, and it can cascade into database overload, timeouts and retries that make the load worse. Another way to say it: a miss is a cache working as designed, a stampede is a cache failing to protect the database it exists to shield. Interviewers ask this to check whether you distinguish a routine event from a failure mode, and whether your prevention ideas — jitter, locking, warming — target the concurrency, not the miss itself.
Example: One user opening a product page after its cache entry expired is a miss: one query reloads it. Ten thousand users opening the same product page in the same second after the entry expired is a stampede: ten thousand identical queries hit MySQL at once.
313. How do you troubleshoot Redis downtime, data loss or cache failures?
Start by deciding what kind of failure you are looking at, because downtime, data loss and silent cache failure have different fixes. For downtime, check whether the Redis process is running, whether the application can reach it over the network, and whether the connection pool is exhausted — a pool full of idle or broken connections looks like Redis being down from the application's side. For data loss, check the persistence configuration: with no persistence, a Redis restart loses everything, which is expected behaviour rather than a bug; with RDB snapshots, data written after the last snapshot is lost; with AOF, the loss window depends on the fsync setting. The INFO persistence output and the Redis logs show which mode is active and whether the last save failed. For silent failures, where the application runs but the cache is not helping, check the hit ratio, memory usage and eviction counts: a hit ratio near zero can mean keys are being written with one serialization and read with another, or that eviction is removing entries as fast as they are written because memory is full. Through all of this, the application should degrade gracefully: a cache failure should mean slower responses from the database, not errors to the user, so check that cache calls have timeouts and fall back to the database instead of failing the request.
Example:
redis-cli INFO stats | grep -E "keyspace_hits|keyspace_misses|evicted_keys"
redis-cli INFO persistence
redis-cli INFO memory | grep -E "used_memory_human|maxmemory_human" High Priority
314. What is distributed caching, and what challenges does it introduce?
Distributed caching means the cache is shared across multiple application instances, usually as a separate service such as a Redis server or cluster, rather than each instance keeping its own private copy. It solves the core problem of local caching in a multi-instance deployment: every instance sees the same data, a cache entry written by one instance is visible to the others, and a restart or redeploy of one instance does not wipe the cache for everyone. The challenges come from the cache now being a network service. There is latency on every cache access, and a network partition or Redis outage affects all instances at once, so the application needs timeouts and a fallback to the database. Consistency gets harder: invalidation must reach the shared store, and in a clustered setup, keys are spread across nodes, so a node failure can make part of the cache unavailable. There is also an operational cost — the cache is now infrastructure to monitor, back up and scale, and a misconfigured eviction policy or memory limit can silently degrade the whole system. As a rule of thumb, distributed caching is worth it once you have more than one instance or a cache that must survive restarts; before that, it is extra infrastructure for little gain.
Example: Three Spring Boot instances behind a load balancer share one Redis server. A user profile cached by instance A is served to a later request routed to instance B with no extra work, whereas with local caches, instance B would have to load the profile from MySQL itself.
315. What is stale cache data, and how do you prevent users from seeing outdated values?
Stale cache data is a cached value that no longer matches the current state of the database — for example a product price that changed in MySQL yesterday but still shows the old amount from Redis. It happens whenever a write path updates the database without updating or deleting the corresponding cache entry, or when an entry lives past the moment its data changed. Prevention is a combination of techniques, chosen by how bad a stale read is for that particular data. A TTL bounds staleness: no value can be older than its expiry, so a short TTL limits the damage. Write-time invalidation removes the affected keys as soon as the database changes, which keeps staleness to the small window between the write and the delete. Event-driven invalidation does the same thing through a change event, which centralizes the logic. For data where staleness is unacceptable — an account balance, an order status, a seat reservation — the answer is not a cleverer cache, but not caching that data at all, or caching it with a TTL of seconds. Two practical points interviewers look for: delete after the database transaction commits, so a concurrent read cannot re-cache the old value, and invalidate every key that embeds the data, including list and search-result keys, not just the single-item key.
Example: A user changes their display name. The service updates MySQL, then deletes user:77 and users:search:* keys from Redis. The next profile read misses the cache and loads the new name from the database, so no user ever sees the old name for longer than the time between the commit and the delete.
316. What is Redis persistence, and what could cause data loss?
Redis persistence is how Redis saves its in-memory data to disk so that it can survive a restart. There are two mechanisms. RDB persistence takes periodic snapshots of the whole dataset to a file; it is compact and fast to reload, but anything written after the last snapshot is lost if the process crashes. AOF persistence appends every write command to a log file, so much less data is lost — how much depends on the fsync setting: syncing on every write loses almost nothing but costs performance, syncing once a second can lose up to a second of writes, and letting the operating system decide can lose more. Many deployments run both: AOF for durability and RDB for fast restarts and backups. Data loss happens when persistence is off entirely, which is the default for a cache-only setup and is fine as long as the data can be rebuilt from MySQL; when the process crashes between snapshots or fsyncs; when the disk fills up and writes fail; or when a replica is promoted with an empty dataset and overwrites the primary. The key interview point: Redis persistence is a durability dial, not a guarantee — decide how much loss is acceptable for the data in question, and configure accordingly.
Example:
# Append-only file, fsync once per second: at most ~1s of writes lost
appendonly yes
appendfsync everysec
# RDB snapshot: save after 900s if 1 key changed, 300s if 10, 60s if 10000
save 900 1
save 300 10
save 60 10000 317. What are Redis eviction policies, and how do you select one?
When Redis reaches its configured memory limit, the eviction policy decides what happens next. The noeviction policy refuses new writes with an error and keeps everything; it suits a store that must never lose data, but a cache that rejects writes is a cache that has stopped working. The allkeys-lru and allkeys-lfu policies evict from all keys by recency or frequency, which suits a pure cache where every entry can be rebuilt from the database. The volatile-lru, volatile-lfu, volatile-random and volatile-ttl policies evict only from keys that have a TTL set, which suits a mixed store where some keys are permanent and others are temporary — the permanent data is protected. allkeys-random evicts an arbitrary key, which is rarely the best choice but is cheap and predictable. Selection follows two questions: can the evicted data be rebuilt, and do some keys matter more than others? If everything is rebuildable, use an allkeys policy, LRU for typical access patterns and LFU when a small set of keys is hot for a long time. If some keys must survive, give the disposable ones a TTL and use a volatile policy. And always set maxmemory — without a limit there is no eviction at all, and Redis will keep growing until the machine runs out of memory.
Example: A session store and a product cache share one Redis instance. Product entries get a TTL and the policy is volatile-lru, so memory pressure evicts old product pages first and never touches a live user session.
318. How can cache warming, request coalescing or locking prevent a stampede?
These are the three standard defenses against a cache stampede, and they attack the problem from different angles. Cache warming means populating the cache before it is needed, or refreshing popular entries in the background before they expire, so the entry is never missing under load. It works well for a known set of hot keys, such as a homepage or a top-products list, and it is usually done by a scheduled job. Request coalescing, also called single-flight, means that when many requests miss the same key at the same time, only one of them goes to the database while the others wait for its result and then share it. It directly removes the duplicate queries that define a stampede. Locking is one way to implement coalescing in a distributed setup: the first request takes a short-lived lock in Redis, often with SET key lock NX EX 10, rebuilds the entry, and releases the lock; the other requests either wait briefly and retry the cache, or fall back to serving the stale value. Warming prevents the miss, coalescing and locking limit the damage when a miss happens anyway. In practice, teams combine them: warm the hottest keys, add jitter to TTLs, and use a lock or coalescing for the rest.
Example:
// One request rebuilds; others wait briefly, then read the fresh value
Boolean locked = redisTemplate.opsForValue()
.setIfAbsent("lock:product:" + id, "1", Duration.ofSeconds(10));
if (Boolean.TRUE.equals(locked)) {
try {
Product product = productRepository.findById(id).orElseThrow();
redisTemplate.opsForValue().set("product:" + id, product,
Duration.ofMinutes(10));
} finally {
redisTemplate.delete("lock:product:" + id);
}
} else {
Thread.sleep(100); // short wait, then retry the cache read
} One caveat: this is a simplified interview illustration, not a production-safe lock — it has no ownership token, so a rebuild that outlives the 10-second TTL could let another request delete a lock it does not own. A production lock needs a unique token per holder and a delete-only-if-mine check (or a library such as Redisson).
319. What is the difference between local cache and distributed cache?
A local cache lives inside one application instance's memory — a ConcurrentHashMap, a Caffeine cache, or Spring's default in-memory provider — and only that instance can read or write it. A distributed cache is a separate shared service, such as Redis, that every instance connects to over the network. The local cache is faster, because there is no network round trip, and it has no external dependency, so it keeps working if the network has trouble. But each instance holds its own copy: the same key can hold different values on different instances, a restart wipes it, and invalidating a value means invalidating it on every instance, which is hard to do reliably. The distributed cache is slower per access and adds an operational dependency, but every instance sees the same data, the cache survives application restarts, and invalidation is a single delete. As a rule of thumb, a local cache fits single-instance services and data that is cheap to rebuild and safe to be briefly stale per instance, while a distributed cache is the default once you run more than one instance. Many systems use both: a small local cache in front of Redis for the hottest keys, with a short TTL so any inconsistency is brief.
Example: With two instances and a local cache, instance A caches a product price of 500 and instance B caches 450 after a price change reached only A — the same user can see two different prices depending on which instance serves them. With Redis, both instances read the same entry and the problem disappears.
320. How do you decide what should and should not be cached?
The decision comes down to four questions about the data. First, is it read far more often than it is written? A product catalog read thousands of times a day and updated a few times is a good candidate; a balance updated on every transaction is not. Second, is it expensive to produce — a slow query, a join across tables, a call to a downstream service? Caching a query that already takes two milliseconds saves almost nothing. Third, can it be stale, and for how long? Reference data, catalogs and rendered pages tolerate minutes of staleness; an order status, a payment result or an available-seat count usually cannot. Fourth, is it safe to share and store? Never cache sensitive data such as passwords, tokens or full payment details, and be careful with per-user data that could leak across users if the key is wrong. Two more practical filters: cache at a granularity that matches how the data is read — caching a whole list when callers only ever need one item wastes memory — and make sure the cached form is actually reusable, because a value that is different for every request, such as a personalized feed with a unique user id in the key, may never get a second hit. A useful interview line: cache the result, not the raw inputs, and only when a hit is likely.
Example: Cache: product details, category lists, exchange-rate tables, rendered homepage fragments. Do not cache: account balances, one-time tokens, search results unique to a single user, or anything whose staleness could cause a wrong payment or a double booking.
321. How do you monitor cache hit ratio, latency and memory usage?
Three numbers tell you most of what you need to know about a cache. The hit ratio is cache hits divided by total lookups, and it answers whether the cache is earning its keep: a ratio below roughly half on a cache that should be warm usually means the TTL is too short, the keys are wrong, or the workload has no repeat reads. Redis reports hits and misses in INFO stats as keyspace_hits and keyspace_misses, and you can compute the ratio from those counters. Latency is measured on both sides: Redis-side latency from INFO stats and slow-log entries, and client-side latency from your application's own timers around cache calls, exposed through Micrometer and Spring Boot Actuator. A sudden latency rise often points to a large key, a blocking command, or memory pressure forcing the operating system to swap. Memory usage comes from INFO memory, which shows used memory against the configured maximum, plus the eviction counters that show whether the cache is throwing entries away to stay under the limit. In production, these are usually scraped into Prometheus and charted in Grafana with alerts on a falling hit ratio, rising evictions and memory approaching the limit — and the most useful alert of all is a hit ratio that drops suddenly, because it usually means something changed in the application rather than in Redis.
Example:
redis-cli INFO stats | grep keyspace_hits
redis-cli INFO stats | grep keyspace_misses
redis-cli INFO memory | grep -E "used_memory_human|maxmemory_human"
redis-cli SLOWLOG GET 5 Medium Priority
322. What is cache penetration, and how can it be mitigated?
Cache penetration is when requests keep asking for keys that do not exist anywhere — not in the cache and not in the database — so every request misses the cache and hits the database anyway. It is often caused by a bug or an attack: a client requesting random product ids, or a crawler probing sequential ids that were never created. Because the miss is never cached, the database absorbs the full load, and the cache provides no protection at all. Mitigation starts with caching the negative result: when a lookup finds nothing in the database, store a short-lived marker, such as an empty value with a TTL of a minute or two, so repeat requests for the same missing key are answered from the cache. A second defense is a Bloom filter in front of the cache: a compact probabilistic structure that can say "this key definitely does not exist" and reject the request before it reaches the database, at the cost of occasionally rejecting a key that does exist. A third is input validation and rate limiting — reject obviously invalid ids at the API layer so they never reach the data layer. As a rule of thumb, cache the absence briefly, validate the input early, and reach for a Bloom filter only when the volume of missing-key requests justifies the added complexity.
Example: A request for product id 999999 returns nothing from MySQL. Store an empty marker under product:999999 with a 60-second TTL. The next hundred requests for that id are answered from Redis in under a millisecond instead of each running a database query.
323. What is cache avalanche, and how is it different from a stampede?
A cache avalanche is when a large number of cached entries expire at roughly the same time, or the cache service itself goes down, and the flood of requests that used to be absorbed by the cache all land on the database at once. The cause is broad: many keys expire together, a Redis restart, or a cache cluster failure. A cache stampede is narrower: many concurrent requests miss one single popular key at the same time and all reload the same data. The difference is scope — an avalanche is many keys failing at once, a stampede is one key failing under many requests — and the difference in cause matters for the fix. Avalanche prevention is about spreading risk: add random jitter to TTLs so entries do not expire together, warm the cache after a restart before traffic returns, and keep the cache highly available so a single node failure does not empty it. Stampede prevention is about serializing the reload of one key: locking, request coalescing and serving stale values while one request rebuilds. One more distinction interviewers look for: a stampede is triggered by expiry of a hot key even when the cache is healthy, while an avalanche is usually triggered by a mass event such as a deploy that warmed everything at once, or a cache outage.
Example: A deploy at midnight warms ten thousand product entries, all with a 60-minute TTL. At 01:00 they all expire within seconds of each other and the database receives ten thousand reload queries at once — that is an avalanche. If only the single best-selling product's entry expired and a thousand users hit it simultaneously, that would be a stampede.
324. What is a write-through versus write-behind cache consistency trade-off?
Write-through and write-behind differ in when the database is updated, and that timing decides the trade-off between consistency and performance. In write-through, the cache writes to the database synchronously before acknowledging the write, so the cache and the database agree at all times and a cache crash loses nothing — the cost is that every write waits for the database, so write latency is the database's latency. In write-behind, the cache acknowledges the write immediately and flushes it to the database asynchronously, so writes are fast and bursty write traffic is smoothed out — the cost is a window of inconsistency where the cache holds data the database does not yet have, and a cache crash in that window loses writes permanently. The choice follows the data: use write-through where correctness matters more than speed, such as inventory counts or financial records, and write-behind where write volume is high and a small loss window is acceptable, such as analytics counters or activity logs. A practical middle ground is write-through for the critical fields and write-behind for the rest, or cache-aside with explicit invalidation, which avoids the problem entirely by never treating the cache as the system of record. Whichever you choose, the interview point is to name the failure mode — write-through fails slow, write-behind fails by losing data — and say which failure your system can tolerate.
Example: A like counter on a post can use write-behind: losing a handful of likes in a crash is acceptable, and the fast write path matters. A wallet balance must use write-through or no cache at all: acknowledging a balance the database never recorded would be a correctness failure, not a performance trade-off.
Comments
Post a Comment