eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

1. Overview

In this tutorial, we’ll learn about Vertical Slice Architecture and how it attempts to solve the issues associated with layered designs. We’ll discuss structuring the code by business capabilities, which leads to a more expressive codebase organized into loosely coupled and cohesive modules. After that, we’ll explore this approach from a Domain Driven Design (DDD) perspective and discuss its flexibility.

2. Layered Architecture

Before exploring Vertical Slice Architecture, let’s first review the key features of its main counterpart, Layered Architecture. Layered designs are popular and widely used, with variations like Hexagonal, Onion, Ports and Adapters, and Clean Architecture.

A Layered Architecture uses a series of stacked or concentric layers that protect the domain logic against external components and factors. A key characteristic of these architectures is that all the dependencies point inwards, towards the domain:Hex arch

2.1. Grouping Components by Technical Concerns

The layered approach solely focuses on grouping components by technical concerns, instead of their business capabilities.

For this article’s code examples, let’s assume we’re building the backend application of a blogging website. The application will support the following use cases:

  • Authors can publish and edit articles
  • Authors can see a dashboard with their article stats
  • Readers can read, like, and add comments to articles
  • Readers receive notifications with article recommendations

For example, our package names reflect technical layers without conveying the true purpose of the project:

hexagonal idle structure

2.2. High Coupling

Moreover, re-using the same domain services for unrelated business use cases can lead to tight coupling. For instance, the ArticleService currently depends on:

  • ArticleRepository – to query the database
  • UserService – to fetch data about the article authors
  • RecommendationService – to update reader recommendations when a new article is published
  • CommentService – to manage article comments

Consequently, we risk interfering with unrelated flows when we add or modify a use case. Furthermore, this highly coupled approach often leads to cluttered tests full of mocks.

2.3. Low Cohesion

Finally, this code structure tends to have low cohesion within components. Since the code for a business use case is scattered in various packages across the project, any minor change will require us to modify files from each layer.

Let’s add a slug field to the Article entity. If we want to allow the clients to use the new field to query the database, we’ll have to change many files throughout the layers:

hexagonal cohesion

Even a simple modification causes changes in almost every package of our application. The fact that the classes that change together don’t live together indicates a low cohesion.

3. The Vertical Slice Architecture

Vertical Slice Architecture was developed to tackle some issues associated with Layered Architecture by organizing the code by business capabilities. Following this approach, our components mirror business use cases and span over multiple layers.

As a result, instead of grouping all the controllers in a common package, they will be moved to packages associated with their respective slices:

vsa diagram

Additionally, we can group related use cases into cohesive slices that align with the business domains. Let’s reorganize our example with the author, reader, and recommendation domains:

vsa ide structure

 

Dividing the project into vertical slices allows us to use the default, package-private access modifiers for most of the classes. This ensures that unexpected dependencies don’t cross the domain boundary.

Lastly, it enables someone unfamiliar with the codebase to understand what the application does by looking at the file structure. Robert C. Martin, the author of Clean Code, refers to this as “Screaming Architecture. He argues that a software project’s design should communicate its purpose clearly, much like architectural blueprints of a building reveal its function.

4. Coupling and Cohesion

As previously discussed, opting for the Vertical Slice Architecture over the Onion Architecture offers improved management of coupling and cohesion.

4.1. Looser Coupling Through Application Events

Instead of eliminating the coupling between slices, let’s focus on defining the right interfaces for communication across boundaries. Using application events is a powerful technique that allows us to maintain loose coupling while facilitating cross-boundary interactions.

In the Layered Architecture approach unrelated services depend on each other to complete a business feature. Specifically, ArticleService depends on RecommendationService to notify it about new articles. Instead, the recommendation flow can be executed asynchronously, and react to the main flow by listening to an application event.

Since we use the Spring Framework for our code example, let’s publish a Spring Event when a new article is created:

@Component
class CreateArticleUseCase {
    
    private final ApplicationEventPublisher eventPublisher;
    
    // constructor

    void createArticle(CreateArticleRequest article) {
        saveToDatabase(article);
        
        var event = new ArticleCreatedEvent(article.slug(), article.name(), article.category());
        eventPublisher.publishEvent(event);
    }

    private void saveToDatabase(CreateArticleRequest aticle) { /* ... */ }
        // ...
    }
}

Now, the SendArticleRecommendationUseCase can use an @EventListener to react to ArticleCreatedEvents and execute its logic:

@Component
class SendArticleRecommendationUseCase {

    @EventListener
    void onArticleRecommendation(ArticleCreatedEvent article) {
        findTopicFollowers(article.name(), article.category());
          .forEach(follower -> sendArticleViaEmail(article.slug(), article.name(), follower));
    }

    private void sendArticleViaEmail(String slug, String name, TopicFollower follower) {
        // ...
    }

    private List<TopicFollower> findTopicFollowers(String articleName, String topic) {
        // ...
    }

    record TopicFollower(Long userId, String email, String name) {}
}

As we can see, the modules operate independently and don’t directly depend on each other. Additionally, any components interested in newly created articles only need to listen for the ArticleCreatedEvent.

4.2. Higher Cohesion

Finding the right boundaries results in cohesive slices and use cases. A use case class should typically have a single public method and a single reason to change, adhering to the Single Responsibility Principle.

Let’s add a slug field to the Article class in our Vertical Slice Architecture and create an endpoint to find articles by slug. This time, the changes are scoped to a single package. We’ll create a SearchArticleUseCase that uses JdbcClient to query the database and return a projection of an Article. As a result, we’ll only modify two files in one package:

vsa git status

We created one use case and modified the ReaderController to expose the new endpoint. The fact that both files are located in the same package indicates higher cohesion within the project.

5. Design Flexibility

Vertical Slice Architecture allows us to customize approaches for each component, and determine the most effective way to organize the code for each use case. In other words, we can utilize various tools, patterns, or paradigms without enforcing a specific coding style or dependencies across the entire application.

Moreover, this flexibility facilitates approaches such as Domain-Driven Design (DDD) and CQRS. While not mandatory, they are well-suited for a vertically sliced application.

5.1. Modeling the Domain With DDD

Domain-Driven Design is an approach that emphasizes modeling software based on the core business domain and its logic. In DDD, the code must use terms and language familiar to business people and clients, to align technical and business perspectives.

In Vertical Slice Architecture, we might encounter the problem of code duplication between use cases. For slices that expand, we can decide to extract general business rules and use DDD to create a domain model, specific to them:

vsa domain

Moreover, DDD uses Bounded Contexts to define specific boundaries, ensuring clear distinctions between different parts of the system.

Let’s revisit a project that follows the layered approach. We’ll notice that we interact with the system’s users through objects like UserService, UserRepository, and the User entity. In contrast, in a vertically-sliced project, the concept of a user varies across different bounded contexts. Each slice has its own representation of a user, referring to them as a “reader”, an “author”, or a “topic follower”, reflecting the specific role they play within that context.

5.2. Bypassing the Domain for Simple Use Cases

Another drawback of strictly following a layered architecture is that it can result in methods that simply pass calls to the next layer, without adding value. This is also known as the “middle man” antipattern, and it leads to tightly coupled layers.

For example, when finding an article by slug, the controller calls the service, which then calls the repository. Even though the service doesn’t add any value in this case, the strict rules of layered architecture prevent us from bypassing the domain and directly accessing the persistence layer.

In contrast, a vertically sliced application offers the flexibility to choose which layers are needed for each specific use case. This allows us to bypass the domain layer for simple use cases, and directly query the database for projections:

vsa use cases

Let’s simplify the use case of viewing an article by slug, using the Vertical Slice Architecture to bypass the domain layer:

@Component
class ViewArticleUseCase {

    private static final String FIND_BY_SLUG_SQL = """
        SELECT id, name, slug, content, authorid
        FROM articles
        WHERE slug = ?
        """;

    private final JdbcClient jdbcClient;

    // constructor

    public Optional<ViewArticleProjection> view(String slug) {
        return jdbcClient.sql(FIND_BY_SLUG_SQL)
          .param(slug)
          .query(this::mapArticleProjection)
          .optional();
    }

    record ViewArticleProjection(String name, String slug, String content, Long authorId) {
    }

    private ViewArticleProjection mapArticleProjection(ResultSet rs, int rowNum) throws SQLException {
        // ...
    }

}

As we can see, ViewArticleUseCase directly queries the database using a JdbcClient. Moreover, it defines its own projection of an article, instead of reusing a common DTO, which would’ve coupled this use case to other components. As a result, unrelated use cases aren’t forced into the same structure and we eliminate unnecessary dependencies.

6. Conclusion

In this article, we’ve learned about Vertical Slice Architecture and compared it to its Layered Architecture counterpart. We learned how to create cohesive components and avoid coupling between unrelated business use cases.

We discussed bounded contexts and how they help us define different projections specific to a part of the system. Finally, we discovered that this approach offers increased flexibility when designing each vertical slice.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments