Knowing Java, Spring Boot, Microservices, and AWS is not enough to become a senior backend engineer.
In real-world projects, senior developers are expected to investigate production issues, understand framework internals, identify performance bottlenecks, design distributed systems, and make architectural decisions under different constraints.
Interviewers increasingly use scenario-based questions to understand how candidates approach problems rather than simply checking whether they remember annotations, definitions, or syntax.
In this article, we will explore 20 advanced scenario-based interview questions covering Core Java, concurrency, JVM internals, Spring Boot, Spring Security, Kafka, Microservices, distributed systems, and AWS.
Each question includes a practical scenario, an explanation of the underlying problem, possible solutions, and important production considerations.
A Spring Boot application is running normally in production. Suddenly, CPU utilization increases from 30% to 95%. However, the incoming request volume remains almost the same.
The application is still responding, but response times are increasing and some requests are timing out.
High CPU usage does not always indicate increased traffic. It can be caused by inefficient application code, excessive garbage collection, thread contention, or background processing.
Common reasons include:
First, identify which process is consuming CPU.
top -H -p <PID>
This displays individual threads and helps identify which threads are consuming the most CPU.
Next, capture a thread dump:
jstack <PID> > thread-dump.txt
Convert the high-CPU thread ID from decimal to hexadecimal and search for it in the thread dump.
For deeper analysis, use Java Flight Recorder:
jcmd <PID> JFR.start duration=60s filename=cpu-analysis.jfr
Analyze the recording using Java Mission Control to identify hot methods, CPU-intensive operations, allocation patterns, and thread activity.
Never assume high CPU is caused by increased traffic. Always identify the actual CPU-consuming threads and methods before applying a fix.
A Java application maintains shared user session information using a ConcurrentHashMap. Multiple threads update and read the map simultaneously.
The application works correctly for individual put and get operations, but an issue appears when multiple operations must be performed together.
ConcurrentHashMap provides thread-safe operations without requiring developers to synchronize the entire map.
In modern Java implementations, it uses a combination of:
For example:
ConcurrentHashMap<String, Integer> counters =
new ConcurrentHashMap<>();
counters.put("JAVA", 10);
Integer value = counters.get("JAVA");
Multiple threads can safely execute these individual operations.
Consider the following code:
if (!counters.containsKey("JAVA")) {
counters.put("JAVA", 1);
}
Although each map operation is thread-safe, the complete check-and-update sequence is not atomic.
Two threads can both observe that the key does not exist and then attempt to insert it.
Use atomic methods provided by ConcurrentHashMap.
counters.putIfAbsent("JAVA", 1);
For counters, use compute or merge:
counters.merge("JAVA", 1, Integer::sum);
Another option is:
counters.compute("JAVA", (key, value) ->
value == null ? 1 : value + 1
);
ConcurrentHashMap does not automatically make a sequence of multiple map operations atomic. It also does not provide a general-purpose transaction mechanism across multiple keys.
If an operation involves several shared objects or business invariants, additional synchronization or a different concurrency design may be necessary.
Production lesson:Thread-safe collections protect individual operations. They do not automatically guarantee thread safety for the complete business workflow.
A Spring Boot application receives thousands of concurrent requests. Many requests spend most of their time waiting for database queries, external API responses, or other network operations.
The application uses a traditional thread-per-request model. Eventually, the thread count increases, memory consumption grows, and the application starts experiencing latency.
Platform threads are relatively expensive operating-system-backed threads. Creating too many threads increases memory consumption and scheduling overhead.
When a request spends most of its time waiting for I/O, the associated platform thread may remain blocked even though it is not actively using the CPU.
Java 21 introduced virtual threads as a permanent feature.
Virtual threads are lightweight threads managed by the Java runtime. They allow applications to support large numbers of concurrent tasks without creating an equivalent number of operating-system threads.
try (var executor =
Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10000; i++) {
executor.submit(() -> {
callExternalService();
});
}
}
Spring Boot applications can also enable virtual threads through configuration when using a compatible Java and Spring Boot version.
spring.threads.virtual.enabled=true
For example, having 10,000 virtual threads does not mean your database can efficiently process 10,000 simultaneous connections.
Production lesson:Virtual threads reduce the cost of concurrency, but they do not remove the limits of databases, networks, external services, or CPU resources.
A Spring Boot application initially uses 1 GB of memory. After running for several days, memory consumption continuously increases.
Restarting the application temporarily resolves the problem, but memory usage starts increasing again.
Memory retention occurs when objects remain reachable even though the application no longer needs them.
Common causes include:
public class UserContext {
private static final ThreadLocal<String> USER =
new ThreadLocal<>();
public static void setUser(String user) {
USER.set(user);
}
public static String getUser() {
return USER.get();
}
}
In a thread pool, worker threads are reused. If ThreadLocal values are not removed, they can remain associated with those long-lived threads.
try {
USER.set("user123");
processRequest();
} finally {
USER.remove();
}
For static collections, introduce explicit lifecycle management, bounded storage, and appropriate eviction policies.
Capture a heap dump:
jcmd <PID> GC.heap_dump heapdump.hprof
Analyze it using Eclipse MAT or another heap analysis tool.
Look for:
A memory leak in Java does not always mean memory was allocated incorrectly. It often means objects are still reachable when they should no longer be retained.
A Spring Boot application requires custom initialization logic after a bean is created. Another requirement is to modify or wrap beans before they are injected into other components.
The developer needs to understand where to implement this logic in the Spring bean lifecycle.
Spring manages bean creation, dependency injection, initialization, post-processing, and destruction.
A simplified lifecycle looks like this:
One option is @PostConstruct:
@Component
public class CacheService {
@PostConstruct
public void initialize() {
System.out.println("Initializing cache");
}
}
Other options include InitializingBean:
@Component
public class CacheService implements InitializingBean {
@Override
public void afterPropertiesSet() {
System.out.println("Bean initialized");
}
}
You can also configure an initialization method using @Bean.
@Bean(initMethod = "initialize")
public CacheService cacheService() {
return new CacheService();
}
BeanFactoryPostProcessor: Works with bean definitions before regular bean instantiation. It is useful when modifying bean metadata.
BeanPostProcessor: Works with bean instances before and after initialization. It is commonly used for wrapping beans, creating proxies, and applying framework-level behavior.
Spring uses proxies for several features, including transaction management and method-level security. A BeanPostProcessor can participate in wrapping beans with proxies.
Production lesson:Choose the correct lifecycle extension point. Use initialization callbacks for bean setup, BeanFactoryPostProcessor for bean definitions, and BeanPostProcessor for bean instance customization.
A service method is annotated with @Transactional. During execution, an exception occurs, but the database changes are still committed.
The developer expects the entire transaction to roll back.
Spring's default transaction rollback behavior does not roll back for every exception type.
By default, Spring rolls back transactions when an unchecked RuntimeException or an Error is thrown. Checked exceptions do not trigger rollback by default.
@Transactional
public void createOrder() throws Exception {
orderRepository.save(new Order());
throw new Exception("Order processing failed");
}
The checked exception does not automatically trigger rollback under the default rules.
Use rollbackFor when checked exceptions should trigger rollback.
@Transactional(rollbackFor = Exception.class)
public void createOrder() throws Exception {
orderRepository.save(new Order());
throw new Exception("Order processing failed");
}
1. Self-invocation: Spring's proxy-based transaction management may not apply when a transactional method is called from another method within the same object.
public void process() {
saveOrder();
}
@Transactional
public void saveOrder() {
orderRepository.save(new Order());
}
If process() invokes saveOrder() directly on the same instance, the call may bypass the Spring proxy.
2. Exception handling: If an exception is caught and swallowed inside the transactional method, Spring may see a normal method return.
@Transactional
public void createOrder() {
try {
orderRepository.save(new Order());
processPayment();
} catch (Exception ex) {
log.error("Processing failed", ex);
}
}
3. Transaction propagation: Review propagation settings and determine whether operations are running in separate transactions.
4. Transaction boundaries: Verify that the method is invoked through the Spring proxy and that the correct transaction manager is being used.
5. Asynchronous execution: Transactions do not automatically propagate to a different thread when work is executed asynchronously.
Production lesson:When a transaction commits unexpectedly, investigate rollback rules, proxy boundaries, exception handling, propagation, and thread boundaries before changing database configuration.
A company operates multiple microservices. User permissions are stored centrally and can change at runtime.
For example, an administrator removes a user's access to a particular operation. The change must take effect across all services without requiring the user to log in again or waiting for a long-lived token to expire.
JWT tokens commonly contain roles or permissions as claims. These claims are generally evaluated using the token's contents.
If permissions change after a token is issued, the token may continue to contain outdated authorization information until it expires.
Separate authentication from authorization.
A centralized authorization service can manage permissions and expose policy evaluation capabilities to multiple services.
Each service can enforce authorization using Spring Security.
@PreAuthorize(
"@permissionService.hasPermission(authentication, 'ORDER_READ')"
)
public Order getOrder(Long orderId) {
return orderRepository.findById(orderId)
.orElseThrow();
}
Several approaches are possible:
Calling a central authorization service for every request can introduce latency and create another dependency.
Local caching improves performance but introduces a consistency delay. For sensitive operations, use stricter validation or fail-closed behavior when authorization cannot be established.
Tenant-level access must also be enforced in the service and data-access layers, not only at the API gateway.
Production lesson:Authentication tokens establish identity, but dynamic authorization requires a strategy for permission freshness, cache invalidation, and consistent enforcement across services.
A Spring Boot application experiences intermittent API timeouts. The database is available, and CPU utilization is normal.
However, requests sometimes wait several seconds before database operations begin.
Spring Boot applications commonly use HikariCP as the JDBC connection pool.
The pool has a limited number of database connections. When all connections are in use, new requests must wait until a connection becomes available.
Common reasons include:
Monitor HikariCP metrics:
For example, if the maximum pool size is 20 and all 20 connections are active while additional requests are waiting, the application may be experiencing pool exhaustion.
Review the HikariCP configuration:
spring:
datasource:
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
These values are examples, not universal recommendations. The correct pool size depends on database capacity, query duration, application concurrency, and the number of application instances.
Also:
HikariCP's leakDetectionThreshold can help identify connections held longer than expected. It is a diagnostic feature, not a replacement for fixing the underlying issue.
Production lesson:Increasing the connection pool size is not always the solution. A larger pool can overload the database and make the problem worse.
An e-commerce platform has separate services for orders, payments, inventory, and shipping.
When a customer places an order, several services must perform related operations. If payment succeeds but inventory reservation fails, the system must handle the inconsistent state.
Each microservice owns its database. A normal local database transaction cannot automatically cover multiple independent databases.
Distributed transactions using two-phase commit can introduce coordination overhead and tighter coupling. Many microservices architectures prefer eventual consistency.
Use the Saga pattern.
A saga breaks a business transaction into a sequence of local transactions. If a step fails, previously completed steps can be compensated.
Example workflow:
Suppose payment succeeds, but inventory reservation fails.
The workflow can initiate a compensation action that refunds the payment and marks the order as failed.
Choreography: Services communicate through events. Each service reacts to events and publishes its own events.
Orchestration: A central coordinator manages the workflow and decides which step should execute next.
Distributed consistency is not achieved by simply calling multiple services sequentially. It requires explicit workflow management, idempotency, failure handling, and compensation strategies.
A Kafka topic contains order events consumed by multiple services.
The Order Service introduces a new field called deliveryType. Some consumers have already been upgraded, while older consumers are still running.
The deployment must not break existing consumers.
Kafka stores events independently of the application version that produced them.
Different consumer versions may read the same event. A schema change that is incompatible with older consumers can cause deserialization failures or incorrect processing.
Use a schema format and compatibility strategy such as Avro, Protobuf, or JSON Schema with a schema registry.
Prefer backward-compatible changes, such as adding an optional field with a default value where the schema format supports it.
Example:
{
"orderId": "ORD-1001",
"customerId": "CUST-101",
"deliveryType": "EXPRESS"
}
Use a dead-letter topic or queue for events that cannot be processed, and establish a controlled replay strategy.
Production lesson:Kafka schema evolution must account for multiple producer and consumer versions running simultaneously. Compatibility should be designed before deployment, not after deserialization failures occur.
An Order Service saves an order in its database and then publishes an OrderCreated event to Kafka.
Sometimes the database transaction succeeds, but Kafka publishing fails. In another situation, the Kafka message is published, but the database transaction rolls back.
The database and Kafka are separate systems. A normal database transaction does not automatically make the database update and Kafka publish one atomic operation.
This is commonly known as the dual-write problem.
@Transactional
public void createOrder(Order order) {
orderRepository.save(order);
kafkaTemplate.send(
"order-events",
new OrderCreatedEvent(order.getId())
);
}
The database and Kafka operations have separate failure and transaction boundaries.
Instead of publishing directly to Kafka inside the business method, save the business data and an event record in the same database transaction.
@Transactional
public void createOrder(Order order) {
orderRepository.save(order);
OutboxEvent event = new OutboxEvent(
"ORDER_CREATED",
order.getId().toString()
);
outboxRepository.save(event);
}
A separate publisher reads the outbox table and publishes pending events to Kafka.
The publisher can use polling or Change Data Capture (CDC) tools to detect new outbox records.
The outbox record remains available for another publishing attempt.
However, duplicate messages are possible. For example, Kafka may accept a message while the publisher fails before recording that it was published.
Therefore, consumers should be idempotent and use event identifiers to prevent duplicate business processing.
Production lesson:The Transactional Outbox pattern solves the database-and-message dual-write problem by storing both the business update and the event record in one local transaction. Reliable delivery still requires retries and idempotent consumers.
A Kafka consumer application processes order events. Over time, consumer lag increases continuously.
CPU utilization is normal, and database queries are performing well. Increasing the number of consumers does not immediately resolve the problem.
Consumer lag represents the difference between the latest available offset in a partition and the offset processed or committed by a consumer group.
Increasing lag means the consumer group is falling behind the producers.
First, inspect consumer group lag by partition:
kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group order-consumer-group
Look for partitions with significantly higher lag than others.
Then investigate:
Adding consumers alone will not increase useful parallelism beyond the available partitions for a consumer group.
Production lesson:Consumer lag is a symptom, not a root cause. Analyze lag by partition and correlate it with processing time, rebalances, offset commits, and broker metrics.
An Order Service depends on Payment, Inventory, and Customer services.
The Payment Service becomes slow. Requests start waiting for payment responses, application threads remain occupied, and other services begin experiencing timeouts.
Eventually, the entire platform becomes unstable.
In a distributed system, failures can propagate through service dependencies.
If a downstream service becomes slow, upstream services may continue sending requests and waiting for responses.
This can exhaust threads, connection pools, and other resources, turning a small failure into a platform-wide outage.
A circuit breaker temporarily stops calls to an unhealthy service after failures cross a configured threshold.
It typically has three states:
Set appropriate connection and response timeouts. Never allow requests to wait indefinitely.
Retry only appropriate failures. Use exponential backoff and jitter to avoid overwhelming an already unhealthy service.
Separate resources for different downstream dependencies so that one failing service cannot consume all available threads or connections.
Limit incoming traffic and reject excess requests when the system reaches its safe operating capacity.
Where business rules permit, return cached data, a degraded response, or an asynchronous processing response.
Production lesson:A resilient microservices architecture must assume that downstream services will become slow or unavailable. Timeouts, circuit breakers, bulkheads, and controlled retries prevent failures from spreading.
A SaaS platform provides APIs to multiple enterprise customers. Each customer has different permissions, usage limits, and service access requirements.
The platform needs a common entry point for authentication, routing, rate limiting, and tenant-level controls.
Identify the tenant using a trusted identity claim or another securely validated tenant identifier.
Maintain usage counters by tenant, API, or other relevant dimensions.
For example:
Tenant A:
Requests per minute: 1000
Tenant B:
Requests per minute: 500
Tenant C:
Requests per minute: 100
A distributed rate limiter backed by Redis can help maintain shared counters across multiple gateway instances.
The gateway can perform authentication and coarse-grained access checks. However, backend services must still enforce business-level authorization.
For example, an Order Service must verify that the authenticated tenant is allowed to access the requested order. It should not trust a tenant ID supplied directly by an untrusted request header.
An API gateway provides a common entry point, but tenant isolation and business authorization must also be enforced inside the services that own the data.
A Spring Boot application supports an important business workflow. The business requires the application to remain available even if an Availability Zone becomes unavailable.
The application must also scale when traffic increases.
Deploy multiple application instances across at least two Availability Zones.
A typical architecture could include:
Users access the application through the load balancer. The load balancer distributes requests across healthy application instances running in different Availability Zones.
If an instance becomes unhealthy, health checks help remove it from normal traffic distribution.
RDS Multi-AZ improves database availability through standby or failover capabilities, depending on the deployment configuration. It is not a replacement for backups or a complete disaster recovery strategy.
Production lesson:High availability is not achieved simply by running multiple Spring Boot instances. The database, networking, dependencies, deployment process, and recovery procedures must also be designed for failure.
An organization runs several Java workloads:
The team must select suitable AWS compute services.
Amazon ECS is a managed container orchestration service. It is suitable when an organization wants to run containerized applications without managing a Kubernetes control plane.
It is a good option for Spring Boot microservices packaged as Docker containers.
Amazon EKS is a managed Kubernetes service.
Choose it when the organization requires Kubernetes APIs, ecosystem tools, portability, advanced orchestration capabilities, or an existing Kubernetes operating model.
However, Kubernetes introduces additional operational complexity around cluster management, networking, security, upgrades, and observability.
AWS Lambda is useful for event-driven and short-lived workloads.
Examples include:
For Java applications, consider startup time, cold starts, memory allocation, execution limits, and workload duration.
Amazon EC2 provides virtual machines with greater control over the operating system and runtime environment.
It may be suitable when applications require custom operating-system configuration, specialized agents, or deployment patterns that do not fit container or serverless models.
| Service | Suitable workloads | Important consideration |
|---|---|---|
| ECS | Containerized microservices | Simpler container orchestration |
| EKS | Kubernetes-based platforms | More operational complexity |
| Lambda | Event-driven short-lived tasks | Execution and runtime constraints |
| EC2 | Custom server workloads | More infrastructure management |
There is no single best AWS compute service for every Java application. Choose based on workload characteristics, operational requirements, scaling behavior, and team expertise.
A Spring Boot service running on AWS needs to access S3, SQS, and other AWS services.
The developer currently stores AWS access keys and secret keys in application configuration.
The organization wants to eliminate long-lived credentials from application code and configuration files.
Static credentials can accidentally be exposed through source control, container images, logs, or deployment configuration.
They are also difficult to rotate safely across multiple environments and services.
Use IAM roles associated with the compute environment.
The AWS SDK can obtain temporary credentials through the standard credential provider chain.
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
var credentialsProvider =
DefaultCredentialsProvider.create();
For communication between application services, use an appropriate authentication mechanism such as OAuth2 client credentials, mutual TLS, or a service identity system.
For AWS API requests, use IAM permissions and AWS Signature Version 4 where required by the service.
Never embed long-lived AWS access keys in application configuration. Prefer workload identity and temporary credentials with narrowly scoped permissions.
An e-commerce platform needs to process order events asynchronously.
When an order is created, multiple independent operations must happen, including sending notifications, updating analytics, and starting fulfillment.
The architecture must support retries and prevent one failing consumer from affecting other consumers.
A possible architecture is:
Amazon SQS: Provides message queues that decouple producers and consumers. It supports asynchronous processing, visibility timeouts, and dead-letter queues.
Amazon SNS: Supports pub/sub messaging and fan-out delivery to multiple subscribers.
Amazon EventBridge: Provides event routing using rules and event patterns. It is useful when different consumers need selected events based on their content.
AWS Lambda: Executes code in response to supported event sources, including SQS messages and EventBridge events.
For reliable publishing from a service that also updates a database, consider combining this architecture with the Transactional Outbox pattern.
Production lesson:Event-driven architecture improves decoupling, but reliability still depends on retries, idempotency, dead-letter handling, monitoring, and clear ownership of events.
A Spring Boot application currently stores a customer's full name in a single database column called full_name.
A new release requires separate first_name and last_name columns.
The application must continue serving requests during deployment, and old and new application versions may run simultaneously.
If the database schema changes before the application is ready, the old application version may fail.
If the new application version is deployed before the database supports its expected schema, the new version may also fail.
The database and application deployment must therefore be compatible across multiple release stages.
Use the expand-and-contract migration strategy.
Add the new columns without removing the existing column.
ALTER TABLE customer
ADD COLUMN first_name VARCHAR(100);
ALTER TABLE customer
ADD COLUMN last_name VARCHAR(100);
Update the application to support both the old and new schema during the transition.
For example, new writes can populate the new columns while maintaining the old representation as required by older application instances.
Populate the new columns for existing records using a controlled migration process.
Validate the results before changing application behavior.
Deploy a version that reads from the new columns after confirming that the data is available and consistent.
Only after all old application versions have been removed and compatibility is no longer required should the old column be considered for removal.
Zero-downtime database deployments require application and schema compatibility across releases. Avoid combining destructive database changes with application deployment in a single step.
A production microservices platform experiences intermittent failures.
Some requests take several seconds to complete, while others fail with timeouts. The same operations work correctly in development and testing environments.
Restarting services temporarily reduces the errors, but the problem eventually returns.
Microservices distribute a single business request across multiple services, databases, queues, and external dependencies.
A failure may originate in one service but appear as a timeout or error in another.
Without proper observability, it is difficult to understand the complete request execution path.
Use OpenTelemetry or another distributed tracing solution to follow a request across multiple services.
Trace IDs and span IDs help correlate individual operations and identify where latency is introduced.
For example, a request may spend:
This makes it easier to identify the slow dependency instead of assuming the entire application is slow.
Use metrics to understand system behavior over time.
Important metrics include:
Use the RED method for services:
The USE method can also help investigate infrastructure resources:
Use structured logging and include correlation identifiers.
log.info(
"Order processing started. orderId={}, traceId={}",
orderId,
traceId
);
Centralized logging makes it easier to correlate events across multiple services.
Investigate infrastructure-level metrics as well as application metrics.
When the evidence points to a JVM issue, capture thread dumps, heap dumps, and Java Flight Recorder data where safe and appropriate.
Investigate deadlocks, blocked threads, garbage collection pauses, memory retention, and CPU-intensive methods.
Compare failures against deployment timestamps, configuration changes, traffic patterns, feature flags, and infrastructure events.
Look for patterns such as failures occurring only during peak traffic, after a particular deployment, or when a specific downstream dependency becomes slow.
Production lesson:Production troubleshooting should be evidence-driven. Distributed traces identify where a request spends time, metrics reveal system behavior, logs provide execution details, and infrastructure telemetry exposes resource-level problems.
Before considering yourself ready for senior-level Java and microservices interviews, make sure you can confidently discuss the following areas:
Yes. These questions cover Java internals, Spring Boot, concurrency, distributed systems, Kafka, AWS, system design, and production troubleshooting. They are suitable for experienced backend developers preparing for senior-level interviews.
Focus on both. Understand how the technology works internally, but also be prepared to explain how you would investigate and resolve a real production issue.
Java concurrency, JVM troubleshooting, Spring transaction management, database performance, Kafka, distributed transactions, resilience patterns, security, and system design are important areas to prepare.
Start by clarifying the problem and identifying the symptoms. Explain possible root causes, describe how you would collect evidence, discuss the solution, and mention trade-offs and production risks.
Senior Java developer interviews are not just about knowing Spring Boot annotations, Java syntax, or AWS services.
They are about understanding how systems behave under real production conditions.
A strong senior developer should be able to investigate JVM performance issues, design concurrent applications, understand transaction boundaries, build resilient microservices, manage distributed data consistency, and operate applications reliably in the cloud.
More importantly, they should be able to explain why a particular solution is appropriate and what trade-offs it introduces.
Senior developers are not defined by how many technologies they know.
They are defined by how well they understand system internals, architectural trade-offs, scalability, and production failures.
Which question would you find the hardest?
Looking for more Java, Spring Boot, Microservices, Cloud, and System Design interview questions?
Explore more practical Java and software engineering articles at LogicBrace.
0 Comments