Skip to main content

Most questions in 2025

Java Spring Boot Senior Engineer Interview Questions & Answers

A complete interview preparation guide for Senior Java Engineers, Spring Boot Developers, and Backend Technical Leads covering Java, Spring Boot, Microservices, Cloud, Database, Security, and Performance Engineering concepts.

Target Audience:
  • Senior Java Developers
  • Spring Boot Engineers
  • Microservice Architects
  • Backend Technical Leads

1. Describe Yourself

A senior engineer introduction should highlight technical experience, architecture knowledge, ownership, and problem-solving capabilities.

Sample Answer


I am a Java backend engineer with 7+ years of experience
designing and developing enterprise applications using Java,
Spring Boot, Microservices, REST APIs, and cloud technologies.

My expertise includes Java, Spring Boot, Spring Cloud,
JPA/Hibernate, PostgreSQL, MySQL, Redis, Kafka,
Docker, Kubernetes, and cloud platforms.

I have experience designing scalable distributed systems,
implementing security using JWT/OAuth2,
optimizing application performance,
and troubleshooting production issues.

I also have experience mentoring developers and
contributing to architecture decisions.


2. RESTful APIs and Standards

REST (Representational State Transfer) is an architectural style used to build scalable web services.

REST Principles

Resource-Based URLs

URLs should represent resources, not actions.



Good:

GET /api/users/100


Avoid:

GET /api/getUser?id=100

HTTP Methods

Method Purpose
GET Retrieve data
POST Create resource
PUT Complete update
PATCH Partial update
DELETE Remove resource

HTTP Status Codes

Status Meaning
200 Successful request
201 Resource created
400 Invalid request
401 Authentication failed
403 Access denied
404 Resource not found
500 Internal server error

REST API Best Practices

  • Use API versioning
  • Use DTO instead of exposing database entities
  • Validate incoming requests
  • Implement centralized exception handling
  • Use pagination for large data
  • Secure APIs using HTTPS


Example:

GET /api/v1/users?page=0&size=20


3. Latest Spring Boot Version and Features

Spring Boot 4 is built on top of Spring Framework 7 and modern Java capabilities.

Major Features

  • Java 17 minimum baseline with Java 25 readiness
  • Improved GraalVM Native Image support
  • Built-in resilience features
  • AI Agent and Model Context Protocol (MCP) support
  • Jackson 3 integration
  • Native gRPC support
  • Declarative HTTP Service Clients
  • Improved modular architecture

HTTP Interface Client Example



@HttpExchange("/users")
public interface UserClient {


    @GetExchange("/{id}")
    Mono<User> findUser(Long id);


}

Interview Point: Spring Boot 4 focuses on cloud-native applications, AI integration, performance optimization, and developer productivity.

4. Java Optional

Optional is a container object introduced in Java 8 to represent a value that may or may not exist.

Without Optional



User user = getUser();

if(user != null){

    System.out.println(user.getName());

}

With Optional



Optional<User> user = getUser();

user.ifPresent(
    u -> System.out.println(u.getName())
);

Advantages

  • Reduces NullPointerException
  • Makes null handling explicit
  • Improves readability

Avoid using Optional as entity fields or method parameters. It is mainly recommended as a return type.


5. WebFlux - Reactive Programming

Spring WebFlux provides a reactive, non-blocking programming model for building highly scalable applications.

Traditional MVC Model



Request

 |

Thread waits

 |

Database Response

 |

Response


Problem:

Thread remains blocked.

Reactive Model



Request

 |

Event Loop

 |

Non Blocking Operation

 |

Response Event


Core Reactive Types

Type Purpose
Mono<T> Single asynchronous value
Flux<T> Multiple asynchronous values
Reactive Benefits:
  • High concurrency
  • Less thread usage
  • Better resource utilization
  • Suitable for streaming applications

6. WebFlux Retry Mechanism

Retry allows applications to automatically retry failed operations caused by temporary failures.

Simple Retry



webClient.get()
.retrieve()
.bodyToMono(User.class)
.retry(3);

Retry With Backoff



.retryWhen(
 Retry.backoff(
   3,
   Duration.ofSeconds(2)
 )
)

Exponential backoff avoids overwhelming a failed service.


7. WebFlux Pagination APIs

Pagination prevents loading large datasets into memory.



@GetMapping("/users")
public Mono<Page<User>> getUsers(
        Pageable pageable){

    return service.findAll(pageable);

}

Example request:



GET /users?page=0&size=20


8. Circuit Breaker

Circuit Breaker prevents cascading failures in distributed systems.



Without Circuit Breaker:

Order Service
      |
      |
Payment Service (Down)
      |
      |
Timeout


With Circuit Breaker:

Order Service

      |

Circuit Breaker

      |

Fallback Response


Circuit States

  • Closed - Normal operation
  • Open - Requests blocked
  • Half Open - Testing recovery

9. Resilience Patterns

Resilience ensures systems continue operating during failures.

  • Retry
  • Timeout
  • Circuit Breaker
  • Bulkhead
  • Rate Limiting

10. Rate Limiter

Rate limiter controls the number of requests accepted by a service.



Example:

100 requests per minute per user

Common Algorithms

  • Token Bucket
  • Fixed Window
  • Sliding Window

Used for:

  • API protection
  • Preventing abuse
  • Traffic control

11. Transaction Management

A transaction is a sequence of database operations that must execute as a single unit of work.

Spring manages transactions using the @Transactional annotation.

Propagation: REQUIRED

REQUIRED is the default propagation mode. It uses an existing transaction if available; otherwise, it creates a new one.



@Transactional
public void createOrder(){

    saveOrder();

    updateInventory();

}

Example flow:



Order Service

    |

Transaction Started

    |

Inventory Service

    |

Uses Same Transaction


Propagation: REQUIRES_NEW

REQUIRES_NEW always creates a new independent transaction.



@Transactional(
 propagation = Propagation.REQUIRES_NEW
)
public void saveAuditLog(){

    auditRepository.save(log);

}

Common use cases:

  • Audit logging
  • Error logging
  • Independent background processing


Main Transaction

Save Order

    |

Save Audit Log
(New Transaction)

    |

Commit



12. Heap, Stack and Garbage Collection

Heap Memory

Heap stores objects created during application execution.



User user = new User();

The User object is stored in Heap memory.

Stack Memory

Stack stores:

  • Method execution frames
  • Local variables
  • Method references


public void calculate(){

    int total = 100;

}

The variable total is stored in Stack memory.

Garbage Collector (GC)

GC automatically removes unused objects from Heap memory.

Common Garbage Collectors

  • Serial GC
  • G1 GC (Default in modern JVMs)
  • ZGC
  • Shenandoah GC
Performance Point: Poor object creation patterns can cause excessive GC activity and impact application response time.

13. Caching - Redis, Caffeine, Hazelcast

Caching improves application performance by reducing database calls.

Caching Flow



Request

 |

Cache

 |

Database


Redis Cache

Redis is a distributed in-memory data store.

Common use cases:

  • Session storage
  • JWT token blacklist
  • Frequently accessed data
  • Distributed cache

Caffeine Cache

Caffeine is a high-performance local JVM cache.



@Cacheable("users")
public User findUser(Long id){

 return repository.findById(id);

}

Advantages:

  • Very fast
  • No network communication
  • Simple configuration

Hazelcast

Hazelcast provides distributed in-memory caching.

Used when multiple application instances need shared cache data.


14. Spring Stereotype Annotations

Stereotype annotations identify Spring-managed components.

Annotation Purpose
@Component Generic Spring Bean
@Service Business Logic Layer
@Repository Database Access Layer
@Controller MVC Controller
@RestController REST API Controller

15. Spring Bean Lifecycle

Spring manages the complete lifecycle of objects.



Create Bean

      |

Dependency Injection

      |

BeanPostProcessor

      |

@PostConstruct

      |

Bean Ready

      |

@PreDestroy

      |

Destroy


Lifecycle Example



@Component
public class PaymentService {


@PostConstruct
public void init(){

    System.out.println("Initialized");

}


@PreDestroy
public void destroy(){

    System.out.println("Destroyed");

}


}


16. How Spring Boot Auto Configuration Works

Spring Boot automatically configures beans based on:

  • Classpath dependencies
  • Application properties
  • Existing Spring beans

Example:



Adding:

spring-boot-starter-data-jpa


Automatically creates:

- DataSource
- EntityManagerFactory
- TransactionManager


Internally Spring Boot uses:

  • @Configuration
  • @Conditional annotations
  • AutoConfiguration classes

17. Aspect Oriented Programming (AOP)

AOP separates cross-cutting concerns from business logic.

Common examples:

  • Logging
  • Security
  • Transactions
  • Performance monitoring


@Before(
"execution(* com.example.service.*.*(..))"
)
public void log(){

 System.out.println("Method Started");

}


18. Heap Dump

Heap dump is a snapshot of JVM memory at a specific point.

Used for investigating:

  • Memory leaks
  • OutOfMemoryError
  • Large object creation

Tools

  • Eclipse MAT
  • VisualVM
  • JProfiler

19. Application Logging and Distributed Tracing

In microservices, a single request can travel through multiple services.



API Gateway

   |

Order Service

   |

Payment Service


Distributed tracing uses a unique Trace ID.

Common tools:

  • OpenTelemetry
  • Jaeger
  • Zipkin
  • ELK Stack
  • Grafana Loki

20. Spring Validation

Spring Validation validates incoming API requests before business processing.

DTO Example



public class UserRequest {


@NotNull
private String name;


@Email
private String email;


@Size(min=8)
private String password;


}

Controller Validation



@PostMapping("/users")
public ResponseEntity save(
 @Valid
 @RequestBody UserRequest request){

 return ResponseEntity.ok().build();

}

Best Practice: Validate data at API boundary and keep business validation inside service layer.

21. Inner Join and Outer Join

SQL joins are used to combine data from multiple tables based on related columns.

Inner Join

Returns only records that have matching values in both tables.



SELECT 
    o.id,
    c.name

FROM orders o

INNER JOIN customer c

ON o.customer_id = c.id;


Example:

Customer Order
John Order 101

Only customers having orders are returned.


Outer Join

Outer join returns matching records plus unmatched records.

Left Join



SELECT *

FROM customer c

LEFT JOIN orders o

ON c.id=o.customer_id;


Returns all customers even if they don't have orders.

Right Join

Returns all records from the right table.

Full Outer Join

Returns all records from both tables.


22. Database Indexing

An index improves query performance by allowing the database to find data faster without scanning the entire table.

Example Without Index



Table Scan

1 million records checked

Find matching row


With Index



Index Lookup

↓

Direct row access


Types of Indexes

Index Type Purpose
B-Tree Index Default index for searching and sorting
Hash Index Fast equality searches
Composite Index Multiple columns
Unique Index Enforces uniqueness

Advantages

  • Faster SELECT queries
  • Improved sorting performance
  • Better filtering

Disadvantages

  • Additional storage usage
  • Slower INSERT operations
  • Slower UPDATE/DELETE operations

23. Query Performance Validation (EXPLAIN)

Database query performance should be analyzed using execution plans.

EXPLAIN



EXPLAIN

SELECT *

FROM customer

WHERE email='test@test.com';


EXPLAIN ANALYZE



EXPLAIN ANALYZE

SELECT *

FROM orders

WHERE customer_id=100;


Things to Check

  • Full table scan
  • Index usage
  • Query cost
  • Number of rows scanned
  • Execution time
Performance Tip: A query returning 10 rows should not scan millions of records.

24. Database Partitioning

Partitioning divides a large table into smaller logical pieces while keeping it as one table from the application perspective.

Example



Transaction Table


Partition 2025

Partition 2026

Partition 2027


Partition Types

  • Range Partitioning
  • List Partitioning
  • Hash Partitioning

Benefits

  • Faster query execution
  • Easier maintenance
  • Improved data management

25. Java Virtual Threads

Virtual Threads were introduced as a preview feature in Java 19 and became permanent in Java 21.

They are lightweight threads managed by the JVM instead of directly mapping one-to-one with operating system threads.

Traditional Threads



Request 1 → OS Thread 1

Request 2 → OS Thread 2

Request 3 → OS Thread 3


Limited concurrency


Virtual Threads



Request 1 → Virtual Thread

Request 2 → Virtual Thread

Request 3 → Virtual Thread


Thousands of concurrent tasks


Advantages

  • High concurrency
  • Lower memory consumption
  • Simpler blocking-style code
  • Better scalability for I/O applications

Example



Thread.startVirtualThread(() -> {

    callExternalService();

});



26. Application Vulnerabilities

Common security vulnerabilities in enterprise applications:

Vulnerability Protection
SQL Injection Prepared statements, ORM
XSS Input encoding
CSRF CSRF tokens
SSRF Network filtering
Broken Authentication Strong authentication mechanisms

27. SOLID Principles

SOLID principles help create maintainable, flexible, and testable software designs.

Letter Meaning
S Single Responsibility Principle
O Open Closed Principle
L Liskov Substitution Principle
I Interface Segregation Principle
D Dependency Inversion Principle

28. ACID Properties

ACID defines reliable database transaction behavior.

Property Meaning
Atomicity Transaction succeeds completely or fails completely
Consistency Database remains valid after transaction
Isolation Transactions do not interfere
Durability Committed data survives failures

29. Symmetric and Asymmetric Encryption

Symmetric Encryption

Uses the same key for encryption and decryption.



Encryption Key

     |

Encrypt Data

     |

Decrypt Using Same Key


Example: AES

Asymmetric Encryption

Uses two keys:

  • Public Key
  • Private Key


Public Key

Encrypt


Private Key

Decrypt


Example: RSA


30. SSL / TLS

TLS provides secure communication between client and server.

Provides

  • Encryption
  • Authentication
  • Data Integrity

Used in:



HTTPS

API Communication

Secure Microservice Calls



31. JWT Validation Using Public and Private Keys

Asymmetric JWT signing improves security by separating token creation and token validation responsibilities.



Authentication Service

Private Key

       |

Generate JWT


API Gateway

Public Key

       |

Validate JWT


Advantages

  • Private key never leaves authentication service
  • Multiple services can validate tokens
  • Better security separation
  • No shared secret distribution
Performance Consideration: JWT validation is faster when public keys are cached instead of fetching them for every request.

32. Microservices Architecture - Pros and Cons

Microservices architecture divides a large application into small independent services that communicate through APIs.

Example Architecture



             API Gateway

                  |

 --------------------------------

 |              |               |

User Service  Order Service  Payment Service


Advantages

  • Independent deployment
  • Independent scaling
  • Technology flexibility
  • Better team ownership
  • Fault isolation

Disadvantages

  • Distributed system complexity
  • Network communication overhead
  • Data consistency challenges
  • More monitoring requirements
  • Deployment complexity

33. Design Patterns

Design patterns are reusable solutions for commonly occurring software design problems.

Creational Patterns

Pattern Purpose
Singleton Single object instance
Factory Object creation abstraction
Builder Complex object creation

Structural Patterns

  • Adapter
  • Proxy
  • Decorator

Behavioral Patterns

  • Strategy
  • Observer
  • Template Method

Spring Examples

Pattern Spring Usage
Singleton Spring Beans
Proxy AOP, Transaction Management
Factory BeanFactory

34. API Gateway

API Gateway acts as a single entry point for client requests in microservice architecture.

Responsibilities

  • Request Routing
  • Authentication and Authorization
  • Rate Limiting
  • Logging
  • Request Transformation
  • Load Balancing

Example



Mobile App

    |

API Gateway

    |

-------------------

User Service

Order Service

Payment Service


Common implementations:

  • Spring Cloud Gateway
  • Kong Gateway
  • NGINX
  • AWS API Gateway

35. Vertical and Horizontal Scaling

Vertical Scaling

Increasing resources of an existing server.



Before:

8 GB RAM
4 CPU


After:

32 GB RAM
16 CPU


Advantages

  • Simple implementation
  • No application changes

Disadvantages

  • Hardware limitation
  • Single point of failure

Horizontal Scaling

Adding more application instances.



Load Balancer


     |

-----------------

App 1

App 2

App 3


Advantages

  • Better availability
  • Unlimited growth
  • Cloud friendly

36. Kubernetes Pod Management

Kubernetes manages containerized applications by deploying and scaling containers using Pods.

Common Tools

  • kubectl
  • Kubernetes Dashboard
  • Rancher
  • OpenShift

Common Commands



kubectl get pods


kubectl logs pod-name


kubectl describe pod pod-name


kubectl get services


Kubernetes Objects

  • Pod
  • Deployment
  • Service
  • ConfigMap
  • Secret
  • Ingress

37. Cloud Storage - Azure Blob and Amazon S3

Cloud object storage is used for storing large unstructured data.

Common Use Cases

  • Documents
  • Images
  • Videos
  • Backup files
  • Reports

Azure Blob Storage

Microsoft Azure object storage service.

Amazon S3

AWS scalable object storage service.

Typical Flow



Application

     |

Upload File

     |

Cloud Storage

     |

Return File URL



38. Akamai CDN

A CDN (Content Delivery Network) distributes content closer to users through geographically distributed servers.

Benefits

  • Faster content delivery
  • Reduced server load
  • Improved availability
  • DDoS protection

Example



User Malaysia

      |

Akamai Edge Server

      |

Origin Server



39. Production Bug Investigation

A structured debugging approach is important for production issues.

Investigation Process

  1. Collect issue details
  2. Check application logs
  3. Analyze stack trace
  4. Reproduce issue locally
  5. Check database behaviour
  6. Review recent deployments
  7. Implement fix and regression test

Common Tools

  • ELK Stack
  • Grafana
  • Prometheus
  • JProfiler
  • JVM Monitoring Tools

40. Performance Testing

Performance testing validates application behaviour under different workloads.

Types of Testing

  • Load Testing
  • Stress Testing
  • Endurance Testing
  • Spike Testing

Tools

  • Apache JMeter
  • Gatling
  • k6

Important Metrics

Metric Purpose
Response Time API performance
Throughput Requests per second
CPU Usage Resource utilization
Memory Usage Memory efficiency
Error Rate Application stability

Conclusion

A Senior Java Engineer is expected not only to understand coding but also architecture, performance, security, database optimization, cloud infrastructure, and production troubleshooting.

Key Areas to Master:
  • Java Internals
  • Spring Boot Architecture
  • Microservices Design
  • Database Performance
  • Cloud Native Development
  • Security Best Practices
  • System Design

Comments

Popular posts from this blog

Spring Boot 4 Ready

Spring Boot 4.x Features Explained:  Java 25, AI Agents, MCP, Resilience, gRPC & Cloud Native Evolution Building on the massive architectural shift introduced in version 3, Spring Boot 4.x bridges the gap between traditional enterprise stability and the rapid demands of modern cloud architecture and AI integration. While Spring Boot 3 introduced the foundations for GraalVM Native Images and Virtual Threads , Spring Boot 4 takes these capabilities mainstream, introduces native resilience patterns, and upgrades the underlying Spring ecosystem. Spring Boot 4 Major Theme: Modern enterprise development with cloud-native architecture, AI integration, improved resilience, better modularity, and optimized JVM performance. Table of Contents 1. Upgraded Foundation & Baselines 2. Built-in Core Resilience Features 3. First-Class Agentic AI & Model Context Protocol (MCP) 4. Native API Versioning Strategy 5. Modern...

Data Structure

Java Data Structures A highly-scannable architectural cheat sheet for developers and technical interviews. 1. Linear vs. Non-Linear: The Core Division Data Structure Classification Hierarchy ┌───────────────────────┐ │ Data Structures │ └───────────┬───────────┘ │ ┌───────────────┴───────────────┐ ▼ ▼ ┌────────────────────┐ ┌────────────────────┐ │ Linear (Seq) │ │ Non-Linear │ └──────────┬─────────┘ └──────────┬─────────┘ │ │ ┌──────┴──────┐ ┌──────┴──────┐ ▼ ▼ ▼ ▼ [Static] [Dynamic] [Trees] [Graphs] (Array) (Queue, Stack) (BST) (Network) ...