Skip to content

Java Solution Architect Interview Questions & Answers

40 questions for Java Solution Architect interviews — 1 easy, 17 medium, 22 hard.

About the Java Solution Architect role

A Java solution architect designs the overall structure of enterprise systems built on Java and Spring. They choose service boundaries, integration patterns, data stores, security models and cloud deployment, and they guide multiple teams to follow consistent standards. The role needs years of hands-on Java experience plus strong communication with business stakeholders and clients. They also review designs, estimate effort and manage technical risk on projects.

Microservice architecture Cloud (AWS or Azure) Design patterns Security Stakeholder communication
Solved for this roleStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the difference between composition and inheritance, and which should you prefer?

Save to ▾
Show answer
Inheritance is an is-a relation where the subclass reuses parent code, but it creates tight coupling and fragile hierarchies. Composition is a has-a relation where a class holds another object and delegates work, such as a Car having an Engine. Prefer composition because it is flexible, allows changing behaviour at runtime and is easier to test. Use inheritance only for a true is-a relationship.
02

Run two tasks in parallel with CompletableFuture and combine their results.

Save to ▾
Show answer
Use a dedicated executor for I/O work. ExecutorService pool = Executors.newFixedThreadPool(4); CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> userApi.get(id), pool); CompletableFuture<List<Order>> orders = CompletableFuture.supplyAsync(() -> orderApi.list(id), pool); Profile p = user.thenCombine(orders, Profile::new) .orTimeout(2, TimeUnit.SECONDS) .join();
03

Write a record with validation in its compact constructor.

Save to ▾
Show answer
A compact constructor runs before fields are assigned. public record Money(String currency, long paise) { public Money { Objects.requireNonNull(currency); if (paise < 0) { throw new IllegalArgumentException("negative amount"); } } public Money add(Money o) { return new Money(currency, paise + o.paise); } } Storing money in paise as long avoids floating point errors.
04

How would you write a simple thread safe rate limiter in Java?

Save to ▾
Show answer
A token bucket with synchronized refill is simple and correct. class RateLimiter { private final long capacity, refillPerSec; private double tokens; private long last = System.nanoTime(); RateLimiter(long cap, long rps) { capacity = cap; refillPerSec = rps; tokens = cap; } synchronized boolean tryAcquire() { long now = System.nanoTime(); tokens = Math.min(capacity, tokens + (now - last) / 1e9 * refillPerSec); last = now; if (tokens >= 1) { tokens--; return true; } return false; } } Across servers, keep the bucket in Redis.
05

What is a deadlock and how can it be prevented?

Save to ▾
Show answer
A deadlock happens when two or more threads each hold a lock and wait for a lock held by the other, so none can continue. It needs mutual exclusion, hold and wait, no preemption and circular wait. Prevent it by always acquiring locks in the same global order, using tryLock with a timeout, holding locks briefly and avoiding calls to unknown code while holding a lock.
06

A deep inheritance hierarchy of six levels is hard to change. How would you refactor it?

Save to ▾
Show answer
I would identify which behaviours actually vary and pull them into small interfaces, then replace inheritance with composition where a class holds strategy objects. Shared helper code can move to separate components. I would refactor step by step behind existing tests, starting from the leaves, so behaviour stays the same. The result is flatter classes that are easier to test and extend.
07

A @Transactional method is not rolling back after an exception. What could be wrong?

Save to ▾
Show answer
Check that the exception is unchecked, since checked exceptions do not roll back unless rollbackFor is set. Check that the method is called through the Spring proxy, not from another method in the same class. Make sure the method is public and the exception is not caught and swallowed inside. Also confirm the database engine supports transactions and the right transaction manager is used.
08

Write a minimal Dockerfile for a Spring Boot application.

Save to ▾
Show answer
A multi-stage build keeps the image small. FROM eclipse-temurin:21-jdk AS build WORKDIR /app COPY . . RUN ./mvnw -q package -DskipTests FROM eclipse-temurin:21-jre WORKDIR /app COPY --from=build /app/target/*.jar app.jar EXPOSE 8080 ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"] Spring Boot can also build images without a Dockerfile using mvn spring-boot:build-image.
09

Tell me about a time you solved a concurrency bug.

Save to ▾
Show answer
Situation: our wallet service sometimes showed wrong balances under load. Task: find the race and fix it without slowing the API. Action: I reproduced it with a JMeter test, found a read-then-update pattern in two concurrent requests, and replaced it with an atomic SQL update plus optimistic locking with a version column. Result: zero balance mismatches across festival traffic and a reusable load test for future changes.
10

How does ExecutorService work and why use a thread pool?

Save to ▾
Show answer
ExecutorService manages a pool of worker threads and a task queue. You submit Runnable or Callable tasks and get Futures, and workers reuse threads instead of creating one per task, which saves creation cost and limits concurrency. Configure core size, max size, queue and rejection policy through ThreadPoolExecutor. Always call shutdown() and awaitTermination() when done.
11

An API calls three independent downstream services one after another and takes 900 ms. How would you speed it up?

Save to ▾
Show answer
Since the calls are independent, run them in parallel with CompletableFuture.supplyAsync on a dedicated executor or with virtual threads, then join with allOf. Total latency becomes roughly the slowest call, about 300 ms. Add a timeout per call with orTimeout and a fallback for failures so one slow service does not block the whole response. Structured concurrency is another option in newer Java.
12

Production shows Connection is not available, request timed out after 30000ms from HikariCP. What do you check?

Save to ▾
Show answer
The pool is exhausted. Check for connection leaks, where code holds connections without closing, by setting leakDetectionThreshold. Look for long transactions doing remote calls inside @Transactional, slow queries holding connections and a pool size too small for the thread count. Fix leaks, move external calls outside transactions, optimise slow queries and then size the pool from load tests.
13

Explain the happens-before relationship in the Java Memory Model.

Save to ▾
Show answer
Happens-before is the rule that guarantees one action's effects are visible to another. Examples: unlocking a monitor happens-before a later lock of the same monitor, a volatile write happens-before later reads of it, Thread.start() happens-before actions in the started thread, and actions in a thread happen-before another thread's successful join() on it. Without such an edge, threads may see stale or reordered values.
14

Implement the Builder pattern for a User class with many optional fields.

Save to ▾
Show answer
A builder avoids long constructors. public class User { private final String name; private final int age; private User(Builder b) { name = b.name; age = b.age; } public static class Builder { private String name; private int age; public Builder name(String n) { name = n; return this; } public Builder age(int a) { age = a; return this; } public User build() { return new User(this); } } } Usage: new User.Builder().name("Asha").age(25).build(). Lombok @Builder generates this.
15

What are the key patterns used in microservices built with Spring Boot?

Save to ▾
Show answer
Common patterns are API gateway (Spring Cloud Gateway) for routing and auth, service discovery or Kubernetes services, externalised config, circuit breaker and retry with Resilience4j, database per service, event-driven communication with Kafka, saga for distributed transactions, and observability with Micrometer, tracing and centralised logs. Each service owns its data and deploys independently.
16

Write a Kafka producer and consumer in Spring Boot.

Save to ▾
Show answer
Spring Kafka hides most boilerplate. @Service class OrderEvents { private final KafkaTemplate<String, OrderPlaced> kafka; OrderEvents(KafkaTemplate<String, OrderPlaced> k) { kafka = k; } void publish(OrderPlaced e) { kafka.send("orders", e.orderId(), e); } } @Component class OrderListener { @KafkaListener(topics = "orders", groupId = "inventory") void on(OrderPlaced e) { inventory.reserve(e); } } Using orderId as key keeps events for one order in the same partition and order.
17

What are sealed classes and how do they help?

Save to ▾
Show answer
Sealed classes and interfaces, final in Java 17, restrict which classes can extend them using the permits clause, for example sealed interface Shape permits Circle, Square. Each subclass must be final, sealed or non-sealed. This models a closed set of types, and with pattern matching for switch in Java 21 the compiler can check that every case is handled without a default branch.
18

Two users booking the last seat both succeed. How do you prevent double booking?

Save to ▾
Show answer
This is a race between read and write. Use a database guarantee: a unique constraint on seat and show, an atomic conditional update like UPDATE seats SET status = 'BOOKED' WHERE id = ? AND status = 'FREE' and check the affected row count, or pessimistic locking with SELECT FOR UPDATE. Optimistic locking with a version column also works, retrying or failing the loser.
19

Configure a Resilience4j circuit breaker on a client call in Spring Boot.

Save to ▾
Show answer
Annotate the method and provide a fallback. @CircuitBreaker(name = "inventory", fallbackMethod = "stockUnknown") public Stock check(String sku) { return restClient.get().uri("/stock/{sku}", sku) .retrieve().body(Stock.class); } private Stock stockUnknown(String sku, Throwable t) { return Stock.unknown(sku); } # application.yml resilience4j.circuitbreaker.instances.inventory: failure-rate-threshold: 50 wait-duration-in-open-state: 10s
20

Your application hangs and CPU is near zero. How do you find out why?

Save to ▾
Show answer
Low CPU with a hang suggests threads are blocked, often a deadlock or waiting on a slow resource. Take several thread dumps with jcmd pid Thread.print. The JVM reports detected deadlocks at the end of the dump. Otherwise look for many threads BLOCKED on the same lock or WAITING on a connection pool or socket read, then fix lock order, add timeouts or increase the pool.
21

How does Spring Boot auto-configuration work?

Save to ▾
Show answer
At startup Spring Boot reads auto-configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Each class uses conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty, so it creates beans only when the library is on the classpath and you have not defined your own. Run with --debug to see the condition report showing what was applied and why.
22

Tell me about a microservice you designed end to end.

Save to ▾
Show answer
Situation: our monolith's notification code slowed every release. Task: extract it into its own service. Action: I designed a Spring Boot service consuming Kafka events, with its own database for templates and delivery logs, retries with backoff, idempotent consumers and Actuator metrics in Grafana. Result: it handles 20 lakh messages a day, deploys independently and notification incidents dropped sharply.
23

What is the Liskov Substitution Principle? Give an example of breaking it.

Save to ▾
Show answer
LSP says any subclass object must be usable wherever the parent is expected without breaking behaviour. A classic violation is Square extends Rectangle: setting width also changes height, so code that sets width 5 and height 4 and expects area 20 fails. Another is a subclass throwing UnsupportedOperationException for a parent method. The fix is a better hierarchy or composition.
24

What are records in Java and when should you use them?

Save to ▾
Show answer
Records, final in Java 16, are concise classes for immutable data. record Point(int x, int y) {} generates private final fields, a canonical constructor, accessors, equals(), hashCode() and toString(). You can add validation in a compact constructor and add methods. Use them for DTOs, API responses and map keys. They cannot extend another class and are not suited to JPA entities, which need mutability.
25

A HashMap shared by many threads sometimes loses updates. How do you fix it?

Save to ▾
Show answer
HashMap is not thread safe, so concurrent put calls can overwrite each other. Replace it with ConcurrentHashMap and use atomic methods instead of get-then-put, for example counts.merge(key, 1, Integer::sum) or computeIfAbsent for lazy creation. Collections.synchronizedMap also works but locks the whole map, which hurts throughput under contention.
26

How does JWT based authentication work in a Spring Boot API?

Save to ▾
Show answer
After login, the auth server issues a signed JWT with claims like user id, roles and expiry. The client sends it in the Authorization: Bearer header. The API, configured as an OAuth2 resource server in Spring Security, verifies the signature with the public key, checks expiry and builds the security context, so no session is needed. Keep tokens short-lived and use refresh tokens for renewal.
27

How does @Transactional work and what are its common pitfalls?

Save to ▾
Show answer
@Transactional is applied through a proxy that opens a transaction before the method and commits or rolls back after. Pitfalls: calling a transactional method from the same class bypasses the proxy, so no transaction starts; by default rollback happens only for unchecked exceptions; it works on public methods; and long transactions with remote calls hold connections. Use propagation and readOnly where suitable.
28

Your Spring Boot service takes 40 seconds to start in Kubernetes and pods get killed. How do you fix it?

Save to ▾
Show answer
First set a startupProbe so Kubernetes waits for startup before liveness checks begin. Then reduce start time: remove unused starters, enable lazy initialisation where safe, avoid heavy work in @PostConstruct, give enough CPU at start and consider AppCDS. For very fast startup, a GraalVM native image built with Spring AOT can start in under a second, with some trade-offs.
29

What is CompletableFuture and how is it better than Future?

Save to ▾
Show answer
Future only lets you block with get() to obtain a result. CompletableFuture supports non-blocking composition: thenApply to transform, thenCompose to chain async calls, thenCombine or allOf to join several, and exceptionally or handle for errors. It runs on the common ForkJoinPool by default, but pass your own executor for blocking I/O to avoid starving the pool.
30

How do you mentor junior developers on your team?

Save to ▾
Show answer
Situation: three freshers joined my Spring Boot team at once. Task: make them productive quickly. Action: I created a starter task list, paired with each on their first story, gave detailed but kind code reviews and held a weekly session on topics like transactions and testing. Result: all three shipped features independently within a month and one now mentors new joiners.
31

What is Spring Boot Actuator used for?

Save to ▾
Show answer
Actuator adds production endpoints such as /actuator/health for liveness and readiness probes, /actuator/metrics and /actuator/prometheus for Micrometer metrics, plus info, loggers and thread dumps. Expose only what you need with management.endpoints.web.exposure.include and secure sensitive endpoints with Spring Security. Kubernetes uses the health groups to decide restarts and traffic routing.
32

Bind typed configuration properties with validation in Spring Boot.

Save to ▾
Show answer
Use a record with @ConfigurationProperties. @ConfigurationProperties(prefix = "payment") @Validated public record PaymentProps( @NotBlank String baseUrl, @Min(100) int timeoutMs) {} // application.yml // payment: // base-url: https://pay.internal // timeout-ms: 2000 Enable it with @ConfigurationPropertiesScan on the main class. The app fails at startup if values are invalid.
33

Why should we hire you as a Java backend developer?

Save to ▾
Show answer
Situation: in my current role I build Spring Boot services for a payments product. Task: show impact beyond writing code. Action: I improved API latency by 60 percent through query tuning and caching, raised test coverage from 40 to 80 percent and handled on-call calmly. Result: I bring solid Java, Spring and SQL skills, ownership of production and a habit of measuring results, which fits this role.
34

A thread pool fills up and tasks get rejected during traffic spikes. How do you handle it?

Save to ▾
Show answer
First check why tasks are slow, since slow tasks fill pools. Then choose a policy: a bounded queue with CallerRunsPolicy applies backpressure by running the task in the submitting thread; otherwise return a fast 503 so clients retry. Tune pool and queue sizes from load tests. Never use an unbounded queue, because it hides the problem until memory runs out.
35

Two scheduled jobs on different servers process the same records twice. How do you prevent this?

Save to ▾
Show answer
In-JVM locks do not work across servers. Use a distributed lock such as ShedLock with a database table or Redis, so only one instance runs the job at a time. Make the processing idempotent too, for example by marking records with a status and updating with WHERE status = 'NEW' so only one worker claims each row. Database SELECT FOR UPDATE SKIP LOCKED also works well.
36

After moving to virtual threads, throughput did not improve and some requests stalled. What could cause it?

Save to ▾
Show answer
Common causes are pinning, where a virtual thread blocks inside a synchronized block or native call and holds its carrier thread; this was largely fixed in Java 24 for synchronized, but native calls still pin. Another cause is a fixed downstream bottleneck such as a small JDBC pool, so more threads just wait. Detect pinning with JFR events, use ReentrantLock in older versions and size pools to real capacity.
37

Use CountDownLatch to wait for three worker threads to finish.

Save to ▾
Show answer
The main thread waits until the count reaches zero. CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { try { doWork(); } finally { latch.countDown(); } }).start(); } latch.await(30, TimeUnit.SECONDS); System.out.println("all done"); countDown in finally makes sure the latch is released even on error.
38

How would you split a monolith into microservices?

Save to ▾
Show answer
Do not split everything at once. Identify bounded contexts with the business, such as orders, payments and catalogue, and pick a module with clear boundaries and high change rate first. Use the strangler fig pattern: route its traffic through a gateway to the new service, give it its own database and sync data through events. Add observability and CI/CD before scaling out further.
39

A downstream payment service is slow and your API threads pile up. How do you protect your service?

Save to ▾
Show answer
Set strict connect and read timeouts on the HTTP client. Add a Resilience4j circuit breaker so calls fail fast once the error rate crosses a threshold, a bulkhead to limit concurrent calls and retry with backoff only for safe idempotent requests. Return a clear fallback such as payment pending. Monitor breaker state through Actuator metrics and alerts.
40

What does the volatile keyword guarantee?

Save to ▾
Show answer
volatile guarantees visibility and ordering: a write to a volatile field is immediately visible to other threads, and it prevents reordering around that access under the Java Memory Model. It does not make compound operations like count++ atomic, because that is a read, modify and write. Use it for flags such as a stop signal, and use AtomicInteger or locks for counters.

Frequently asked questions

What does a Java Solution Architect do?

A Java solution architect designs the overall structure of enterprise systems built on Java and Spring. They choose service boundaries, integration patterns, data stores, security models and cloud deployment, and they guide multiple teams to follow consistent standards. The role needs years of hands-on Java experience plus strong communication with business stakeholders and clients. They also review designs, estimate effort and manage technical risk on projects.

Which skills are tested in a Java Solution Architect interview?

Expect questions on Microservice architecture, Cloud (AWS or Azure), Design patterns, Security, Stakeholder communication. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Java Solution Architect interview?

Revise Spring Boot and Microservices, Multithreading and Concurrency, OOP in Java first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.