Java Backend Developer 1st Round Interview: 20 Questions Being Asked in 2026
A battle-tested guide to the top 20 core Java, JVM, Spring Boot, JPA, and distributed systems questions asked in senior first-round technical interviews in 2026—with code examples, root causes, and production fixes.
Vivek Adarsh
Founder & Systems Architect, Veltoryx Technologies · Published November 5, 2026
In 2026, first-round technical screenings for Java Backend Engineers have evolved dramatically. Interviewers rarely ask you to recite textbook definitions of polymorphism or invert a binary tree on a whiteboard.
Instead, modern hiring managers want to know: what happens when your code meets real production load?
Can you debug a silent database race condition that costs money? Do you understand why a Spring proxy bypassed your transaction? Why did an unmonitored ThreadLocal crash a cluster after 30 days of seamless uptime?
Here are the top 20 technical questions currently asked in 2026 Java backend rounds, organized across five essential domains: Core Java, JVM & Memory, Spring Boot, Database & JPA, and System Design & Production.
Part 1: Core Java & Concurrency
1. HashMap has 1 million entries. Performance is degrading. Why and what do you do?
The Root Cause
A default HashMap starts with an initial capacity of 16 and a load factor of 0.75. When you push 1 million elements into an unconfigured map:
- Rehash Storms: The map must resize itself 17 separate times (
16 → 32 → 64 → ... → 1,048,576). Every single resize allocates a new array double the previous size, recomputes bucket indexes for every entry, and migrates references. Under continuous ingestion, this causes massive CPU spikes and pause times. - Hash Collisions & Treeification: If your keys have poorly distributed
hashCode()implementations, entries concentrate in a few bucket indexes. Once a bucket exceeds 8 nodes (and total capacity reaches 64), Java treeifies that linked list into a Red-Black Tree (TreeNode). While this caps lookup time fromO(n)down toO(log n),TreeNodeconsumes more than double the memory of a standardNode(~56 bytes vs ~24 bytes per entry). - Garbage Collection Pressure: Storing 1 million boxed objects (e.g.,
IntegerorLong) plus 1 million node wrappers consumes 80MB+ of heap, leading to frequent Minor GC pauses.
The Production Fix
// Calculate required initial capacity to prevent ALL resizes:
// capacity = (expectedSize / loadFactor) + 1
int expectedSize = 1_000_000;
int initialCapacity = (int) Math.ceil(expectedSize / 0.75f) + 1; // 1,333,334
// Pre-sized map: 0 resizes, O(1) constant-time writes
Map<String, UserProfile> userCache = new HashMap<>(initialCapacity);Want to master how Java internals work under the hood? Explore our comprehensive Java Collections & Memory Masterclass in the Veltoryx Learn library.
2. Your code uses synchronized everywhere. Application is slow. What's wrong?
The Root Cause
Placing synchronized on entire methods or critical paths forces the JVM to acquire an exclusive monitor lock on the object. In high-throughput backend services, this causes:
- Thread Contention & CPU Thrashing: When 200 Tomcat worker threads hit the same synchronized block, 1 thread executes while 199 threads enter the
BLOCKEDstate. The operating system continuously context-switches threads, burning CPU cycles in kernel space instead of doing actual business computation. - Coarse-Grained Locking: Locking an entire map or service method prevents concurrent reads even when data is completely unrelated.
- Priority Inversion & Starvation: Low-priority threads holding the lock stall high-priority user-facing web requests.
The Production Fix
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.StampedLock;
public class HighThroughputMetricsStore {
// 1. Lock-free or striping data structures instead of synchronized collections
private final ConcurrentHashMap<String, Long> counterMap = new ConcurrentHashMap<>();
// 2. Optimistic read locking with StampedLock for read-heavy state
private final StampedLock lock = new StampedLock();
private double balance = 1000.0;
public double getBalanceOptimistic() {
long stamp = lock.tryOptimisticRead();
double current = balance;
if (!lock.validate(stamp)) { // If a write occurred concurrently
stamp = lock.readLock(); // Fall back to a standard pessimistic read lock
try {
current = balance;
} finally {
lock.unlockRead(stamp);
}
}
return current;
}
}Deep dive into locks, memory barriers, and virtual thread pinning in our Java Concurrency & Thread Safety Guide.
3. Explain double-checked locking in Singleton. Why do you need volatile?
The Failure Mechanism Without volatile
Double-checked locking checks the instance once without synchronization, and only synchronizes if the instance is null:
public class ConfigurationRegistry {
// REQUIRED: volatile ensures visibility and prevents instruction reordering
private static volatile ConfigurationRegistry instance;
private ConfigurationRegistry() {
// Expensive setup (load files, connect to vault)
}
public static ConfigurationRegistry getInstance() {
if (instance == null) { // 1st Check (No Lock)
synchronized (ConfigurationRegistry.class) {
if (instance == null) { // 2nd Check (With Lock)
instance = new ConfigurationRegistry();
}
}
}
return instance;
}
}Why is volatile strictly mandatory?
Creating an object in Java (instance = new ConfigurationRegistry()) is not an atomic operation. Under the hood, the JVM executes three steps:
allocateMemory(): Reserve heap memory for the object.constructor(): Initialize instance fields and run constructor code.assignReference(): Point theinstancevariable to the allocated memory address.
The JVM JIT compiler and CPU cache out-of-order execution are allowed to reorder steps 2 and 3:
Thread A: Step 1 (Allocate) ──► Step 3 (Assign Reference) ──► [CONSTRUCTOR STILL RUNNING]
▲
Thread B: Calls getInstance() ────────────┘
Sees instance != null!
Returns partially-initialized object! 💥If Thread B calls getInstance() at that instant, it sees instance != null, skips the synchronized block, and attempts to read fields from a half-initialized object, causing silent data corruption or null pointer exceptions in production.
Declaring instance as volatile establishes a happens-before relationship, preventing the compiler and CPU from reordering memory writes across the volatile store barrier.
Read our complete breakdown of volatile memory semantics and hardware memory models in Java Memory Model & Volatile Internals.
4. ThreadLocal variable in your app is causing a memory leak. How?
The Root Cause
A ThreadLocal variable is not stored inside the ThreadLocal object itself—it is stored in the Thread object's internal threadLocals map (ThreadLocal.ThreadLocalMap).
In servlet containers (Spring Boot with embedded Tomcat or Jetty), threads do not terminate after handling an HTTP request. They are returned to an executor thread pool to handle subsequent user requests.
The entry inside ThreadLocalMap holds a WeakReference to the ThreadLocal key, but a Strong Reference to the value:
Thread (GC Root in Pool)
└─► ThreadLocalMap
└─► Entry[]
├─► Key = WeakReference<ThreadLocal> (Collected by GC)
└─► Value = StrongReference<LargeUserContext> (LEAKED!)When the ThreadLocal reference goes out of scope, the garbage collector cleans up the key (leaving it null). However, because the worker thread is still alive in the pool, the value object remains reachable and will never be collected by the GC. Over days of high traffic, thousands of orphaned user contexts stay trapped in the Old Generation until an OutOfMemoryError occurs.
The Production Fix
public class SecurityContextFilter implements Filter {
private static final ThreadLocal<UserContext> CONTEXT = new ThreadLocal<>();
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
try {
CONTEXT.set(extractUserContext(req));
chain.doFilter(req, res);
} finally {
// MANDATORY: Always clear the thread's map entry in a finally block!
CONTEXT.remove();
}
}
}Learn how to profile heap dumps and hunt down thread-bound memory leaks in our JVM Troubleshooting & Profiling Track.
5. What is the difference between wait() and sleep()? Where would each cause a deadlock?
| Dimension | Thread.sleep(millis) | Object.wait() |
|---|---|---|
| Origin | Static method on java.lang.Thread | Instance method on java.lang.Object |
| Lock Handling | Holds all locks while sleeping | Releases the monitor lock of the target object |
| Prerequisites | Can be called anywhere | Must be called inside a synchronized context |
| Wakeup Condition | Timer expires or interrupted | notify(), notifyAll(), or timeout |
How Each Causes a Deadlock
1. Deadlock with sleep() (Holding Locks Idle):
A thread enters a synchronized block, acquires lock L1, and calls Thread.sleep(10000). Because sleep() never releases locks, any other thread needing L1 to complete its transaction is starved. If the sleeping thread is waiting for the second thread to update a condition, circular deadlock occurs.
2. Deadlock with wait() (The Missed Signal Trap):
If threadA calls wait() without wrapping it in a condition loop, or if threadB calls notify() before threadA reaches wait(), the notification is lost forever. threadA sleeps indefinitely, holding up any downstream dependencies.
synchronized (lock) {
// ALWAYS use while, NEVER use if (guards against spurious wakeups & missed signals)
while (!isConditionMet) {
lock.wait();
}
// Proceed with business computation
}Master condition queues and monitor synchronizers in our Java Thread Synchronization Lesson.
Part 2: JVM & Memory Internals
6. Your app ran fine for 30 days. Crashed with OutOfMemoryError. No code changes. What happened?
The Diagnosis Checklist
When an application runs cleanly for weeks and suddenly crashes with java.lang.OutOfMemoryError without code deployments, the cause is cumulative state accumulation.
To diagnose the crash immediately in your post-mortem:
- Inspect the exact error message:
java.lang.OutOfMemoryError: Java heap space→ Cumulative object retention.java.lang.OutOfMemoryError: Metaspace→ Dynamic class generation leak.java.lang.OutOfMemoryError: Direct buffer memory→ Netty / Off-heap buffer leak.java.lang.OutOfMemoryError: Unable to create new native thread→ OS thread exhaustion.
The Four Common Silent Culprits
// CULPRIT 1: Unbounded static collections or caches without TTL/eviction
public class EventTracker {
// Grows by 10,000 entries/day. Never pruned. Explodes in 30 days.
private static final Map<String, Event> HISTORY = new ConcurrentHashMap<>();
// FIX: Use a bounded cache with size limits and eviction
// Cache<String, Event> cache = Caffeine.newBuilder()
// .maximumSize(50_000).expireAfterWrite(Duration.ofHours(2)).build();
}- Unclosed I/O Resources / Connection Pools: Database connections or HTTP client response streams not wrapped in
try-with-resources. - Dynamic CGLIB / Bytecode Proxies: Certain ORMs or serialization frameworks repeatedly generating dynamic classes into Metaspace when processing dynamic JSON schemas.
- Growing Database Table Fetches: A scheduled background job doing
repository.findAll()that fetched 1,000 records on Day 1, but by Day 30 attempts to load 2.5 million rows into memory at once.
7. GC is running every 30 seconds. Application pauses for 2 seconds each time. How do you fix it?
The Problem: Stop-The-World (STW) Old Generation Sweeps
A 2-second pause every 30 seconds indicates that the JVM is undergoing continuous Full Garbage Collections (Old Generation STW sweeps).
The root cause is either premature object promotion (short-lived objects surviving Young Generation and spilling into Old Generation) or an undersized Young Generation relative to high throughput.
Step-by-Step Production Resolution
- Enable GC Logging (Unified JVM GC Logging in Java 17+):
bash
-Xlog:gc*,gc+phases=debug:file=/var/log/gc.log:time,uptime,pid:filecount=5,filesize=100M - Increase Young Gen Capacity (
-XX:NewRatioor-XX:MaxGCPauseMillis): If young gen is too small, transient request buffers (large JSON payloads, byte arrays) get promoted to Old Gen before Young GC can collect them. - Switch to G1GC with Target Pause Time:
bash
# Tell G1GC to bound pauses to 100 milliseconds -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:InitiatingHeapOccupancyPercent=45 - Eliminate Allocation Hotspots: Profile your codebase using async-profiler or JFR (Java Flight Recorder). Look for object churning—such as serializing 5MB JSON strings inside hot loops or creating heavy regex matchers on every request.
Explore complete JVM flag recipes and pause-time diagnostics in our JVM Garbage Collection Architecture Course.
8. When would you choose G1GC over ZGC in production?
In modern Java (Java 21 / 25 LTS), Generational ZGC (-XX:+UseZGC -XX:+ZGenerational) delivers sub-millisecond maximum pause times regardless of whether your heap is 16GB or 16TB.
However, G1GC is still preferred in several key scenarios:
| Factor | G1GC (-XX:+UseG1GC) | Generational ZGC (-XX:+UseZGC) |
|---|---|---|
| Heap Size | Best for small-to-medium heaps (< 8GB–16GB) | Built for large heaps (16GB up to multiple Terabytes) |
| Max Pause Time | 50ms – 200ms tunable target | < 1ms guaranteed ultra-low latency |
| Throughput vs Latency | Higher throughput (uses less overall CPU for GC) | Slightly lower throughput (~3–5% CPU overhead for read/write barriers) |
| Memory Footprint | Low memory overhead for internal metadata | Requires extra heap headroom to prevent allocation stalls |
When to choose G1GC:
- Small containerized microservices running in Kubernetes with
2GBto6GBheap allocations. G1GC uses less auxiliary memory for colored pointers and load barriers. - Batch processing or throughput-focused services where 100ms pauses do not impact user experience.
When to choose ZGC:
- Interactive real-time systems (financial trading, multiplayer gaming, low-latency API gateways) where a 100ms pause violates strict client SLAs.
- Applications with large heap caches (> 32GB).
Part 3: Spring Boot & Framework Internals
9. @Transactional on a private method. Why does it silently fail?
The Core Reason: Dynamic Proxies and CGLIB
Spring's declarative transaction management (@Transactional) is built entirely on Spring AOP (Aspect-Oriented Programming).
When Spring starts, it wraps your bean inside a dynamic proxy (using CGLIB or JDK dynamic proxies). The proxy intercepts method calls, starts a transaction on the PlatformTransactionManager, invokes your target method, and commits or rolls back based on exception rules.
Client ──► [ CGLIB Proxy: beginTx() ] ──► [ Target Bean: actualMethod() ] ──► [ CGLIB Proxy: commitTx() ]Why it fails silently:
- Private Methods Cannot Be Overridden: CGLIB generates a dynamic subclass of your service class at runtime. Private methods are invisible to subclasses and cannot be overridden by the proxy.
- Spring AOP Ignores Non-Public Methods: By design, Spring's
TransactionAttributeSourceignores non-public methods. The code inside executes directly without any proxy interceptor, running in raw database autocommit mode. No exception is thrown, but rollbacks will never occur.
The Second Trap: Self-Invocation (this.method())
Even on a public method, calling another @Transactional method within the same class will fail to create a transaction:
@Service
public class OrderService {
public void processOrder(Order order) {
// CALLING VIA "this" BYPASSES THE SPRING PROXY!
// No transaction will be opened for saveInternal()!
this.saveInternal(order);
}
@Transactional
public void saveInternal(Order order) {
orderRepository.save(order);
}
}The Fix
- Move the transactional method to a separate collaborator bean.
- Alternatively, use programmatic transactions via
TransactionTemplate.
@Service
@RequiredArgsConstructor
public class OrderService {
private final TransactionTemplate transactionTemplate;
private final OrderRepository orderRepository;
public void processOrder(Order order) {
// Guaranteed transaction demarcation without proxy traps:
transactionTemplate.executeWithoutResult(status -> {
orderRepository.save(order);
});
}
}Learn how Spring AOP, reflection, and bean lifecycle interceptors work in our Spring Core & Architecture Guide.
10. Two beans of same type in Spring context. How does Spring decide which to inject?
When multiple beans implement the same interface (e.g., StripePaymentService and RazorpayPaymentService implementing PaymentGateway), Spring resolves ambiguity using this priority hierarchy:
1. @Primary annotation on one bean
▼ (If not found)
2. @Qualifier("beanName") at injection site
▼ (If not found)
3. Matching parameter/field name to Bean ID
▼ (If not found)
💥 NoUniqueBeanDefinitionException@Configuration
public class PaymentConfig {
@Bean
@Primary // Default fallback bean when no qualifier is specified
public PaymentGateway stripeGateway() {
return new StripePaymentService();
}
@Bean("razorpay")
public PaymentGateway razorpayGateway() {
return new RazorpayPaymentService();
}
}
@Service
public class CheckoutService {
private final PaymentGateway paymentGateway;
// Injects razorpayGateway explicitly:
public CheckoutService(@Qualifier("razorpay") PaymentGateway paymentGateway) {
this.paymentGateway = paymentGateway;
}
}11. Your @Async method throws an exception. Nobody catches it. What happens?
The Behavior
The outcome depends entirely on the method's return type:
- If the method returns
Future<T>orCompletableFuture<T>: The exception is captured inside the returned future object. It is only thrown when the caller invokes.get()or handled via.exceptionally(). - If the method returns
void(Fire-and-Forget): The exception cannot bubble back to the caller thread. The worker thread logs a brief stack trace and terminates, silently dropping the failure. The client assumes the operation succeeded.
The Production Fix: Custom AsyncUncaughtExceptionHandler
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (throwable, method, params) -> {
// Forward failure to alert system, Datadog, or Dead Letter Queue
log.error("Async error in method: {} with params: {}", method.getName(), params, throwable);
metricsService.increment("async.failures", "method", method.getName());
};
}
}12. Spring Boot startup taking 45 seconds. How do you diagnose and fix it?
Diagnosis: Spring Boot Startup Actuator & Profiling
Do not guess. Enable the built-in startup flight recorder in application.properties:
spring.cloud.bootstrap.enabled=false
management.endpoints.web.exposure.include=startupOr profile programmatically using StartupStep:
# Run with JVM flight recorder for class loading:
java -XX:StartFlightRecording=filename=startup.jfr,duration=60s -jar app.jarThe Five Primary Bottlenecks & Fixes
- JPA Entity Schema Validation / Flyway / Liquibase: Connecting to a remote database and validating 300 tables at boot time.
- Aggressive Eager Initialization: In Spring Boot 3 / 4, enable lazy bean initialization for local development:
properties
spring.main.lazy-initialization=true - Heavy
@PostConstructor Database Pre-Warming: Never perform blocking HTTP calls or heavy queries inside@PostConstruct. Move pre-warming to anApplicationReadyEventlistener running on a background virtual thread. - Oversized Component Scanning: If
@ComponentScanpoints to root packages (com.*), Spring spends seconds scanning thousands of irrelevant classpath jars. Restrict component scanning to your explicit base package. - AOT Pre-Compilation & GraalVM: For sub-second startup, leverage Spring AOT processing introduced in modern Spring Boot releases.
Check out our production tuning guide in Spring Boot Actuator & Production Monitoring.
Part 4: Database, JPA & Hibernate
13. Lazy loading throws LazyInitializationException in production but not in dev. Why?
The Root Cause: Open Session In View (OSIV)
In development, Spring Boot enables Open Session in View (OSIV) by default (spring.jpa.open-in-view=true). OSIV keeps the Hibernate Session open through the entire HTTP request lifecycle, including during Thymeleaf rendering or Jackson JSON serialization.
In production, best-practice configuration or reactive web layers explicitly disable OSIV (spring.jpa.open-in-view=false) to avoid holding database connections hostage during slow network transmissions.
When your service method finishes, its @Transactional boundary closes and the Hibernate session terminates. If your controller then attempts to serialize an uninitialized lazy collection (order.getItems()), Hibernate throws:
org.hibernate.LazyInitializationException: could not initialize proxy [Order#123] - no SessionThe Production Fix: DTO Projections & Fetch Joins
public interface OrderRepository extends JpaRepository<Order, Long> {
// 1. Explicit Fetch Join: Retrieves parent and children in a SINGLE query
@Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :orderId")
Optional<Order> findByIdWithItems(@Param("orderId") Long orderId);
// 2. High-Performance Read-Only DTO Projection
@Query("SELECT new com.veltoryx.dto.OrderSummaryDTO(o.id, o.status, COUNT(i)) " +
"FROM Order o JOIN o.items i WHERE o.id = :orderId GROUP BY o.id, o.status")
OrderSummaryDTO findSummaryById(@Param("orderId") Long orderId);
}Read our comprehensive analysis of ORM pitfalls in The N+1 Problem and Fetching Strategies.
14. Your JPA query works fine with 100 rows. Takes 45 seconds with 1 million rows. What is wrong?
The Three Culprits
- The N+1 Query Cascade: Fetching 100 orders triggers 101 queries (1 for orders + 100 for customers). On 100 rows, this takes 20ms. On 1,000,000 rows, your app executes 1,000,001 separate network round-trips to PostgreSQL.
- Missing Database Composite Index: A query with
WHERE status = 'PENDING' ORDER BY created_at DESCdoes a fast sequential scan on 100 rows. On 1 million rows, the database performs a full table scan and an in-memory disk merge sort (Using filesort), saturating database CPU. - Cartesian Product via Multiple List Joins: Fetching two
@OneToManycollections (order.getItems()andorder.getPayments()) with multipleJOIN FETCHclauses causes Hibernate to cross-join row multipliers (100 × 100 = 10,000rows transferred across the wire).
The Fix
- Replace multiple fetch joins with
@EntityGraphor batch fetching (hibernate.default_batch_fetch_size=50). - Use database-level cursor or keyset pagination (
WHERE id > :lastSeenId LIMIT 50) instead of expensiveOFFSETpagination. - Create covering B-Tree indexes matching your filter and order columns.
15. Two transactions updating same row simultaneously. One silently overwrites the other. How do you prevent it?
The Problem: The Lost Update Anomaly
Transaction 1 reads account balance ($100). Transaction 2 reads account balance ($100). T1 deposits $50 and writes $150. T2 immediately withdraws $20 and writes $80. T1's deposit is completely wiped out.
Solution A: Optimistic Locking (Best for High Read / Low Write Contention)
Add a @Version column to your entity:
@Entity
public class Account {
@Id
private Long id;
private BigDecimal balance;
@Version // Automatically checked and incremented by Hibernate
private Long version;
}Hibernate generates SQL:
UPDATE account SET balance = 80, version = 2 WHERE id = 1 AND version = 1;If Transaction 1 already committed and incremented version to 2, the update updates 0 rows. Hibernate throws an OptimisticLockException, allowing your service to catch the error and retry.
Solution B: Pessimistic Locking (Best for High Contention / Financial Balances)
public interface AccountRepository extends JpaRepository<Account, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT a FROM Account a WHERE a.id = :id")
Optional<Account> findByIdForUpdate(@Param("id") Long id);
}Generates:
SELECT * FROM account WHERE id = 1 FOR UPDATE;The database acquires an exclusive row-level lock. Transaction 2 blocks until Transaction 1 commits or rolls back.
Learn transaction isolation levels (READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE) and locking in our Spring Data Transactions & Isolation Deep Dive.
Part 5: System Design & Production Resilience
16. Your payment API receives same request twice due to network retry. How do you prevent double processing?
The Failure Scenario
A mobile customer taps "Pay $100". The backend charges the card successfully, but an edge gateway timeout drops the HTTP response before reaching the phone. The mobile app automatically retries the network request. Without protection, the user is charged twice.
The Production Fix: The Idempotency Key Pattern
@Service
@RequiredArgsConstructor
public class PaymentProcessingService {
private final StringRedisTemplate redisTemplate;
private final PaymentRecordRepository paymentRepo;
@Transactional
public PaymentResponse processPayment(String idempotencyKey, PaymentRequest request) {
// Step 1: Distributed Lock via Redis SETNX (TTL: 120 seconds)
Boolean acquired = redisTemplate.opsForValue()
.setIfAbsent("lock:pay:" + idempotencyKey, "PROCESSING", Duration.ofSeconds(120));
if (Boolean.FALSE.equals(acquired)) {
// Request is already being processed or completed
return paymentRepo.findByIdempotencyKey(idempotencyKey)
.map(PaymentResponse::from)
.orElseThrow(() -> new ConcurrentPaymentException("Payment in flight. Please wait."));
}
try {
// Step 2: Check database for already completed charge
Optional<PaymentRecord> existing = paymentRepo.findByIdempotencyKey(idempotencyKey);
if (existing.isPresent()) {
return PaymentResponse.from(existing.get());
}
// Step 3: Execute external payment gateway charge
ChargeResult result = stripeClient.charge(request);
// Step 4: Persist record with database UNIQUE constraint
PaymentRecord record = new PaymentRecord(idempotencyKey, result);
paymentRepo.save(record);
return PaymentResponse.from(record);
} finally {
redisTemplate.delete("lock:pay:" + idempotencyKey);
}
}
}Explore end-to-end idempotent architectures in our Swiggy Hyperlocal Fleet Orchestration & System Design Case Study.
17. Microservice A calls Microservice B. B is down. A keeps retrying. B never recovers. What pattern solves this?
The Problem: The Retry Storm / Cascading Death Spiral
When Microservice B slows down due to CPU saturation or database connection limits, downstream clients that implement naive aggressive retries compound the failure:
1,000 req/sec × 3 retries = 4,000 req/sec slammed against a dying serviceService B never recovers, and Service A's thread pool fills up waiting for socket read timeouts, bringing down Service A as well.
The Solution: Circuit Breaker + Exponential Backoff + Jitter
Integrate Resilience4j to manage three states:
[ CLOSED: Normal Traffic ] ──► (Failures > 50%) ──► [ OPEN: Fail-Fast Without Calling B ]
▲ │
│ ▼ (Wait 10s)
└─── (Probe Requests Succeed) ◄─── [ HALF-OPEN: Send 10 Test Probes ]@Service
public class OrderServiceClient {
private final RestClient restClient;
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
@Retry(name = "paymentService")
public PaymentConfirmation callPaymentService(PaymentPayload payload) {
return restClient.post()
.uri("https://payments.internal/v1/charge")
.body(payload)
.retrieve()
.body(PaymentConfirmation.class);
}
// Fast-fail fallback when circuit is OPEN:
public PaymentConfirmation paymentFallback(PaymentPayload payload, Throwable t) {
log.warn("Payment service unavailable. Enqueuing for offline processing.", t);
return PaymentConfirmation.queued(payload.orderId());
}
}Master fault-tolerant microservice patterns in our Resilience4j & Circuit Breaker Deep Dive.
18. Your Redis cache is working. But database load is still at 100%. What is wrong?
The Three Classic Cache Failures
| Pattern | What Happens | How to Fix It |
|---|---|---|
| 1. Cache Penetration | Malicious or buggy clients query millions of non-existent IDs. Redis misses every time; every request hits the DB. | Store null values with a short TTL (60s) or use a Bloom Filter at the edge. |
| 2. Cache Stampede (Dog-Piling) | A hot key with 50,000 req/sec expires at 12:00:00. Thousands of concurrent requests miss Redis simultaneously and hammer the DB. | Use Mutex Locks around cache reloading or implement background probabilistic pre-computation (XFetch). |
| 3. Cache Avalanche | Thousands of cache keys were written at the same time with identical 1-hour TTLs. At 1:00:00, all keys vanish at once. | Add random jitter to expiration times: ttl = baseTtl + random(0, 300). |
public ProductDTO getProduct(String productId) {
String cached = redisTemplate.opsForValue().get("product:" + productId);
if (cached != null) return deserialize(cached);
// Mutual exclusion: Only 1 thread refreshes the cache; others wait
String lockKey = "lock:product:" + productId;
if (Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, "1", Duration.ofSeconds(5)))) {
try {
ProductDTO fresh = databaseRepository.findById(productId);
// Add jitter to prevent avalanche:
int jitter = ThreadLocalRandom.current().nextInt(60, 300);
redisTemplate.opsForValue().set("product:" + productId, serialize(fresh), Duration.ofSeconds(3600 + jitter));
return fresh;
} finally {
redisTemplate.delete(lockKey);
}
} else {
// Brief sleep and read again from cache
Thread.sleep(50);
return getProduct(productId);
}
}Learn enterprise caching strategies in our High-Level Design Caching Architecture Course.
19. API response time is 20ms normally. Spikes to 8 seconds under load. No errors in logs. Where do you start?
When latency spikes 400x under load without error logs, the cause is queue starvation and blocking waits.
Where to Start (The Golden Path)
- Check Thread Pool Utilization (Tomcat / Virtual Threads): Under load, all worker threads become occupied. New incoming requests sit waiting in the TCP backlog / accept queue. The actual computation still takes 20ms, but requests wait 7,980ms in the queue just to get a thread!
- Inspect HikariCP Database Connection Pool Metrics: Look at
HikariPool-1 - Connection acquisition time. If your pool size is10and you have200concurrent requests executing 50ms queries, requests will queue for seconds waiting for a free database connection. - Check Downstream Socket Timeouts: A downstream microservice or payment provider is stalling for 8 seconds before responding. If your HTTP client does not set explicit connect/read timeouts, your worker threads block indefinitely.
- JVM STW GC Pauses: Verify with JFR or GC logs that the JVM is not performing full heap compactions during traffic peaks.
20. New feature deployed Friday evening. By Monday morning everything is slow. Nobody touched code over weekend. What happened?
The Anatomy of the Monday Morning Slowness
This classic interview question tests whether you understand asynchronous growth and unindexed temporal datasets:
- Unindexed Table Growth Over the Weekend: The Friday feature added an unindexed column filter (e.g.,
WHERE notification_status = 'PENDING'). On Friday night, the table had 5,000 rows, and full table scans executed in 3ms. By Monday morning, 800,000 new activity rows accumulated over the weekend. Queries that took 3ms now take 6,000ms, causing database CPU to peg at 100%. - Database Connection Leak: A code branch in the new feature failed to close an open connection (e.g., streaming large results without
@Transactional(readOnly = true)or failing to close a raw JDBC cursor on error). HikariCP slowly ran out of available connections over 60 hours. - Kafka Consumer Group Lag & Rebalance Loop: A bug in event parsing caused poison-pill messages. Consumers exceeded
max.poll.interval.ms, triggering continuous rebalances that halted consumption across partitions. - Memory Leak in Long-Lived Static Cache: As discussed in Question 4 & 6, an unpruned collection gradually consumed 90% of heap, forcing the JVM into a 24/7 GC loop by Monday morning.
Accelerate Your Engineering Career with Veltoryx
Preparing for senior and staff-level backend engineering interviews requires more than memorizing trivia. It demands an intuitive, architectural grasp of how JVM memory, Spring proxies, relational engines, and distributed nodes interact under pressure.
Explore the Veltoryx Learn Platform
Veltoryx offers 8 comprehensive tracks with over 500 deep interactive lessons:
- Java Core & Concurrency: Memory models, virtual threads, lock-free data structures, and GC tuning.
- Spring Boot & Microservices: Advanced transactions, AOP internals, security, and Resilience4j.
- System Design Case Studies: Full-scale architectural blueprints for WhatsApp, Swiggy, Netflix, and Uber.
- High-Level & Low-Level Design: Distributed caching, consensus, schema modeling, and OOP clean architecture.
Ready to test your code in our interactive browser-based visualizers and unlock complete interview blueprints?
👉 Unlock Veltoryx Pro Today and get unlimited access to all private lessons, code tracers, and system design roadmaps.
Explore Real-World System Design Case Studies
Trace verified production architectures from WhatsApp, Swiggy, and Netflix with UML diagrams and LLD class breakdowns.
Related Engineering Articles
Java 8 to Java 21: Top 40 Interview Questions for Senior Software Engineers & Tech Leads
The definitive 2026 guide covering the 40 essential modern Java interview questions across Java 8 through Java 21, concurrency, JVM internals, virtual threads, and production scenarios.
Vivek Adarsh
Nov 5, 2026
Java DSA Interview – Complete Methods & Syntax Cheat Sheet
The ultimate quick-reference cheat sheet for Java DSA coding interviews — covering essential Java 8+ syntax, collection methods, and LeetCode problem-solving patterns.
Vivek Adarsh
Nov 24, 2026
35 Java Streams API Questions for SDE-2 Interviews
The definitive 2026 guide to 35 essential Java Streams coding and conceptual interview questions for SDE-2 and Senior Backend roles—with production code, edge cases, and collector architectures.
Vivek Adarsh
Nov 5, 2026