← All topics

Microservices

Service-to-service communication, Kafka, reliability and observability.

200 questions

Start ▶
Level:
1 What is a microservices architecture, and how is it different from a monolith? In microservices the system is split into several small, separately deployable applications; each one owns its own part of the business and its own data. In a monolith everything is one application and usually sits in one database. Junior 2 A small team is starting a new project. Why is jumping straight into microservices often a mistake? At the start the domain boundaries aren't clear yet, the team is small, and microservice infrastructure (deployment, monitoring, tracing) is expensive. Starting with a well-structured modular monolith and splitting later when needed is usually cheaper. Junior 3 Where should you draw a service boundary: by technical layer or by business capability? By business capability: "orders", "payments", "delivery". Splitting by technical layer (a controller service, a DAO service) forces you to change every service together on each change. Junior 4 What is a bounded context? Explain with a simple example. A bounded context is a boundary within which one model and its terms are used with a single meaning. For example, a "product" in the catalog lives with a description and pictures, while in the warehouse it's only a quantity and a location. Those are two different contexts. Junior 5 What does the "database per service" rule mean? Each service is the sole owner of its data: only it reads and writes its tables. Other services get this data only through its API or its events. Junior 6 What problems come up if two services read and write one shared table directly? The services become tightly coupled through the table structure: if one changes a column, the other breaks on prod. It's unclear who changed which row and why, and independent deployment is lost. Junior 7 What's the difference between synchronous and asynchronous communication between services? In synchronous communication the caller waits for the response (HTTP, gRPC). In asynchronous communication it drops a message to a broker and moves on, and the receiver processes it in its own time (Kafka, RabbitMQ). Junior 8 How do you write an HTTP call from one service to another in Spring Boot 3? Usually you use RestClient (Spring 6.1+) or WebClient, and for a declarative style an @HttpExchange interface or OpenFeign. RestTemplate still works, but RestClient is recommended for new code. Junior 9 What is a message broker, and what problem does it solve in microservices? A broker is a separate system between services that accepts, stores and delivers messages (Kafka, RabbitMQ). It decouples the sender and the receiver in time: even if the receiver is down, the message isn't lost. Junior 10 What's the difference between the queue and topic (publish/subscribe) models? In a queue, each message is taken by only one consumer: the work is divided. In a topic, the message goes to all subscribers: each subscriber group gets its own copy. Junior 11 What's the benefit of putting an API Gateway in front of a mobile app and a frontend, and what work can you give it? An API Gateway is the single entry point for external clients. It routes the request to the right service and does the common work in one place: authentication, rate limiting, CORS, logging. Junior 12 Why do you need service discovery? Can't we just put the IP address in the configuration? In container and cloud environments, service instances keep appearing and disappearing and their IPs change. Service discovery automatically knows their current addresses, so the caller uses only the service name. Junior 13 What's the difference between client-side discovery and server-side discovery? In client-side, the caller gets the list of instances from the registry and does the load balancing itself (Eureka + Spring Cloud LoadBalancer). In server-side, the caller talks to a single address, and a load balancer or the platform picks the instance (a Kubernetes Service, AWS ALB). Junior 14 Where can load balancing happen in microservices? In several places: for traffic coming from outside, at the front load balancer or the gateway; between services, at a Kubernetes Service, a service mesh sidecar, or a client-side balancer inside the caller. Junior 15 What is a timeout, and why should every network call have one? A timeout is a limit on how long to wait for a response. Without it, a slow or hung service ties up the caller's threads indefinitely and eventually brings the caller down too. Junior 16 What is a retry, and in which cases should you not retry? A retry repeats a call a few more times after a transient error. But only for transient errors (timeout, 503) and only for idempotent operations; retrying on 400, 404 or on operations that are dangerous to repeat, like a payment, does harm. Junior 17 What is the circuit breaker pattern, and what does it protect against? When errors pile up, a circuit breaker temporarily stops calls to the problem service and immediately returns an error or a fallback. It saves the caller from waiting for nothing, and the problem service from extra load. Junior 18 How do the closed, open and half-open states of a circuit breaker switch? In closed, calls go through and errors are counted. If the error rate goes above the threshold, it goes to open: calls are rejected immediately. After a set time it goes to half-open: a few trial calls are let through, and if they succeed it goes back to closed, otherwise back to open. Junior 19 What is a fallback? Which fallbacks are good and which are dangerous? A fallback is the backup response returned when the main call fails: a cached value, an empty list, or "try again later". A good fallback doesn't mislead the user; a dangerous one hides the error and presents wrong data as if it were true. Junior 20 What is the bulkhead pattern? A bulkhead splits resources (threads, connections) into separate compartments for different dependencies. That way one slow service can't take all the threads and stop everything else. Junior 21 What is a cascading failure, and how does it start? It's when a problem in one service spreads to the services that call it, and from them to the next ones, until the whole system stops. It often starts with missing timeouts, unlimited retries and shared resources. Junior 22 What is idempotency, and why does it matter especially in microservices? An idempotent operation gives the same result whether it runs once or five times. In microservices it's normal for one request to arrive several times because of retries, network failures and broker redelivery, so you have to be ready for it. Junior 23 How does an idempotency key work? Explain a simple implementation. The client generates a unique key (a UUID, for example) for each logical operation and sends it in a request header. The server stores the key together with the result; if a request with the same key comes again, it returns the stored result without doing the operation again. Junior 24 Why can't `@Transactional` combine changes in two different services into one transaction? @Transactional manages a transaction on one database connection inside one application. Another service is another process and another database; you can't roll back its HTTP call. Junior 25 What is the saga pattern? A saga splits a business operation that touches several services into a sequence of local transactions. Each step commits in its own database; if one step fails, the earlier steps are undone with compensating operations. Junior 26 How does a compensating transaction differ from a plain rollback? A rollback wipes out uncommitted changes without a trace. A compensation undoes an already committed operation with a new, reversing business operation: a trace remains, and it doesn't always restore the "exact previous state". Junior 27 What problem does the outbox pattern solve? It removes the case of "I wrote to the database but the message wasn't sent" (or the other way around). The event is written to a separate outbox table in the database, in the same transaction as the business data, and then a separate process sends it to the broker. Junior 28 What is eventual consistency? How does a user experience it? With eventual consistency, after a change the data in different services doesn't become the same instantly, but within a short time. The user sometimes notices this as "the update showed up a bit later". Junior 29 What is distributed tracing? What do trace ID and span ID mean? Distributed tracing follows the path of a single request through several services. The trace ID is one shared identifier for the whole request; a span ID identifies a single step on that path (a piece of work inside one service, or a single call). Junior 30 How do you link log entries for a single request across different services? Write the trace ID (or a correlation ID) in every log line. In Spring Boot 3, Micrometer Tracing puts it into the MDC, and you can output it in the log pattern; then you search by that ID in the central log system. Junior 31 Why should you collect logs into a central system in microservices? There are many services and they run in many copies, in containers; when a container goes away, the log inside it disappears too. A central system (ELK, Loki, etc.) keeps all the logs in one place and lets you search across them. Junior 32 What's the difference between liveness and readiness probes? Liveness answers "is the process alive, does it need a restart?". Readiness says "is it ready to accept traffic right now?"; if it isn't, the instance isn't killed, only temporarily taken out of the load balancer. Junior 33 What is externalized configuration, and why shouldn't you keep configuration inside the code? Configuration (URLs, limits, feature flags) is kept outside the code: in environment variables, a config server or a Kubernetes ConfigMap. That way a single built artifact runs unchanged in dev, test and prod. Junior 34 Where is the right place to keep secrets like passwords and API keys in microservices? Not in Git and not in application.yml. They live in a dedicated secret store (Vault, a cloud secret manager, a Kubernetes Secret) and are given to the application at startup as an environment variable or a file. Junior 35 What ways are there to version a REST API? The most common are in the URL (/api/v1/orders), in a header (X-API-Version: 2), or in the media type (Accept: application/vnd.shop.v2+json). The URL approach is the simplest and most visible, so it's the one chosen most often in practice. Junior 36 Which API changes are backward compatible, and which break clients? Adding a new optional field or a new endpoint is usually backward compatible. Removing a field, renaming it or changing its type, or making an optional field required breaks old clients. Junior 37 What does "deploy a service independently" require in practice? You must be able to release a new version of a service without coordinating with other services and without redeploying them. That takes backward compatible API changes, no shared database, and a separate build/deploy pipeline. Junior 38 What do Docker containers give you for microservices? A container wraps a service together with its runtime and dependencies into one image. As a result it runs the same in any environment, starts quickly, and orchestrators (Kubernetes) can easily scale or replace it. Junior 39 A request goes through a synchronous chain A → B → C → D. What problems does that have? Latencies add up and availabilities multiply: if each is 99.9% available, the whole chain is about 99.6%. On top of that, a single slow or dead service stops the entire request. Junior 40 What's the difference between an event and a command message? Command / Event — Name: imperative: ReserveStock / past tense: StockReserved; Receiver: one, specific / unknown, zero or many; Can it be rejected: yes ("out of stock") / no, it's a fact that already happened; Coupling: the sender knows the receiver / the sender knows nobody Junior 41 What's wrong in this code, and how does it show up on prod? This is a "dual write": the order goes to the database and the event goes to Kafka, two separate systems. If send succeeds and then the transaction rolls back, an event goes out about an order that doesn't exist; in the opposite case, the event is lost. Strong Junior 42 Can a Kafka consumer receive the same message twice? How do you prepare for it? Yes, in the default "at-least-once" mode that's normal: if the message was processed and the consumer goes down before the offset is committed, or a rebalance happens, the message comes again. The protection is to make the consumer idempotent, for example by storing the IDs of processed messages. Strong Junior 43 Why do you need exponential backoff and jitter in retries? Exponential backoff increases the wait after each attempt (100 ms, 200, 400...), giving a struggling service time to breathe. Jitter adds a random amount to the wait, so hundreds of clients don't retry together at the same instant. Strong Junior 44 If `@Retry` and `@CircuitBreaker` are put on the same method in Resilience4j, in what order do they run, and what does that affect? In the default order, Retry is on the outside and CircuitBreaker on the inside. So each retry passes through the breaker and is counted separately; once the breaker opens, later attempts immediately get a CallNotPermittedException. Strong Junior 45 What's dangerous in this HTTP client configuration? What happens if the payment service hangs? No timeout is configured: SimpleClientHttpRequestFactory waits forever by default. If payment hangs, every request ties up a Tomcat thread forever, and order-service soon stops responding entirely. Strong Junior 46 All services use a shared `common-dto` library. It looks convenient. What are the traps? A shared DTO library ties services together at the code level: adding or changing a field in one class forces every service to move to the new version, often to deploy together. As a result, independence is lost. Strong Junior 47 If the API Gateway validates the JWT, can internal services accept requests with no checks at all? That's risky. If it's possible to bypass the gateway and send requests straight from the internal network, forging any header is easy. Internal services should also validate the token (or at least the identity that comes with mTLS) and do authorization themselves. Strong Junior 48 When does Kafka preserve message order, and when does it break? Order is guaranteed only inside a single partition. If messages belonging to one object (say, one order) are sent with the same key, they land in one partition and are read in order; with no key or with different keys there's no ordering guarantee. Strong Junior 49 The trace ID is passed on HTTP calls, but the trace breaks after a Kafka message or an `@Async` method. Why? The trace context is bound to the thread and passes automatically only through instrumented places. A new thread (@Async, your own ExecutorService) or a Kafka producer/consumer without observation enabled doesn't carry the context over, so a new trace begins. Strong Junior 50 You want to remove a field in a service's internal API. In what order do you proceed so you don't break the services that use it? With "expand and contract": first you add the new variant and keep the old one too, verify the clients have moved to the new one (logs, metrics, contract tests), and only then remove the old field. It all happens in several separate deploys. Strong Junior 51 Why is the list page of `order-service` slow in this code, and how do you fix it? A separate HTTP request goes to customer-service for every order, which is N+1 over the network. 50 orders means 50 calls. The fix: collect the IDs and fetch them through one batch endpoint, or keep the needed field as a local copy. Strong Junior 52 What does "a service must be stateless" mean, and where do you keep the user session? Stateless means an instance doesn't keep user state in its own memory between requests, so any replica can handle any request. If you need a session, it lives inside a JWT or in a shared place like Redis. Strong Junior 53 A service you called returned 404 or 500. What status do you return to your own client? I don't blindly pass through the downstream status code: its 404 often isn't a 404 for my client. I translate the error into my own domain, "not found", "bad request" or "a dependent service is unavailable" (502/503), and return it with a clear response body. Strong Junior 54 Why do you need a startup probe in Kubernetes? What happens without one on a slow-starting Spring Boot service? A startup probe delays the liveness and readiness checks until the application has fully started. Without it, liveness sees a service that takes 70 seconds to come up as "dead" and keeps restarting it before it can finish starting. Strong Junior 55 Why is exposing all Actuator endpoints on prod dangerous? Endpoints like /actuator/heapdump, /env and /configprops can leak passwords, tokens and in-memory data. Only health is exposed to the outside; the rest sit on a separate port or behind authentication. Strong Junior 56 How do you set memory for a Java service running in a container: `-Xmx` or `MaxRAMPercentage`? A modern JVM sees the container limit, so I give the heap relative to the limit with -XX:MaxRAMPercentage, usually 60-75%. The rest is needed for metaspace, thread stacks and direct buffers; if you make the heap equal to the limit, the pod gets OOMKilled. Strong Junior 57 The service you work on depends on 5 more services, PostgreSQL and Kafka. How do you make local development easier? I don't run every service locally. I bring up the infrastructure (DB, Kafka) with Docker Compose or Testcontainers, and replace neighboring services with WireMock stubs or with their version in a shared dev environment. Strong Junior 58 What is meant by a "distributed monolith", and how do you recognize it? It's a system that looks like microservices from the outside but is really tightly coupled: the services can only be deployed together, and if one goes down everything goes down. You pay the price of microservices and don't get the benefits. Strong Junior 59 What is a consumer group in Kafka, and how does the number of partitions in a topic limit the number of consumers? Consumers in one group split the topic's partitions among themselves: each partition goes to one consumer within the group. So a topic with 6 partitions can't be read in parallel by more than 6 consumers in a group; the extras sit idle. Strong Junior 60 How do you generate record IDs in microservices: auto-increment, UUID or something else? Auto-increment works inside a service, but if the ID leaves the service or is needed before the DB write, I choose a UUID, preferably the time-ordered UUIDv7. It's generated without the DB and doesn't wreck the index the way a random UUID does. Strong Junior 61 How do you configure timeouts and error responses in a Spring Cloud OpenFeign client? I set the timeouts per client under spring.cloud.openfeign.client.config.<name>, and I turn 4xx/5xx responses into domain exceptions through my own ErrorDecoder. Middle 62 How do you test client code that depends on another HTTP service? How do you simulate a slow response or a 503? I bring up a real HTTP server with WireMock and point the client at it. That way serialization, headers, timeouts and retries are checked through the real network layer; when you replace the client with a mock bean, none of this gets tested. Middle 63 How do you write an `@HttpExchange` interface client in Spring 6, and how is it different from OpenFeign? I put @GetExchange and @PostExchange on an interface and proxy it through HttpServiceProxyFactory on top of a RestClient or WebClient. It looks like Feign, but it lives in Spring Framework itself and works without Spring Cloud; timeouts and tracing come from the underlying client. Middle 64 If two clients change the same resource at the same time, how do you prevent a "lost update" in a service API? How do ETag and `If-Match` help? I return the resource version in the ETag header, and the client sends it back with If-Match when changing the resource. If the version doesn't match, the service returns 412 Precondition Failed. Internally this ties into optimistic locking with JPA @Version. Middle 65 What are a route, a predicate and a filter in Spring Cloud Gateway? Show how to configure a simple route. A route is a "which request goes where" rule: it consists of an ID, a destination (uri), predicates and filters. A predicate checks whether a request matches the route (path, header, method), and a filter changes the request or response along the way. Middle 66 What is Kafka consumer lag, and how do you monitor it? Lag is the difference between the partition's last offset and the offset the consumer group has committed, meaning the number of messages not yet read. If lag keeps growing, the consumer can't keep up with the write rate; I watch it in a metric and alert on the growth trend. Middle 67 What is a feature flag, and how does it separate deploy from release? A feature flag lets you keep a new feature in the code and turn it on and off through configuration. The code is deployed to prod ahead of time, the feature is enabled for the right users when it's ready, and if there's a problem it's turned off without a redeploy. Middle 68 What is event sourcing, and how is it different from "write to a table, then send an event"? In event sourcing the primary data isn't the current state in a table but the sequence of changes (events). The current state is obtained by replaying the events. In plain CRUD + events, the source of truth is the table, and the event is only a notification. Middle 69 How do the choreography and orchestration variants of a saga differ? In choreography there's no center: each service listens to an event, does its step and emits a new event. In orchestration a single orchestrator service commands the steps in order and manages compensation if something fails. Middle 70 What are the key and headers of a Kafka message for? What metadata do you add to an event? The key chooses the partition: messages with the same key land in one partition and keep their order; in a compacted topic the latest value per key is kept. Headers hold metadata that doesn't mix with the business body: event ID, type, schema version, traceparent. Middle 71 How do you set up distributed tracing in a Spring Boot 3 application, and how does the traceId show up in logs? Add micrometer-tracing-bridge-otel (or Brave) and an exporter, and set the sampling percentage. After that HTTP and Kafka calls are automatically wrapped in spans, and the traceId and spanId go into the MDC. Middle 72 What does generating code from an OpenAPI specification (API-first) give you, and what are the traps? The contract is agreed in openapi.yaml before the code, and DTOs and interfaces are generated from it. This guarantees the client and the server use the same contract, but generator settings, the quality of the generated code and versioning of the specification need separate attention. Middle 73 `order-service` needs the customer's name: do you call `customer-service` each time, or keep a copy of the data yourself? It depends on how fresh that data has to be. For data that rarely changes and does no harm if it's slightly stale, I keep a local copy updated through events; when I need the exact current value (a balance, for example), I call synchronously. Middle 74 What is the bulkhead pattern, and how do the semaphore and thread pool bulkheads in Resilience4j differ? A bulkhead limits the number of parallel calls to a single dependency, so even if it slows down, resources remain for other work. The semaphore variant runs on the current thread and only limits the count, while the thread pool variant runs the call in a separate pool. Middle 75 Why do you need a connection pool for HTTP calls between services, and how do you configure it? Opening a new TCP (and TLS) connection for each request is expensive; a pool reuses connections. But the pool has a limit too: if it's small, requests queue up waiting for a connection. So the maximum connections, the per-host limit and the timeout for waiting for a connection from the pool are set explicitly. Middle 76 What's the problem with the Kafka and HTTP calls in this order-creating method? The Kafka message goes out before the transaction commits. If the commit fails, other services get an event for an order that doesn't exist; if Kafka fails, the event is lost. The fix is an outbox, or at least sending after the commit. Middle 77 How do you pass the user's identity between microservices, and how do services recognize each other? The user's JWT is validated at the gateway and passed on to internal calls, and each service validates it itself as a resource server. For background jobs the service obtains a client credentials token in its own name. Middle 78 How do you do rate limiting at an API gateway, and why must the limit counter live in a shared place? Usually a token bucket algorithm is used: for each key (user, API key, IP) there's a "bucket" that refills at a set rate. The gateway runs in several instances, so the counter has to be in a shared place like Redis. Middle 79 What is consumer-driven contract testing, and how is it different from integration tests? The client service writes the request and response it needs as a contract, and the provider checks in its own CI that it matches that contract. Without bringing up the whole system, the provider catches a change that would break a client right at build time. Middle 80 What is an anti-corruption layer, and when do you add one when integrating with a legacy system or an external API? An anti-corruption layer is a layer that translates an external or legacy system's model into your own domain model. You need it so the external system's names, codes and odd rules don't leak into your code: if something changes on the outside, only this layer changes. Middle 81 If every service in a chain retries 3 times, what happens when the lowest service is failing? The retries multiply: in a four-layer chain, one user request reaches the lowest service as 3^3 = 27 or more requests. A service that's already struggling goes down completely under the load. Strong Middle 82 How do you choose the circuit breaker's sliding window type and thresholds for prod? If traffic is low or uneven, a time-based window is better; if traffic is steady, count-based works too. I set minimumNumberOfCalls and slowCallDurationThreshold from real metrics, otherwise the breaker either opens for nothing or never opens. Strong Middle 83 How do you divide timeouts in a chain of synchronous calls, and what is deadline propagation? Each lower layer's timeout must be smaller than the one above it, otherwise the layers below keep going with work the upper layer has already given up on. Deadline propagation means passing the remaining time budget along with the request, so each service knows how much time it has left. Strong Middle 84 When delivering events from the outbox table to the broker, how do polling and CDC (Debezium) differ? Polling is simple: a scheduler reads the unsent rows from the table and ships them, but it adds extra queries to the database and some delay. CDC reads the transaction log, has low delay and preserves order, but it needs infrastructure like Kafka Connect. Strong Middle 85 What do you do when a compensation step in a saga itself fails? A compensation is retried "until it's done": it must be idempotent and eventually succeed with retries. If it keeps failing, the saga moves to a manual-review state and an alert goes to an operator; it's never silently dropped. Strong Middle 86 What anomalies does the lack of isolation in a saga cause, and how do you reduce them? Saga steps commit separately, so other operations see intermediate states: a reservation that isn't confirmed yet, a payment that will be cancelled later. You reduce this with a semantic lock (PENDING states), rechecking, and ordering the steps correctly. Strong Middle 87 If an old event reaches a consumer after a newer one (a retry, a replay, or from another topic), what do you do so it doesn't overwrite the new data with the old? I add the aggregate version to the event, and the consumer applies only a version greater than the one it has stored. That way a late or repeated event is ignored, and the state doesn't go backward. Strong Middle 88 What do you do when a consumer keeps failing on one "poison" message and the whole partition stalls? You shouldn't retry the message forever: after a few retries it's moved to a dead letter topic and the consumer goes on to the next message. The DLT is monitored, and once the bug is fixed the messages are resent. Strong Middle 89 Why does the retry never fire in this Resilience4j configuration? In the default order, the Retry aspect wraps the CircuitBreaker. Since the CircuitBreaker has a fallback, the error is turned into a normal value inside, so Retry sees a successful response and doesn't retry. Strong Middle 90 If you enable Java 21 virtual threads in a service, what changes in calls between services, and what should you watch out for? With spring.threads.virtual.enabled=true each request runs on a virtual thread, and blocking HTTP/JDBC calls don't tie up a platform thread, so Tomcat's 200-thread limit goes away. But if the resources below aren't limited (the DB pool, the downstream service), you can now overwhelm them. Strong Middle 91 Why is 100% sampling expensive in tracing, and how do head-based and tail-based sampling differ? Creating, sending and storing spans for every request costs network, CPU and storage, and at a high RPS that's a lot of money. Head-based sampling makes the decision randomly at the start of the trace; tail-based sampling waits until the trace finishes and keeps the ones with errors or that were slow. Strong Middle 92 Why do clients get errors by sending requests to an instance that's been shut down during a deploy? The list of instances in the client or load balancer is updated with a delay: the pod is already stopping, but requests are still being sent to it. It's solved with graceful shutdown, a preStop wait, and a retry to another instance on a connection error on the client side. Strong Middle 93 When you change an event schema, what do you watch for so old and new consumers don't break? Events live a long time and consumers are updated at different times, so schema changes must follow compatibility rules. Schema Registry checks the compatibility type (BACKWARD, FORWARD, FULL) and doesn't let a breaking change be written by the producer. Strong Middle 94 An admin panel has to show orders, customer names and payment statuses in one table with filtering and pagination. How do you do it if the data lives in three different services? API composition (querying each service and merging in memory) works at a small scale, but breaks with filtering and pagination on another service's field. In that case I build a separate read model (CQRS) assembled from events. Strong Middle 95 If two requests with the same `Idempotency-Key` arrive at the same time, what do you do so that both don't get executed? "Check first, then execute" is open to a race: both requests fail to see the key and both execute. You have to claim the key atomically before starting the work, with an INSERT under a unique constraint or SET NX in Redis, and the second request gets a 409 or waits. Strong Middle 96 How does a service protect itself when it can't handle the load? Talk about load shedding and backpressure. Load shedding means rejecting requests beyond capacity early and cheaply (503/429), and backpressure means slowing the producer down. The goal: serve the requests within capacity normally, instead of serving everyone slowly and badly. Strong Middle 97 The moment a popular cache key expires, hundreds of requests hit the downstream service at once (a cache stampede). How do you prevent it? At the moment the key is gone, every request goes to the downstream at the same time because it's "not in the cache". To prevent it, only one request reloads the value (coalescing or a lock) while the rest wait or get the stale value; you add jitter to TTLs and refresh hot keys before they expire. Strong Middle 98 How does `@RefreshScope` update configuration without a restart, and what problems can it cause? @RefreshScope beans are served through a proxy; after a refresh event the cached bean is discarded and recreated with the new configuration on the next call. The problems: intermediate states, loss of state inside the bean, and pods being updated at different times. Strong Middle 99 A user updates their profile and, after refreshing the page, sees the old data. How does this happen because of eventual consistency, and how do you solve it? The write goes to one service, while the read comes from a read model or replica updated later through events, so there's a short window in between. The solutions: read from the write source for the user who just wrote, wait by version, or an optimistic update in the UI. Strong Middle 100 When do you choose gRPC instead of REST for calls between internal services, and what are its traps? gRPC is handy when there are many internal calls, a strict contract, streaming or low latency is needed: Protobuf is compact, code is generated, and HTTP/2 carries many requests over one connection. The traps: load balancing, difficulty debugging, and not working directly with browsers. Strong Middle 101 Your HPA is configured on CPU, but when traffic grows the service slows down and almost no pods get added. What could be the cause, and what metric would you scale on? If the service spends its time waiting on I/O (downstream calls, the DB) rather than burning CPU, CPU stays low and the HPA sees nothing, while requests pile up in queues. I scale such a service on a load metric like concurrent requests per pod, RPS or Kafka lag, and I factor in how long a pod takes to become ready. Strong Middle 102 Why is it dangerous to add `userId` or the full URL as a tag on Micrometer metrics? Every unique tag value creates a separate time series. A userId tag with a million users means a million series, and both Prometheus memory and the service's own heap fill up. Tags must come from a small, bounded set: method, status, URI template. Strong Middle 103 What exactly happens in the HALF_OPEN state of a circuit breaker? After the configured time in OPEN, the breaker moves to HALF_OPEN and lets through a limited number of trial requests. If enough of them succeed it goes back to CLOSED, otherwise it goes to OPEN again. Strong Middle 104 What are the RED and USE methods? Which metrics do you put on a service dashboard first? RED is for services that handle requests: Rate (request rate), Errors, Duration (latency distribution). USE is for resources: Utilization, Saturation, Errors. A service dashboard starts with RED, and when you hunt for the cause you drop down to USE: pools, CPU, queues. Strong Middle 105 What are SLI, SLO and error budget, and how do you tie alerts to them? An SLI is a measurable indicator (for example, the share of successful requests faster than 500 ms), an SLO is the target set for it (99.9% over 30 days), and the error budget is the failure you are still allowed (0.1%). I alert on how fast the budget is burning, not on CPU or a single error. Strong Middle 106 What is the risk in this code where @Retry is put on a payment call? Creating a payment is not idempotent: if the first attempt actually went through and the response was lost to a timeout, the retry creates a second payment. Before retrying you need an idempotency key or a status check. Strong Middle 107 What is the difference between a connect timeout and a read timeout, and what happens in prod if you set no timeout at all? The connect timeout is how long you wait for the TCP connection to be established; the read (response) timeout is how long you wait for a response after connecting. Without timeouts, a hung downstream holds your threads forever and the service stops completely. Strong Middle 108 After the service sits idle for a while, the first requests fail with `Connection reset` or `NoHttpResponseException`. What is the cause and how do you fix it? Most often an intermediate load balancer, NAT or the server itself has silently closed the pooled keep-alive connection after its idle timeout, while the client still thinks it is alive and reuses it. The fix: make the client's idle time shorter than the ones in between, evict idle connections, and add a single retry for idempotent requests. Strong Middle 109 The outbox table grows every day and events reach the broker late. What do you check and how do you fix it? This is usually two problems: sent rows are not being deleted (the table and index bloat, polling slows down) and the relay can't keep up with the write rate. A cleanup job, a partial index, batched sending and a relay lag metric are often enough. Strong Middle 110 In which cases does the `OrderPlaced` event get lost or behave unexpectedly in this code? An AFTER_COMMIT listener runs after the commit: if the service dies before sending to Kafka, or the send fails, the event is lost for good while the order is saved. On top of that, a DB write inside the listener is not committed without REQUIRES_NEW. Strong Middle 111 How do you build an idempotent consumer, and is a "processed_messages" table enough? Each message's unique ID is written to a table with a unique constraint, in the same transaction as the business change. If a duplicate arrives, the constraint fails and the message is skipped. But this only protects side effects that take part in the transaction. Strong Middle 112 How do you make an endpoint that receives webhooks from a payment provider reliable and secure? I verify the signature, write the event to the DB first and return 2xx right away, and do the heavy work in the background. The provider may send the same event several times and out of order, so processing is idempotent by event ID. Strong Middle 113 What happens in an orchestration saga if the response to one step never arrives? How do you design saga timeouts? If no response arrives, the saga hangs: the order sits in "waiting for payment" forever and the reserved stock in the warehouse is never released. A deadline for each step is stored in the saga state, and a scheduler finds the expired ones and either resends the step or moves it to compensation. Strong Middle 114 Why is a compensating transaction not a rollback, and what is a pivot step? A compensation "cancels" the effect of an earlier step with a new, separate operation, because the change was already committed and others have seen it. A pivot step is the one after which the saga no longer goes back, it can only complete forward. Strong Middle 115 How do you design temporary stock reservation in a warehouse, and how are unpaid reservations released? A reservation is a separate record: which order, how much, until when. Sellable stock = total − active reservations. A scheduler releases expired reservations, and if the payment goes through the reservation is confirmed. Every operation is idempotent by order ID. Strong Middle 116 Why are messages processed twice in a Kafka consumer during a rebalance, and how do you reduce it? If the consumer processed a message but the partition moved to another consumer before it could commit the offset, the new owner starts from the last committed offset and receives those messages again. Idempotent processing is the main defense, and settings only reduce the probability. Strong Middle 117 How do you choose the Kafka partition key for order events, and what problem does a wrong choice cause? Events whose order matters must share one key, usually the aggregate ID, such as orderId. With no key or the wrong one, OrderCancelled can be processed before OrderCreated; a key that is too "fat" overheats a single partition. Strong Middle 118 A Kafka consumer processes messages slowly. How do you raise parallelism: concurrency, partition count, or a thread pool inside the listener? The main lever is the partition count and a matching concurrency: one partition is processed by one consumer thread at a time. Handing work to your own thread pool inside the listener looks fast, but it breaks offset commits and ordering and can lead to lost messages. Strong Middle 119 Why do you need structured (JSON) logging, and how do you turn it on in Spring Boot 3.4+? A log system parses JSON logs without regexes: filtering and aggregation by fields like traceId, level and orderId work directly. Since Boot 3.4 you turn it on with logging.structured.format.console=ecs (or logstash, gelf), with no extra library. Strong Middle 120 In this code that uses CompletableFuture, why does the traceId disappear from the logs? The trace context is stored in a ThreadLocal. CompletableFuture.supplyAsync runs on another thread of a plain pool, and the context doesn't get passed there. You need an executor that propagates the context. Strong Middle 121 What do you do to keep passwords, tokens or personal data (PII) from ending up in logs? The main defense is at the code level: don't log whole request and response bodies, control the toString() of DTOs, and wrap secret values in a dedicated type. Extra layers are masking in the log pipeline and restricting who can access the logs. Strong Middle 122 In an aggregator endpoint that assembles price, stock and reviews for a product page from different services, how do you handle timeouts and partial responses? I make the calls in parallel and give the whole page one overall deadline. I mark each dependency as required or optional: if the price doesn't arrive it's an error, if the reviews don't arrive I return the response without them and say in the response which part is missing. Strong Middle 123 What is the difference between client-side and server-side service discovery, and what problem does Eureka's self-preservation mode cause? In client-side discovery the client gets the list of instances from the registry and picks one itself (Eureka + Spring Cloud LoadBalancer). In server-side discovery the client talks to a single address and a load balancer or the platform makes the choice. In self-preservation, Eureka may stop removing dead instances from the registry. Strong Middle 124 If you run on Kubernetes, do you need Eureka or Consul? In most cases no: a Kubernetes Service and DNS do the discovery, and kube-proxy does the balancing. You need Eureka when there are services outside the cluster, complex client-side balancing, or several clusters to join together. Strong Middle 125 What happens if you write blocking code in a Spring Cloud Gateway filter? Spring Cloud Gateway (the WebFlux variant) runs on the Netty event loop, and there are very few threads, by default the number of cores (at least 4). A blocking call in one filter (JDBC, RestTemplate, Thread.sleep) stalls the event loop and slows down the whole gateway. Strong Middle 126 In Kubernetes, how do you restrict which service can connect to which? What does NetworkPolicy give you and what doesn't it? By default, any pod in the cluster can connect to any pod. NetworkPolicy gives an allow list at the L3/L4 level by namespace and labels: for example, only payment-service connects to payment-db. It does not cryptographically verify who is calling and does not know the HTTP path. That is the job of mTLS and authorization. Strong Middle 127 What is the BFF (Backend for Frontend) pattern, and how does it differ from a regular API gateway? A BFF is a separate backend layer for each client type (web, mobile), tailored to that client's needs. A gateway handles shared concerns (routing, auth, rate limiting), while a BFF handles assembling data and shaping it for the client. Strong Middle 128 How do Flyway migrations work when several pods start at the same time, and where do you run a long-running migration? Flyway takes a lock in the DB before migrating (an advisory lock in PostgreSQL), so one pod migrates and the others wait, then continue knowing "everything is already applied". But a long migration blocks pod startup and probes may kill it, so I move such work into a separate job or a background backfill. Strong Middle 129 How do you build a Docker image for a Spring Boot service so that it is small, quick to update and secure? I don't copy the fat jar as a single layer: with Boot's layered jar the dependencies go into their own layer, and when the code changes only a small layer is updated. A small JRE base image, a non-root user and a multi-stage build, or Buildpacks, which give you all of that out of the box. Strong Middle 130 Why can adding a new value to an enum in an event or response DTO break old consumers even though it looks backward compatible? By default Jackson throws InvalidFormatException when it sees an unknown enum value. When the producer starts sending status: "ON_HOLD", the old consumer can't parse the message: in Kafka that is a poison message, in HTTP a 500. Consumers must be ready for unknown values, and they must be upgraded first. Strong Middle 131 When an inter-service API returns a large list, what is the difference between offset and cursor (keyset) pagination, and which do you choose? Offset (?page=500&size=50) is simple, but on deep pages the DB still reads the skipped rows, and if the data changes, rows get repeated or dropped. A cursor continues from the last seen key, which is fast and stable. When another service has to read all the data, I pick the cursor. Strong Middle 132 In Avro and Schema Registry, what do the BACKWARD and FORWARD compatibility modes mean, and how do they affect deploy order? BACKWARD means the new schema can read old messages, so consumers are upgraded first. FORWARD means the old schema can read new messages, so the producer is upgraded first. FULL requires both. Strong Middle 133 How do you write an integration test with Testcontainers for a scenario that touches Kafka and PostgreSQL, and what does `@ServiceConnection` give you? The test runs against real PostgreSQL and Kafka containers, so there are no differences like those you get with H2 or embedded Kafka. Since Boot 3.1, @ServiceConnection wires the container address into spring.datasource.* and spring.kafka.* automatically, so you don't have to write @DynamicPropertySource by hand. Strong Middle 134 You routed reads to a read replica to cut the load. What "stale data" bugs show up, and which queries do you keep on the primary? Replication is asynchronous and the replica lags by milliseconds to seconds. A user doesn't see what they just saved, and "check, then write" logic makes wrong decisions. Checks before a write, reads after a write, and everything involving money stay on the primary. Strong Middle 135 How do you keep an Elasticsearch/OpenSearch index for product search in sync with the service's DB, and how do you do a full reindex? The DB is the source of truth and the index is a copy derived from it. I pass changes to an indexing consumer through outbox or CDC events and use versions so an old record can't overwrite a newer one. A full reindex goes into a new index, then the alias is swapped in an instant. Strong Middle 136 Should you add a DB check to liveness and readiness probes? Not to liveness: restarting a pod doesn't fix a missing DB, and all the pods reboot at once. To readiness, carefully: if one shared dependency goes down, all the pods leave traffic and the service doesn't respond at all instead of returning 503. Strong Middle 137 What is a PodDisruptionBudget, and what do you do so your service doesn't go down during a node drain or a cluster upgrade? A PDB limits how many pods can be evicted at the same time during voluntary disruptions (node drain, cluster upgrade, the autoscaler removing a node). But it is only half the protection: if the pods aren't spread across nodes and zones, they all go anyway when one node dies. Strong Middle 138 What do you do when an @Scheduled job fires at the same time on all the service's replicas? @Scheduled runs independently on every instance, so with 3 pods the job runs 3 times. The solutions: a distributed lock (ShedLock), splitting the work by rows with SKIP LOCKED, or moving the job to a separate Kubernetes CronJob. Strong Middle 139 If every instance has a local cache (Caffeine), how do you keep them in sync when the data changes? The simplest way is a short TTL and living with staleness. If you need faster updates, the change event is broadcast to all instances through Kafka or Redis pub/sub and they evict the key. If you need strict accuracy, a local cache is the wrong choice. Strong Middle 140 How do the rate limiting algorithms (fixed window, sliding window and token bucket) differ, and when do you pick which? Fixed window is simple, but at a window boundary it lets through twice the limit in a short time. Sliding window smooths that out. Token bucket limits the average rate while allowing a short burst, and for APIs it is often the most natural choice. Strong Middle 141 Which part of a monolith do you extract into a separate service first, and how do you determine the boundary? First I take a part that is independent from a business point of view and loosely coupled, but changes often or needs to scale separately. I set the boundary by bounded context and data ownership, not by technical layer, and then migrate gradually with a strangler fig. Senior 142 How do you release a new version of a microservice with a canary release, and on which signals do you roll back automatically? I first give the new version a small part of the traffic (1–5%) and compare it with the old version at the same time, on the same metrics: error rate, p99 latency, a business metric. If a threshold is crossed, an automatic rollback; if it looks good, step by step to 25, 50, 100%. Senior 143 Design a fault-tolerant order placement flow involving order, warehouse, payment and delivery services. The order is created in PENDING and the saga starts through the outbox. Every step is idempotent, has a compensation, and is watched with a timeout. Payment is the pivot step, and delivery is the last step, which is only retried. Senior 144 At night one service's p99 latency went up and within a few minutes other services stopped responding too. What could have happened, and how do you prevent it? A classic cascading failure: a slow downstream ties up the callers' thread and connection pools, they slow down too, and it spreads up the chain. Defenses: short timeouts, bulkheads, circuit breakers, bounded queues and load shedding. Senior 145 How do you decide whether service-to-service communication for a new feature should be synchronous or asynchronous? The main question is whether the caller needs the result now, inside this request. If so, synchronous, but with a timeout and a fallback. If not, an event or message: the coupling in time goes away, but you take on eventual consistency, observability and dealing with duplicates. Senior 146 How do you move a table shared by two services to the ownership of a single service with zero downtime? Step by step: first I switch the second service from writing directly to writing through an API, then reads too. If needed I move the data to the new DB with dual writes or CDC and verify by comparing. Each step must be a separate deploy and reversible. Senior 147 You need to make a breaking change in an internal API that many teams use. How do you plan it? First I find out who uses what (logs, tracing, contracts). Then I release the new version in parallel with the old one, add deprecation signals to the old one, watch the consumers migrate, and delete the old one only once its traffic drops to zero. Senior 148 What does Kafka's "exactly-once" guarantee actually cover, and what does it not cover? Through the idempotent producer and transactions, Kafka EOS makes the offset commit and the outgoing messages atomic in a "read from Kafka, write to Kafka" chain. External side effects like writing to a DB, an HTTP call or an email are not part of this guarantee. Senior 149 In a system of 30 services, checkout's p99 latency went up. How do you find the guilty service, and how do you build observability to be ready for cases like this? I start from the SLO alert, then open checkout's slow traces to see which spans took the time, and confirm with the RED metrics and logs of the service I find. For that, every service needs identical metrics, tail sampling and a traceId linked to the logs in place beforehand. Senior 150 What are a retry budget and a hedged request, and what makes them better than the plain "retry 3 times" policy? A retry budget limits retries relative to total traffic, say to no more than 10%, so that when a downstream struggles, retries don't add to the load. A hedged request, instead of waiting for a slow response, sends a parallel request to another replica after a set time and brings p99 down. Senior 151 After every deploy or scale-up, the new pods respond slowly in their first minute and p99 spikes. What is the cause, and how do you get a new Java pod ready for traffic? A new JVM is "cold": code is still interpreted, the JIT hasn't had time to compile, classes aren't loaded, and the connection pool and caches are empty. What helps: warm-up before traffic, slow start on the load balancer, and a CDS/AOT cache that speeds up startup. Senior 152 When the service autoscaled from 4 replicas to 20, the DB fell over with "too many connections". How do you plan connection pool size together with the replica count? Total connections = number of replicas × pool size, and that adds up separately for every service. I calculate it from the DB's max_connections, leaving headroom for admin and migrations; I keep the pool small, tie the HPA's maxReplicas to that calculation, and add a pooler like PgBouncer if needed. Senior 153 How do you plan in advance which system features to switch off (graceful degradation) under load or failure? I split features into tiers by business importance: checkout and payment are protected to the end, while recommendations, reviews and analytics are the first to be switched off. For every second-tier feature, a kill switch and "what do we show when it's missing" are prepared in advance and rehearsed. Senior 154 `order-service` calls `pricing-service`, and `pricing-service` calls `order-service` again to calculate a discount. What problems does this circular dependency cause, and how do you break it? A cycle amplifies failures (both services spend their threads waiting for each other) and makes deploys and changes harder. It usually means the boundary was drawn wrong. Ways to break it: send the needed data in the request itself, copy it with events, or move the responsibility into one service. Senior 155 A bug in a consumer corrupted a read model and it has to be rebuilt from a Kafka topic. How do you plan retention, compaction and the replay process? Replay works only if history is kept in the topic: retention must be long enough or the topic must be compacted. I do the rebuild into a new table with a new consumer group, idempotently and at a speed that doesn't flood prod traffic, then switch reads over in one moment. Senior 156 What is wrong with the following idempotent consumer code, and how do you fix it? The check and the write are separate steps without a transaction: two parallel consumers can both see the same message as "new". The dedup record must be written in the same transaction as the business change, through a unique constraint. Senior 157 How do you make sure money amounts agree between the payment, order and ledger services, and how do you detect differences? Every money movement is stored in the ledger as a double-entry record, immutable and with an idempotency key. For agreement between services I rely not only on real-time guarantees but on regular reconciliation too: the reports of the services and the external provider (bank, PSP) are compared, and differences go to an alert and a review queue. Senior 158 What errors does clock skew between services cause, and how do you make a design tolerant of it? The clocks of different servers differ by milliseconds to seconds. Ordering events by timestamp, "last write wins", JWT exp/nbf checks and lock expiry all go wrong because of it. For ordering, use versions; for expiry, use a single source clock and a small tolerance. Senior 159 How do you design a bulk API that accepts up to 1000 items in one request for other services? How do you return partial success? Every item gets its own result: the response has a status, an error code and the client-sent ID for each one. Whether the whole request should be "all or nothing" is something I state explicitly in the contract. A size limit, idempotency and an asynchronous mode for large volumes are part of the contract too. Senior 160 How do you use traffic mirroring (shadow traffic) to test a rewritten service in prod with real traffic but without affecting users? A copy of the requests is also sent to the new version, and its response is discarded: the user gets only the old version's response. Responses and latency are compared. The biggest risk is side effects: the shadow version must not write to the prod DB, send events or charge money. Senior 161 The platform team has to create a "golden path" (a ready-made template and infrastructure) for new services. What do you put in it, and how do you get teams onto it without forcing them? A golden path is a ready road to ship a new service to prod in one day: a template repo, CI/CD, observability, security and a runbook, all wired up by default. It must not be a mandate but the easiest road: teams choose it for its convenience, and going off it is possible, but at its own price. Staff 162 In an organization with dozens of microservices, how do you choose between a monorepo and a separate repo per service (polyrepo), and what is the hidden cost of each? A monorepo makes atomic changes, single versions and broad refactoring easier, but it requires investment in build tooling, CI time and ownership management. A polyrepo gives independence and simple CI, but shared changes and version sprawl become expensive. The choice is more organizational: how coupled the teams are and how much effort goes into the platform. Staff 163 When do you pick a modular monolith instead of microservices? If the team is small (one or two teams), the domain is still changing, or the platform isn't mature (no CI/CD, observability, on-call): a modular monolith. Microservices solve an organizational scaling problem, not a technical one. Staff 164 A user asked to delete their data, and the data is spread across 15 services, Kafka topics, caches, backups and logs. How do you design this? First you need to know where personal data is: a PII map in the service catalog. Then the deletion request is broadcast as an event, each service deletes or anonymizes its part and returns a confirmation, and a central orchestrator tracks the deadline and status. For immutable places (Kafka, backups) you use crypto-shredding. Staff 165 The analytics team wants to pull the data of all services into the DWH. How do you organize this without turning the services' internal schemas into a contract and without slowing them down? I don't connect analytics straight to service DBs: that turns the internal schema into a hidden contract. Each service provides analytical data under a published data contract, through business events or a CDC stream controlled by the owner, with a schema registry, and ownership stays with the service team. Staff 166 A regulator demands an answer across the whole system to "who changed which data, and when". How do you design an audit log for microservices? An audit log is not an ordinary log: it is an immutable, complete, searchable record. Each service writes its audit event together with the business transaction (through the outbox), and they are gathered in a common format into a central append-only store. To answer "who", the user and service identifiers are propagated along the whole chain. Staff 167 Why do you need a service catalog (for example, Backstage), and what information about each service must it have? When the number of services goes past 30–50, questions like "who owns this service, where are its logs, who does it call" eat incident time. A catalog gathers this information in one place from metadata files that live next to the code. The mandatory minimum: the owner and on-call, lifecycle stage, API contracts, dependencies, and links to the dashboard and runbook. Staff 168 How do you manage the evolution of event schemas in Kafka across dozens of teams? I set up a schema registry (Avro/Protobuf/JSON Schema) with the compatibility mode usually BACKWARD or FULL, and CI checks every schema change against the registry. A breaking change goes only through a new topic or a new event type. Staff 169 How do you choose between event-carried state transfer and "thin" notification events? A thin event carries only "what changed" and the ID, and the consumer asks for the details through an API, so the coupling stays. A fat event brings the full state, the consumer works independently, but the schema is larger and data gets copied. Staff 170 Dozens of teams use a single Kafka cluster. How do you manage topic naming, ownership, permissions, quotas and capacity? Topics are self-service but created as code (GitOps): the naming rule, owner, retention and partition count go through review. Permissions are ACLs so each service gets only the topics it needs, and quotas keep one team from hogging the cluster. Capacity and cost are visible per owner. Staff 171 How do you plan a load test for a microservice system: in which environment, with what data and traffic profile, and how do you judge the result? I start from the goal: which question needs an answer: a capacity limit, readiness for a peak, or a regression. You need scenarios that replay the real traffic mix, data volume close to prod and a suitable environment, and the result is judged not by RPS alone but by SLOs, the saturation point and the first resource to run out. Staff 172 Besides the outbox, what other ways are there to solve the dual write problem, and what does each cost? The options: outbox, "listen to yourself" (first an event, then you update your own DB from that event), event sourcing (the event itself is the source of truth) and CDC. Each one distributes consistency, latency and complexity differently. Staff 173 You are opening a public API for external partners. What do you design differently from an internal service-to-service API? A public API is a commitment that lives for years: you don't control the clients and can't force them to upgrade. So a clear versioning and deprecation policy, strong authentication and quotas, idempotency, a stable error format, webhooks, a sandbox and documentation are part of the contract. I don't expose the internal model directly. Staff 174 How do you decide between doing resilience and mTLS at the library level (Resilience4j, Spring) and a service mesh (Istio, Linkerd)? If all services are Java/Spring and there are dozens of them, libraries are enough and simpler. If you have a multi-language environment, hundreds of services, mandatory mTLS and a centralized traffic policy, a mesh is useful, but it is a complex system in its own right. Staff 175 When do you choose a GraalVM native image for Spring Boot microservices, and what price do you pay? A native image cuts startup from seconds to milliseconds and memory several times over, which is useful for scale-to-zero, serverless, short jobs and dense packing. The price: a long, memory-hungry build, restrictions on reflection and dynamic code, lower peak throughput than the JIT on long-running services, and different debugging. Staff 176 We had this incident in prod. How do you analyze the root cause, and what systemic changes do you propose? This is a cascading failure: a slow dependency was called without a timeout, the threads ran out and it spread up the chain. The fix is timeouts, bulkheads, a circuit breaker, separating health checks from dependencies, and shortening the synchronous chain. Staff 177 By law, citizens' personal data must be stored on servers inside the country, but some services run in a foreign cloud. How do you adapt the architecture? First I map which data is personal and where it flows. Then I separate PII into its own in-country zone, with its own services, DBs, backups and logs, while services abroad work only with IDs or pseudonymous tokens. The places people most often forget are logs, traces, backups and external SaaS tools. Staff 178 One page sends parallel requests to 12 services. Every service's p99 is good, but the page's p99 is bad. Why, and what do you do? In a fan-out the result equals the slowest response: the probability that at least one of 12 services lands in its p99 case is about 11%. So each service's p99 becomes the page's p89. The solution: reduce the fan-out, hedged requests, partial responses and caching. Staff 179 How do you design authentication and authorization between services: passing the user's JWT, token exchange, or mTLS? I separate two questions: "which service is calling" (workload identity, mTLS or client credentials) and "on whose behalf" (the user context). Instead of spreading the external JWT inward unchanged, it's better to issue a short-lived token with a limited audience at the gateway or through token exchange. Staff 180 In a multi-tenant SaaS, how do you ensure tenant isolation across services? The tenant ID is carried from the entry point in a trusted context (a token claim), and every layer has a mandatory filter: in the DB row-level security or a separate schema/DB, in cache keys, topic messages, logs and metrics. The isolation level (shared table, schema, DB) is chosen by risk and cost. Staff 181 What risks come with centrally managed configuration (Spring Cloud Config, ConfigMap, a feature flag service)? Central config is the ability to break every service at once with a single change. So config changes need the same review, versioning, gradual rollout and fast rollback as code. Staff 182 As microservices multiply, how do you organize storing and rotating secrets (DB passwords, API keys)? Secrets are kept not in code or images but in a dedicated secret store (Vault, a cloud secret manager), and a service gets only its own through its identity. Where possible, short-lived dynamic credentials, with rotation automatic, without a restart or with a rolling restart. Staff 183 How do you build an observability strategy for a system with hundreds of services: what do you measure, and how do you control the cost of tracing? The same base for every service: RED metrics (rate, errors, duration), SLOs by user journey, and alerts only on SLO violations. Storing everything in tracing is expensive: start with head sampling and move to tail-based sampling that keeps errors and slow requests. Staff 184 How do you roll out OpenTelemetry as the single standard across dozens of teams on different technologies? First at the platform level: the OTel Collector, shared semantic conventions and W3C trace context. Then for each language the path of least effort: in Java, an agent or the Spring Boot starter, with standard resource attributes. Gradually, starting with the paths where the most expensive incidents come from. Staff 185 An old service must be completely shut down (decommissioned). How do you find out who still uses it, and how do you run the process safely? First I find the real users with data: traces and gateway logs, Kafka consumer groups, DB connections. Then a deprecation announcement, blocking new usage, help with migration, pre-announced "brownout" tests, and only when traffic drops to zero: stop it, archive it and delete it. Staff 186 To deploy services independently, how do you ensure compatibility between versions N and N-1, especially for DB migrations? Every change is split so that during a rolling deploy the old and new versions run at the same time and both must be able to work. In the DB, expand–migrate–contract: first an additive change, then moving data, and removing the old thing only in a later release. Staff 187 What governance do you put in place for internal APIs at the organization level so that it doesn't slow teams down? Not a manual approval committee but automated rules: OpenAPI/Proto files in the repo, linting and breaking-change checks in CI, a single API catalog and a clear deprecation policy. Human review only for new public APIs. Staff 188 Reference data like currency rates, tariffs and the list of branches is needed by dozens of services. Where do you store it and how do you distribute it? Each reference dataset has a single owner who writes and versions it. The others don't call it synchronously on every request; they take it through events or a snapshot and keep a local copy. What matters: when a change takes effect (an effective date) and which version a calculation used are recorded. Staff 189 A microservice system has to run active-active in two regions. What are the main difficulties and how do you solve them? The main problem is data: writing in both regions at the same time leads to conflicts. Usually each record has a "home" region (sharding by user or tenant), cross-region replication is asynchronous, and operations that can't tolerate conflicts are routed to a single region. Staff 190 Every service has its own DB. How do you plan disaster recovery, especially the consistency of data between services? I set an RPO/RTO for every service depending on its business importance, with point-in-time recovery as the basis. You can't restore all services to the same point, so after recovery you need reconciliation that finds and fixes the differences between them. Staff 191 How does Conway's law affect microservice architecture, and how do you structure teams? A system's architecture copies the communication structure of the organization. So you should first pick the architecture you need and then structure the teams to match it (the inverse Conway maneuver): stream-aligned teams by business area, and a platform team that provides shared infrastructure as a service. Staff 192 How do you standardize the error format and error codes in service-to-service calls across the organization? For HTTP APIs I take RFC 9457 ProblemDetail as the common format: a stable, machine-readable type/code, status, detail, and extensions like traceId. The error code catalog is open, whether a retry is possible is stated explicitly, and the format is checked with a linter and contract tests. Staff 193 One service caches another service's data. How do you keep the cache updated and manage the risk of stale data? A TTL is the simplest, but stale data is visible during the TTL. A more accurate way is invalidation or refresh with change events emitted by the data owner, with the TTL remaining as a backup. How much staleness is acceptable is agreed with the business for each piece of data. Staff 194 Only one of several instances should do the work (a scheduler, a leader). How do you build a distributed lock, and why do you need a fencing token? The lock is taken through a DB, Redis or ZooKeeper/etcd, but because of a GC pause or a network partition, an "old owner" whose lock has expired may still be running. A fencing token is a number that increases every time a lock is acquired: the resource rejects a write that arrives with an old token. Staff 195 A service runs a heavy multi-hour batch job every night (calculations, an export), and online traffic slows down meanwhile. How do you separate them? Batch and online load compete for the same resources: pod CPU, the connection pool, the DB and Kafka. I move the batch into a separate deployment or Kubernetes Job with its own pool and limits, and in the DB I route it to a replica or into small, rate-limited chunks. Staff 196 Microservices have driven up infrastructure cost and team load. How do you determine whether services should be merged? Each service's cost (compute, on-call, pipeline, library upgrades) is compared with the benefit it provides (independent deploy, separate scaling, isolation). Services that always change together, belong to one team and don't scale separately are candidates for merging. Staff 197 How do you introduce chaos engineering and game day practice into an organization? I start with small, controlled experiments: a clear hypothesis, a small "blast radius", a stop button and observable metrics. First in staging, then in prod at low traffic. The goal isn't to break the system but to check that the expected resilience really works. Staff 198 How do you design a business process that lasts for days (for example, a loan application: checks, human approval, deadlines) across microservices? I store the process state as a durable workflow: every step, wait and timer is recorded in the DB or in a workflow engine (Temporal, Camunda). Human approval is an external signal, deadlines are durable timers, and the steps are idempotent activities. Staff 199 An external provider like SMS or payments is unreliable. How do you design failover, limits and cost across several providers? I hide the providers behind a single internal interface, each with its own timeout, circuit breaker and quota; routing rules live in configuration. The hardest part is the "unknown outcome": sending an operation that timed out to another provider produces a duplicate, so the failover rule depends on the type of operation. Staff 200 Why is it bad to run an operation that takes several minutes (generating a report, processing a video) through a synchronous API, and what contract do you propose instead? A long synchronous request runs into gateway and client timeouts, ties up a thread and a connection, and if it's cut off, resending creates duplicate work. Better is an asynchronous contract: 202 Accepted and a job resource, with status known through polling, a webhook or SSE. Staff