Skip to content
Veltoryx Technologies
JavaSpring BootJVMDatabaseSystem DesignInterviews·22 min read

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.

V

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

HashMap internal architecture showing bucket array collisions and red-black treeification in Java
HashMap internal architecture showing bucket array collisions and red-black treeification in Java

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:

  1. 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.
  2. 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 from O(n) down to O(log n), TreeNode consumes more than double the memory of a standard Node (~56 bytes vs ~24 bytes per entry).
  3. Garbage Collection Pressure: Storing 1 million boxed objects (e.g., Integer or Long) plus 1 million node wrappers consumes 80MB+ of heap, leading to frequent Minor GC pauses.

The Production Fix

OptimizedHashMapInitialization.java
// 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 BLOCKED state. 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

FineGrainedConcurrency.java
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:

DoubleCheckedLocking.java
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:

  1. allocateMemory(): Reserve heap memory for the object.
  2. constructor(): Initialize instance fields and run constructor code.
  3. assignReference(): Point the instance variable to the allocated memory address.

The JVM JIT compiler and CPU cache out-of-order execution are allowed to reorder steps 2 and 3:

text
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?

JVM ThreadLocal memory leak anatomy in Tomcat worker thread pools
JVM ThreadLocal memory leak anatomy in Tomcat worker thread pools

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:

text
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

SafeThreadLocalCleanup.java
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?

DimensionThread.sleep(millis)Object.wait()
OriginStatic method on java.lang.ThreadInstance method on java.lang.Object
Lock HandlingHolds all locks while sleepingReleases the monitor lock of the target object
PrerequisitesCan be called anywhereMust be called inside a synchronized context
Wakeup ConditionTimer expires or interruptednotify(), 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.

SafeWaitNotifyPattern.java
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:

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

UnboundedCacheLeak.java
// 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

  1. 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
  2. Increase Young Gen Capacity (-XX:NewRatio or -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.
  3. Switch to G1GC with Target Pause Time:
    bash
    # Tell G1GC to bound pauses to 100 milliseconds
    -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:InitiatingHeapOccupancyPercent=45
  4. 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:

FactorG1GC (-XX:+UseG1GC)Generational ZGC (-XX:+UseZGC)
Heap SizeBest for small-to-medium heaps (< 8GB–16GB)Built for large heaps (16GB up to multiple Terabytes)
Max Pause Time50ms – 200ms tunable target< 1ms guaranteed ultra-low latency
Throughput vs LatencyHigher throughput (uses less overall CPU for GC)Slightly lower throughput (~3–5% CPU overhead for read/write barriers)
Memory FootprintLow memory overhead for internal metadataRequires extra heap headroom to prevent allocation stalls

When to choose G1GC:

  • Small containerized microservices running in Kubernetes with 2GB to 6GB heap 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

Spring AOP dynamic proxy transaction failure mechanism on self-invocation
Spring AOP dynamic proxy transaction failure mechanism on self-invocation

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.

text
Client ──► [ CGLIB Proxy: beginTx() ] ──► [ Target Bean: actualMethod() ] ──► [ CGLIB Proxy: commitTx() ]

Why it fails silently:

  1. 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.
  2. Spring AOP Ignores Non-Public Methods: By design, Spring's TransactionAttributeSource ignores 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:

SelfInvocationTrap.java
@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.
TransactionTemplateSolution.java
@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:

text
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
BeanResolution.java
@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:

  1. If the method returns Future<T> or CompletableFuture<T>: The exception is captured inside the returned future object. It is only thrown when the caller invokes .get() or handled via .exceptionally().
  2. 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

AsyncConfiguration.java
@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:

properties
spring.cloud.bootstrap.enabled=false
management.endpoints.web.exposure.include=startup

Or profile programmatically using StartupStep:

bash
# Run with JVM flight recorder for class loading:
java -XX:StartFlightRecording=filename=startup.jfr,duration=60s -jar app.jar

The Five Primary Bottlenecks & Fixes

  1. JPA Entity Schema Validation / Flyway / Liquibase: Connecting to a remote database and validating 300 tables at boot time.
  2. Aggressive Eager Initialization: In Spring Boot 3 / 4, enable lazy bean initialization for local development:
    properties
    spring.main.lazy-initialization=true
  3. Heavy @PostConstruct or Database Pre-Warming: Never perform blocking HTTP calls or heavy queries inside @PostConstruct. Move pre-warming to an ApplicationReadyEvent listener running on a background virtual thread.
  4. Oversized Component Scanning: If @ComponentScan points to root packages (com.*), Spring spends seconds scanning thousands of irrelevant classpath jars. Restrict component scanning to your explicit base package.
  5. 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

Lost update race condition and optimistic locking resolution in database transactions
Lost update race condition and optimistic locking resolution in database transactions

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:

text
org.hibernate.LazyInitializationException: could not initialize proxy [Order#123] - no Session

The Production Fix: DTO Projections & Fetch Joins

FetchJoinSolution.java
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

  1. 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.
  2. Missing Database Composite Index: A query with WHERE status = 'PENDING' ORDER BY created_at DESC does 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.
  3. Cartesian Product via Multiple List Joins: Fetching two @OneToMany collections (order.getItems() and order.getPayments()) with multiple JOIN FETCH clauses causes Hibernate to cross-join row multipliers (100 × 100 = 10,000 rows transferred across the wire).

The Fix

  • Replace multiple fetch joins with @EntityGraph or batch fetching (hibernate.default_batch_fetch_size=50).
  • Use database-level cursor or keyset pagination (WHERE id > :lastSeenId LIMIT 50) instead of expensive OFFSET pagination.
  • 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:

AccountEntity.java
@Entity
public class Account {
    @Id
    private Long id;
    private BigDecimal balance;

    @Version // Automatically checked and incremented by Hibernate
    private Long version;
}

Hibernate generates SQL:

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)

PessimisticLockRepository.java
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:

sql
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

System design resilience showing payment idempotency key state machine and circuit breaker pattern
System design resilience showing payment idempotency key state machine and circuit breaker pattern

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

IdempotentPaymentService.java
@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:

text
1,000 req/sec × 3 retries = 4,000 req/sec slammed against a dying service

Service 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:

text
[ CLOSED: Normal Traffic ] ──► (Failures > 50%) ──► [ OPEN: Fail-Fast Without Calling B ]
            ▲                                                   │
            │                                                   ▼ (Wait 10s)
            └─── (Probe Requests Succeed) ◄─── [ HALF-OPEN: Send 10 Test Probes ]
Resilience4jSetup.java
@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

PatternWhat HappensHow to Fix It
1. Cache PenetrationMalicious 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 AvalancheThousands 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).
CacheStampedeMutex.java
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)

  1. 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!
  2. Inspect HikariCP Database Connection Pool Metrics: Look at HikariPool-1 - Connection acquisition time. If your pool size is 10 and you have 200 concurrent requests executing 50ms queries, requests will queue for seconds waiting for a free database connection.
  3. 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.
  4. 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:

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.

Interactive Engineering Platform

Explore Real-World System Design Case Studies

Trace verified production architectures from WhatsApp, Swiggy, and Netflix with UML diagrams and LLD class breakdowns.

Written by Vivek Adarsh, Founder & Systems Architect, Veltoryx Technologies.

Related Engineering Articles