Java, Spring Boot, Microservices & AWS – 20 Advanced Scenario-Based Interview Questions for Senior Developers


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.

1. How would you investigate a Java application experiencing high CPU usage even though its request volume has not increased?

Scenario:

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.

Why does this happen?

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:

  • Infinite loops or unexpectedly long-running loops.
  • Excessive object creation causing frequent garbage collection.
  • Regular expressions with catastrophic backtracking.
  • High CPU consumption from serialization or deserialization.
  • Lock contention causing excessive thread activity.
  • Background scheduled jobs processing large datasets.
  • Unexpected retry loops.

How would you investigate it?

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.

How should you fix it?

  • Optimize CPU-intensive methods.
  • Remove unnecessary object creation.
  • Fix inefficient loops and regular expressions.
  • Investigate excessive garbage collection.
  • Review scheduled jobs and background workers.
  • Use profiling data to identify the actual bottleneck before changing thread pool sizes.
Production lesson:

Never assume high CPU is caused by increased traffic. Always identify the actual CPU-consuming threads and methods before applying a fix.

2. How does ConcurrentHashMap achieve thread safety internally, and what are its limitations when multiple operations must be atomic?

Scenario:

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.

How does ConcurrentHashMap work internally?

ConcurrentHashMap provides thread-safe operations without requiring developers to synchronize the entire map.

In modern Java implementations, it uses a combination of:

  • CAS (Compare-And-Swap) operations.
  • Volatile reads and writes.
  • Synchronized blocks for updates to individual bins when necessary.
  • Coordinated resizing and tree-based bins for handling collisions.

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.

Where can problems occur?

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.

How should you fix 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
);

Important limitation

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.

3. How would you design a highly concurrent Java application that processes thousands of requests without exhausting platform threads?

Scenario:

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.

Why does this happen?

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.

How do virtual threads help?

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

What should you consider?

  • Virtual threads are useful for I/O-bound workloads.
  • They do not automatically improve CPU-bound processing.
  • Database connection pools still have limited capacity.
  • External APIs may impose concurrency limits.
  • Unbounded task creation can still overwhelm downstream systems.
  • Use backpressure, rate limiting, and bounded resource pools.

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.

4. How would you identify and resolve memory retention issues caused by ThreadLocal, static collections, or improperly managed object references?

Scenario:

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.

Why does this happen?

Memory retention occurs when objects remain reachable even though the application no longer needs them.

Common causes include:

  • ThreadLocal values that are never removed.
  • Static collections retaining unnecessary objects.
  • Listeners and callbacks that are never unregistered.
  • Unbounded caches.
  • Collections that continuously accumulate data.
  • Long-lived objects retaining large object graphs.

Example: ThreadLocal memory retention

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.

How should you fix it?

try {
    USER.set("user123");

    processRequest();

} finally {
    USER.remove();
}

For static collections, introduce explicit lifecycle management, bounded storage, and appropriate eviction policies.

How would you investigate it?

Capture a heap dump:

jcmd <PID> GC.heap_dump heapdump.hprof

Analyze it using Eclipse MAT or another heap analysis tool.

Look for:

  • Objects with unexpectedly large retained heap.
  • Collections with continuously increasing sizes.
  • Unexpected GC root references.
  • ThreadLocalMap entries retaining application objects.
  • Static fields holding large object graphs.
Production lesson:

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.

5. How does Spring's bean lifecycle work internally, and where would you implement custom initialization and post-processing logic?

Scenario:

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.

How does the Spring bean lifecycle work?

Spring manages bean creation, dependency injection, initialization, post-processing, and destruction.

A simplified lifecycle looks like this:

  1. Spring reads bean definitions.
  2. BeanFactoryPostProcessor implementations can modify bean definitions.
  3. Spring instantiates the bean.
  4. Dependencies are injected.
  5. Aware callbacks are invoked where applicable.
  6. BeanPostProcessor runs before initialization.
  7. Initialization callbacks are executed.
  8. BeanPostProcessor runs after initialization.
  9. The bean is available for use.
  10. Destruction callbacks execute when the container shuts down, where applicable.

How would you implement initialization logic?

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();
}

What is the difference between BeanFactoryPostProcessor and BeanPostProcessor?

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.

What about Spring proxies?

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.

6. How would you troubleshoot a Spring Boot application where transactions appear to commit even though an exception is thrown?

Scenario:

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.

Why does this happen?

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.

Example

@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.

How should you fix it?

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");
}

What else should you investigate?

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.

7. How would you design dynamic authorization in Spring Security when permissions can change at runtime across multiple services?

Scenario:

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.

Why is this challenging?

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.

How would you design the solution?

Separate authentication from authorization.

  • Authentication verifies the identity of the user.
  • Authorization determines whether the user can perform a specific operation.

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();
}

How can you handle permission changes?

Several approaches are possible:

  • Use short-lived access tokens to reduce the lifetime of stale claims.
  • Use token introspection for centrally validated tokens.
  • Maintain a permission cache with a short TTL.
  • Publish permission-change events to invalidate cached authorization data.
  • Use a centralized policy engine for fine-grained authorization.

What should you consider?

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.

8. How would you investigate intermittent latency caused by database connection pool exhaustion in a Spring Boot application?

Scenario:

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.

Why does this happen?

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:

  • Slow SQL queries.
  • Long-running transactions.
  • Connections not being released correctly.
  • Database locks and blocking queries.
  • Too many concurrent requests.
  • Connection pool configuration that does not match the workload.

How would you investigate it?

Monitor HikariCP metrics:

  • Active connections.
  • Idle connections.
  • Maximum connections.
  • Pending connection requests.
  • Connection acquisition time.

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.

How should you fix it?

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:

  • Optimize slow queries.
  • Keep transaction boundaries as short as possible.
  • Avoid making external API calls while holding database connections.
  • Investigate connection leaks.
  • Review database locks and execution plans.
  • Size connection pools across all application instances, not just one instance.

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.

9. How would you design a microservices architecture that maintains consistency when a business transaction spans multiple databases?

Scenario:

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.

Why is this challenging?

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.

How would you solve it?

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:

  1. Order Service creates an order with PENDING status.
  2. Payment Service processes the payment.
  3. Inventory Service reserves the required items.
  4. Shipping Service creates a shipment.
  5. Order Service marks the order as CONFIRMED.

What happens when a step fails?

Suppose payment succeeds, but inventory reservation fails.

The workflow can initiate a compensation action that refunds the payment and marks the order as failed.

Orchestration vs choreography

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.

Important production considerations

  • Make operations idempotent.
  • Handle duplicate events.
  • Define compensation actions.
  • Track workflow state.
  • Handle timeouts and retries.
  • Use an outbox pattern where reliable event publishing is required.
Production lesson:

Distributed consistency is not achieved by simply calling multiple services sequentially. It requires explicit workflow management, idempotency, failure handling, and compensation strategies.

10. How would you handle schema evolution in Kafka when multiple consumer versions process the same events?

Scenario:

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.

Why is this challenging?

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.

How should you manage schema evolution?

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"
}

What should you avoid?

  • Removing fields that older consumers require.
  • Changing a field's data type without a migration strategy.
  • Changing field meaning while keeping the same field name.
  • Deploying producers and consumers with incompatible assumptions.

How should you deploy schema changes?

  1. Introduce a compatible schema change.
  2. Deploy consumers that can handle both old and new events.
  3. Deploy producers that start publishing the new field.
  4. Monitor consumer errors and processing behavior.
  5. Remove obsolete fields only after all consumers have migrated and compatibility requirements are satisfied.

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.

11. How would you guarantee reliable event publishing when a service must update its database and publish a Kafka message?

Scenario:

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.

Why does this happen?

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.

Why is the following approach unsafe?

@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.

How does the Transactional Outbox pattern solve this?

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.

What happens if publishing fails?

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.

12. How would you troubleshoot increasing Kafka consumer lag when CPU utilization and database performance appear normal?

Scenario:

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.

What is Kafka consumer lag?

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.

What could cause it?

  • Slow message processing.
  • Long-running external API calls.
  • Frequent consumer rebalances.
  • Uneven partition distribution.
  • One partition receiving significantly more traffic than others.
  • Messages that repeatedly fail processing.
  • Incorrect offset commit behavior.
  • Network or broker-related issues.

How would you investigate it?

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:

  • Message processing time.
  • Consumer poll frequency.
  • Partition assignment.
  • Rebalance frequency.
  • Offset commit failures.
  • Producer throughput versus consumer throughput.
  • Broker fetch latency and network activity.

How should you fix it?

  • Optimize slow message-processing logic.
  • Increase consumer parallelism where partition count permits.
  • Review partition key distribution.
  • Move slow external operations to controlled asynchronous processing where appropriate.
  • Handle poison messages without blocking an entire partition indefinitely.
  • Review max.poll.interval.ms and related consumer settings.
  • Monitor rebalance events and processing duration.

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.

13. How would you prevent cascading failures when several microservices depend on the same unstable downstream service?

Scenario:

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.

Why does this happen?

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.

How should you prevent it?

1. Circuit breaker

A circuit breaker temporarily stops calls to an unhealthy service after failures cross a configured threshold.

It typically has three states:

  • Closed: Requests are allowed.
  • Open: Requests are rejected or handled through a fallback.
  • Half-open: A limited number of requests test whether the service has recovered.

2. Timeout

Set appropriate connection and response timeouts. Never allow requests to wait indefinitely.

3. Retry with backoff

Retry only appropriate failures. Use exponential backoff and jitter to avoid overwhelming an already unhealthy service.

4. Bulkhead

Separate resources for different downstream dependencies so that one failing service cannot consume all available threads or connections.

5. Rate limiting and load shedding

Limit incoming traffic and reject excess requests when the system reaches its safe operating capacity.

6. Fallback strategies

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.

14. How would you design an API gateway strategy for authentication, rate limiting, routing, and tenant-level isolation?

Scenario:

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.

What should the API gateway handle?

  • Request routing to backend services.
  • Authentication token validation.
  • Rate limiting and request throttling.
  • TLS termination.
  • Request and response transformations where appropriate.
  • Correlation IDs and basic request telemetry.
  • Tenant-aware quotas and API usage controls.

How would you implement tenant-level rate limiting?

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.

How should authorization work?

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.

How do you prevent tenant data leakage?

  • Validate tenant identity from trusted authentication context.
  • Apply tenant filters in data-access operations.
  • Use tenant-aware cache keys.
  • Enforce tenant isolation in asynchronous event processing.
  • Include tenant identity in audit logs and tracing context.
  • Test authorization boundaries between tenants.
Production lesson:

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.

15. How would you architect a highly available Spring Boot application on AWS across multiple Availability Zones?

Scenario:

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.

How would you design the architecture?

Deploy multiple application instances across at least two Availability Zones.

A typical architecture could include:

  • Amazon Route 53 for DNS routing.
  • Application Load Balancer for request distribution.
  • Amazon ECS or EKS for running application containers.
  • Private subnets for application workloads.
  • Amazon RDS Multi-AZ for database availability.
  • Amazon ElastiCache for distributed caching where required.
  • Amazon SQS or Kafka for asynchronous processing.
  • Amazon CloudWatch for monitoring and alerting.
  • AWS Secrets Manager for sensitive configuration.

How does traffic flow?

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.

How should the application be designed?

  • Keep application instances stateless where possible.
  • Store shared session data outside individual instances.
  • Configure health checks and graceful shutdown.
  • Use autoscaling based on suitable workload metrics.
  • Ensure database connectivity and failover behavior are tested.
  • Use retries carefully when database failover occurs.
  • Configure backups and test restoration procedures.

What is an important distinction?

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.

16. How would you choose between ECS, EKS, Lambda, and EC2 for deploying different types of Java workloads?

Scenario:

An organization runs several Java workloads:

  • A long-running Spring Boot REST API.
  • A collection of containerized microservices.
  • A short-lived event-processing function.
  • A legacy application that requires operating-system-level customization.

The team must select suitable AWS compute services.

When would you choose ECS?

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.

When would you choose EKS?

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.

When would you choose Lambda?

AWS Lambda is useful for event-driven and short-lived workloads.

Examples include:

  • Processing SQS messages.
  • Responding to EventBridge events.
  • Handling lightweight background tasks.
  • Executing scheduled operations.

For Java applications, consider startup time, cold starts, memory allocation, execution limits, and workload duration.

When would you choose EC2?

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.

How would you compare them?

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
Production lesson:

There is no single best AWS compute service for every Java application. Choose based on workload characteristics, operational requirements, scaling behavior, and team expertise.

17. How would you securely manage service-to-service authentication and AWS permissions without embedding credentials in application configuration?

Scenario:

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.

Why is this a security risk?

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.

How should you manage AWS permissions?

Use IAM roles associated with the compute environment.

  • EC2 applications can use instance profiles.
  • ECS tasks can use task IAM roles.
  • EKS workloads can use EKS Pod Identity or IAM Roles for Service Accounts, depending on the cluster configuration.
  • Lambda functions can use execution roles.

The AWS SDK can obtain temporary credentials through the standard credential provider chain.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;

var credentialsProvider =
        DefaultCredentialsProvider.create();

What about service-to-service authentication?

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.

What should you consider?

  • Apply least-privilege IAM policies.
  • Use temporary credentials instead of long-lived access keys.
  • Store application secrets in AWS Secrets Manager or an appropriate secret store.
  • Rotate secrets where applicable.
  • Audit role usage and access patterns.
  • Separate IAM roles between services and environments.
Production lesson:

Never embed long-lived AWS access keys in application configuration. Prefer workload identity and temporary credentials with narrowly scoped permissions.

18. How would you design an event-driven architecture using AWS SQS, SNS, EventBridge, and Lambda for reliable asynchronous processing?

Scenario:

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.

How would you design it?

A possible architecture is:

  1. Order Service creates the order.
  2. The service publishes an order event.
  3. Amazon SNS distributes the event to multiple subscribers.
  4. Each subscriber can use its own SQS queue.
  5. Lambda functions or containerized consumers process messages from the queues.
  6. Failed messages are moved to dead-letter queues after the configured retry policy is exhausted.

What is the role of each AWS service?

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.

How do you handle failures?

  • Configure appropriate retry behavior.
  • Use dead-letter queues for repeatedly failing messages.
  • Set visibility timeouts according to processing duration.
  • Make consumers idempotent.
  • Monitor queue depth and message age.
  • Use FIFO queues when ordering or deduplication requirements justify them.
  • Implement controlled replay of failed messages.

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.

19. How would you implement zero-downtime deployments when application releases involve backward-incompatible database changes?

Scenario:

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.

Why is this challenging?

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.

How should you solve it?

Use the expand-and-contract migration strategy.

Step 1: Expand the database schema

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);

Step 2: Deploy a backward-compatible application version

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.

Step 3: Backfill existing data

Populate the new columns for existing records using a controlled migration process.

Validate the results before changing application behavior.

Step 4: Switch application reads

Deploy a version that reads from the new columns after confirming that the data is available and consistent.

Step 5: Contract the schema

Only after all old application versions have been removed and compatibility is no longer required should the old column be considered for removal.

What else should you consider?

  • Use backward-compatible database migrations.
  • Make migration scripts safe to rerun where practical.
  • Monitor errors during each deployment stage.
  • Plan rollback and recovery procedures.
  • Avoid destructive schema changes during the initial rollout.
  • Test old and new application versions against the transitional schema.
Production lesson:

Zero-downtime database deployments require application and schema compatibility across releases. Avoid combining destructive database changes with application deployment in a single step.

20. A microservices platform experiences intermittent production failures that cannot be reproduced in lower environments. How would you approach root-cause analysis using distributed tracing, metrics, logs, and infrastructure telemetry?

Scenario:

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.

Why is this difficult to investigate?

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.

How would you investigate it?

1. Distributed tracing

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:

  • 50 ms in the API Gateway.
  • 100 ms in the Order Service.
  • 3,000 ms waiting for the Payment Service.
  • 200 ms in the database.

This makes it easier to identify the slow dependency instead of assuming the entire application is slow.

2. Metrics

Use metrics to understand system behavior over time.

Important metrics include:

  • Request rate.
  • Error rate.
  • Response latency, including percentiles such as p95 and p99.
  • CPU and memory utilization.
  • Garbage collection activity.
  • Thread pool utilization.
  • Database connection pool metrics.
  • Kafka consumer lag.
  • Queue depth and message age.

Use the RED method for services:

  • Rate: Number of requests.
  • Errors: Number or percentage of failed requests.
  • Duration: Request processing time.

The USE method can also help investigate infrastructure resources:

  • Utilization: How much of a resource is being used.
  • Saturation: How much work is waiting.
  • Errors: Resource-related failures.

3. Centralized logging

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.

4. Infrastructure telemetry

Investigate infrastructure-level metrics as well as application metrics.

  • Container restarts and memory limits.
  • Pod scheduling and resource throttling.
  • Network errors and connection resets.
  • Load balancer response codes.
  • Database CPU, locks, and connections.
  • Storage latency and I/O saturation.
  • Deployment and configuration changes.

5. JVM diagnostics

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.

6. Correlate failures with changes

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.

Senior Java Developer Production Readiness Checklist

Before considering yourself ready for senior-level Java and microservices interviews, make sure you can confidently discuss the following areas:

  • JVM memory management, garbage collection, and CPU profiling.
  • Java concurrency, thread safety, and virtual threads.
  • ConcurrentHashMap internals and atomic operations.
  • Memory leaks and object retention.
  • Spring bean lifecycle and proxy-based features.
  • Spring transaction management and propagation.
  • Dynamic authorization with Spring Security.
  • HikariCP connection pool tuning.
  • Distributed transactions and the Saga pattern.
  • Kafka schema evolution and consumer lag.
  • Transactional Outbox and reliable event publishing.
  • Circuit breakers, bulkheads, timeouts, and retries.
  • API gateway design and tenant isolation.
  • AWS high availability and compute choices.
  • IAM roles, workload identity, and secrets management.
  • SQS, SNS, EventBridge, and Lambda.
  • Zero-downtime application and database deployments.
  • Distributed tracing, metrics, and centralized logging.

Frequently Asked Questions

1. Are these questions suitable for senior Java developers?

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.

2. Should I focus on theory or practical implementation?

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.

3. Which topics are most important for Java microservices interviews?

Java concurrency, JVM troubleshooting, Spring transaction management, database performance, Kafka, distributed transactions, resilience patterns, security, and system design are important areas to prepare.

4. How should I answer scenario-based interview questions?

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.

Conclusion

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?

Interview Preparation Resources

Looking for more Java, Spring Boot, Microservices, Cloud, and System Design interview questions?

Explore more practical Java and software engineering articles at LogicBrace.



Post a Comment

0 Comments

Close Menu