Layered Architecture Pattern

DEVDEVO / LOW-LEVEL DESIGN

Layered Architecture Pattern

Learn how to organize a backend application into clear responsibilities. Understand Controller, Service, Repository, Model, DTO, Mapper, Security and supporting components through one practical Book Management API.

Architecture Fundamentals Java / Spring Example Interview Preparation

1. What is Layered Architecture?

A Layered Architecture organizes an application into layers, where each layer has a defined responsibility. Instead of putting HTTP handling, business rules, and database queries into one large class, we separate them into components that work together.

Imagine building a Book Management API. A user sends a request to get a book. The controller receives the request, the service decides what should happen, and the repository fetches the book from the database.

Remember: Each layer should focus on its own job. This makes the application easier to test, understand, maintain, and change.

Why use it?

Separation of concerns

HTTP handling, business rules, and data access do not become mixed together.

Maintainability

Changes are easier to locate because responsibilities are organized.

Testability

You can test business logic without requiring a real HTTP request or database.

Reuse

Multiple endpoints can call the same service operations when appropriate.

2. Understand the architecture flow

For a typical read request, the call path looks like this:

1
ClientSends GET /api/books/10
↓ HTTP request
2
ControllerReceives the request and delegates to the service
↓ Method call
3
ServiceApplies business rules and coordinates the operation
↓ Method call
4
RepositoryQueries the database for the book
↓
5
DatabaseReturns the stored book record
↑ Result returns through the layers
6
DTO / Mapper / ControllerBuilds and returns the API response
This is a common arrangement, not a strict rule for every framework. A DTO and mapper may be used to shape the response; exceptions may be handled by shared exception-handling code. Security filters can run before the controller receives the request.

3. Practical example: Book Management API

Suppose a client requests GET /api/books/10. The API should return the book’s ID, title, and author. If the book does not exist, it should return a suitable not-found response.

Step 1 — Model: represent the book

The model represents the stored entity. In a JPA application, an entity is commonly mapped to a database table.

Book.java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;

    protected Book() {}

    public Long getId() { return id; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }

    public void setTitle(String title) { this.title = title; }
    public void setAuthor(String author) { this.author = author; }
}

Step 2 — Repository: retrieve the book

The repository handles persistence operations. Spring Data JPA can generate the implementation for common CRUD operations.

BookRepository.java
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository
        extends JpaRepository<Book, Long> {
}

Step 3 — DTO: define the API response

A Data Transfer Object controls what information is exposed to the API client. It avoids returning the persistence entity directly when a separate response shape is appropriate.

BookResponse.java
public record BookResponse(
    Long id,
    String title,
    String author
) {}

Step 4 — Mapper: convert the entity to a DTO

The mapper keeps conversion code out of the controller and service.

BookMapper.java
public final class BookMapper {
    private BookMapper() {}

    public static BookResponse toResponse(Book book) {
        return new BookResponse(
            book.getId(),
            book.getTitle(),
            book.getAuthor()
        );
    }
}

Step 5 — Exception: represent a missing book

A custom exception gives the application a clear way to represent a domain error.

BookNotFoundException.java
public class BookNotFoundException
        extends RuntimeException {
    public BookNotFoundException(Long id) {
        super("Book not found with id: " + id);
    }
}

Step 6 — Service: apply the business operation

The service coordinates the use case. It asks the repository for the book and throws a meaningful exception if no record exists.

BookService.java
import org.springframework.stereotype.Service;

@Service
public class BookService {
    private final BookRepository repository;

    public BookService(BookRepository repository) {
        this.repository = repository;
    }

    public Book getBook(Long id) {
        return repository.findById(id)
            .orElseThrow(() -> new BookNotFoundException(id));
    }
}

Step 7 — Controller: expose the HTTP endpoint

The controller handles the HTTP request and response. It delegates the work to the service instead of querying the database itself.

BookController.java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/books")
public class BookController {
    private final BookService service;

    public BookController(BookService service) {
        this.service = service;
    }

    @GetMapping("/{id}")
    public ResponseEntity<BookResponse> getBook(
            @PathVariable Long id) {
        Book book = service.getBook(id);
        return ResponseEntity.ok(BookMapper.toResponse(book));
    }
}
What this example demonstrates: the controller does not write SQL, the repository does not decide HTTP status codes, and the DTO defines the response shape. Each part has a focused responsibility.

What response does the client receive?

For an existing book, the API could return HTTP 200 OK:

Example JSON response
{
  "id": 10,
  "title": "Clean Code",
  "author": "Robert C. Martin"
}

For a missing book, the custom exception needs a handler to translate it into HTTP 404 Not Found. The next section explains the supporting components.

4. Components explained with examples

Expand each component to understand its responsibility and how it fits into the Book API. The first four are the core parts of a common layered application; the rest support cross-cutting concerns, data conversion, configuration, or asynchronous workflows.

Responsibility: Handles HTTP requests, reads path/query parameters, validates incoming request shapes where appropriate, calls the service, and returns an HTTP response.

Book example: GET /api/books/10 enters BookController, which calls bookService.getBook(10).

Should not: contain complex business rules or direct database query logic.

5. Example project structure

One possible Spring Boot structure for the Book Management API is:

Project structure
com.example.books
├── controller
│   └── BookController.java
├── service
│   └── BookService.java
├── repository
│   └── BookRepository.java
├── model
│   └── Book.java
├── dto
│   └── BookResponse.java
├── mapper
│   └── BookMapper.java
├── exception
│   ├── BookNotFoundException.java
│   └── GlobalExceptionHandler.java
├── config
│   └── AppConfig.java
├── specification
│   └── BookSpecification.java
├── security
│   └── SecurityConfig.java
├── util
│   └── DateUtils.java
└── resources
    └── application.properties

This is an illustrative structure, not a mandatory folder layout. Add constants or messaging producer/consumer packages only when the application needs them. A small application does not need a class or folder for every possible component.

6. Best practices and common mistakes

Good practiceCommon mistake
Keep controllers focused on HTTP and delegation.Putting business rules and database calls directly in controllers.
Keep business rules in cohesive services or domain objects.Making one service class responsible for every feature.
Use repositories for persistence operations.Making repositories decide API responses or business workflows.
Use DTOs when an API contract should differ from an entity.Exposing every database field automatically.
Handle exceptions centrally where appropriate.Returning HTTP 200 for failures or leaking internal stack traces.
Keep dependencies pointing through clear abstractions.Letting every component call every other component without boundaries.
Add messaging, specifications and utilities when they solve a real need.Creating extra layers and classes without a clear responsibility.

What are the limitations?

  • Applications can become over-layered if every simple operation requires many unnecessary classes.
  • Business logic can become scattered if responsibilities are poorly defined.
  • Strict layer boundaries need deliberate design; a folder structure alone does not enforce them.
  • Layered architecture is not the same as microservices. A single application can use layered architecture internally.

7. Test your understanding

In the Book API example, which component should fetch the book record from the database?

Share