1.
HashMap Infinite Loop Production Issue
A high-volume financial application suddenly goes to 100% CPU usage during peak traffic.
Thread dumps show multiple threads stuck inside [Link]() for a very long time. The
application eventually becomes unresponsive.
Main Questions
How can a simple read operation like get() enter an infinite loop?
What kind of internal corruption can happen inside HashMap?
Why was this issue more common in Java 7 compared to Java 8?
Why does concurrent resizing become dangerous?
Short Answer
Concurrent modifications during resize operations can corrupt the linked list structure inside
buckets, creating cyclic references. When get() traverses the bucket, it loops forever.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Suppose two threads simultaneously trigger a HashMap resize operation. Explain step-by-step
how bucket corruption can occur internally.
Short Answer
During resize, nodes are rehashed and moved to new buckets. Without synchronization, threads
may overwrite each other’s next pointers, creating circular linked lists.
Follow-Up 2:
Why did Java 8 reduce the probability of this issue but still not make HashMap thread-safe?
Short Answer
Java 8 improved resizing and introduced balanced tree bins for high-collision buckets, but
concurrent writes are still unsafe because HashMap lacks synchronization.
Follow-Up 3:
Explain how ConcurrentHashMap internally avoids full-map locking and improves concurrency.
Short Answer
Java 8 ConcurrentHashMap uses bucket-level synchronization and CAS operations instead of
locking the entire map.
Follow-Up 4:
If hashCode() implementation is poor and returns the same value for many objects, what
performance issue happens internally?
Short Answer
Too many collisions occur in the same bucket, degrading lookup from near O(1) to O(n), or
O(log n) after treeification.
Follow-Up 5:
Why does ConcurrentHashMap not allow null keys or null values?
Short Answer
Nulls create ambiguity during concurrent reads because null could mean either “missing key” or
“key mapped to null”.
2. Volatile vs Synchronized Production
Scenario
A developer claims:
“We fixed the race condition issue by making the counter variable volatile.”
However, duplicate transaction IDs still appear in production.
Main Questions
Why is volatile insufficient here?
What exactly does volatile guarantee?
Why is increment operation still unsafe?
Short Answer
volatile guarantees visibility of changes between threads, but does not make compound
operations atomic. Increment involves read-modify-write steps.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain step-by-step why counter++ is not atomic even when counter is volatile.
Short Answer
Increment involves:
1. Read current value
2. Add 1
3. Write new value
Multiple threads can interleave these operations and overwrite updates.
Follow-Up 2:
What is the difference between visibility and atomicity in multithreading?
Short Answer
Visibility means one thread sees another thread’s latest value. Atomicity means an operation
completes fully without interruption.
Follow-Up 3:
Explain how CPU cache and memory reordering relate to volatile.
Short Answer
Volatile prevents certain instruction reordering and ensures reads/writes go directly to main
memory instead of stale CPU cache copies.
Follow-Up 4:
Why is volatile mandatory in double-checked locking singleton implementation?
Short Answer
Without volatile, instruction reordering may expose a partially constructed object to other
threads.
Follow-Up 5:
When would synchronized be preferred over volatile?
Short Answer
When multiple operations must execute atomically or shared mutable state requires locking
consistency.
3. CompletableFuture Deadlock Scenario
A Spring Boot microservice uses CompletableFuture heavily for parallel downstream API calls.
Under production load, requests start hanging indefinitely.
Main Questions
Why do async systems sometimes deadlock?
Why is using blocking operations inside async tasks dangerous?
Why can CompletableFuture silently freeze under load?
Short Answer
Blocking calls inside ForkJoinPool exhaust worker threads. Async tasks wait for threads that are
already blocked.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
What exactly happens internally when many CompletableFuture tasks call blocking database
operations?
Short Answer
ForkJoinPool worker threads become blocked waiting for DB responses, leaving no free threads
available for remaining tasks.
Follow-Up 2:
Why is calling join() inside async chains dangerous?
Short Answer
join() blocks the current thread until completion, potentially causing thread starvation or
deadlock.
Follow-Up 3:
Explain the difference between thenApply() and thenCompose() with a real microservice
example.
Short Answer
thenApply() transforms a result synchronously.
thenCompose() chains another async operation and flattens nested futures.
Example:
Get customer
Then asynchronously fetch customer orders
Follow-Up 4:
Why is the default ForkJoinPool risky in enterprise applications?
Short Answer
It is shared globally and optimized for CPU-bound tasks, not long-running blocking operations.
Follow-Up 5:
How would you redesign this system safely?
Short Answer
Use dedicated thread pools for blocking operations, apply timeouts, bulkheads, circuit breakers,
and avoid blocking joins.
4. Spring Transaction Rollback Mystery
A method annotated with @Transactional throws an exception, but database changes are still
committed.
Main Questions
Why does rollback sometimes fail?
How does Spring transaction management actually work internally?
Why does self-invocation break transactions?
Short Answer
Spring transactions use proxy-based AOP. Internal method calls bypass the proxy, so transaction
interception never occurs.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain step-by-step how Spring creates transactional behavior using proxies.
Short Answer
Spring creates a proxy object around the bean. Calls through the proxy start/commit/rollback
transactions before invoking actual method.
Follow-Up 2:
Why does calling a transactional method from another method inside the same class fail?
Short Answer
Internal method calls bypass the proxy and directly invoke the target object.
Follow-Up 3:
Why do checked exceptions often fail to trigger rollback?
Short Answer
By default Spring rolls back only unchecked RuntimeExceptions unless explicitly configured.
Follow-Up 4:
Why can private methods not be transactional?
Short Answer
Proxy interception works only for externally accessible methods. Private methods cannot be
proxied.
Follow-Up 5:
Explain a real production issue caused by incorrect transaction propagation settings.
Short Answer
Using REQUIRES_NEW excessively may commit partial updates independently, causing
inconsistent business state.
5. REST API Timeout Cascade Scenario
Architecture:
API Gateway
Auth Service
User Service
Payment Service
Notification Service
One downstream service becomes slow, and suddenly the entire platform starts timing out.
Main Questions
How does one slow microservice crash the entire system?
Why do retries worsen outages?
Why are synchronous chains dangerous?
Short Answer
Blocked threads accumulate across services causing connection pool exhaustion and cascading
failures.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain step-by-step how thread exhaustion spreads across services.
Short Answer
Slow downstream calls hold upstream threads longer. Eventually thread pools fill up, requests
queue, and latency spreads system-wide.
Follow-Up 2:
Why can aggressive retries amplify failures dramatically?
Short Answer
Retries increase traffic against already overloaded services, multiplying pressure and worsening
outages.
Follow-Up 3:
How do circuit breakers protect systems during downstream failures?
Short Answer
Circuit breakers stop sending requests temporarily after repeated failures, preventing resource
exhaustion.
Follow-Up 4:
What is timeout budgeting and why is it important?
Short Answer
Total request timeout must be divided carefully across downstream calls to avoid cascading
latency accumulation.
Follow-Up 5:
Why are asynchronous event-driven systems often more resilient than synchronous chains?
Short Answer
Async systems decouple services and reduce blocking dependencies, preventing cascading
thread exhaustion.
6. Kafka Duplicate Payment Scenario
A Kafka-based payment processing system occasionally charges customers twice.
Main Questions
Why does Kafka allow duplicate processing?
What failures typically cause duplicate events?
Why is exactly-once processing difficult?
Short Answer
Kafka guarantees at-least-once delivery. Consumer crashes before offset commit may reprocess
messages.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain exactly how duplicate processing happens when a consumer crashes.
Short Answer
Message is processed successfully, but consumer crashes before committing offset. After restart,
Kafka redelivers message.
Follow-Up 2:
Why is idempotency critical in financial systems?
Short Answer
Operations must produce same result even if repeated multiple times to prevent duplicate
payments.
Follow-Up 3:
Why does Kafka’s exactly-once semantics not fully solve database consistency issues?
Short Answer
Kafka transaction guarantees do not automatically include external databases or REST APIs.
Follow-Up 4:
Explain the Outbox Pattern and why it improves consistency.
Short Answer
DB changes and event creation occur in same transaction. Separate process reliably publishes
events afterward.
Follow-Up 5:
How would you safely replay failed payment events?
Short Answer
Replay idempotently using unique transaction IDs, deduplication logic, and audit tracking.
1. HashMap Corruption Production Scenario
A high-volume payment system suddenly goes to 100% CPU. Thread dump shows threads stuck
inside [Link]() forever.
Main Questions
How can a read operation enter an infinite loop?
What internal corruption happens inside HashMap?
Why was this issue more common before Java 8?
Why does concurrent resizing become dangerous?
Short Answer
Concurrent modifications during resize can create cyclic bucket linked lists. Reads then loop
forever. Java 8 improved bucket handling using tree bins and resize optimizations.
Follow-up Questions
Difference between HashMap and ConcurrentHashMap internals
Why does ConcurrentHashMap not lock entire map?
Explain CAS
Why is size() approximate in ConcurrentHashMap?
Hidden Trap
Candidate says:
“HashMap is thread-safe in Java 8.”
Correct understanding:
Java 8 improved behavior but HashMap is still NOT thread-safe.
2. Volatile vs Synchronized Killer Scenario
Developer says:
“We made the counter variable volatile, so race conditions are fixed.”
Main Questions
Why is this statement incorrect?
What exactly does volatile guarantee?
Why is increment still unsafe?
Short Answer
volatile guarantees visibility, not atomicity. count++ is multiple operations.
Follow-up Questions
Happens-before relationship
CPU cache coherence
Memory barriers
Why double-checked locking requires volatile
Hidden Trap
Many candidates cannot explain instruction reordering.
3. CompletableFuture Thread Starvation
Your async Spring Boot service hangs randomly under load.
Main Questions
Why do CompletableFuture systems freeze?
Why is using join() dangerous?
Why is blocking DB/API calls inside async tasks problematic?
Short Answer
Blocking operations exhaust ForkJoinPool worker threads causing starvation/deadlocks.
Follow-up Questions
thenApply() vs thenCompose()
get() vs join()
Difference between async and non-async variants
Exception handling in CompletableFuture chains
Hidden Trap
Candidate thinks async automatically improves performance.
4. Parallel Stream Disaster
A developer changes stream to parallelStream(). Application becomes slower.
Main Questions
Why can parallel streams reduce performance?
Why are parallel streams dangerous for IO operations?
Why can synchronized blocks destroy parallelism?
Short Answer
Parallel streams are best for CPU-intensive stateless workloads. Thread coordination overhead
can outweigh benefits.
Follow-up Questions
ForkJoinPool work stealing
Stateful intermediate operations
Why ordering hurts parallel performance
Why shared mutable state breaks streams
Hidden Trap
Candidate assumes “parallel = faster”.
5. JVM GC Pause Production Failure
A trading application pauses for 15 seconds during market open.
Main Questions
Why are GC pauses catastrophic in distributed systems?
Why can increasing heap worsen latency?
Difference between throughput GC and low-latency GC?
Short Answer
Large heaps increase stop-the-world pause times, causing cascading failures and timeouts.
Follow-up Questions
G1 vs ZGC
Young generation vs old generation
Promotion failure
Why allocation rate matters more than heap size
Hidden Trap
Candidate focuses only on heap utilization instead of allocation pressure.
ROUND 2 — JAVA 8 DEEP DIVE (15 mins)
6. Stream Lazy Evaluation Trap
Logs inside filter() never print.
Main Questions
Why is stream code not executing?
Which operations are lazy?
What is a terminal operation?
Short Answer
Intermediate operations are lazy. Without terminal operations, stream pipeline never executes.
Follow-up Questions
map() vs flatMap()
Why peek() is dangerous
Why streams should avoid side effects
Why streams cannot be reused
Hidden Trap
Candidate confuses iteration with execution.
7. Optional Misuse Scenario
A team wraps every DTO field in Optional.
Main Questions
Why is Optional bad in entities/DTOs?
Why should Optional rarely be method parameter?
Serialization issues with Optional?
Short Answer
Optional is intended mainly for return types. Using it in models causes serialization/JPA
problems.
Follow-up Questions
orElse() vs orElseGet()
Why orElse() can hurt performance
Can Optional contain null?
Hidden Trap
Candidate says Optional eliminates all null problems.
8. Functional Interface Ambiguity
Lambda expression fails compilation because overloaded methods accept different functional
interfaces.
Main Questions
Why does compiler fail here?
How does target typing work?
Short Answer
Lambda requires a single clear target functional interface.
Follow-up Questions
Predicate vs Function vs Consumer vs Supplier
Primitive specializations
Method references vs lambdas
Hidden Trap
Candidate memorized syntax but not compiler inference rules.
ROUND 3 — SPRING + SPRING BOOT (15
mins)
9. Transaction Rollback Mystery
@Transactional method throws exception but DB commits data.
Main Questions
Why does rollback fail?
Why does self-invocation break transactions?
Why private methods cannot be transactional?
Short Answer
Spring transactions use proxies. Internal calls bypass proxy interception.
Follow-up Questions
JDK proxy vs CGLIB
Checked vs unchecked rollback
Propagation types
Isolation levels
Hidden Trap
Candidate does not understand proxy-based AOP.
10. Circular Dependency Failure
Two Spring services constructor-inject each other.
Main Questions
Why does Spring fail startup?
Why field injection sometimes hides issue?
Proper redesign approach?
Short Answer
Constructor injection exposes circular dependencies during bean creation.
Follow-up Questions
Bean lifecycle
Singleton vs prototype scope
@PostConstruct
Lazy initialization
Hidden Trap
Candidate solves using @Lazy without discussing design flaw.
11. Spring Boot Memory Leak Scenario
Microservice crashes after several days.
Main Questions
How do you investigate memory leaks?
What metrics/tools do you use?
How can thread pools leak memory?
Short Answer
Analyze heap dumps, thread dumps, GC logs, caches, thread pools, Kafka lag, and unbounded
queues.
Follow-up Questions
Heap vs metaspace
ThreadLocal leaks
Why static collections are dangerous
Connection pool exhaustion
Hidden Trap
Candidate immediately blames heap size.
ROUND 4 — REST APIs +
MICROSERVICES (10 mins)
12. REST API Backward Compatibility
Failure
Mobile apps break after adding fields to API response.
Main Questions
Why can “small” response changes break clients?
Safe API evolution strategy?
API versioning approaches?
Short Answer
Clients may tightly bind to schemas. APIs should evolve additively and remain backward
compatible.
Follow-up Questions
URI vs header versioning
Consumer-driven contracts
Idempotency
Pagination strategies
Hidden Trap
Candidate thinks adding fields is always safe.
13. Distributed Transaction Failure
Order service commits successfully but payment service fails.
Main Questions
Why are distributed transactions difficult?
Why is 2PC avoided in microservices?
Explain Saga pattern.
Short Answer
Microservices prefer eventual consistency using compensating transactions instead of global
rollback.
Follow-up Questions
Choreography vs orchestration
Outbox pattern
Kafka exactly-once limitations
Idempotent retries
Hidden Trap
Candidate assumes Kafka solves distributed consistency automatically.
14. Cascading Failure Scenario
Recommendation service slows down. Entire platform crashes.
Main Questions
How does one slow service crash entire system?
Why are retries dangerous?
Why can autoscaling worsen outages?
Short Answer
Blocked threads accumulate across services causing connection pool exhaustion and retry
storms.
Follow-up Questions
Circuit breaker
Bulkhead pattern
Retry jitter
Timeout budgeting
Hidden Trap
Candidate focuses only on CPU instead of thread/resource exhaustion.
FINAL KILLER ARCHITECTURE
QUESTION (Last 5 mins)
15. Complete Production Meltdown
Architecture:
Spring Boot microservices
Kafka
Redis
MySQL
Kubernetes
REST APIs
AWS Lambda
Incident:
Kafka lag growing rapidly
APIs timing out
Pods restarting
DB pool exhausted
Duplicate payment events occurring
GC pauses increasing
Main Questions
What is your first 10-minute action plan?
Which metrics determine root cause?
How do you separate symptoms from causes?
What do you stabilize first?
Short Answer
1. Stop retry amplification
2. Protect database
3. Reduce incoming traffic/load shedding
4. Scale critical consumers
5. Analyze bottleneck metrics
6. Pause non-critical workloads
7. Replay failed events idempotently later
Follow-up Questions
Backpressure handling
Safe event replay
DLQ strategy
Preserving ordering
Multi-region failover
Advanced Scenario-Based Interview
Questions (Java + Spring + Microservices +
AWS + JOLT + XSLT)
1. Java 8 Streams – Lazy Evaluation Trap
You have a production issue where a stream pipeline that validates transactions is not executing
validation logic, even though the code looks correct. Logs inside filter() are never printed.
Questions
Why can a stream pipeline silently do nothing?
Which operations are lazy and which are terminal?
What happens if multiple terminal operations are executed on the same stream?
Why is this dangerous in financial systems?
Short Answer
Intermediate operations (map, filter, peek) are lazy. Without a terminal operation (collect,
forEach, count, reduce) the pipeline never executes. Streams cannot be reused after a terminal
operation.
Follow-up Questions
Difference between map() and flatMap()
Why is peek() dangerous in production?
Why should streams avoid side effects?
What happens when exceptions occur inside streams?
2. Parallel Stream Production Failure
A developer changed a sequential stream to parallelStream() to improve performance. After
deployment, transaction totals became inconsistent.
Questions
Why can parallel streams corrupt results?
Which collections are unsafe in parallel streams?
Why is using ArrayList inside forEach() dangerous?
How does ForkJoinPool work internally?
Short Answer
Parallel streams run across multiple threads. Shared mutable state causes race conditions. Non-
thread-safe collections become corrupted.
Follow-up Questions
When should parallel streams NOT be used?
Difference between CPU-bound vs IO-bound workloads
Why can parallel streams degrade performance?
How do you control custom thread pools?
3. Optional Misuse Scenario
A team wrapped every object in Optional, including DTO fields and entity fields.
Questions
Why is Optional not recommended in entity models?
Why should Optional rarely be used in method parameters?
What serialization problems occur with JSON/JPA?
Short Answer
Optionalis intended mainly for return types. Using it in entities and DTOs causes serialization,
JPA mapping, and readability problems.
Follow-up Questions
Difference between orElse() and orElseGet()
Why can orElse() hurt performance?
Can Optional contain null?
5. CompletableFuture Thread Starvation
Async APIs randomly freeze under load.
Questions
Why does CompletableFuture commonly deadlock?
What happens if blocking DB calls run inside ForkJoinPool?
Why is commonPool dangerous in enterprise systems?
Short Answer
ForkJoinPool is optimized for non-blocking tasks. Blocking operations exhaust worker threads.
Follow-up Questions
thenApply vs thenCompose
join vs get
allOf vs anyOf
Why async chains silently swallow exceptions
Deep Follow-up
How do you propagate MDC/logging context across async threads?
Why do ThreadLocals fail in async systems?
6. Java Stream Parallelism Catastrophe
Parallel stream made application slower.
Questions
Why can parallel streams reduce performance?
Why is parallelism harmful for IO workloads?
How does task splitting overhead hurt small datasets?
Short Answer
Parallel streams work best for CPU-intensive stateless operations with large datasets.
Follow-up Questions
Spliterator internals
ForkJoin work stealing
Stateful intermediate operations
Why ordering hurts parallel performance
Killer Follow-up
Why can synchronized blocks inside parallel streams completely destroy throughput?
Spring Deep Internals
7. Transaction Rollback Not Happening
@Transactional method throws exception, but data commits anyway.
Questions
Why?
How does Spring transaction proxying actually work?
Why does self-invocation break transactions?
Short Answer
Spring uses AOP proxies. Internal method calls bypass proxy interception.
Follow-up Questions
JDK dynamic proxies vs CGLIB
Why private methods cannot be transactional
Checked vs unchecked rollback rules
TransactionSynchronizationManager internals
Deep Follow-up
Explain transaction propagation internals
REQUIRES_NEW suspension mechanics
Nested transaction savepoints
8. Hibernate N+1 Disaster
API latency jumps from 200ms to 15 seconds after deployment.
Questions
Explain exactly how N+1 occurs.
Why can EAGER fetching worsen performance?
Why does JOIN FETCH sometimes create duplicates?
Short Answer
ORM lazily loads child entities individually, creating excessive DB round trips.
Follow-up Questions
Batch fetching
Entity graphs
First-level vs second-level cache
Dirty checking internals
Killer Follow-up
Why does Open Session In View hide architectural problems?
4. CompletableFuture Deadlock Scenario
A microservice uses multiple async API calls with CompletableFuture. Under load, requests
hang indefinitely.
Questions
Why do async systems deadlock?
What happens when blocking calls are used inside async chains?
Why is join() dangerous?
Difference between thenApply() and thenCompose()?
Short Answer
Blocking calls inside async pipelines exhaust thread pools. join() can block worker threads.
thenCompose() is used for dependent async chaining.
Follow-up Questions
Difference between supplyAsync() and runAsync()
Exception handling using exceptionally()
How to combine multiple futures safely?
How to implement timeout handling?
5. HashMap Internal Corruption Scenario
A legacy Java 7 application experienced infinite loops in HashMap during heavy concurrent
writes.
Questions
Why was HashMap unsafe before Java 8?
What changed internally in Java 8?
Explain bucket structure evolution.
Short Answer
Concurrent resizing in older HashMap implementations could create cyclic linked lists. Java 8
improved bucket balancing using trees after threshold limits.
Follow-up Questions
Difference between HashMap and ConcurrentHashMap
Why does ConcurrentHashMap not allow null?
Explain lock striping
What is CAS?
6. Functional Interface Ambiguity
A lambda expression fails compilation because two overloaded methods accept different
functional interfaces.
Questions
Why does Java fail type inference here?
How does compiler determine target typing?
Short Answer
Lambdas require a clear target functional interface. Multiple matching overloads create
ambiguity.
Follow-up Questions
Built-in functional interfaces in Java 8
Difference between Function, Consumer, Supplier, Predicate
Primitive specializations (IntFunction, etc.)
Spring Framework Scenarios
7. Circular Dependency Failure
Two Spring services inject each other using constructor injection.
Questions
Why does Spring fail startup?
Why does field injection sometimes hide the issue?
How do you redesign this properly?
Short Answer
Constructor injection exposes circular dependencies during bean creation. Usually indicates poor
service design.
Follow-up Questions
Difference between singleton and prototype scope
Bean lifecycle phases
What does @PostConstruct do?
8. Transaction Rollback Mystery
A method annotated with @Transactional throws an exception, but database records still
commit.
Questions
Why does rollback sometimes fail?
Which exceptions trigger rollback by default?
What happens during self-invocation?
Short Answer
Spring rolls back only unchecked exceptions by default. Internal method calls bypass proxies, so
transactions are skipped.
Follow-up Questions
Propagation types
Isolation levels
Difference between pessimistic and optimistic locking
Dirty reads vs phantom reads
9. Spring Boot Memory Leak Scenario
A Spring Boot microservice slowly consumes memory and crashes after several days.
Questions
How would you investigate?
What metrics would you inspect?
How can thread pools cause memory leaks?
Short Answer
Analyze heap dumps, thread dumps, GC logs, and metrics. Common causes include unbounded
caches, thread pools, static references, and Kafka consumer lag.
Follow-up Questions
Difference between heap memory and metaspace
Explain minor GC vs major GC
Why do thread-local variables leak memory?
10. API Gateway Timeout Scenario
A request passes through API Gateway → Auth Service → User Service → Payment Service
and randomly times out.
Questions
How do you identify the bottleneck?
What distributed tracing tools would you use?
Why are synchronous chains dangerous?
Short Answer
Use correlation IDs, distributed tracing, metrics, and timeout analysis. Deep synchronous chains
amplify latency and failures.
Follow-up Questions
Circuit breaker pattern
Retry storm problem
Bulkhead pattern
Idempotency in REST APIs
Microservices + Kafka Scenarios
11. Duplicate Kafka Event Processing
A payment event is processed twice, charging users twice.
Questions
Why does Kafka allow duplicates?
What is at-least-once delivery?
How do you implement idempotency?
Short Answer
Kafka guarantees delivery, not uniqueness. Consumers must implement idempotent processing
using transaction IDs or deduplication keys.
Follow-up Questions
Difference between partition and offset
Consumer group rebalance issues
Exactly-once semantics limitations
Why ordering breaks across partitions
12. Kafka Consumer Lag Explosion
Consumer lag suddenly grows from 0 to millions.
Questions
Possible root causes?
How do you diagnose bottlenecks?
Why can slow downstream APIs affect Kafka?
Short Answer
Consumer lag occurs when producers outpace consumers. Causes include slow processing,
rebalances, network issues, DB bottlenecks, or insufficient partitions.
Follow-up Questions
Batch consumption optimization
Manual vs auto offset commit
Backpressure handling
REST + JSON + XML Scenarios
13. Backward Compatibility Failure
A mobile app stops working after a backend JSON response changes slightly.
Questions
How should APIs evolve safely?
Why is removing fields dangerous?
How do you version APIs?
Short Answer
APIs must remain backward compatible. Removing or renaming fields breaks consumers. Use
additive changes and versioning strategies.
Follow-up Questions
URI vs header versioning
Contract testing
Consumer-driven contracts
14. Huge JSON Payload Performance Issue
A service processing large nested JSON payloads suddenly spikes CPU usage.
Questions
Why is object mapping expensive?
Difference between Jackson streaming API and databind?
Why does deep nesting hurt performance?
Short Answer
Large object graphs increase parsing, memory allocation, and GC overhead. Streaming parsers
are more memory efficient.
Follow-up Questions
ObjectMapper thread safety
Serialization recursion issues
Handling unknown properties safely
15. XML Namespace Nightmare
An external SOAP integration suddenly fails after a vendor changes XML namespaces.
Questions
Why are XML namespaces critical?
How does XPath break?
How do you design resilient XML parsing?
Short Answer
XPath and XSLT heavily depend on namespaces. Namespace changes invalidate mappings and
transformations.
Follow-up Questions
DOM vs SAX vs StAX parsing
XSD validation
SOAP Fault handling
XSLT + JOLT Advanced Scenarios
16. XSLT Performance Bottleneck
An XSLT transformation on 500MB XML files takes 20 minutes.
Questions
How do you optimize XSLT?
Why are deep XPath expressions expensive?
Why can recursive templates become dangerous?
Short Answer
Optimize template matching, reduce XPath traversals, use keys/indexing, and avoid repeated
node scans.
Follow-up Questions
Difference between XSLT 1.0 and 2.0
Template matching priority
Modes in XSLT
17. JOLT Transformation Failure
A downstream service starts failing because nested JSON arrays changed structure unexpectedly.
Questions
Which JOLT operation is most likely impacted?
How do you debug complex shift specs?
Why does wildcard mapping become risky?
Short Answer
shift operations are sensitive to path structure. Wildcards can unintentionally map incorrect
nodes after schema evolution.
Follow-up Questions
Difference between shift, modify-overwrite-beta, remove, default
Performance optimization in JOLT
Schema evolution strategies
AWS + Lambda Scenarios
18. Lambda Cold Start Production Issue
An API backed by Lambda experiences random 8-second delays.
Questions
What causes cold starts?
Why are Java Lambdas slower?
How do you optimize startup time?
Short Answer
Cold starts occur when AWS initializes new containers. Java startup/JVM initialization increases
latency.
Follow-up Questions
Provisioned concurrency
SnapStart
Lambda memory vs CPU relationship
Why VPC Lambdas are slower
19. Distributed Transaction Failure Across Microservices
An order service updates DB successfully, but payment service fails afterward.
Questions
Why are distributed transactions difficult?
Why is 2PC rarely preferred in microservices?
Explain Saga pattern.
Short Answer
Microservices favor eventual consistency. Saga coordinates compensating actions instead of
global rollback.
Follow-up Questions
Choreography vs orchestration
Outbox pattern
Event sourcing challenges
Security + OAuth Scenarios
20. OAuth Token Leakage Incident
An access token leaked through logs.
Questions
Why is logging JWT dangerous?
Difference between access token and refresh token?
How do you secure microservice communication?
Short Answer
JWTs may contain sensitive claims and allow unauthorized access. Tokens must never appear in
logs.
Follow-up Questions
mTLS
OAuth authorization code flow
API Gateway security enforcement
Ultra-Tricky Rapid Fire Questions
Java
Why are strings immutable?
Why is volatile not enough for atomicity?
Difference between fail-fast and fail-safe iterators
Why can equals() and hashCode() bugs destroy HashMap behavior?
Why are checked exceptions controversial?
Spring
Why does @Autowired sometimes inject null?
Difference between @Component, @Service, @Repository
Why is field injection discouraged?
What happens if two beans of same type exist?
Microservices
Why are shared databases anti-patterns?
Why does distributed logging become difficult?
What causes cascading failures?
Why is clock synchronization important?
AWS
Difference between ECS, EKS, Lambda
When NOT to use Lambda
Why can autoscaling worsen failures?
Why are retries dangerous?
Docker/Kubernetes
Difference between Docker image and container
Why do Kubernetes pods restart repeatedly?
Liveness vs readiness probes
Why do memory limits cause OOMKills?
Architecture-Level Killer Scenario
21. Complete Real-Time Failure Scenario
Your system processes millions of financial transactions daily.
Architecture:
Spring Boot microservices
Kafka event streaming
JOLT transformations
XSLT legacy integrations
AWS Lambda enrichment
MongoDB + MySQL
Kubernetes deployment
Production issue:
Kafka lag increases
Lambdas timeout
Memory spikes in transformation services
Duplicate payment events occur
Kubernetes pods restart continuously
Questions
How would you approach incident triage?
What metrics are most critical?
Which failure is likely primary vs secondary?
How do you prevent cascading failures?
Which components require immediate scaling?
How do you preserve message ordering?
How would you safely replay failed events?
Short Answer
Prioritize stabilization:
1. Stop cascading retries
2. Scale consumers
3. Inspect dead-letter queues
4. Analyze GC/thread dumps
5. Identify bottleneck service
6. Protect downstream systems using circuit breakers and backpressure
7. Replay events idempotently
Final Follow-up
Design changes you would implement afterward
Observability improvements
Event schema governance
Multi-region disaster recovery strategy
5. CompletableFuture Thread Starvation
Async APIs randomly freeze under load.
Questions
Why does CompletableFuture commonly deadlock?
What happens if blocking DB calls run inside ForkJoinPool?
Why is commonPool dangerous in enterprise systems?
Short Answer
ForkJoinPool is optimized for non-blocking tasks. Blocking operations exhaust worker threads.
Follow-up Questions
thenApply vs thenCompose
join vs get
allOf vs anyOf
Why async chains silently swallow exceptions
Deep Follow-up
How do you propagate MDC/logging context across async threads?
Why do ThreadLocals fail in async systems?
6. Java Stream Parallelism Catastrophe
Parallel stream made application slower.
Questions
Why can parallel streams reduce performance?
Why is parallelism harmful for IO workloads?
How does task splitting overhead hurt small datasets?
Short Answer
Parallel streams work best for CPU-intensive stateless operations with large datasets.
Follow-up Questions
Spliterator internals
ForkJoin work stealing
Stateful intermediate operations
Why ordering hurts parallel performance
Killer Follow-up
Why can synchronized blocks inside parallel streams completely destroy throughput?
Spring Deep Internals
7. Transaction Rollback Not Happening
@Transactional method throws exception, but data commits anyway.
Questions
Why?
How does Spring transaction proxying actually work?
Why does self-invocation break transactions?
Short Answer
Spring uses AOP proxies. Internal method calls bypass proxy interception.
Follow-up Questions
JDK dynamic proxies vs CGLIB
Why private methods cannot be transactional
Checked vs unchecked rollback rules
TransactionSynchronizationManager internals
Deep Follow-up
Explain transaction propagation internals
REQUIRES_NEW suspension mechanics
Nested transaction savepoints
8. Hibernate N+1 Disaster
API latency jumps from 200ms to 15 seconds after deployment.
Questions
Explain exactly how N+1 occurs.
Why can EAGER fetching worsen performance?
Why does JOIN FETCH sometimes create duplicates?
Short Answer
ORM lazily loads child entities individually, creating excessive DB round trips.
Follow-up Questions
Batch fetching
Entity graphs
First-level vs second-level cache
Dirty checking internals
Killer Follow-up
Why does Open Session In View hide architectural problems?
16. JOLT Transformation Corruption
A schema change silently corrupts downstream financial payloads.
Questions
Why are wildcard mappings dangerous?
Why is schema evolution difficult in transformation pipelines?
Why are deeply nested transformations fragile?
Short Answer
Path-dependent transformations silently mis-map fields after structural schema changes.
Follow-up Questions
shift vs modify-overwrite-beta
Performance bottlenecks in JOLT
Validation before transformation
Contract testing
17. XSLT Performance Collapse
Transformation latency jumps from milliseconds to minutes.
Questions
Why are XPath expressions expensive?
Why can recursive template matching explode complexity?
Why does XML namespace handling break integrations?
Short Answer
Repeated tree traversal and inefficient template matching create exponential processing
overhead.
Follow-up Questions
SAX vs DOM vs StAX
XSLT modes
Template priority resolution
Streaming XML parsing
Security + OAuth + JWT
18. JWT Security Incident
A JWT token was stolen from browser local storage.
Questions
Why is localStorage risky?
Why are JWTs dangerous if too large?
Why should sensitive data never be embedded inside JWTs?
Short Answer
JWTs are bearer tokens. Anyone possessing them gains access until expiration.
Follow-up Questions
OAuth flows
Refresh token rotation
Token revocation challenges
mTLS between services
Ultimate Architecture Question
19. Complete Production Meltdown
Architecture:
Spring Boot microservices
Kafka
Redis
MongoDB
MySQL
Kubernetes
AWS Lambda
JOLT transformations
XSLT legacy integrations
Incident:
Kafka lag grows rapidly
Redis memory spikes
Pods restart
DB connection pool exhaustion
Lambda retries explode
Duplicate payments occur
GC pauses increase
APIs timeout
Questions
What is your first 10-minute action plan?
Which metrics determine primary root cause?
How do you separate symptom vs cause?
Which systems would you intentionally degrade first?
Would you disable retries? Why?
How do you preserve data consistency during incident mitigation?
How do you replay safely afterward?
Short Answer
Stabilize before fixing:
1. Stop retry amplification
2. Protect databases
3. Reduce traffic/load shedding
4. Scale critical consumers
5. Pause non-critical processing
6. Analyze bottleneck metrics
7. Replay idempotently later
Deep Follow-up Questions
Designing resilient retry strategies
Backpressure implementation
Event ordering guarantees
Multi-region failover tradeoffs
CAP theorem practical implications
Why distributed systems fail differently than monoliths
7. Spring Boot Connection Pool Exhaustion
Scenario
A production REST API suddenly becomes extremely slow during peak traffic. CPU usage is
low, but requests are timing out. Logs show:
“Unable to acquire JDBC Connection”.
Main Questions
Why can APIs fail even when CPU usage is low?
What causes database connection pool exhaustion?
How can one slow query impact the entire application?
Short Answer
Threads block waiting for DB connections. Slow queries hold connections longer, exhausting the
pool and causing request timeouts.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain step-by-step how a single slow database query can eventually crash the entire REST
API.
Short Answer
Slow queries keep DB connections occupied. Incoming requests wait longer for free connections.
Thread pools fill up, request queues grow, and eventually APIs timeout.
Follow-Up 2:
Why does increasing connection pool size sometimes worsen the problem instead of fixing it?
Short Answer
Too many DB connections can overload the database itself, increasing lock contention, CPU
usage, and query latency.
Follow-Up 3:
How would you identify whether the bottleneck is:
application threads
database
connection pool
network latency
Short Answer
Use thread dumps, DB monitoring, connection pool metrics, slow query logs, and distributed
tracing.
Follow-Up 4:
What production metrics would you monitor continuously?
Short Answer
Active DB connections
Pool wait time
Query latency
API response time
Thread pool utilization
Error rates
Follow-Up 5:
How would you protect the system from cascading failure?
Short Answer
Use timeouts, circuit breakers, query optimization, bulkheads, rate limiting, and backpressure.
8. REST API Serialization Failure Scenario
A Spring Boot API suddenly starts throwing:
StackOverflowError
during JSON response generation.
Main Questions
Why can JSON serialization cause StackOverflowError?
How do circular object references happen?
Why is this common with JPA entities?
Short Answer
Bidirectional relationships recursively serialize parent-child references indefinitely.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain how a Parent → Child → Parent relationship causes infinite recursion during
serialization.
Short Answer
Serializer repeatedly traverses references between parent and child objects without termination.
Follow-Up 2:
Why is directly exposing JPA entities in REST APIs considered dangerous?
Short Answer
Entities contain lazy proxies, bidirectional relationships, and persistence concerns that can leak
internal implementation details.
Follow-Up 3:
How do @JsonManagedReference and @JsonBackReference solve this issue?
Short Answer
They control serialization direction and prevent recursive traversal loops.
Follow-Up 4:
Why are DTOs generally preferred over exposing entities directly?
Short Answer
DTOs provide API stability, security isolation, serialization control, and prevent lazy loading
issues.
Follow-Up 5:
What other production issues can lazy loading cause during serialization?
Short Answer
LazyInitializationException occurs when serializer accesses unloaded entities outside
transaction/session scope.
9. Spring Boot Thread Pool Starvation
Scenario
A REST API works fine in testing but hangs randomly in production under heavy load.
Main Questions
What is thread starvation?
How do blocking operations exhaust thread pools?
Why do APIs appear “alive” but stop responding?
Short Answer
All request-handling threads become blocked waiting on slow downstream resources like DBs or
external APIs.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain step-by-step how blocked threads spread across the application.
Short Answer
Requests occupy threads while waiting for slow dependencies. New requests cannot get threads,
causing queue buildup and timeouts.
Follow-Up 2:
Why can increasing thread pool size make latency even worse?
Short Answer
More threads increase contention, memory usage, context switching, and downstream pressure.
Follow-Up 3:
How would you identify thread starvation using thread dumps?
Short Answer
Many threads appear blocked or waiting on IO, DB connections, locks, or external service calls.
Follow-Up 4:
What is backpressure and why is it important?
Short Answer
Backpressure limits incoming work to prevent systems from accepting more load than they can
process safely.
Follow-Up 5:
How would reactive programming help in this scenario?
Short Answer
Reactive systems reduce thread blocking by using non-blocking asynchronous processing.
10. XML Namespace Production Failure
An external SOAP integration suddenly stops working after vendor-side XML changes.
Main Questions
Why do XML namespace changes break integrations?
Why does XPath suddenly stop matching nodes?
Why are namespaces critical in XML parsing?
Short Answer
XPath expressions depend on namespaces. Namespace changes invalidate node matching logic.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain how two XML tags with same name can still represent different elements.
Short Answer
Namespaces uniquely identify XML elements even when tag names are identical.
Follow-Up 2:
Why do developers often ignore namespaces during testing but fail in production?
Short Answer
Test XML may omit namespaces while production payloads include strict schema definitions.
Follow-Up 3:
How would you design XML processing more safely?
Short Answer
Always use namespace-aware parsers and externalized XPath/XSLT configurations.
Follow-Up 4:
Difference between DOM, SAX, and StAX parsing?
Short Answer
DOM loads entire XML into memory
SAX streams sequentially
StAX provides pull-based streaming
Follow-Up 5:
Why is DOM dangerous for very large XML files?
Short Answer
Entire XML tree loads into memory causing high heap usage and GC pressure.
11. XSLT Transformation Performance
Collapse
An XSLT transformation processing large XML files suddenly slows from seconds to minutes.
Main Questions
Why can XSLT performance degrade dramatically?
Why are deep XPath expressions expensive?
Why can recursive template matching become dangerous?
Short Answer
Repeated XML tree traversal and inefficient XPath/template logic create excessive processing
overhead.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Why does repeatedly scanning large XML trees hurt performance?
Short Answer
Each XPath traversal walks portions of the XML tree repeatedly, increasing CPU usage
significantly.
Follow-Up 2:
How do XSLT keys improve performance?
Short Answer
Keys create indexed lookups instead of repeated full-tree scans.
Follow-Up 3:
What is template priority conflict in XSLT?
Short Answer
Multiple matching templates may compete for same node selection causing unexpected
transformation behavior.
Follow-Up 4:
Why do recursive templates become risky with deeply nested XML?
Short Answer
Deep recursion increases stack usage and processing complexity.
Follow-Up 5:
How would you optimize very large XML transformations?
Short Answer
Use streaming parsers, indexed lookups, optimized XPath expressions, and avoid repeated node
traversal.
12. JOLT Transformation Corruption
Scenario
A downstream microservice begins receiving corrupted JSON after a schema update.
Main Questions
Why are JOLT transformations fragile during schema evolution?
Why can wildcard mappings become dangerous?
Why do nested arrays often break transformations?
Short Answer
JOLT mappings depend heavily on JSON structure. Structural changes silently mis-map fields.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain how a small nested JSON structure change can silently corrupt downstream payloads.
Short Answer
Path-based mappings may redirect fields incorrectly without throwing transformation errors.
Follow-Up 2:
What is the difference between:
shift
remove
default
modify-overwrite-beta
operations in JOLT?
Short Answer
shift → remaps fields
remove → deletes fields
default → inserts missing defaults
modify-overwrite-beta → transforms existing values
Follow-Up 3:
Why are wildcard (*) mappings risky in financial or transactional systems?
Short Answer
Unexpected new fields may match wildcard rules and map into incorrect locations.
Follow-Up 4:
How would you validate transformed payloads safely before downstream processing?
Short Answer
Use JSON schema validation, contract testing, integration testing, and transformation audits.
Follow-Up 5:
How do you debug complex JOLT transformation failures in production?
Short Answer
Log intermediate payloads, isolate transformation stages, compare schemas, and validate
mappings incrementally.
13. Spring Boot Memory Leak via Caching
Scenario
A microservice gradually consumes memory over several days until Kubernetes kills the pod.
Main Questions
How can caching create memory leaks?
Why are unbounded caches dangerous?
Why can memory leaks appear slowly over time?
Short Answer
Cached objects accumulate continuously without eviction causing heap growth and GC pressure.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Why do memory leaks often appear only in production but not during testing?
Short Answer
Production traffic patterns, data size, and long uptime expose accumulation issues not visible in
short tests.
Follow-Up 2:
How would you identify whether cache is causing memory growth?
Short Answer
Analyze heap dumps for retained object references and cache growth patterns.
Follow-Up 3:
Why can excessive caching worsen performance instead of improving it?
Short Answer
Large caches increase memory pressure, GC pauses, serialization cost, and eviction overhead.
Follow-Up 4:
Difference between strong references, weak references, and soft references?
Short Answer
Strong → prevents GC
Weak → GC eligible immediately
Soft → retained until memory pressure increases
Follow-Up 5:
How would you safely implement production-grade caching?
Short Answer
Use bounded caches, TTL expiration, eviction policies, metrics monitoring, and cache
invalidation strategies.
14. REST API Idempotency Failure Scenario
A payment REST API occasionally processes duplicate payments after retries.
Main Questions
Why are retries dangerous in payment systems?
What is idempotency?
Why is POST usually non-idempotent?
Short Answer
Retries may repeat operations unless requests are uniquely identified and safely deduplicated.
Follow-Up Questions (Clear + Elaborated)
Follow-Up 1:
Explain step-by-step how network timeout can still result in successful payment plus duplicate
retry.
Short Answer
Payment succeeds on server, but client times out before receiving response and retries same
request again.
Follow-Up 2:
How would you design idempotent payment APIs safely?
Short Answer
Use unique idempotency keys and persist processed request tracking.
Follow-Up 3:
Why is relying only on frontend retry prevention insufficient?
Short Answer
Retries may occur from gateways, proxies, clients, load balancers, or network failures.
Follow-Up 4:
Difference between PUT and POST regarding idempotency?
Short Answer
PUT replaces resource deterministically. POST usually creates new resources on each request.
Follow-Up 5:
How would you safely replay failed requests later?
Short Answer
Store request IDs, audit logs, deduplication logic, and transaction state history.