Learn. Practice. Feel prepared.
50 Microservices Interview Questions for Senior Java Developers
Prepare for senior Java microservices interviews with 50 questions ranging from architectural fundamentals to real production challenges. Explore service boundaries, REST and messaging, distributed data consistency, fault tolerance, Spring Boot security, Kubernetes deployments, and troubleshooting distributed systems.
Top Microservices Interview Questions for Freshers and Experienced
50 Questions
Easy · Medium · Hard
Try answering from memory, then check the reference answer and rate yourself. Your notes are optional and are not automatically graded.
1 What makes a Spring Boot application a microservice rather than simply a small REST application? easy
microservicesspring-bootarchitecture
Reference answer
A microservice is defined primarily by its business responsibility and independent deployment capability, not its code size.
It typically owns a cohesive business capability and exposes explicit interfaces to other services.
A small REST application sharing databases and release cycles with other applications may still be part of a distributed monolith.
Did you know it?
2 Why should microservices generally own their data instead of directly accessing each other's database tables? easy
database-per-servicedata-ownershipcoupling
Reference answer
Data ownership prevents services from becoming tightly coupled to another service's internal schema.
Services communicate through APIs or events, allowing database structures to evolve independently.
For example, an Order Service should request customer information through a contract rather than directly querying Customer Service tables.
Did you know it?
3 When should a Java microservice use synchronous REST communication instead of asynchronous messaging? easy
rest-apiasynchronous-messagingcommunication
Reference answer
Use synchronous communication when the caller needs an immediate response to continue processing.
Use asynchronous messaging when work can be decoupled, buffered, or processed independently.
For example, checking inventory during checkout may require a synchronous response, while sending an order confirmation email can happen asynchronously.
Did you know it?
4 What problem does service discovery solve when multiple instances of a Spring Boot microservice are running? easy
service-discoverykubernetesload-balancing
Reference answer
Service discovery helps clients locate healthy service instances without maintaining fixed instance addresses.
Instances register with a discovery system or are discovered through infrastructure-managed endpoints.
For example, Kubernetes Services provide stable DNS names while routing traffic to eligible application pods.
Did you know it?
5 What is the difference between an API Gateway and a load balancer in a microservices architecture? easy
api-gatewayload-balancingrouting
Reference answer
A load balancer distributes traffic across available backend instances.
An API Gateway provides an application-level entry point that may handle routing, authentication integration, rate limiting, and request transformation.
An API Gateway may use load balancing internally, but the two components solve different architectural concerns.
Did you know it?
6 A Spring Boot microservice becomes temporarily unavailable. How do readiness and liveness probes help? easy
spring-boot-actuatorhealth-checkskubernetes
Reference answer
Readiness indicates whether an instance should receive application traffic, while liveness indicates whether it should be restarted.
An instance can be alive but not ready because it is initializing or temporarily unable to serve requests.
Spring Boot Actuator can expose health endpoints, but probe groups and health indicators must be configured appropriately.
Did you know it?
7 Why are HTTP timeouts important when one Java microservice calls another? easy
http-clienttimeoutsresilience
Reference answer
Timeouts prevent requests from waiting indefinitely when downstream services are slow or unreachable.
Connection timeouts limit connection establishment, while response-related timeouts constrain waiting for data according to client semantics.
Without appropriate limits, blocked requests can exhaust threads, connections, and other resources during failures.
Did you know it?
8 What is the purpose of a correlation ID in a distributed microservices application? easy
correlation-iddistributed-tracinglogging
Reference answer
A correlation ID associates related operations across multiple services for troubleshooting.
It can be propagated through HTTP headers or messaging metadata and included in structured logs.
For distributed tracing, trace IDs and span IDs provide a more structured way to connect operations and their relationships.
Did you know it?
9 What happens when a Spring Boot method annotated with @Transactional makes an HTTP call to another microservice? easy
spring-transactionsdistributed-transactionsconsistency
Reference answer
The annotation manages a transaction for participating local transactional resources, not a distributed transaction across HTTP services.
A remote service may commit successfully even if the caller later rolls back its database transaction.
Cross-service consistency requires an explicit strategy such as a saga, compensation, or reliable event-driven coordination.
Did you know it?
10 Why is centralized configuration useful when deploying the same Spring Boot service to development, staging, and production? easy
spring-bootconfiguration-managementsecrets
Reference answer
Centralized configuration separates environment-specific settings from application binaries.
It helps manage endpoints, feature settings, and operational parameters consistently across deployments.
Secrets should still be protected through appropriate secret-management mechanisms rather than stored as plaintext configuration.
Did you know it?
11 An Order Service calls Payment Service and Inventory Service synchronously. Checkout latency increases whenever Inventory Service slows down. How would you redesign the interaction? medium
service-communicationlatencyasynchronous-processing
Reference answer
First identify which operations must complete before checkout can return a meaningful result.
Use explicit timeouts, concurrency limits, and a bounded critical path for required synchronous operations; move noncritical work to asynchronous processing.
If inventory reservation can complete later, introduce a pending order state and communicate the eventual result rather than pretending checkout is immediately final.
Explain how the business requirement for immediate inventory confirmation influences the architecture.
Did you know it?
12 A client retries POST /orders after a network timeout and creates two orders. How would you prevent duplicate order creation? medium
idempotencyrest-apiduplicate-requests
Reference answer
Support an idempotency key representing one logical order-creation request.
Persist the key and its processing outcome with appropriate uniqueness constraints and atomic state transitions.
A retry with the same key and equivalent request should return the previous outcome; a reused key with different request data should be rejected.
Did you know it?
13 A Spring Boot service experiences cascading failures because a downstream pricing API frequently times out. How would a circuit breaker help? medium
circuit-breakerresilience4jfault-tolerance
Reference answer
A circuit breaker tracks failures and temporarily prevents calls when configured failure conditions are exceeded.
Its open state allows requests to fail quickly or use an appropriate fallback, while a half-open state permits limited recovery checks.
Combine it with timeouts and concurrency limits because a circuit breaker alone does not prevent resource exhaustion.
Did you know it?
14 A Kafka consumer updates an order status and crashes before committing its message offset. What happens after restart? medium
apache-kafkaconsumer-offsetsidempotency
Reference answer
The broker may redeliver the message because the offset was not committed.
If the database update already succeeded, processing the message again can duplicate side effects.
Make the consumer idempotent using event identifiers, conditional updates, or database uniqueness constraints, and coordinate offset handling with processing outcomes.
Did you know it?
15 A product catalog microservice receives ten times its normal read traffic during a sale. How would you scale it without immediately scaling its database? medium
horizontal-scalingcachingperformance
Reference answer
Measure whether the bottleneck is application CPU, database queries, connection limits, or external dependencies.
Use horizontal application scaling and appropriately designed caching for frequently accessed catalog data.
Monitor cache hit rates, database load, and stale-data tolerance because adding service instances alone can increase database pressure.
Did you know it?
16 Two Spring Boot services share a common Java entity library containing JPA entities. Why can this become problematic? medium
jpaservice-couplingdomain-modeling
Reference answer
Sharing persistence entities couples services to a common database model and release lifecycle.
A schema or entity change required by one service may unintentionally affect another.
Share narrowly scoped contract definitions when justified, but keep persistence entities and business rules owned by their respective services.
Did you know it?
17 An authentication service issues RS256-signed JWTs to clients. How should other Spring Boot services validate these tokens? medium
spring-securityjwtrs256
Reference answer
Configure each resource service to validate JWT signatures using trusted public keys and enforce issuer, expiration, and intended audience checks as appropriate.
Spring Security OAuth2 Resource Server can perform signature and claim validation with correctly configured issuer or key-set information.
Authorization still requires checking scopes, roles, or domain permissions; a valid signature alone does not grant access.
Did you know it?
18 A Spring Boot service publishes an OrderCreated event immediately after saving an order, but consumers sometimes receive events for orders that do not exist. What is the likely cause? medium
transactional-outboxspring-transactionsevent-publishing
Reference answer
The event may be published before the database transaction commits, allowing consumers to act on uncommitted or rolled-back data.
Saving an entity does not necessarily mean the enclosing transaction has committed.
Use a transactional outbox or another reliable post-commit publishing design that accounts for publication failures.
Did you know it?
19 An API response changes from a string field to a nested JSON object, breaking older clients. How would you manage the contract evolution? medium
api-versioningbackward-compatibilitycontract-testing
Reference answer
Treat the structural change as potentially incompatible and preserve the existing contract for clients that still depend on it.
Introduce a new field or API version, migrate consumers, and retire the old representation through a documented process.
Consumer-driven contract tests and compatibility checks help detect breaking changes before deployment.
Did you know it?
20 A Java microservice running in Kubernetes repeatedly restarts during startup because database migrations take longer than expected. How would you investigate? medium
kubernetesstartup-probedatabase-migrations
Reference answer
Inspect pod events, termination reasons, application startup logs, and configured probe thresholds.
A liveness probe may be restarting the container before initialization finishes; a startup probe can protect slow initialization.
Also investigate migration duration and consider running database migrations as a controlled deployment step rather than on every application instance.
Did you know it?
21 A customer updates their address, but Order Service continues displaying the previous address from its local cache. How would you handle this consistency issue? medium
cache-invalidationeventual-consistencydata-ownership
Reference answer
Define how fresh the address must be for each business operation before selecting a cache strategy.
Use expiration, explicit invalidation, or customer-change events to refresh cached data.
For legally or operationally critical actions, fetch authoritative data or store a deliberate historical snapshot rather than assuming cached values are current.
Did you know it?
22 A service performs five sequential HTTP calls, each with a two-second timeout. Why might the overall request still violate a three-second latency requirement? medium
latency-budgettimeoutsdistributed-systems
Reference answer
Sequential dependency timeouts can accumulate, producing a much larger end-to-end latency than the client budget.
Connection setup, retries, serialization, and application processing add further delay.
Propagate an overall deadline, allocate bounded per-dependency budgets, and parallelize independent calls where appropriate.
Did you know it?
23 A payment event is delivered to two consumers, and both attempt to update the same account balance. How can concurrent processing be made safe? medium
optimistic-lockingconcurrency-controlevent-processing
Reference answer
Use database-enforced concurrency control such as optimistic locking, conditional updates, or row-level locking where appropriate.
Ensure duplicate events are detected independently of concurrent-update protection.
For example, combine a unique payment-event identifier with an atomic balance update so repeated processing cannot apply the same payment twice.
Did you know it?
24 An API Gateway validates access tokens before forwarding requests. Should downstream services trust every request arriving from the gateway? medium
api-gatewayzero-trustauthorization
Reference answer
No. Gateway validation does not automatically establish the identity or authorization of every downstream request.
Services must protect their trust boundaries using network controls, authenticated service identities, or independently validated credentials as appropriate.
Direct access, misconfigured routing, and compromised internal components must be considered in the security design.
Did you know it?
25 A Spring Boot microservice uses a fixed thread pool of 20 workers to process incoming tasks. During peak traffic, memory usage grows continuously. What should you inspect? medium
thread-poolsbackpressurejava-concurrency
Reference answer
Inspect the executor queue type, queue depth, task arrival rate, and average processing time.
A fixed worker count combined with an unbounded queue can accumulate tasks faster than workers complete them.
Use bounded queues, appropriate rejection or backpressure policies, and workload-specific concurrency limits.
Did you know it?
26 An Order Service publishes events containing the complete customer entity. Why might this create long-term integration problems? medium
event-driven-architectureschema-evolutiondata-privacy
Reference answer
Publishing internal entities exposes fields and structures that may change for reasons unrelated to consumers.
Consumers can become coupled to sensitive data, persistence details, and unnecessary schema changes.
Publish purpose-specific event contracts containing only required information, with explicit schema evolution and data minimization.
Did you know it?
27 A team wants to replace all REST calls between microservices with Kafka events. What architectural concerns would you raise? medium
apache-kafkarest-apiarchitecture-tradeoffs
Reference answer
Event-driven communication can reduce temporal coupling but introduces asynchronous state transitions and delivery semantics.
Operations requiring immediate answers may become unnecessarily complex when modeled entirely through events.
Choose communication patterns per interaction, considering consistency, latency, ordering, operational complexity, and failure recovery.
Did you know it?
28 A microservice has healthy CPU and memory metrics but its API response time suddenly increases. How would you investigate? medium
distributed-tracinglatency-analysisobservability
Reference answer
Compare request latency distributions, distributed traces, database query timings, and downstream dependency metrics.
Check connection-pool waits, thread contention, garbage collection pauses, network latency, and slow external calls.
CPU and memory utilization alone cannot reveal blocking or queueing bottlenecks, so correlate traces with resource and dependency metrics.
Did you know it?
29 A Spring Boot application has two production instances behind Nginx. Users intermittently lose their session after requests reach different instances. What is happening? medium
session-managementredisload-balancing
Reference answer
Session state may be stored only in the memory of the instance that originally handled the user.
Subsequent requests routed to another instance cannot access that local session state.
Use a shared session store such as Redis when server-side sessions are required, or redesign suitable APIs around stateless authentication.
Did you know it?
30 A team deploys a new microservice version and immediately sees errors from older instances communicating with it. How would you make rolling deployments safer? medium
rolling-deploymentbackward-compatibilityrelease-management
Reference answer
Design compatible request, response, and event contracts across versions that may coexist during deployment.
Apply expand-and-contract changes for databases and interfaces, and verify compatibility through integration and contract tests.
Use readiness checks, controlled rollout strategies, and rollback plans without assuming rollback can reverse database changes.
Did you know it?
31 A distributed checkout workflow reserves inventory, charges payment, and creates a shipment. Payment succeeds, but shipment creation fails. Design a recovery strategy without distributed database transactions. hard
saga-patterndistributed-transactionscompensation
Reference answer
Model the workflow as a saga with durable states, explicit success transitions, and compensating actions.
On shipment failure, decide whether to retry fulfillment, release inventory, and refund payment according to business rules.
Compensations can fail or be non-instantaneous, so persist progress, make actions idempotent, and provide reconciliation for unresolved transactions.
Explain why compensation is a business operation rather than a database rollback.
Did you know it?
32 A transactional outbox implementation writes business data and an event into one database transaction. The publisher crashes after sending the event but before marking it delivered. How would you guarantee correct downstream behavior? hard
transactional-outboxdelivery-semanticsidempotency
Reference answer
Assume the event may be published more than once because the publisher cannot atomically commit a database status change with an external broker acknowledgement.
Use stable event IDs, retryable publishing, and idempotent consumers with durable deduplication.
The outbox protects against losing committed events, but end-to-end exactly-once business effects require additional application and storage guarantees.
Did you know it?
33 An inventory microservice uses Redis to cache available stock. Two concurrent orders read the same remaining quantity and both succeed, causing overselling. How would you prevent this? hard
inventory-managementredisrace-conditions
Reference answer
Make stock reservation an atomic operation against an authoritative inventory state, using conditional database updates or appropriately coordinated reservation records.
A normal cache read followed by a separate write cannot safely enforce stock invariants under concurrency.
Redis can accelerate reads or participate in carefully designed atomic reservation logic, but persistence, failure recovery, and reconciliation remain necessary.
Did you know it?
34 A Java service makes requests to three downstream systems. During an outage, automatic retries increase traffic until all services become unstable. How would you redesign the retry strategy? hard
retry-stormexponential-backoffcircuit-breaker
Reference answer
Apply retries only to failures that are likely transient and to operations that are safe to repeat.
Use bounded attempts, exponential backoff with jitter, deadline awareness, and retry budgets; avoid multiplying retries across every dependency layer.
Combine these with circuit breakers, bulkheads, and overload signals so recovery traffic does not overwhelm unhealthy services.
Did you know it?
35 A Spring Boot service validates JWTs using a remote JWKS endpoint. The authentication server becomes unavailable during public-key rotation. How would you maintain security and availability? hard
jwksjwt-key-rotationspring-security
Reference answer
Cache previously validated public keys and plan overlapping key validity periods so existing tokens remain verifiable during rotation.
Publish new verification keys before issuing tokens signed with them, and retain old keys until relevant tokens expire.
Unknown signing keys must not be trusted merely because the JWKS endpoint is unavailable; define secure failure behavior and operational recovery procedures.
Did you know it?
36 A payment processing microservice consumes Kafka events and writes to MySQL. The team enables Kafka exactly-once processing and assumes duplicate charges are impossible. What is wrong with this assumption? hard
kafka-transactionsexactly-once-semanticspayment-processing
Reference answer
Kafka transactional processing does not automatically make an external MySQL update or payment-provider call part of the same atomic transaction.
A crash between the external side effect and Kafka transaction completion can cause the operation to be attempted again.
Use business-level idempotency keys, durable processing records, and reconciliation to prevent duplicate financial effects.
Did you know it?
37 A Spring Boot application uses @Transactional and @Async on a workflow that saves an order and sends a notification. Occasionally the notification thread cannot find the newly created order. Explain the failure and redesign. hard
spring-asynctransaction-boundariesevent-publishing
Reference answer
The asynchronous operation may run on another thread and database transaction before the original transaction commits.
Spring transaction context does not automatically propagate across arbitrary asynchronous thread boundaries.
Publish work through a transactional outbox for reliable delivery, or use an after-commit listener when its weaker delivery guarantees are acceptable.
Did you know it?
38 A product search API aggregates information from five microservices. One dependency frequently fails, but the product page should remain partially usable. How would you design graceful degradation? hard
graceful-degradationapi-aggregationfault-tolerance
Reference answer
Classify each dependency as essential or optional and define which partial results remain valid for users.
Apply independent timeouts, bounded concurrency, and selective fallbacks such as cached ratings or omitted recommendations.
Expose partial-data freshness or availability clearly, and avoid returning misleading success for missing critical information such as authoritative pricing.
Did you know it?
39 A microservice system experiences inconsistent customer records after processing events from multiple Kafka partitions. How would you reason about ordering and consistency? hard
kafka-partitioningevent-orderingversioning
Reference answer
Kafka preserves record order within an individual partition, not a total order across all partitions.
Use a stable customer identifier as the partition key when per-customer ordering is required, and handle producer concurrency and retries appropriately.
Include entity versions or sequence numbers so consumers can reject stale updates and detect gaps where business correctness requires it.
Did you know it?
40 A Java microservice uses HikariCP with a maximum pool size of 30. Under load, requests time out waiting for database connections even though MySQL CPU utilization is low. How would you diagnose the problem? hard
hikaricpconnection-poolingmysql
Reference answer
Inspect active, idle, and pending connection counts along with transaction duration and connection acquisition time.
Look for leaked connections, long transactions, blocked SQL statements, slow network operations inside transactions, and excessive concurrent requests.
Fix connection retention and query behavior before increasing pool size, because larger pools may worsen contention or exceed database connection capacity.
Did you know it?
41 You must migrate a large monolithic Java application to microservices while maintaining production availability. How would you choose extraction boundaries and migration order? hard
strangler-patterndomain-driven-designmonolith-migration
Reference answer
Identify business capabilities, data ownership, dependency relationships, and areas with independent change or scaling requirements.
Use an incremental strangler approach, extracting bounded capabilities behind stable interfaces while keeping old and new paths operational during transition.
Avoid splitting tightly coupled database operations prematurely; measure migration risk, operational overhead, and whether each extraction improves autonomy.
Did you know it?
42 A production service has a 99th-percentile latency spike after moving from synchronous Spring MVC calls to a reactive WebClient implementation. What would you investigate? hard
spring-webfluxwebclientevent-loop
Reference answer
Inspect event-loop blocking, connection-pool saturation, pending connection queues, downstream latency, and reactive pipeline concurrency.
Blocking JDBC calls or CPU-intensive work executed on event-loop threads can reduce responsiveness despite using a reactive HTTP client.
Use appropriate schedulers for unavoidable blocking work, enforce concurrency limits, and compare end-to-end measurements rather than assuming reactive code is automatically faster.
Did you know it?
43 A distributed workflow requires customers to see their latest order immediately, but order search uses an asynchronously updated Elasticsearch index. How would you provide read-your-writes behavior? hard
cqrselasticsearchread-your-writes
Reference answer
Do not assume an asynchronously maintained search index reflects a committed database write immediately.
Return the committed order directly from the authoritative service or provide a version-aware read path until the index catches up.
Use Elasticsearch for search and discovery while defining explicit freshness guarantees for operations requiring immediate consistency.
Did you know it?
44 A Kubernetes Horizontal Pod Autoscaler adds application replicas, but throughput barely improves and database failures increase. How would you identify the scaling limit? hard
kubernetes-hpadatabase-bottleneckcapacity-planning
Reference answer
Measure throughput, queueing, database connections, lock contention, and downstream saturation as replica counts increase.
Horizontal scaling of stateless application instances cannot overcome a shared database or dependency bottleneck.
Control aggregate concurrency, optimize database access, introduce suitable caching or partitioning, and select autoscaling signals that reflect useful capacity.
Did you know it?
45 An internal microservice accepts an X-User-Id header forwarded by the API Gateway to determine the authenticated user. What security weakness does this introduce, and how would you fix it? hard
identity-propagationheader-spoofingservice-security
Reference answer
The header can become an identity-spoofing vulnerability if callers can reach the service directly or inject an untrusted value.
Establish a trusted gateway-to-service channel, strip client-supplied identity headers, and authenticate the component asserting identity.
Alternatively, propagate a properly scoped signed token and validate its issuer, audience, signature, and authorization claims at the receiving service.
Did you know it?
46 A microservice deployment introduces a new non-null database column. Old and new application versions must run simultaneously during a rolling update. How would you execute the schema migration? hard
database-migrationexpand-contractrolling-deployment
Reference answer
Use an expand-and-contract migration that keeps the database compatible with both application versions during rollout.
First add a compatible nullable column or safe default, deploy code that handles both representations, and backfill existing records.
Enforce the final non-null constraint only after data is complete and all active writers satisfy the new requirement.
Did you know it?
47 A Spring Boot microservice runs scheduled jobs on three replicas, causing the same billing task to execute three times. How would you guarantee that only one valid billing operation is applied? hard
distributed-lockingscheduled-jobsidempotency
Reference answer
Coordinate scheduling through a single designated worker, a distributed lease, or a durable job queue with competing consumers.
A distributed lock reduces concurrent execution but does not eliminate duplicate effects during crashes, lease expiry, or network partitions.
Protect billing with durable idempotency keys and database-enforced state transitions; use fencing tokens where stale lock holders could corrupt shared state.
Did you know it?
48 A distributed trace shows that Service A takes 900 ms, while its downstream Service B takes only 100 ms. How would you locate the missing 800 ms? hard
opentelemetrydistributed-tracinglatency-debugging
Reference answer
Inspect span boundaries and determine whether the unexplained time occurs before the downstream call, during connection acquisition, or after the response.
Investigate thread-pool queues, serialization, authentication filters, database access, connection waits, and uninstrumented work.
Add targeted spans and correlate them with thread dumps and metrics rather than assuming downstream execution time equals total client-call latency.
Did you know it?
49 A service must handle 10,000 requests per second while calling a downstream API limited to 2,000 requests per second. How would you prevent overload without losing important work? hard
rate-limitingbackpressureload-shedding
Reference answer
Enforce admission control and rate limits based on the downstream system's sustainable capacity rather than accepting unlimited concurrent calls.
Queue durable asynchronous work where business requirements permit, with bounded backlog, prioritization, and explicit retry or expiry policies.
For synchronous requests, apply backpressure and return appropriate overload responses; use caching or batching only when they preserve correctness.
Did you know it?
50 A company operates 15 Spring Boot microservices and wants centralized authentication, independent authorization, and secure service-to-service communication. How would you design the security architecture? hard
oauth2spring-securityservice-to-service-auth
Reference answer
Use a trusted identity provider or authorization server to issue appropriately scoped tokens, with each resource service enforcing its own authorization rules.
Validate token signatures, issuer, audience, expiration, and permissions at trust boundaries; use service identities and suitable credentials for machine-to-machine communication.
Centralize identity and policy management where useful, but preserve domain-specific authorization, key rotation, least privilege, auditability, and resilience to identity-provider outages.
Distinguish user authentication, service authentication, token validation, and domain authorization.
Did you know it?
0 / 0 answered