Custom Query Methods in Spring Data JPA with Real Examples

3:25 AM

One of the most powerful features of Spring Data JPA is its ability to generate SQL queries automatically from method names.


Instead of writing SQL manually, developers can create repository methods following specific naming conventions and Spring Data JPA automatically generates the required query.


What are Query Methods?

Query Methods are repository methods whose names describe the query that should be executed.

Spring Data JPA analyses the method name and generates the SQL query automatically.


Why Use Query Methods?

  • Less boilerplate code
  • No SQL required for simple queries
  • Improved readability
  • Faster development
  • Better maintainability

Employee Entity


@Entity
public class Employee {

    @Id
    @GeneratedValue(
        strategy =
        GenerationType.IDENTITY
    )
    private Long id;

    private String name;

    private String department;

    private Double salary;

}

Repository Layer


@Repository
public interface EmployeeRepository
extends JpaRepository<
        Employee,
        Long> {

}

Find By Name

Retrieve employees by name.



List<Employee>
findByName(String name);

Generated Query Conceptually:



SELECT *
FROM employees
WHERE name = ?

Find By Department


List<Employee>
findByDepartment(
    String department
);

Generated Query:



SELECT *
FROM employees
WHERE department = ?

Find By Salary Greater Than


List<Employee>
findBySalaryGreaterThan(
    Double salary
);

Returns employees with salaries higher than the specified amount.



SELECT *
FROM employees
WHERE salary > ?

Find By Salary Less Than


List<Employee>
findBySalaryLessThan(
    Double salary
);

Returns employees whose salary is below the specified value.


Find By Department And Salary

Multiple conditions can be combined.



List<Employee>
findByDepartmentAndSalaryGreaterThan(
    String department,
    Double salary
);

Generated Query:



SELECT *
FROM employees
WHERE department = ?
AND salary > ?

Find By Name Containing

Useful for search functionality.



List<Employee>
findByNameContaining(
    String keyword
);

Generated Query:



SELECT *
FROM employees
WHERE name LIKE '%keyword%'

Find By Name Starting With


List<Employee>
findByNameStartingWith(
    String prefix
);

Example:



findByNameStartingWith("Jo")

Matches:



John

Joseph

Jordan

Find By Name Ending With


List<Employee>
findByNameEndingWith(
    String suffix
);

Find Top Records

Spring Data JPA supports limiting results.



List<Employee>
findTop5ByOrderBySalaryDesc();

Returns the top five highest-paid employees.


Find First Record


Employee
findFirstByOrderBySalaryDesc();

Returns the highest-paid employee.


Find By Multiple Fields


List<Employee>
findByNameAndDepartment(
    String name,
    String department
);

Find By In Clause


List<Employee>
findByDepartmentIn(
    List<String>
    departments
);

Example:



IT

HR

Finance

Ignore Case Searches


List<Employee>
findByNameIgnoreCase(
    String name
);

Useful for user-friendly searches.


Combining Query Methods with Pagination


Page<Employee>
findByDepartment(

    String department,

    Pageable pageable

);

Results can be paginated while still using query methods.


Service Layer Example


public List<Employee>
getITEmployees() {

    return repository
            .findByDepartment(
                "IT"
            );

}

Controller Example


@GetMapping("/department")

public List<Employee>
getEmployeesByDepartment(

@RequestParam String department

) {

    return repository
            .findByDepartment(
                department
            );

}

Common Interview Questions

What are Query Methods in Spring Data JPA?

Methods whose names are automatically converted into SQL queries by Spring Data JPA.


Can query methods contain multiple conditions?

Yes. Conditions can be combined using And and Or.


Can pagination be used with query methods?

Yes. Query methods can accept Pageable parameters.


Can sorting be combined with query methods?

Yes. Spring Data JPA supports sorting and pagination together.


What happens if a method name becomes too long?

It may be better to use JPQL or @Query annotations.


Best Practices

  • Keep query method names readable.
  • Use query methods for simple queries.
  • Use JPQL for complex business queries.
  • Combine pagination whenever possible.
  • Avoid excessively long method names.

Frequently Asked Questions (FAQ)

Do query methods require SQL knowledge?

No. Spring Data JPA generates the queries automatically.


Can query methods join multiple tables?

For simple use cases yes. Complex joins often require JPQL or native queries.


Are query methods production ready?

Yes. They are widely used in enterprise Spring Boot applications.


Conclusion

Custom Query Methods are one of the most productive features of Spring Data JPA. They reduce boilerplate code and allow developers to create powerful database queries using simple method naming conventions. Understanding query methods is essential for Spring Boot development and interview preparation.


Keywords

Spring Data JPA Query Methods, Custom Query Methods, Spring Boot Repository Queries, findBy Example, JpaRepository Query Methods, Spring JPA Tutorial, Spring Data JPA Interview Questions, Repository Methods, Database Queries Spring Boot, Derived Query Methods, Spring Boot CRUD, Java Backend Development, Spring Framework Tutorial, JPA Methods, Spring Boot Database Access



Custom Query Methods in Spring Data JPA with Real Examples Custom Query Methods in Spring Data JPA with Real Examples Reviewed by 13thGhost on 3:25 AM Rating: 5

Pagination and Sorting in Spring Data JPA with Complete REST API Example

3:17 AM

Retrieving large amounts of data from a database can significantly impact application performance. Returning thousands of rows in a single API response consumes memory, increases response times and creates a poor user experience.


Spring Data JPA provides built-in support for Pagination and Sorting, allowing applications to fetch only the required records efficiently.


What is Pagination?

Pagination is the process of dividing data into smaller chunks called pages. Instead of loading all records at once, only a subset of records is returned.


Without Pagination


SELECT *
FROM employees;

This query returns every employee record. For large tables, this approach is inefficient.


With Pagination


Page 1 -> Records 1 to 10

Page 2 -> Records 11 to 20

Page 3 -> Records 21 to 30

Only the requested page is loaded.


What is Sorting?

Sorting allows records to be returned in a specific order.

Examples

  • Sort by Salary
  • Sort by Employee Name
  • Sort by Joining Date
  • Sort by Department

Sorting improves usability and data presentation.


Project Structure


controller
    EmployeeController

service
    EmployeeService

repository
    EmployeeRepository

entity
    Employee

Employee Entity


@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(
        strategy =
        GenerationType.IDENTITY
    )
    private Long id;

    private String name;

    private String department;

    private Double salary;

}

Repository Layer

Pagination support is automatically available through JpaRepository.



@Repository
public interface EmployeeRepository
extends JpaRepository<
        Employee,
        Long> {

}

Fetching Data Using Pagination

Spring Data JPA uses the Pageable interface.



Pageable pageable =
        PageRequest.of(
            0,
            5
        );

Page<Employee>
employees =
repository.findAll(pageable);

Parameters

  • 0 = Page Number
  • 5 = Records Per Page

This loads the first five employees.


Service Layer Example


@Service
public class EmployeeService {

    private final
        EmployeeRepository repository;

    public EmployeeService(
            EmployeeRepository repository) {

        this.repository = repository;

    }

    public Page<Employee>
        getEmployees(
            int page,
            int size) {

        Pageable pageable =
            PageRequest.of(
                page,
                size
            );

        return repository
                .findAll(pageable);

    }
}

Controller Example


@GetMapping
public Page<Employee>
getEmployees(

    @RequestParam int page,

    @RequestParam int size) {

    return service
            .getEmployees(
                page,
                size
            );
}

API Call Example


GET

/employees?page=0&size=5

This returns the first page with 5 records.


Pagination Response


{
  "content": [
    {
      "id": 1,
      "name": "John"
    }
  ],

  "totalPages": 5,

  "totalElements": 25,

  "size": 5,

  "number": 0
}

Sorting Example

Sorting is implemented using the Sort class.



Sort sort =
        Sort.by("salary");

repository.findAll(sort);

Employees are sorted by salary in ascending order.


Descending Sort Example


Sort sort =
        Sort.by("salary")
            .descending();

repository.findAll(sort);

Highest salaries appear first.


Multiple Column Sorting


Sort sort =
        Sort.by("department")
            .ascending()
            .and(
                Sort.by("salary")
                    .descending()
            );

Results are grouped by department and sorted by salary within each department.


Pagination and Sorting Together


Pageable pageable =
PageRequest.of(

    0,

    5,

    Sort.by("salary")
        .descending()

);

repository.findAll(pageable);

This is one of the most common approaches in production applications.


REST API Example


GET

/employees

?page=0

&size=10

&sort=salary,desc

This fetches ten employees sorted by salary in descending order.


Why Pagination is Important

  • Reduces memory usage
  • Improves API performance
  • Supports large datasets
  • Faster response times
  • Better user experience

Real Interview Questions

What is Pageable?

Pageable is an interface used to define pagination information such as page number and page size.


What is Page?

Page is a paginated result that contains records and pagination metadata.


Can Sorting and Pagination be used together?

Yes. This is a very common production use case.


Which repository supports pagination?

PagingAndSortingRepository and JpaRepository.


What happens if pagination is not implemented?

Large datasets may slow down applications and consume unnecessary memory.


Best Practices

  • Always paginate large datasets.
  • Use sensible page sizes.
  • Avoid returning thousands of records.
  • Combine sorting with pagination.
  • Validate page and size parameters.

Frequently Asked Questions (FAQ)

What is the difference between List and Page?

List contains only data, while Page contains data along with pagination information.


Can pagination improve performance?

Yes. It reduces the amount of data loaded into memory.


Does JpaRepository support sorting automatically?

Yes. Sorting support is built into JpaRepository.


Conclusion

Pagination and Sorting are essential techniques for building efficient Spring Boot applications. Spring Data JPA provides powerful built-in support using Pageable, PageRequest and Sort, making it easy to handle large datasets while maintaining excellent application performance.


Keywords

Pagination Spring Data JPA, Sorting Spring Data JPA, Spring Boot Pagination, JpaRepository Pagination, Pageable Example, PageRequest Example, Sorting Example Spring Data JPA, Spring Boot REST API Pagination, Pagination and Sorting Interview Questions, Spring Data JPA Tutorial, Spring Boot Database Performance, Java Backend Development, JPA Paging Example, Spring Boot CRUD, Spring Framework Tutorial

Pagination and Sorting in Spring Data JPA with Complete REST API Example Pagination and Sorting in Spring Data JPA with Complete REST API Example Reviewed by 13thGhost on 3:17 AM Rating: 5

CrudRepository vs PagingAndSortingRepository vs JpaRepository in Spring Data JPA

2:58 AM

Spring Data JPA provides multiple repository interfaces to simplify database operations. One of the most common interview questions for Spring developers is understanding the difference between CrudRepository, PagingAndSortingRepository and JpaRepository.


Although these interfaces appear similar, they offer different capabilities and are designed for different use cases.


Repository Hierarchy

Before comparing these interfaces, it is important to understand their inheritance relationship.



Repository
     |
     v
CrudRepository
     |
     v
PagingAndSortingRepository
     |
     v
JpaRepository

Each interface extends the previous one and provides additional functionality.


What is Repository?

Repository is the base marker interface in Spring Data.



public interface Repository<T, ID> {

}

It does not provide any methods. It simply identifies an interface as a Spring Data repository.


CrudRepository

CrudRepository provides basic Create, Read, Update and Delete operations.



public interface EmployeeRepository
extends CrudRepository<
        Employee,
        Long> {

}

Common Methods


save()

findById()

findAll()

deleteById()

existsById()

count()

Example


Employee employee =
        new Employee(
            "John",
            "IT",
            50000.0
        );

repository.save(employee);

The save() method inserts or updates records.


When Should You Use CrudRepository?

  • Simple CRUD applications
  • Basic database operations
  • Small projects
  • Learning Spring Data JPA

PagingAndSortingRepository

PagingAndSortingRepository extends CrudRepository and adds pagination and sorting support.



public interface EmployeeRepository
extends PagingAndSortingRepository<
        Employee,
        Long> {

}

This repository is useful when working with large datasets.


Additional Methods


findAll(Pageable pageable)

findAll(Sort sort)

Pagination Example


Pageable pageable =
        PageRequest.of(
            0,
            5
        );

Page<Employee>
employees =
repository.findAll(pageable);

This fetches the first page containing five records.


Sorting Example


Sort sort =
        Sort.by("salary")
            .descending();

Iterable<Employee>
employees =
repository.findAll(sort);

Results are returned in descending salary order.


When Should You Use PagingAndSortingRepository?

  • Large datasets
  • Pagination requirements
  • Sorting requirements
  • REST APIs returning large results

JpaRepository

JpaRepository extends PagingAndSortingRepository and provides JPA-specific functionality.



public interface EmployeeRepository
extends JpaRepository<
        Employee,
        Long> {

}

This is the most commonly used repository interface in Spring Boot applications.


Additional Methods


flush()

saveAndFlush()

deleteAllInBatch()

deleteAllByIdInBatch()

getReferenceById()

saveAndFlush() Example


repository.saveAndFlush(
        employee
);

It immediately writes changes to the database.


Batch Delete Example


repository.deleteAllInBatch();

Deletes all records using batch operations.


Feature Comparison

Feature CrudRepository PagingAndSortingRepository JpaRepository
CRUD Operations Yes Yes Yes
Pagination No Yes Yes
Sorting No Yes Yes
Batch Operations No No Yes
Flush Support No No Yes

Which Repository Should You Use?

In modern Spring Boot applications, JpaRepository is usually the preferred choice because it includes all CRUD, pagination, sorting and JPA-specific features.

Most enterprise applications directly use JpaRepository instead of CrudRepository or PagingAndSortingRepository.


Real Project Example


@Repository
public interface EmployeeRepository
        extends JpaRepository<
            Employee,
            Long> {

}

This single interface provides CRUD, paging, sorting and batch operations.


Common Interview Questions

Does JpaRepository extend CrudRepository?

Yes. JpaRepository indirectly extends CrudRepository through PagingAndSortingRepository.


Which repository supports pagination?

PagingAndSortingRepository and JpaRepository.


Which repository is most commonly used?

JpaRepository.


What is the advantage of JpaRepository?

It provides CRUD, pagination, sorting and additional JPA-specific operations.


Best Practices

  • Prefer JpaRepository for most projects.
  • Use pagination for large datasets.
  • Avoid returning huge result sets.
  • Use sorting to improve API usability.
  • Leverage batch operations when necessary.

Frequently Asked Questions (FAQ)

Can JpaRepository perform CRUD operations?

Yes. It inherits all CRUD methods from CrudRepository.


Can CrudRepository perform pagination?

No. Pagination requires PagingAndSortingRepository or JpaRepository.


Should new Spring Boot projects use JpaRepository?

Yes. JpaRepository is generally the preferred repository interface for modern applications.


Conclusion

CrudRepository, PagingAndSortingRepository and JpaRepository build upon each other. While CrudRepository provides basic CRUD operations and PagingAndSortingRepository adds pagination and sorting support, JpaRepository includes all features and additional JPA-specific functionality. For most Spring Boot applications, JpaRepository is the recommended choice.


Keywords

CrudRepository vs JpaRepository, JpaRepository vs PagingAndSortingRepository, Spring Data JPA Repository, JpaRepository Tutorial, CrudRepository Example, PagingAndSortingRepository Example, Spring Boot JPA, Spring Data Repository Comparison, Pagination Spring Data JPA, Sorting Spring Data JPA, JPA Interview Questions, Spring Boot Interview Questions, JpaRepository Methods, Spring Data JPA Tutorial, Java Backend Development



CrudRepository vs PagingAndSortingRepository vs JpaRepository in Spring Data JPA CrudRepository vs PagingAndSortingRepository vs JpaRepository in Spring Data JPA Reviewed by 13thGhost on 2:58 AM Rating: 5

Spring Data JPA Explained with Complete CRUD Example

2:53 AM

Spring Data JPA is one of the most popular modules in the Spring ecosystem. It simplifies database operations by reducing boilerplate code and providing ready-made repository implementations.


Instead of writing lengthy JDBC code, developers can use Spring Data JPA repositories to perform Create, Read, Update and Delete (CRUD) operations with minimal effort.


What is Spring Data JPA?

Spring Data JPA is a framework built on top of JPA (Java Persistence API) that simplifies database access in Spring applications.

It provides repository interfaces that automatically generate SQL queries behind the scenes.


Why Use Spring Data JPA?

  • Less boilerplate code
  • Automatic query generation
  • Built-in CRUD methods
  • Pagination support
  • Sorting support
  • Easier database access

Project Structure


src/main/java

├── controller
│    └── EmployeeController
│
├── service
│    └── EmployeeService
│
├── repository
│    └── EmployeeRepository
│
├── entity
│    └── Employee
│
└── EmployeeApplication

Step 1: Maven Dependencies

Add the required dependencies in pom.xml.


<dependency>
    <groupId>
        org.springframework.boot
    </groupId>

    <artifactId>
        spring-boot-starter-data-jpa
    </artifactId>
</dependency>

<dependency>
    <groupId>
        com.mysql
    </groupId>

    <artifactId>
        mysql-connector-j
    </artifactId>
</dependency>

<dependency>
    <groupId>
        org.springframework.boot
    </groupId>

    <artifactId>
        spring-boot-starter-web
    </artifactId>
</dependency>

Step 2: Configure Database

Create application.properties.


spring.datasource.url=
jdbc:mysql://localhost:3306/employeedb

spring.datasource.username=root

spring.datasource.password=root

spring.jpa.hibernate.ddl-auto=update

spring.jpa.show-sql=true

Step 3: Create Entity Class

The Entity class represents a database table.


@Entity
@Table(name = "employees")
public class Employee {

    @Id
    @GeneratedValue(
        strategy =
            GenerationType.IDENTITY
    )
    private Long id;

    private String name;

    private String department;

    private Double salary;

    public Employee() {

    }

    public Employee(
            String name,
            String department,
            Double salary) {

        this.name = name;
        this.department = department;
        this.salary = salary;

    }

    // Getters and Setters

}

What Do These Annotations Mean?

Annotation Purpose
@Entity Marks class as database entity
@Table Maps to database table
@Id Primary key
@GeneratedValue Auto-generates ID

Step 4: Create Repository Layer

The Repository layer handles database communication.



@Repository
public interface EmployeeRepository
        extends JpaRepository<
            Employee,
            Long> {

}

That's it.


Spring automatically provides CRUD methods.


Available CRUD Methods


save()

findById()

findAll()

deleteById()

count()

existsById()

Step 5: Create Service Layer

Business logic belongs in the service layer.


@Service
public class EmployeeService {

    private final
        EmployeeRepository repository;

    public EmployeeService(
            EmployeeRepository repository) {

        this.repository = repository;

    }

    public Employee saveEmployee(
            Employee employee) {

        return repository.save(
                employee);

    }

    public List<Employee>
        getEmployees() {

        return repository.findAll();

    }

    public Employee getEmployee(
            Long id) {

        return repository
                .findById(id)
                .orElseThrow();

    }

    public void deleteEmployee(
            Long id) {

        repository.deleteById(id);

    }
}

Step 6: Create REST Controller

The Controller exposes API endpoints.


@RestController
@RequestMapping("/employees")
public class EmployeeController {

    private final
        EmployeeService service;

    public EmployeeController(
            EmployeeService service) {

        this.service = service;

    }

    @PostMapping
    public Employee createEmployee(
            @RequestBody Employee employee) {

        return service.saveEmployee(
                employee);

    }

    @GetMapping
    public List<Employee>
        getEmployees() {

        return service.getEmployees();

    }

    @GetMapping("/{id}")
    public Employee getEmployee(
            @PathVariable Long id) {

        return service.getEmployee(id);

    }

    @DeleteMapping("/{id}")
    public void deleteEmployee(
            @PathVariable Long id) {

        service.deleteEmployee(id);

    }
}

Testing Create Employee API

POST Request:



POST /employees

Request Body:


{
  "name":"John",
  "department":"IT",
  "salary":50000
}

Response:


{
  "id":1,
  "name":"John",
  "department":"IT",
  "salary":50000
}

Testing Get All Employees


GET /employees

Response


[
  {
    "id":1,
    "name":"John",
    "department":"IT"
  }
]

Custom Query Method Example

Spring Data JPA can generate queries directly from method names.



List<Employee>
findByDepartment(
    String department
);

Spring automatically generates the SQL query.


Generated Query Conceptually


SELECT *
FROM employees
WHERE department = ?

Common Interview Questions

What is Spring Data JPA?

A framework that simplifies database operations using JPA repositories.


What is JpaRepository?

An interface that provides built-in CRUD operations.


Difference Between JPA and Hibernate?

JPA is a specification. Hibernate is one implementation of JPA.


What does @Entity do?

Marks a class as a database entity.


Can we create custom queries?

Yes, using method names, JPQL or native SQL queries.


Best Practices

  • Keep business logic in service layer.
  • Avoid database logic in controllers.
  • Use constructor injection.
  • Create custom queries only when needed.
  • Use pagination for large datasets.

Frequently Asked Questions (FAQ)

Does Spring Data JPA create tables automatically?

Yes, when Hibernate DDL auto generation is enabled.


Can Spring Data JPA work with PostgreSQL?

Yes. It supports PostgreSQL, MySQL, Oracle, SQL Server and many other databases.


Is Hibernate required?

Hibernate is the default JPA implementation in Spring Boot applications.


Conclusion

Spring Data JPA drastically reduces database-related boilerplate code and allows developers to focus on business logic. Understanding Entities, Repositories, Services, Controllers and CRUD operations is essential for building Spring Boot applications and succeeding in Spring interviews.


Keywords

Spring Data JPA, Spring Boot CRUD Example, JpaRepository Example, Spring JPA Tutorial, Hibernate JPA, Spring Boot Database Example, Spring Boot REST API, CRUD Operations Spring Boot, JPA Interview Questions, Spring Data JPA Tutorial, Entity Repository Service Controller, Java Persistence API, Spring Framework, Spring Boot Example, Java Backend Development



Spring Data JPA Explained with Complete CRUD Example Spring Data JPA Explained with Complete CRUD Example Reviewed by 13thGhost on 2:53 AM Rating: 5

Global Exception Handling in Spring Boot using @ControllerAdvice

2:45 AM

Proper exception handling is an essential part of every production-grade Spring Boot application. Without a centralized approach, exception handling logic quickly becomes repetitive, difficult to maintain and inconsistent across APIs.


Spring Boot provides @ControllerAdvice and @ExceptionHandler annotations that allow developers to handle exceptions globally and return meaningful error responses to clients.


Why Exception Handling is Important

Applications often encounter unexpected situations such as invalid input, missing data, database failures and business validation errors.

If exceptions are not handled properly, users may receive confusing error messages or generic server errors.


Common Problems

  • Duplicate try-catch blocks
  • Inconsistent API responses
  • Difficult maintenance
  • Poor user experience
  • Harder debugging

Traditional Exception Handling Approach

Many beginners handle exceptions directly inside controller methods.


@GetMapping("/{id}")
public Employee getEmployee(
        @PathVariable Long id) {

    try {

        return employeeService
                .findById(id);

    }
    catch(Exception ex) {

        throw ex;

    }
}

This works but becomes difficult to maintain when the application grows.


What is @ControllerAdvice?

@ControllerAdvice is a Spring annotation used to provide centralized exception handling across multiple controllers.

Instead of writing exception handling logic in every controller, we can define it in a single class.


Benefits of @ControllerAdvice

  • Centralized exception handling
  • Cleaner controller code
  • Consistent API responses
  • Improved maintainability
  • Better error management

Creating a Custom Exception

Let's create a custom exception for situations where an employee cannot be found.


public class EmployeeNotFoundException
        extends RuntimeException {

    public EmployeeNotFoundException(
            String message) {

        super(message);

    }
}

Controller Example

Suppose a client requests an employee that does not exist.


@RestController
@RequestMapping("/employees")
public class EmployeeController {

    @GetMapping("/{id}")
    public Employee getEmployee(
            @PathVariable Long id) {

        throw new EmployeeNotFoundException(
                "Employee not found");

    }
}

Without exception handling, Spring will return a generic error response.


Implementing Global Exception Handler

Now let's create a centralized exception handling class.



@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(
        EmployeeNotFoundException.class
    )
    public ResponseEntity<String>
        handleEmployeeNotFound(
                EmployeeNotFoundException ex) {

        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(ex.getMessage());

    }
}

Whenever EmployeeNotFoundException occurs, Spring automatically invokes this method.


Response Example

Request:



GET /employees/100

Response:



Employee not found

Returning Standard JSON Error Response

In real-world applications, returning structured JSON responses is preferred.


Error Response Class


public class ErrorResponse {

    private String message;
    private int status;

    public ErrorResponse(
            String message,
            int status) {

        this.message = message;
        this.status = status;

    }

}

Updated Exception Handler


@ExceptionHandler(
    EmployeeNotFoundException.class
)
public ResponseEntity<ErrorResponse>
handleEmployeeNotFound(
    EmployeeNotFoundException ex) {

    ErrorResponse response =
        new ErrorResponse(
            ex.getMessage(),
            404
        );

    return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(response);
}

JSON Response


{
  "message": "Employee not found",
  "status": 404
}

Handling Multiple Exceptions

A single @ControllerAdvice can handle multiple exception types.



@ExceptionHandler(
    IllegalArgumentException.class
)
public ResponseEntity<String>
handleBadRequest(
    IllegalArgumentException ex) {

    return ResponseEntity
            .badRequest()
            .body(ex.getMessage());
}


@ExceptionHandler(
    RuntimeException.class
)
public ResponseEntity<String>
handleRuntimeException(
    RuntimeException ex) {

    return ResponseEntity
            .internalServerError()
            .body(ex.getMessage());
}

Handling Validation Errors

Spring Boot applications frequently validate incoming requests using Bean Validation.



public class EmployeeRequest {

    @NotBlank
    private String name;

}

Validation failures can also be handled globally.


@ControllerAdvice vs @RestControllerAdvice

@ControllerAdvice @RestControllerAdvice
Used for MVC Controllers Used for REST APIs
May require @ResponseBody Automatically adds @ResponseBody
Supports Views Returns JSON/XML Responses

For REST APIs, @RestControllerAdvice is generally preferred.


Real World Example

Imagine an e-commerce application.


Possible exceptions:

  • ProductNotFoundException
  • OrderNotFoundException
  • PaymentFailedException
  • CustomerNotFoundException

Instead of handling each exception in every controller, one GlobalExceptionHandler can manage them all.


How Spring Handles Exceptions Internally

When an exception occurs:



Controller
    |
    v
Exception Thrown
    |
    v
@ControllerAdvice
    |
    v
Error Response
    |
    v
Client

Spring automatically finds the matching @ExceptionHandler method and returns the appropriate response.


Common Interview Questions

What is @ControllerAdvice?

A Spring annotation used for centralized exception handling across multiple controllers.


What is @ExceptionHandler?

It defines a method that handles specific exception types.


What is the difference between @ControllerAdvice and @RestControllerAdvice?

@RestControllerAdvice automatically returns response bodies and is typically used for REST APIs.


Can there be multiple @ControllerAdvice classes?

Yes. Spring can manage multiple exception handler classes.


Why use global exception handling?

To avoid duplication and ensure consistent API responses.


Best Practices

  • Use custom exceptions for business scenarios.
  • Return consistent JSON error structures.
  • Avoid exposing internal stack traces.
  • Use @RestControllerAdvice for REST APIs.
  • Log exceptions appropriately.

Frequently Asked Questions (FAQ)

Can @ControllerAdvice handle all controllers?

Yes, unless specific packages or annotations are configured.


Can multiple exceptions share the same handler?

Yes. Multiple exception types can be mapped to a single method.


Should I use try-catch in controllers?

Generally no. Global exception handling provides a cleaner solution.


Conclusion

Global exception handling is a critical feature in Spring Boot applications. Using @ControllerAdvice and @ExceptionHandler helps create cleaner controllers, consistent API responses and maintainable applications. Understanding centralized exception handling is essential for both production development and Spring Boot interviews.


Keywords

@ControllerAdvice, @RestControllerAdvice, Spring Boot Exception Handling, Global Exception Handling Spring Boot, @ExceptionHandler Example, Spring Boot Interview Questions, REST API Error Handling, Custom Exception Spring Boot, Spring Framework Exception Handling, Java Spring Boot Tutorial, Centralized Exception Handling, Spring Boot Best Practices, Error Response JSON, Spring MVC Exception Handling, Spring Boot Development



Global Exception Handling in Spring Boot using @ControllerAdvice Global Exception Handling in Spring Boot using @ControllerAdvice Reviewed by 13thGhost on 2:45 AM Rating: 5

Factory Design Pattern in Java with Real Examples

2:34 AM

The Factory Design Pattern is one of the most commonly used Creational Design Patterns in Java. Instead of creating objects directly using the new keyword, object creation logic is delegated to a factory class.


The Factory Pattern promotes loose coupling, improves maintainability and simplifies object creation. It is used extensively in enterprise applications, Spring Framework, Hibernate and Java SDK libraries.


What is Factory Design Pattern?

Factory Design Pattern provides an interface or method for creating objects without exposing object creation logic to the client.

The client requests an object from the factory instead of creating it directly.


Why Do We Need Factory Pattern?

Imagine an application that creates different types of vehicles.

Without a Factory Pattern, the client would need to know exactly which class to instantiate.


Vehicle vehicle = new Car();

As the number of vehicle types grows, object creation becomes difficult to manage.


Problem Without Factory Pattern


if(type.equals("CAR")) {

    vehicle = new Car();

}
else if(type.equals("BIKE")) {

    vehicle = new Bike();

}
else if(type.equals("TRUCK")) {

    vehicle = new Truck();

}

This approach violates the Open/Closed Principle and makes maintenance harder.


Factory Pattern Solution

Move object creation logic into a dedicated factory.


Client
   |
   v
Factory
   |
   +---- Car

   +---- Bike

   +---- Truck

The client no longer needs to know how objects are created.


Step 1: Create Interface


public interface Vehicle {

    void drive();

}

All vehicle implementations will follow this contract.


Step 2: Create Implementations

Car Class


public class Car
        implements Vehicle {

    @Override
    public void drive() {

        System.out.println(
            "Driving Car"
        );

    }
}

Bike Class


public class Bike
        implements Vehicle {

    @Override
    public void drive() {

        System.out.println(
            "Driving Bike"
        );

    }
}

Truck Class


public class Truck
        implements Vehicle {

    @Override
    public void drive() {

        System.out.println(
            "Driving Truck"
        );

    }
}

Step 3: Create Factory Class


public class VehicleFactory {

    public static Vehicle
        getVehicle(String type) {

        if(type.equalsIgnoreCase("CAR")) {

            return new Car();

        }

        if(type.equalsIgnoreCase("BIKE")) {

            return new Bike();

        }

        if(type.equalsIgnoreCase("TRUCK")) {

            return new Truck();

        }

        throw new IllegalArgumentException(
            "Invalid Vehicle Type"
        );
    }
}

Step 4: Client Code


public class FactoryDemo {

    public static void main(String[] args) {

        Vehicle vehicle =
            VehicleFactory
                .getVehicle("CAR");

        vehicle.drive();

    }
}

Output


Driving Car

How Factory Pattern Works Internally

The client requests an object from the factory.

The factory decides which concrete implementation should be created and returned.


Client
   |
   v
VehicleFactory
   |
   +---- Car

   +---- Bike

   +---- Truck

This hides object creation details from the client.


Real World Example

Consider a Notification System.


Email Notification

SMS Notification

Push Notification

Instead of directly creating notification objects, a factory can return the correct implementation.


Notification notification =
NotificationFactory
    .getNotification("EMAIL");

Factory Pattern in Spring Framework

Spring internally uses factory-based approaches for bean creation.

A common example is FactoryBean.


FactoryBean<Object>

Spring delegates bean creation logic through factory mechanisms extensively.


Factory Pattern Advantages

  • Loose Coupling
  • Better Maintainability
  • Centralized Object Creation
  • Easier Extension
  • Improved Readability

Factory Pattern Disadvantages

  • Additional Classes
  • Increased Complexity for Small Projects
  • May Introduce Extra Abstraction

Factory Pattern vs Singleton Pattern

Factory Pattern Singleton Pattern
Creates Objects Restricts Object Creation
Multiple Instances Possible Single Instance
Focuses on Creation Logic Focuses on Object Uniqueness

Common Interview Questions

What is Factory Design Pattern?

A creational design pattern that delegates object creation to a factory class.


Why use Factory Pattern?

To reduce coupling and centralize object creation logic.


Which SOLID principle does Factory Pattern support?

Open/Closed Principle and Dependency Inversion Principle.


Is Factory Pattern used in Spring Framework?

Yes. Spring uses factory-based mechanisms internally for bean creation and management.


When should Factory Pattern be used?

When object creation logic becomes complex or multiple implementations exist.


Best Practices

  • Use interfaces for products.
  • Keep factory logic centralized.
  • Avoid overly complex factory implementations.
  • Combine Factory Pattern with Dependency Injection where appropriate.
  • Follow SOLID principles.

Frequently Asked Questions (FAQ)

Can Factory Pattern return different object types?

Yes. That is one of its primary purposes.


Can Factory Pattern improve maintainability?

Yes. It centralizes object creation and reduces direct dependencies.


Is Factory Pattern a Creational Pattern?

Yes. Factory Pattern belongs to the Creational Design Pattern category.


Conclusion

The Factory Design Pattern simplifies object creation and promotes loose coupling between application components. It is widely used across enterprise Java applications, Spring Framework and design pattern-based architectures. Mastering Factory Pattern is essential for interviews and writing maintainable software solutions.


Keywords

Factory Design Pattern, Factory Pattern Java, Creational Design Patterns, Java Design Patterns, Factory Method Pattern, Factory Pattern Interview Questions, Spring FactoryBean, Object Creation Pattern, Design Patterns Java, Factory Example Java, Core Java Interview Questions, Java Architecture, OOP Design Patterns, Software Design Patterns, Java Best Practices



Factory Design Pattern in Java with Real Examples Factory Design Pattern in Java with Real Examples Reviewed by 13thGhost on 2:34 AM Rating: 5

Singleton Design Pattern in Java with Real Examples and Thread Safety

2:20 AM

The Singleton Design Pattern is one of the most widely used and frequently asked design patterns in Java interviews. It ensures that only one instance of a class exists throughout the application lifecycle and provides a global access point to that instance.


The Singleton Pattern belongs to the Creational Design Patterns category because it controls how objects are created.


What is Singleton Design Pattern?

Singleton is a design pattern that restricts object creation to exactly one instance.

Instead of allowing multiple objects to be created, the class manages its own instance internally and exposes a method to access it.


Why Do We Need Singleton Pattern?

Some resources should exist only once in an application. Creating multiple instances may waste memory or cause inconsistent behaviour.

Examples

  • Database Connection Manager
  • Configuration Manager
  • Logging Service
  • Cache Manager
  • Thread Pool Manager

Problem Without Singleton


DatabaseConfig config1 =
        new DatabaseConfig();

DatabaseConfig config2 =
        new DatabaseConfig();

The application creates two separate objects. Sometimes this behaviour is undesirable.


Basic Singleton Implementation


public class Singleton {

    private static Singleton instance =
            new Singleton();

    private Singleton() {

    }

    public static Singleton getInstance() {

        return instance;

    }
}

The constructor is private, preventing direct object creation.


Using Singleton


Singleton s1 =
        Singleton.getInstance();

Singleton s2 =
        Singleton.getInstance();

System.out.println(s1 == s2);

Output


true

Both references point to the same object.


How Singleton Works Internally

The Singleton class creates an object internally and stores it in a static variable.

Whenever getInstance() is called, the same object is returned.



Application
      |
      v
getInstance()
      |
      v
Single Object

Lazy Initialization Singleton

In Eager Initialization, the object is created immediately. Sometimes we want to create the object only when it is first needed.



public class Singleton {

    private static Singleton instance;

    private Singleton() {

    }

    public static Singleton getInstance() {

        if(instance == null) {

            instance =
                new Singleton();

        }

        return instance;
    }
}

This approach is called Lazy Initialization.


Problem With Lazy Initialization

The previous implementation is not thread-safe.

If two threads call getInstance() simultaneously, multiple objects may be created.


Thread Safe Singleton


public class Singleton {

    private static Singleton instance;

    private Singleton() {

    }

    public static synchronized
        Singleton getInstance() {

        if(instance == null) {

            instance =
                new Singleton();

        }

        return instance;
    }
}

The synchronized keyword prevents simultaneous object creation.


Drawback of Synchronized Method

Synchronization solves the problem but may reduce performance because every call requires locking.


Double Checked Locking

A more efficient solution is Double Checked Locking.



public class Singleton {

    private static volatile
        Singleton instance;

    private Singleton() {

    }

    public static Singleton
        getInstance() {

        if(instance == null) {

            synchronized(Singleton.class) {

                if(instance == null) {

                    instance =
                        new Singleton();

                }
            }
        }

        return instance;
    }
}

This approach provides thread safety while minimizing synchronization overhead.


Bill Pugh Singleton

One of the most recommended Singleton implementations is the Bill Pugh approach.



public class Singleton {

    private Singleton() {

    }

    private static class Holder {

        private static final
            Singleton INSTANCE =
                new Singleton();

    }

    public static Singleton
        getInstance() {

        return Holder.INSTANCE;

    }
}

This implementation is thread-safe, efficient and lazy-loaded.


Enum Singleton

Java provides an elegant approach using enums.



public enum Singleton {

    INSTANCE;

}

Joshua Bloch recommends Enum Singleton because it protects against reflection and serialization issues.


Real World Example

Consider a logging system.



public class Logger {

    private static final
        Logger INSTANCE =
            new Logger();

    private Logger() {

    }

    public static Logger
        getInstance() {

        return INSTANCE;

    }
}

All modules use the same Logger instance.


Advantages of Singleton Pattern

  • Controlled object creation
  • Global access point
  • Memory efficient
  • Useful for shared resources
  • Easy to implement

Disadvantages of Singleton Pattern

  • Can introduce global state
  • Difficult unit testing
  • Tight coupling risks
  • Can violate Single Responsibility Principle

Singleton vs Spring Singleton Bean

Java Singleton Spring Singleton
One Object Per JVM One Bean Per Container
Managed By Class Managed By Spring
Manual Implementation Framework Managed

This difference is frequently asked in Spring interviews.


Common Interview Questions

What is Singleton Design Pattern?

A design pattern that ensures only one object instance exists.


Why make constructor private?

To prevent external object creation using the new keyword.


Is Singleton thread-safe by default?

No. Thread safety depends on implementation.


Which Singleton implementation is preferred?

Bill Pugh Singleton and Enum Singleton are commonly recommended.


Can Singleton be broken?

Yes. Reflection, serialization and cloning can break Singleton implementations if not handled properly.


Best Practices

  • Use Singleton only when a single instance is truly required.
  • Prefer Bill Pugh implementation for most applications.
  • Consider Enum Singleton when appropriate.
  • Avoid excessive use of global state.
  • Evaluate whether Spring can manage the object instead.

Frequently Asked Questions (FAQ)

Can Singleton improve performance?

Yes. It avoids repeated object creation for shared resources.


Can a Singleton class have multiple methods?

Yes. Singleton only restricts object creation, not functionality.


Does Spring use Singleton scope by default?

Yes. Singleton is the default bean scope in Spring Framework.


Conclusion

The Singleton Design Pattern is one of the most important design patterns in Java. Understanding Eager Initialization, Lazy Initialization, Thread-Safe Singleton, Double Checked Locking and Bill Pugh Singleton helps developers build efficient applications and perform well in Java interviews.


Keywords

Singleton Design Pattern, Singleton Pattern Java, Thread Safe Singleton, Bill Pugh Singleton, Java Design Patterns, Creational Design Patterns, Singleton Interview Questions, Double Checked Locking Java, Enum Singleton, Spring Singleton vs Java Singleton, OOP Design Patterns, Core Java Interview Questions, Singleton Example Java, Java Architecture, Software Design Patterns



Singleton Design Pattern in Java with Real Examples and Thread Safety Singleton Design Pattern in Java with Real Examples and Thread Safety Reviewed by 13thGhost on 2:20 AM Rating: 5

Microservices Architecture Explained with Real Examples

2:16 AM

Microservices Architecture has become the preferred approach for building large-scale enterprise applications. Companies such as Netflix, Amazon, Uber and Spotify use microservices to build highly scalable and resilient systems.


Understanding microservices is essential for modern Java developers because Spring Boot and Kafka are frequently used together when building microservices-based applications.


What is Microservices Architecture?

Microservices Architecture is an architectural style where an application is divided into multiple small, independently deployable services.

Each service is responsible for a specific business capability and can be developed, deployed and scaled independently.


Monolithic Architecture vs Microservices

Traditionally applications were built as monolithic systems where all modules existed inside a single application.



Monolithic Application

User Module
Order Module
Payment Module
Inventory Module

Single Deployment

In Microservices Architecture, these modules are separated into independent services.



User Service

Order Service

Payment Service

Inventory Service

Why Were Microservices Introduced?

As applications grow, monolithic systems become difficult to maintain and scale.

Microservices solve several problems:


  • Independent deployments
  • Better scalability
  • Technology flexibility
  • Improved fault isolation
  • Faster development cycles

Microservices Architecture Diagram


Client
   |
   v
API Gateway
   |
   +-------- User Service
   |
   +-------- Order Service
   |
   +-------- Payment Service
   |
   +-------- Inventory Service

Each service focuses on a single business function.


Key Characteristics of Microservices

  • Independent Deployment
  • Decentralised Data Management
  • Loose Coupling
  • High Availability
  • Scalability
  • Fault Isolation

Service Independence

Each microservice can be deployed independently without affecting other services.

For example, the Payment Service can be upgraded without redeploying the Order Service.


Database Per Service Pattern

Each microservice should ideally manage its own database.



User Service
    |
    +--- User Database

Order Service
    |
    +--- Order Database

Payment Service
    |
    +--- Payment Database

This prevents tight coupling between services.


Communication Between Microservices

Microservices can communicate using synchronous or asynchronous mechanisms.


Synchronous Communication

REST APIs are commonly used.



Order Service
      |
      v
Payment Service

Asynchronous Communication

Messaging systems such as Kafka are used.



Order Service
      |
      v
Kafka Topic
      |
      v
Payment Service

Asynchronous communication improves scalability and resilience.


API Gateway

An API Gateway acts as the single entry point for client requests.

Instead of contacting multiple services directly, the client communicates with the API Gateway.


Benefits

  • Centralised Authentication
  • Rate Limiting
  • Request Routing
  • Load Balancing

Real World Example

Consider an e-commerce platform.



User Service

Product Service

Order Service

Payment Service

Notification Service

When a customer places an order:


  1. Order Service creates order.
  2. Kafka publishes Order Created event.
  3. Payment Service processes payment.
  4. Inventory Service updates stock.
  5. Notification Service sends email.

Each service operates independently.


Advantages of Microservices

  • Independent deployment
  • Improved scalability
  • Technology flexibility
  • Faster release cycles
  • Better fault isolation

Challenges of Microservices

  • Distributed complexity
  • Data consistency challenges
  • Monitoring difficulties
  • Network latency
  • Service discovery management

Microservices and Spring Boot

Spring Boot is one of the most popular frameworks for implementing Microservices Architecture.

Commonly used Spring technologies include:


  • Spring Boot
  • Spring Cloud Gateway
  • Eureka
  • OpenFeign
  • Resilience4j
  • Spring Security
  • Spring Cloud Config

Common Interview Questions

What are Microservices?

Microservices are independently deployable services that focus on specific business capabilities.


What is the difference between Monolithic and Microservices Architecture?

Monolithic applications are deployed as a single unit, while Microservices consist of multiple independent services.


Why is Kafka commonly used with Microservices?

Kafka enables asynchronous communication and reduces service dependency.


What is an API Gateway?

An API Gateway acts as a single entry point for client requests.


Should all microservices share the same database?

Generally no. Each service should ideally own its database.


Best Practices

  • Keep services small and focused.
  • Use database-per-service design.
  • Prefer asynchronous communication where appropriate.
  • Monitor service health continuously.
  • Implement resilience patterns.

Frequently Asked Questions (FAQ)

Can microservices be built without Spring Boot?

Yes. However, Spring Boot is one of the most widely used frameworks for building Java microservices.


Is Microservices Architecture always better than Monolithic Architecture?

No. For small applications, a monolithic architecture may be simpler and easier to maintain.


What is the biggest challenge in Microservices?

Managing distributed systems complexity and maintaining data consistency.


Conclusion

Microservices Architecture enables organisations to build scalable, maintainable and resilient applications. Understanding concepts such as API Gateway, Service Independence, Database-Per-Service, Kafka Integration and Spring Boot support is essential for modern Java developers and architects.


Keywords

Microservices Architecture, Microservices Tutorial, Spring Boot Microservices, Microservices Interview Questions, API Gateway, Kafka Microservices, Monolithic vs Microservices, Distributed Systems, Java Microservices, Microservices Design Patterns, Service Discovery, Spring Cloud, Event Driven Architecture, Backend Architecture, Microservices Examples



Microservices Architecture Explained with Real Examples Microservices Architecture Explained with Real Examples Reviewed by 13thGhost on 2:16 AM Rating: 5

Kafka Partitions Explained with Real Examples and Interview Questions

1:57 AM

Kafka Partitions are one of the most important concepts in Apache Kafka. Almost every Kafka interview includes questions about partitions because they are responsible for Kafka's scalability, performance and parallel processing capabilities.


Understanding partitions helps developers design highly scalable event-driven applications and troubleshoot consumer group issues in production.


What is a Kafka Partition?

A Partition is a subdivision of a Kafka Topic. Instead of storing all messages in a single location, Kafka distributes messages across multiple partitions.

Each partition is an ordered, immutable sequence of records.


Why Do We Need Partitions?

Suppose a Topic receives millions of messages every day. A single partition would quickly become a bottleneck.

Partitions allow Kafka to distribute workload across multiple brokers and consumers.


Benefits of Partitions

  • Horizontal Scalability
  • Parallel Processing
  • Higher Throughput
  • Better Fault Tolerance
  • Efficient Consumer Scaling

Topic Without Partitions


Orders Topic

Message 1
Message 2
Message 3
Message 4
Message 5

All messages are stored in a single location. Scaling such a system becomes difficult.


Topic With Partitions


Orders Topic

Partition 0
-----------
Message 1
Message 4

Partition 1
-----------
Message 2
Message 5

Partition 2
-----------
Message 3

Messages are distributed across multiple partitions.


How Kafka Assigns Messages to Partitions

Kafka uses partitioning strategies to determine where messages should be stored.


Round Robin

Messages are distributed evenly across partitions.



Message 1 -> Partition 0

Message 2 -> Partition 1

Message 3 -> Partition 2

Message 4 -> Partition 0

Key Based Partitioning

If a message contains a key, Kafka hashes the key and routes the message to a specific partition.



CustomerId = 1001
     |
     v
Hash(CustomerId)
     |
     v
Partition 2

This ensures all events for the same customer go to the same partition.


Message Ordering in Kafka

One of the most important interview concepts is message ordering.

Kafka guarantees ordering only within a partition.



Partition 0

Order Created
Payment Successful
Invoice Generated

These messages will always be consumed in the same order.

Across multiple partitions, global ordering is not guaranteed.


Partition Offsets

Every message inside a partition receives a unique offset.



Partition 0

Offset 0
Offset 1
Offset 2
Offset 3

Consumers use offsets to track which messages have already been processed.


Producer Example


ProducerRecord<String, String>
record =
new ProducerRecord<>(
    "orders",
    "1001",
    "Order Created"
);

The key "1001" determines the target partition.


Consumer and Partitions

Partitions directly impact consumer scalability.


Example


Orders Topic

Partition 0
Partition 1
Partition 2

Consumer Group:



Consumer 1 -> Partition 0

Consumer 2 -> Partition 1

Consumer 3 -> Partition 2

Multiple consumers can process messages in parallel.


Partition Rebalancing

Rebalancing occurs whenever consumers join or leave a consumer group.

Kafka automatically redistributes partitions among available consumers.


Before Rebalancing


Consumer 1

Partition 0
Partition 1
Partition 2

After Consumer 2 Joins


Consumer 1

Partition 0
Partition 1

Consumer 2

Partition 2

Kafka performs this redistribution automatically.


How Many Partitions Should You Create?

There is no universal answer.

The number of partitions depends on:

  • Expected throughput
  • Consumer count
  • Future scaling requirements
  • Ordering requirements

Real World Example

An e-commerce platform receives 2 million orders per day.

Instead of using one partition, it may use:



orders-topic

50 Partitions

This allows dozens of consumers to process orders simultaneously.


Common Interview Questions

What is a Kafka Partition?

A partition is a subdivision of a Kafka Topic used for scalability and parallel processing.


Why are Partitions important?

Partitions enable horizontal scaling and improve throughput.


Does Kafka guarantee ordering?

Yes, but only within a single partition.


Can multiple consumers read the same partition?

Within the same consumer group, only one consumer can consume a partition at a given time.


What happens if partitions increase?

Scalability improves but partition management becomes more complex.


Best Practices

  • Choose partition counts carefully.
  • Use message keys when order matters.
  • Monitor partition skew.
  • Avoid excessive partition counts.
  • Plan for future scaling.

Frequently Asked Questions (FAQ)

Can Kafka increase partitions later?

Yes. Partitions can be increased after topic creation.


Can partitions be reduced?

Reducing partitions is generally not supported because it may result in data consistency issues.


Can ordering break across partitions?

Yes. Kafka only guarantees ordering inside an individual partition.


Conclusion

Partitions are the foundation of Kafka scalability and performance. Understanding how partitions work, how messages are assigned, how ordering behaves and how consumer groups interact with partitions is essential for designing reliable Kafka-based systems and succeeding in Kafka interviews.


Keywords

Kafka Partitions, Apache Kafka Partitions, Kafka Ordering, Kafka Scaling, Kafka Consumer Groups, Kafka Offsets, Kafka Interview Questions, Kafka Topic Partitions, Kafka Producer Partitioning, Kafka Architecture, Distributed Systems, Kafka Performance, Kafka Rebalancing, Kafka Examples, Microservices Architecture



Kafka Partitions Explained with Real Examples and Interview Questions Kafka Partitions Explained with Real Examples and Interview Questions Reviewed by 13thGhost on 1:57 AM Rating: 5

Apache Kafka Architecture Explained with Real Examples

1:49 AM

Apache Kafka is one of the most popular distributed event streaming platforms used by modern enterprises for building scalable and fault-tolerant applications.


Kafka is widely used in microservices, real-time analytics, event-driven architectures and large-scale data processing systems. Understanding Kafka Architecture is essential for Java developers, backend engineers and architects.


What is Apache Kafka?

Apache Kafka is a distributed messaging and event streaming platform that allows applications to publish, store and consume events in real time.

Kafka acts as a central communication hub between different applications and services.


Simple Example


Order Service
      |
      v
    Kafka
      |
      v
Payment Service

Inventory Service

Notification Service

Instead of services communicating directly with each other, they communicate through Kafka.


Why Do We Need Kafka?

In large systems, direct communication between services can create tight coupling and scalability problems.

Kafka solves these problems by enabling asynchronous communication.


Benefits

  • High Throughput
  • Fault Tolerance
  • Scalability
  • Durability
  • Loose Coupling
  • Real-Time Processing

Kafka Architecture Overview


Producer
    |
    v
+-----------+
|   Topic   |
+-----------+
    |
    v
Kafka Brokers
    |
    v
Consumer Group

Kafka Architecture consists of multiple components working together to deliver messages reliably.


Producer

A Producer is responsible for publishing messages to Kafka topics.


Example


Order Created Event
Customer Registered Event
Payment Completed Event

These events are produced and sent to Kafka Topics.


Topic

A Topic is a logical category where messages are stored.

Topics are similar to database tables, but instead of rows, they store events.


Examples


orders

payments

customers

notifications

Partition

A Topic can be divided into multiple partitions.

Partitions allow Kafka to scale horizontally and process messages in parallel.


Example


orders

Partition 0

Partition 1

Partition 2

Messages are distributed across these partitions.


Why Partitions Are Important

  • Improve scalability
  • Enable parallel processing
  • Support higher throughput
  • Allow consumer scaling

Kafka Broker

A Broker is a Kafka server responsible for storing and managing messages.

A Kafka cluster typically contains multiple brokers.



Broker 1

Broker 2

Broker 3

Messages are distributed across brokers for reliability and scalability.


Kafka Cluster

Multiple brokers together form a Kafka Cluster.

The cluster continues functioning even if one broker fails.


Replication

Kafka provides fault tolerance through replication.

Each partition can have multiple replicas stored on different brokers.


Example


Partition 0

Leader Replica
     |
     +---- Follower Replica
     |
     +---- Follower Replica

If the leader broker fails, a follower can automatically become the new leader.


Consumer

Consumers read messages from Kafka topics.

Applications such as Payment Services, Notification Systems and Analytics Platforms often act as Kafka consumers.


Consumer Groups

Consumer Groups allow multiple consumers to cooperate while processing messages.



Consumer Group

Consumer 1

Consumer 2

Consumer 3

Kafka distributes partitions among consumers within the same group.


Offset

Every message inside a partition receives a unique offset number.



Offset 0

Offset 1

Offset 2

Offset 3

Consumers track offsets to know which messages have already been processed.


Message Flow Example


Customer Places Order
         |
         v
Order Service
         |
         v
Kafka Topic
         |
         +-- Payment Service

         +-- Inventory Service

         +-- Notification Service

One event can be consumed by multiple independent services.


Zookeeper vs KRaft

Historically Kafka relied on Zookeeper for cluster management.


Modern Kafka versions are moving towards KRaft mode, removing the dependency on Zookeeper.


Zookeeper Responsibilities

  • Broker Coordination
  • Leader Election
  • Metadata Management

KRaft Benefits

  • Simpler Architecture
  • Reduced Operational Complexity
  • Better Scalability

Free Kafka Cheat Sheet PDF Download

Download the PDF using the link below.

Download PDF: Download Apache Kafka Cheat Sheet

Real Interview Questions

What is Kafka?

Kafka is a distributed event streaming platform used for real-time data processing and messaging.


What is a Kafka Topic?

A Topic is a logical category where events are stored.


What is a Kafka Partition?

A Partition is a subdivision of a Topic used for scalability and parallel processing.


What is a Kafka Broker?

A Broker is a server responsible for storing and serving Kafka messages.


What is Replication?

Replication creates multiple copies of data to improve fault tolerance.


Best Practices

  • Use multiple partitions for scalability.
  • Enable replication for critical topics.
  • Monitor consumer lag.
  • Use meaningful topic names.
  • Plan retention policies carefully.

Frequently Asked Questions (FAQ)

Can Kafka work with microservices?

Yes. Kafka is commonly used as the communication backbone for microservices architectures.


Does Kafka guarantee message ordering?

Kafka guarantees ordering within a partition.


Can one message be consumed by multiple services?

Yes. Different consumer groups can consume the same message independently.


Conclusion

Apache Kafka is a powerful distributed event streaming platform that enables scalable communication between applications. Understanding Producers, Topics, Partitions, Brokers, Consumer Groups, Offsets and Replication is essential for building modern event-driven systems and succeeding in Kafka interviews.


Keywords

Apache Kafka Architecture, Kafka Tutorial, Kafka Architecture Explained, Kafka Producer Consumer, Kafka Topics, Kafka Partitions, Kafka Broker, Kafka Consumer Groups, Kafka Replication, Kafka Interview Questions, Event Driven Architecture, Microservices Communication, Kafka for Java Developers, Distributed Systems, Kafka Examples

Apache Kafka Architecture Explained with Real Examples Apache Kafka Architecture Explained with Real Examples Reviewed by 13thGhost on 1:49 AM Rating: 5

Apache Kafka Cheat Sheet for Senior Java Developers (Free PDF Download)

1:35 AM

Apache Kafka has become one of the most widely used technologies in modern distributed systems, microservices architectures and event-driven applications.

Today, Kafka knowledge is expected from experienced Java developers, especially those working with Spring Boot, Microservices, Cloud Platforms and Data Streaming solutions.


To help developers revise Kafka concepts quickly, I created a Kafka Cheat Sheet that covers the most important topics frequently discussed in real-world projects and technical interviews.


Free Kafka Cheat Sheet PDF Download

Download the PDF using the link below.

Download PDF: Download Apache Kafka Cheat Sheet


Who Should Download This Cheat Sheet?

  • Java Developers
  • Spring Boot Developers
  • Microservices Developers
  • Technical Leads
  • Solution Architects
  • Interview Candidates
  • Backend Engineers

Why Kafka Is So Important Today

Modern enterprise systems process millions of events every day. Traditional synchronous communication between services can become difficult to scale and maintain.

Kafka solves this problem by providing a distributed event streaming platform that allows applications to communicate asynchronously.


Many organisations use Kafka for:

  • Microservices Communication
  • Audit Logging
  • Real-Time Analytics
  • Order Processing
  • Financial Transactions
  • Event Sourcing
  • Data Integration

Kafka Concepts Covered in the Cheat Sheet

  • Kafka Architecture
  • Topics
  • Partitions
  • Replication
  • Brokers
  • Zookeeper
  • KRaft Mode
  • Producers
  • Consumers
  • Consumer Groups
  • Offsets
  • Leader and Follower Replicas
  • Kafka Retention Policies
  • Delivery Guarantees
  • Idempotent Producers
  • Transactions
  • Kafka Streams
  • Spring Kafka

Frequently Asked Kafka Interview Questions

The cheat sheet includes quick revision notes for popular interview topics such as:

  • What happens when a Kafka broker goes down?
  • What is a Kafka partition?
  • How does replication work?
  • What is ISR (In-Sync Replica)?
  • How do consumer groups work?
  • What is exactly-once delivery?
  • Kafka vs RabbitMQ?
  • How does Kafka achieve high throughput?
  • Difference between Zookeeper and KRaft?

Senior-Level Topics Included

Many Kafka resources focus only on basic producer and consumer examples. This cheat sheet also covers topics commonly asked in senior developer and architect interviews.

  • Partition Rebalancing
  • Consumer Lag
  • Idempotent Producer
  • Transactional Producer
  • Log Compaction
  • Retention Policies
  • Ordering Guarantees
  • Scaling Kafka Clusters
  • Monitoring and Metrics
  • Performance Tuning

Common Kafka Architecture Diagram


Producer
    |
    v
+-------------------+
|   Kafka Topic     |
+-------------------+
    |
    v
Consumer Group
    |
    v
Consumers

Understanding this flow is critical for building scalable microservices.


Real Interview Tip

Many developers can explain what a Kafka Topic is. Fewer developers can explain how Kafka maintains message ordering, handles broker failures or manages rebalancing.

These are the topics that frequently differentiate junior and senior developers during interviews.


How to Use This Cheat Sheet

  • Revise before interviews
  • Use during project discussions
  • Review Kafka architecture concepts
  • Prepare for senior developer roles
  • Refresh knowledge before certifications

More Free Downloads Coming Soon

  • Core Java Cheat Sheet
  • Collections Framework Cheat Sheet
  • JVM Cheat Sheet
  • Spring Framework Cheat Sheet
  • Spring Boot Cheat Sheet
  • Microservices Cheat Sheet
  • Design Patterns Cheat Sheet
  • System Design Cheat Sheet

Final Thoughts

Kafka is no longer a niche technology. It has become a core component of modern enterprise applications and microservices ecosystems. Whether you are preparing for interviews or working on production systems, having a concise Kafka revision guide can save significant time and help you focus on the concepts that matter most.

Download the cheat sheet, bookmark JavaCompass and keep an eye out for additional cheat sheets and interview preparation resources.


Keywords

Kafka Cheat Sheet, Apache Kafka PDF Download, Kafka Interview Questions, Kafka Architecture, Kafka for Java Developers, Senior Kafka Interview Questions, Kafka Consumer Groups, Kafka Partitions, Kafka Replication, Kafka Producer Consumer, Kafka Cheat Sheet PDF, Spring Kafka Tutorial, Microservices Interview Questions, Apache Kafka Notes, JavaCompass Downloads



Apache Kafka Cheat Sheet for Senior Java Developers (Free PDF Download) Apache Kafka Cheat Sheet for Senior Java Developers (Free PDF Download) Reviewed by 13thGhost on 1:35 AM Rating: 5

Spring Boot Architecture Explained with Internal Workflow and Request Lifecycle

1:18 AM

Spring Boot is one of the most popular Java frameworks used to build enterprise applications, REST APIs and microservices. It simplifies application development by reducing configuration effort and providing production-ready features out of the box.


Understanding Spring Boot Architecture is important because it is frequently asked in interviews and helps developers understand what happens internally when a request reaches an application.


What is Spring Boot?

Spring Boot is an extension of the Spring Framework that simplifies application development through auto-configuration, starter dependencies and embedded servers.

Before Spring Boot, developers had to spend significant time configuring XML files, servlet containers and application settings. Spring Boot eliminates most of this manual configuration.


Why Was Spring Boot Introduced?

Traditional Spring applications required extensive configuration before development could even begin.

Spring Boot was introduced to solve common problems such as:


  • Complex XML configuration
  • Manual server deployment
  • Dependency management issues
  • Lengthy project setup
  • Boilerplate configuration code

Spring Framework vs Spring Boot

Feature Spring Framework Spring Boot
Configuration More Manual Minimal
Server Setup External Server Embedded Server
Startup Time Slower Setup Faster Setup
Production Features Additional Setup Built In

Spring Boot Architecture Overview

A typical Spring Boot application follows a layered architecture.



Client
   |
   v
DispatcherServlet
   |
   v
Controller
   |
   v
Service
   |
   v
Repository
   |
   v
Database

Each layer has a specific responsibility, making applications easier to maintain and scale.


Spring Boot Main Components

  • SpringApplication
  • Auto Configuration
  • Spring IoC Container
  • Embedded Server
  • DispatcherServlet
  • Controllers
  • Services
  • Repositories

SpringApplication Class

The SpringApplication class is the entry point of every Spring Boot application.



@SpringBootApplication
public class EmployeeApplication {

    public static void main(String[] args) {

        SpringApplication.run(
            EmployeeApplication.class,
            args
        );

    }
}

When SpringApplication.run() executes, it starts the Spring Container, scans components, creates beans and launches the embedded web server.


What Happens During Application Startup?

Internally Spring Boot performs several operations during startup.


  1. Creates Application Context
  2. Scans Spring Beans
  3. Creates Bean Instances
  4. Injects Dependencies
  5. Applies Auto Configuration
  6. Starts Embedded Tomcat
  7. Makes Application Ready

What is Auto Configuration?

Auto Configuration is one of the most powerful Spring Boot features. It automatically configures application components based on dependencies available in the project's classpath.

For example, when you add:



spring-boot-starter-web

Spring Boot automatically configures:

  • DispatcherServlet
  • Embedded Tomcat
  • Jackson JSON Support
  • Validation Framework
  • Error Handling Components

@SpringBootApplication Annotation

The most important Spring Boot annotation is:



@SpringBootApplication

Internally it combines three annotations.



@Configuration

@EnableAutoConfiguration

@ComponentScan

This is another very common interview question.


Embedded Server

One of the biggest advantages of Spring Boot is the embedded server feature.

Traditional Spring applications required deploying WAR files into external servers. Spring Boot includes an embedded web server inside the application.


By default, Spring Boot uses:



Apache Tomcat

Other supported servers include:


  • Jetty
  • Undertow

Controller Layer

The Controller layer receives HTTP requests from clients.



@RestController
@RequestMapping("/employees")
public class EmployeeController {

}

Controllers should contain request handling logic only. Business logic should not be placed here.


Service Layer

The Service layer contains business logic and application rules.



@Service
public class EmployeeService {

}

This layer acts as a bridge between controllers and repositories.


Repository Layer

Repositories handle interactions with the database.



@Repository
public interface EmployeeRepository
        extends JpaRepository<
                Employee,
                Long> {

}

Repositories simplify data access through Spring Data JPA.


Request Lifecycle in Spring Boot

Understanding request flow is extremely important for interviews.



Browser
   |
   v
DispatcherServlet
   |
   v
Controller
   |
   v
Service
   |
   v
Repository
   |
   v
Database

Step 1: Client Sends Request

The browser or API client sends an HTTP request to the application.



GET /employees

Step 2: DispatcherServlet Receives Request

DispatcherServlet is the front controller of Spring MVC.


Every incoming request first reaches DispatcherServlet.


Step 3: Controller Processes Request


@GetMapping("/employees")
public List<Employee> getEmployees() {

}

The Controller receives the request and delegates processing to the Service layer.


Step 4: Service Executes Business Logic


@Service
public class EmployeeService {

}

Business rules and validations are executed here.


Step 5: Repository Accesses Database

Repository fetches data from the database.


Step 6: Response Returns to Client

Spring Boot converts Java objects into JSON and returns them to the client.



[
  {
    "id":1,
    "name":"John"
  }
]

Complete Example

Entity


@Entity
public class Employee {

    @Id
    private Long id;

    private String name;
}

Repository


@Repository
public interface EmployeeRepository
 extends JpaRepository<
         Employee,
         Long> {

}

Service


@Service
public class EmployeeService {

    private final EmployeeRepository repository;

    public EmployeeService(
            EmployeeRepository repository) {

        this.repository = repository;

    }

}

Controller


@RestController
@RequestMapping("/employees")
public class EmployeeController {

    private final EmployeeService service;

    public EmployeeController(
            EmployeeService service) {

        this.service = service;

    }

}

Why Spring Boot Became So Popular

  • Auto Configuration
  • Starter Dependencies
  • Embedded Servers
  • Production Ready Features
  • Microservices Support
  • Less Boilerplate Code
  • Fast Development Cycle

Common Interview Questions

What is Spring Boot?

Spring Boot is an opinionated framework built on top of Spring that simplifies application development.


What does SpringApplication.run() do?

It starts the Spring application, creates beans and launches the embedded server.


What is DispatcherServlet?

DispatcherServlet is the front controller that receives all incoming requests.


What is Auto Configuration?

Auto Configuration automatically configures application components based on project dependencies.


What is the difference between Spring and Spring Boot?

Spring Boot reduces configuration effort and provides production-ready features on top of the Spring Framework.


Best Practices

  • Keep Controllers lightweight.
  • Place business logic in Services.
  • Use Constructor Injection.
  • Keep Repository classes focused on data access.
  • Follow layered architecture principles.

Frequently Asked Questions (FAQ)

Can Spring Boot work without Tomcat?

Yes. Spring Boot supports Jetty and Undertow as alternatives.


Can we deploy Spring Boot as a WAR file?

Yes. Although embedded servers are common, WAR deployment is still supported.


Does Spring Boot require XML configuration?

No. Most applications can be configured using annotations and properties files.


Conclusion

Spring Boot simplifies enterprise application development by combining auto-configuration, embedded servers, dependency injection and production-ready features. Understanding its architecture, component interactions and request lifecycle helps developers build scalable applications and answer Spring Boot interview questions confidently.


Keywords

Spring Boot Architecture, Spring Boot Internal Workflow, Spring Boot Request Lifecycle, DispatcherServlet, SpringApplication Run, Spring Boot Tutorial, Spring Boot Interview Questions, Spring Boot Internals, Spring MVC Architecture, Auto Configuration Spring Boot, Spring Boot Request Flow, Spring Framework Tutorial, Java Spring Boot Guide, Enterprise Java Development, Spring Boot Examples



Spring Boot Architecture Explained with Internal Workflow and Request Lifecycle Spring Boot Architecture Explained with Internal Workflow and Request Lifecycle Reviewed by 13thGhost on 1:18 AM Rating: 5

Recommended Posts

Powered by Blogger.