When and Why You Should Transition to a Microservices Architecture
In recent years, microservices architecture has gained significant attention as a solution to the limitations often associated with monolithic systems. But what does it actually mean, and why has this architecture become such a popular choice? Fundamentally, a microservices architecture divides an application into a set of small deployable services. Each service is built to perform a single specific role and to interact with the rest using well-defined APIs.
This is quite different from the architecture of monolithic systems, in which all functionalities are tightly coupled and work as an integral unit. While monoliths are easier to develop and deploy at the beginning, their tightly coupled nature may result in challenges regarding scalability, maintainability, and development speed as the application grows. Microservices promote modularity and flexibility, thus being an attractive choice for organizations that look for agility and scalability.
Understanding the difference between monolithic and microservices architectures is crucial to determining whether a move to microservices aligns with an organization’s goals. This chapter lays out the foundational knowledge and practical insights needed to determine when and why microservices may be the right choice for your organization, focusing on the migration from a modular monolith—a step many organizations take as they explore this architectural approach.
We specifically explore how to migrate from monolithic solutions to microservices architectures, focusing on aligning technical decisions with business needs. By delving into foundational concepts and practical approaches, you’ll gain the tools to navigate this transition effectively.
This chapter will cover the following:
- The role of modular monoliths as a foundation for transitioning to microservices
- Insights into the trade-offs and complexities inherent in distributed systems
- Practical steps for evolving your architecture incrementally, minimizing risk, and maximizing value
The complete code for this chapter can be found in the 02-monolith_with_cqrs ( https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/02-monolith_with_cqrs ), 03-monolith_with_cqrs_and_event_sourcing ( https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/03-monolith_with_cqrs_and_event_sourcing ), and 04-microservices ( https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/04-microservices ) branches in the book’s GitHub repository.
Exploring microservices architecture
At its heart, microservices emphasize building distributed systems composed of small, independently deployable components, each responsible for a specific functionality. While this architectural style has reshaped how we think about scalability, agility, and maintainability, its alignment with the core principles of DDD is where its true potential lies.
One of the key advantages of microservices is their alignment with business capabilities. By structuring services around specific domains, teams can work more independently, reducing bottlenecks and enabling faster iteration. This approach dovetails naturally with DDD principles, which emphasize organizing software around the core domains and subdomains of a business.
Microservices can offer the following:
- Improved scalability : Every single service can scale independently as per its demand
- Enhanced resilience : When one service fails, it will not necessarily bring down the whole application
- Faster development cycles : Self-sufficient teams can develop, deploy, and iterate on services independently, reducing time to market for new features
While these benefits are impressive, they are not without a trade-off: microservices architectures are inherently more complex than monolithic systems. This added complexity raises questions about when the transition makes sense and how to execute it effectively.
Moving from a modular monolith to microservices
In general, the leap to microservices is framed as a natural evolution rather than a complete overhaul for organizations transitioning from a modular monolith. After all, modular monoliths already incorporate some of the principles foundational to microservices, such as clear module boundaries and separation of concerns. This similarity makes them a common starting point for organizations contemplating the switch.
However, the decision to adopt microservices should never be based solely on trends or perceived industry best practices. It must be grounded in a deep understanding of the organization’s current needs, future goals, and the constraints of its existing systems. Factors such as team structure, operational readiness, and the complexity of the domain should play a pivotal role in shaping this decision.
Figure 10 .1 shows the transformation from a modular monolith to the microservices equivalent in simple terms. As you can see, the components in every layer of the monolith are moved to a standalone service.
Figure 10 .1 – Moving from a modular monolith to microservices
Monolith versus microservices
To understand when and why moving to microservices might be beneficial, it is crucial to first explore the key differences between monolithic and microservices architectures across several dimensions:
- Development : Monolithic systems are developed as a single, unified code base. This approach clearly simplifies initial development since all components are part of the same system. However, as the code base grows, coordinating changes among teams becomes increasingly challenging. Microservices, in contrast, allow different teams to work on separate services with minimal interdependencies. So, each team can focus on its domain, leading to shorter development cycles and fewer bottlenecks. However, it is important to note that starting a greenfield project with microservices is significantly more complex and costly than with a well-structured modular monolith, as it requires setting up infrastructure, service communication, and deployment automation from the outset.
- Deployment : A monolith is deployed as a single unit, simplifying deployment pipelines but making updates riskier. A small change in one component requires the entire application to be redeployed. Instead, with microservices, each service is independently deployable and enables faster and more frequent updates while minimizing the impact of changes on unrelated services.
- Scalability : Scaling a monolith usually involves adding more resources (known as vertical scaling), which has physical and cost limitations. On the other hand, microservices enable horizontal scaling, allowing specific services to be scaled independently based on their needs. For example, a high-demand service such as a recommendation engine can be scaled without affecting the rest of the system.
- Resilience : A failure in a monolithic application can bring down the entire system since all components are tightly coupled. In a microservices architecture, failures are isolated to individual services, improving the overall resilience of the system. It is worth noting that this advantage heavily depends on robust service communication and error-handling mechanisms.
- Complexity : Monolithic architectures are less complex to design and manage initially. The fact that all components reside in the same code base reduces the need for sophisticated infrastructure and operational practices. Microservices introduce significant complexity, requiring advanced DevOps practices, distributed system design, and monitoring to manage multiple services and their interactions.
- Team autonomy : Monolithic systems force all teams to use the same technology stack, which can limit innovation and create dependencies between teams. Microservices grant teams the freedom to choose the best technology for their specific service, enabling experimentation and optimization. This autonomy also aligns better with DDD principles.
- Maintenance and performance : Over time, monoliths become harder to maintain as the code base grows larger and more intertwined. Microservices, with their smaller and more focused code bases, are easier to maintain but introduce performance challenges due to network overhead in service-to-service communication.
- Startup costs : Monoliths have lower initial development and infrastructure costs, making them suitable for start-ups or small applications. Microservices require investment in tooling, automation, and infrastructure, which can be a barrier for smaller organizations.
Table 10.1 summarizes these key points for a quick reference:
| Aspect | Monolithic Architecture | Microservices Architecture |
|---|---|---|
| Development | Simplified development with a single code base | Teams can develop independently, enabling faster iterations |
| Deployment | A single deployment unit makes deployment straightforward | Independent deployment of services allows flexibility |
| Scalability | Vertical scaling (increasing hardware capacity) | Horizontal scaling (scaling individual services) |
| Resilience | A failure in one component can crash the whole system | Failures are isolated to individual services |
| Complexity | Less initial operational complexity | High operational complexity due to the distributed nature |
| Team Autonomy | Teams must coordinate tightly, leading to bottlenecks | Teams can work autonomously on different services |
| Technology Flexibility | Single technology stack across the application | Freedom to use different technologies per service |
| Performance | No network overhead; everything runs in one process | Network latency between services impacts performance |
| Maintenance | Challenging as the code base grows larger and more intertwined | Easier to maintain; smaller, focused code bases |
| Startup Cost | Lower initial cost for setup and infrastructure | Higher upfront investment in tools and infrastructure |
Table 10.1 – Monolith vs. microservices
The microservices movement has not only influenced system design but has also prompted a rediscovery and renewed appreciation of DDD concepts such as bounded contexts. Many organizations, while grappling with the challenges of implementing microservices, have stumbled upon a revelation: to design microservices effectively, understanding and applying DDD is not just helpful, it’s essential.
DDD and microservices share a symbiotic relationship. Microservices provide an operational lens, a way to structure and deploy software systems in a distributed fashion. DDD, on the other hand, offers a conceptual and strategic foundation, particularly through its emphasis on modeling the problem space and aligning software design with business domains. The most significant bridge between these two paradigms is the bounded context, a concept in DDD that maps cleanly to the boundaries and responsibilities of microservices.
However, we need to handle this relationship with care. A bounded context defines a semantic boundary, meaning that within it, every element of the software model has a well-defined meaning and role, shaped by the domain’s language and logic. It is structured around the purpose and conceptual integrity of the model.
A microservice, on the other hand, defines a physical boundary—it is a deployable unit of an application, encapsulated within infrastructure elements such as containers or virtual machines. You can think of this boundary as containing a Docker image or runtime environment.
While, in some scenarios, the driving forces behind defining a bounded context and a microservice may overlap, they serve different purposes: one ensures conceptual clarity , and the other enforces deployment and operational independence .
You can have a microservice with more than one bounded context, but you cannot have a bounded context split through many microservices! Keep your boundaries logically clean and enforce physical separation when it is worth the cost.
The rationale behind microservices
There isn’t a clear definition for microservices architecture , except in a famous blog by Martin Fowler and James Lewis entitled Microservices ( https://www.martinfowler.com/articles/microservices.html ), published in March 2014, which explains the characteristics of microservices architecture. Scrolling through the characteristics in the article, you can find many of them really align with bounded context principles. If you are asking yourself why you should move your project to a microservices architecture style, you need to analyze these characteristics and check how they relate to DDD. Four of them must capture your attention:
- Organized around business capabilities : Usually, when breaking down a large application into smaller parts, management often organizes teams based on technological layers. This is a direct consequence of Conway’s Law (Melvin Conway, 1968, https://martinfowler.com/bliki/ConwaysLaw.html ). This approach can create significant bottlenecks due to the need for additional approvals even for minor changes. The microservices approach, on the other hand, advocates for splitting up the application into services organized around specific business capabilities and encourages cross-functional teams to focus on addressing these specific business problems. This is very much in line with the Ubiquitous Language pattern, which is a vertical language for a specific business problem.
- Decentralized governance : Companies with centralized governance have the tendency to standardize on single technology platforms, but, as you know, not every problem is a nail, and not every solution is a hammer. When splitting your monolith into microservices, you must choose the right technology for a specific problem. This approach aligns with the idea of having a model that fits the business purpose in DDD.
- Decentralized data management : This is one of the most critical aspects of microservices architecture. Unlike traditional architectures that rely on a single centralized database for persistence, microservices adopt a different approach. Because of the principles of DDD, which emphasize the importance of private persistence for maintaining language consistency within a bounded context, each microservice must have its own dedicated database.
- Evolutionary design : One of the main purposes of microservices practitioners is evolutionary design. They view service decomposition as an additional tool that empowers application developers to manage changes in their systems without hindering the pace of development. Here, the match with DDD starts with the Whirlpool approach to the problem. The system grows with your knowledge about the domain itself.
In their blog, Martin Fowler and James Lewis provide a more comprehensive exploration of other characteristics of microservices architecture. Some of these are orthogonal to DDD, while others coexist without issues or conflicts. The real question, after reading and analyzing the whole blog, is Why do you have to move from monolith to microservices architecture?
Remember the second law of software architecture: The why is more important than the how .
After outlining the benefits and challenges of microservices, you could dive deeper into the connection between bounded contexts and how they mitigate some of the challenges while enhancing the advantages.
The bounded context seems to be a natural microservices boundary. By aligning each microservice with a bounded context, you can minimize the risk of shared dependencies or unclear responsibilities that often plague poorly implemented microservices. This alignment helps maintain the cohesion and autonomy of each service while allowing the system to evolve naturally alongside the domain.
As an architect, you must analyze the trade-off of the cost of autonomy versus duplication of data models and the increased complexity in orchestration. DDD provides patterns such as anti-corruption layers, domain events, and shared kernels that can help manage these complexities. For example, an anti-corruption layer ensures that communication between services respects their individual boundaries without introducing coupling or leaking domain details.
If you are asking yourself why to transition to microservices, the decision often needs to be taken when the limitations of a monolithic architecture become apparent. These may include slower development cycles to include new features, bottlenecks in scaling specific parts of the application, or challenges in onboarding new teams. Microservices offer a solution by creating modular, independently deployable units of functionality. But the question remains: Do the benefits outweigh the operational and development costs in your specific context?
The transition from a monolith to microservices is not a one-size-fits-all process. It is critical to identify the most problematic or independent bounded context first. These are often the areas where the business domain is well understood, and the potential for scalability or independent development is most significant. Start small, evaluate the result, and iterate incrementally. Remember, the goal is not to create microservices for their own sake but to solve real-world challenges more effectively.
Figure 10 .2 shows the process to adopt when moving from monolith to microservices. Keep your boundaries logically clean and enforce physical separation when it’s worth the cost.
Figure 10 .2 – Domain analysis first
As shown in the preceding figure, the process begins with the most critical step: analyzing the domain. This foundational activity is essential for understanding the problem space and identifying the appropriate bounded contexts. These contexts help to encapsulate distinct areas of your domain and provide clarity for defining aggregates, which represent the core business models and rules within each context.
Once these conceptual steps are complete, you can move on to the design phase, determining the physical boundaries within your system. At this stage, you can decide whether to implement a microservices architecture immediately or adopt a modular monolithic approach, deferring the physical separation until it becomes necessary.
Challenges and considerations
Microservices represent a distributed architecture, meaning each service runs in its own process. However, we must beware of the fallacies of distributed systems! We will cover these in detail in the upcoming subsection. Transitioning from a monolith to a microservices architecture involves analyzing numerous factors. So far, we have focused on the architectural aspects of the system and explored how to gradually refactor your code to prepare your monolith for decomposition.
Introducing the events in your monolith seems to be an over-engineering approach, and it is if you don’t need to split the monolith. However, because you are looking for a safe appropriate approach, it isn’t! With events, you can easily debug the whole system, even if the communication is asynchronous, by setting the appropriate breakpoints in your code and inspecting the process. At the end of this step, you can be confident that the system still works after moving to a microservices architecture—at least for the functional requirements.
On the other hand, it is time to take a look at the non-functional requirements. As Fred Brooks said in his famous paper No Silver Bullets – Essence and Accident in Software Engineering in 1986, there are two kinds of complexity: accidental complexity and essential complexity . The first one is particularly important when you move to a microservices architecture. When moving to a microservices architecture, you enter the distributed systems world, and the game rules change.
Fallacies of distributed computing
Back in 1994, L. Peter Deutsch, one of the original Sun fellows, created a list of seven fallacies, starting from a list of four created by Bill Joy and Dave Lyon. In 1997, James Gosling, the inventor of Java, added the eighth fallacy.
The fallacies of distributed computing are a set of assertions describing false assumptions that programmers, new to distributed applications, invariably make.
Table 10.2 shows the eight fallacies of distributed computing .
Fallacy | Description |
The network is reliable | Assumes that the network will always work perfectly, with no failures or interruptions |
Latency is zero | Assumes that messages sent over the network will arrive instantly, ignoring delays |
Bandwidth is infinite | Assumes that there is unlimited network capacity, disregarding limitations such as congestion or speed |
The network is secure | Assumes that the network is inherently secure, ignoring vulnerabilities and threats |
Topology doesn’t change | Assumes that the network structure is static, ignoring changes such as nodes joining or leaving |
There is one administrator | Assumes that a single authority manages the network, ignoring decentralized ownership |
Transport cost is zero | Assumes that data transfer has no cost, ignoring expenses related to bandwidth and latency |
The network is homogeneous | Assumes that all systems in the network are identical, ignoring differences in hardware, software, or configurations |
Table 10.2 – The eight fallacies of distributed computing
Later, Udi Dahan, a well-known expert in distributed systems and software architecture, expanded on the original list by adding two more fallacies. These additional fallacies address modern challenges in distributed systems, as shown in Table 10.3
Fallacy | Description |
The system is consistent | Assumes that the system will always maintain consistency across all nodes, ignoring the challenges of eventual consistency in distributed systems |
The system is predictable | Assumes that the system will behave in a predictable manner under all conditions, ignoring the impact of varying loads, failures, and delays |
Table 10.3 – Udi Dahan’s two fallacies
These two additional fallacies reflect the complexity of modern distributed systems and emphasize the need for architects and developers to account for inconsistency and unpredictability in their design.
In distributed systems, achieving strong consistency (where all nodes see the same data at the same time) is extremely difficult due to network delays and partitions. Many systems rely on eventual consistency, where consistency is achieved over time, not instantly. Because of network latency, distributed systems often face unpredictable behavior. Assuming that the system will behave predictably under all conditions is unrealistic.
Over the years, other authors have added more fallacies to the original list. While not officially part of the original set, these are often discussed in the context of modern distributed systems. Table 10.4 highlights these additional fallacies.
| Fallacy | Description |
|---|---|
| The system has infinite resources | Assumes that computing resources (e.g., CPU, memory, and storage) are unlimited, ignoring real-world constraints |
| The system is free of state | Assumes that stateless systems are easier to scale and maintain, ignoring the challenges of managing distributed state |
| Scaling is easy | Assumes that scaling a system (horizontally or vertically) can be done seamlessly, ignoring bottlenecks and architectural limitations |
| Failures are rare | Assumes that failures (hardware, software, or network) are infrequent, ignoring the inevitability of failure in large-scale systems |
| Time is consistent | Assumes that clocks across distributed systems are synchronized, ignoring clock drift and issues with event ordering |
Table 10.4 – Additional fallacies relevant to modern distributed systems
Let’s discuss the fallacies from the preceding table in more detail. The first is the assumption that systems have infinite resources, such as CPU, memory, or storage, particularly in cloud environments where resources appear abundant but remain limited and costly. Secondly, there is a belief that systems are free of state, assuming that stateless designs are inherently scalable while ignoring the challenges of managing distributed states, such as coordinating sessions or ensuring consistency across databases. The third fallacy is that scaling is easy, as developers often underestimate the complexity of partitioning data, managing load balancing, and avoiding bottlenecks as systems grow.
Fourthly, there’s the false assumption that failures are rare, when, in reality, hardware, software, and network failures are inevitable, and systems must be designed to handle them gracefully. Finally, distributed systems often rely on time synchronization, leading to the fallacy that time is consistent across all nodes. In practice, clock drift and synchronization issues can cause inconsistencies, making event ordering and coordination a significant challenge. These additional fallacies highlight the importance of recognizing the practical limitations of distributed systems and designing for resilience, scalability, and consistency. These fallacies also reflect the evolving challenges in distributed systems as they grow in scale, complexity, and reliance on cloud infrastructure. While not part of the original list, they are widely recognized in modern system design discussions.
As you can see, transitioning to a microservices architecture means embracing the challenges of distributed systems. In a monolithic solution, most of the problems you face are essential , as the infrastructure’s complexity is minimal—your entire application runs on a single machine. However, in distributed systems, you must also contend with accidental problems. These arise because your application is no longer confined to one machine but spans multiple machines or nodes, each with its own memory and processing capabilities. These nodes work together as a single system, communicating over a network, which introduces latency, potential failures, and other complexities.
Benefits and trade-offs in moving to microservices
So, why move to a distributed system? The answer lies in the benefits: distributed systems are designed to handle increased workloads by distributing tasks across multiple nodes. This architecture improves performance, fault tolerance, and scalability compared to centralized systems. For example, adding a new feature in an independent microservice is often simpler and less risky than modifying a large, tightly coupled monolithic system.
Does this mean there are only advantages to moving from a monolith to microservices? Absolutely not. While microservices offer significant benefits, they also come with trade-offs. You must carefully evaluate the characteristics of each architectural style, understand the specific needs of your stakeholders, and choose the approach that best aligns with your goals and constraints. Moving to microservices is not a one-size-fits-all solution; it’s a strategic decision that requires balancing the risks and rewards.
Table 10.5 shows a translation of domain concerns to architecture characteristics, like the one that Mark Richards and Neil Ford summarized in their book, Fundamentals of Software Architecture . This table was created with the aim of supporting architects in identifying the right architectural style in the face of stakeholder demands.
Domain Concern | Architecture Characteristics |
Mergers and acquisitions | Interoperability, scalability, adaptability, and extensibility |
Time to market | Agility, testability, and deployability |
User satisfaction | Performance, availability, fault tolerance, testability, deployability, agility, and security |
Competitive advantage | Agility, testability, deployability, scalability, availability, and fault tolerance |
Time and budget | Simplicity and feasibility |
Table 10.5 – Domain concerns vs. architecture characteristics
Once you have this table, the next step is to create a rating for each characteristic in each architectural style, as the authors did in their book. For our purpose, we have summarized this epic battle in Table 10.6
Architecture Characteristic | Modular Architecture | Microservices Architecture |
Partition type | Technical | Domain |
Number of quanta | One | One to many |
Deployability | ⭐ ⭐ ⭐ | ⭐ ⭐ ⭐ ⭐ |
Elasticity | ⭐ | ⭐ ⭐ ⭐ ⭐ ⭐ |
Evolutionary | ⭐ ⭐ ⭐ | ⭐ ⭐ ⭐ ⭐ ⭐ |
Fault tolerance | ⭐ | ⭐ ⭐ ⭐ ⭐ |
Modularity | ⭐ ⭐ ⭐ | ⭐ ⭐ ⭐ ⭐ ⭐ |
Overall cost | ⭐ ⭐ ⭐ ⭐ ⭐ | ⭐ |
Performance | ⭐ ⭐ ⭐ | ⭐ ⭐ |
Reliability | ⭐ ⭐ ⭐ | ⭐ ⭐ ⭐ ⭐ |
Scalability | ⭐ | ⭐ ⭐ ⭐ ⭐ ⭐ |
Simplicity | ⭐ ⭐ ⭐ ⭐ | ⭐ |
Testability | ⭐ ⭐ ⭐ | ⭐ ⭐ ⭐ ⭐ |
Table 10.6 – Modular architecture vs. microservices architecture
This table is not intended to be the definitive answer, but a guide. Think of it as one more tool in your toolbox for evaluating all aspects of your decision.
Assessing readiness for microservices
The decision to adopt a microservices architecture is as much about organizational and technical readiness as it is about aspiration. While the allure of microservices is strong—offering scalability, resilience, and team autonomy—the transition involves considerable complexity. Moving prematurely or without the necessary groundwork can lead to significant setbacks, technical debt, or even failure.
Signals of readiness for microservices
Before moving to microservices, evaluate your current architecture, team capabilities, and organizational needs. The following are strong indicators that the move can be made with minimum risk:
- Clear domain boundaries : You have well-defined domains and subdomains based on DDD principles. This ensures that the boundaries of each microservice align naturally with business capabilities, reducing the risk of overlapping responsibilities or fragmented logic.
- Scaling pressures on specific areas : Certain parts of your system require scaling due to high demand, while others do not. This imbalance is a strong indicator that horizontal scaling through microservices could be advantageous, so it enables targeted scaling of high-demand components.
- Independent development needs : Your teams are frequently blocked by interdependencies in a monolithic code base. Moving to microservices can enable teams to work autonomously, deploying updates without coordinating with unrelated parts of the application.
- Operational maturity : Your organization has invested in DevOps practices, including CI/CD, robust monitoring, and automated testing. These capabilities are essential to manage the complexity of a microservices architecture effectively.
- Technical expertise : Your development teams are proficient in distributed system design, including handling challenges such as eventual consistency, network latency, and service failures.
- Business justification : The decision to move is driven by measurable business needs, such as reducing time to market, improving system reliability, or enabling rapid scaling, rather than by trends or external pressures.
The role of a modular monolith as a foundation
Before transitioning to microservices, it’s often best to develop a modular monolith. A modular monolith applies to many of the same principles as microservices—such as clear boundaries and separation of concerns—within the context of a single deployable unit. This approach provides a strong foundation for eventual decomposition into microservices. Here’s why:
- Eases transition : A modular monolith enforces clean boundaries between modules, making it easier to identify which modules can be extracted as independent services. Without this preparation, disentangling a tightly coupled monolith can be a daunting task.
- Simplifies testing and deployment : Modules within a monolith can be tested and deployed together, simplifying operational overhead. This allows your teams to refine their understanding of domain boundaries without the complexity of managing distributed systems from the outset.
- Supports incremental decomposition : Once the modular monolith is stable, you can gradually extract services one at a time. This reduces risk and provides flexibility to adapt as your understanding of system requirements evolves.
Why the mediator pattern falls short for decoupling
Many modular monoliths rely on a mediator pattern for communication between modules. While this approach centralizes control and simplifies interactions within a monolith, it inherently keeps modules tightly coupled. The mediator acts as a hub, making all modules dependent on it for communication. This tight coupling can create challenges when breaking down modules into independent microservices:
- Centralized dependencies : The mediator becomes a critical dependency, limiting the autonomy of individual modules
- Difficult to extract services : Because modules rely on the mediator, you may need to rewrite significant portions of code to enable independent communication between services
Transitioning to event-driven communication
A more effective approach to decoupling modules is adopting event-driven communication within the modular monolith. This method replaces synchronous interactions through the mediator with asynchronous event-based messaging. Events are published by one module and consumed by others, enabling the following:
- Loose coupling : Modules no longer depend directly on one another, making them easier to extract as independent services
- Scalability : Event-driven systems can handle higher throughput as modules communicate asynchronously
- Simplified service extraction : Since modules are already communicating through events, the same messaging infrastructure can be used when transitioning to microservices
Preparing for microservices
Before embarking on a transition to microservices, consider these preparatory steps:
- Refactor toward modularity : Establish clear boundaries between modules, ensuring they align with DDD principles. Replace the mediator pattern with event-driven communication to decouple modules.
- Invest in operational readiness : Build the necessary infrastructure for CI/CD, monitoring, and automated testing.
- Start with pilot services : Identify one or two modules that are self-contained and have a high impact. Extract these as microservices to validate your approach and refine your processes.
By carefully assessing your readiness and laying a solid foundation with a modular monolith, you can transition to microservices more effectively, avoiding many common pitfalls. This approach ensures that your organization is positioned to fully realize the benefits of microservices while minimizing risks and disruptions.
Strategies for transitioning to microservices
It is time to dive into the code of our ERP system to bring all the patterns discussed in this chapter together. The first step in transitioning from a monolith to microservices is identifying the contexts and establishing clear boundaries around them. This ensures proper subdomain isolation, which is critical for successful migration.
Figure 10 .3 shows the solution as found in the 02-monolith_with_cqrs branch of the book’s GitHub repository:
Figure 10 .3 – Modular architecture with mediator
It’s crucial to progress in small, manageable steps. Once you’ve split the solution into clearly defined bounded contexts, it’s essential to ensure that each bounded context remains independent, with no dependencies on one another. At this stage, you can leverage fitness functions (see the Testing and stabilizing section in Chapter 6 , Transitioning from Chaos ) to validate your design.
As discussed earlier, while the mediator pattern isn’t ideal for preparing a monolith to transition into microservices, it serves as an effective intermediate solution. Jumping directly to an event-driven architecture introduces unnecessary complexity at this stage, which you should avoid. The mediator pattern provides a simpler way to manage communication between bounded contexts during this phase of refactoring.
The following code snippet demonstrates how the mediator facilitates communication between the Sales and Warehouse bounded contexts, ensuring that they do not directly interact with each other:
public class BrewUpMediator(ISalesFacade salesFacade, IWarehousesFacade warehouseFacade) : IBrewUpMediator
{
public async Task<string> CreateOrderAsync(SalesOrderJson body, CancellationToken cancellationToken)
{
List<BeerAvailabilityJson> availabilities = new();
foreach (var row in body.Rows)
{
var availability = await warehouseFacade.GetAvailabilityAsync(row.BeerId, cancellationToken);
if (availability.TotalRecords > 0)
availabilities.Add(availability.Results.First());
}
// Prepare the list of rows that are available for sale
List<SalesOrderRowJson> rowsForSale = (from row in body.Rows
let beerAvailability = availabilities.Find(a => a.BeerId == row.BeerId.ToString())
where beerAvailability != null && beerAvailability.Availability.Available >= row.Quantity.Value
select row).ToList();
if (rowsForSale.Count == 0)
{
return "No beer available for sale";
}
body = body with { Rows = rowsForSale };
return await salesFacade.CreateOrderAsync(body, cancellationToken);
}
}
As shown in the preceding code, BrewUpMediator receives the façades for both Sales and Warehouse . This allows it to facilitate communication between these bounded contexts and manage the process of order creation without establishing direct dependencies between them.
After completing this step and verifying that everything functions as expected, you can proceed to replace the mediator pattern with an event-driven communication pattern. At first, introducing events into a monolithic project might appear to be unnecessary overhead—and it would be if you intended to maintain the project in its monolithic state. However, our goal is to prepare the solution for eventual decomposition into multiple microservices. Therefore, replacing the mediator with events becomes a crucial step. Making this change within the monolithic project allows for simpler testing and reduced risk. As always, prioritize simplicity and avoid adding unnecessary complexity during this transition.
Figure 10 .4 shows the new structure of our ERP solution. You can find the whole solution in the 03-monolith_with_cqrs_and_event_sourcing branch in the book’s GitHub repository:
Figure 10 .4 – Modular architecture with events
At this stage, as you can see, the mediator has been removed, and communication between Sales and Warehouse is now managed through events. This eliminates the need for a mediator to orchestrate interactions between bounded contexts.
In this setup, the Sales bounded context maintains a copy of the availability data, while Warehouse owns the Availability aggregate. Naturally, the copy in Sales follows an eventual consistency model, so it’s essential to ensure that this approach aligns with your business requirements.
The following code snippet demonstrates how the Warehouse bounded context raises an integration event whenever its availability is updated:
public class AvailabilityUpdatedDueToProduction OrderForIntegrationEventHandler(ILoggerFactory loggerFactory,
IEventBus eventBus) : DomainEventHandlerBase<AvailabilityUpdated DueToProductionOrder>(loggerFactory)
{
public override async Task HandleAsync(AvailabilityUpdatedDueToProductionOrder @event,
CancellationToken cancellationToken = new())
{
cancellationToken.ThrowIfCancellationRequested();
var correlationId =
new Guid(@event.UserProperties.FirstOrDefault(u => u.Key.Equals("CorrelationId")).Value.ToString()!);
AvailabilityUpdatedForNotification availabilityUpdatedForNotification = new(@event.BeerId, correlationId, @event.BeerName, @event.Quantity);
await eventBus.PublishAsync(availabilityUpdatedForNotification, cancellationToken);
}
}
The following code snippet receives and manages the integration event within the Sales bounded context anti-corruption layer:
public sealed class AvailabilityUpdatedForNotificationEventHandler(ILoggerFactory loggerFactory, IServiceBus serviceBus) : IntegrationEventHandlerAsync <AvailabilityUpdatedForNotification>(loggerFactory)
{
public override async Task HandleAsync(AvailabilityUpdatedForNotification @event,
CancellationToken cancellationToken = new())
{
cancellationToken.ThrowIfCancellationRequested();
var correlationId =
new Guid(@event.UserProperties.FirstOrDefault(u => u.Key.Equals("CorrelationId")).Value.ToString()!);
UpdateAvailabilityDueToWarehousesNotification command = new(@event.BeerId, correlationId, @event.BeerName, @event.Quantity);
await serviceBus.SendAsync(command, cancellationToken);
}
}
Another approach to managing a process like this is to use a long-running process or saga. You’ll learn more about this pattern in Chapter 12 , Orchestrating Complexity – Advanced Approaches to Business Processes.
Transitioning from the modular event-driven architecture we developed throughout this book to a microservices architecture can be considered a straightforward process. We have demonstrated this in the 04-microservices branch of the book’s GitHub repository. The key steps involved isolating the Sales and Warehouses modules into their own solutions. This was achieved by moving all related projects (including BrewUp.Shared ) and exposing their respective endpoints. The result is two fully independent services, each capable of evolving at their own pace. Figure 10 .5 illustrates the structure of these newly created solutions.
Figure 10 .5 – The new solutions for Sales and Warehouses
To conclude, it’s best to avoid introducing unnecessary complexity at the outset of your refactoring process. Instead, as demonstrated, you can achieve your goals through incremental steps that not only enable you to gain deeper insights into your domain but also empower you to make well-informed decisions at the right time.
Summary
In this chapter, you explored the critical considerations and strategies for transitioning from a monolithic solution to a microservices architecture. You learned that architectural decisions require careful alignment between technical and business needs, balancing domain concerns with technical constraints to evolve systems effectively and without unnecessary complexity.
The transition begins with identifying appropriate bounded contexts and ensuring clear boundaries. Initial communication between these contexts can be handled with simpler patterns such as the mediator, which can later be replaced with event-driven communication. This prepares the monolith for eventual decomposition into independent microservices aligned with specific bounded contexts.
In this chapter, you should have learned the following:
- How to recognize and utilize bounded contexts as a foundational element for microservices architecture
- How to adopt a step-by-step approach to transition from a monolithic to a microservices architecture, reducing risks and maintaining system stability
- What the roles of mediator and event-driven patterns are in decoupling and facilitating communication during the transition
- What accidental complexities are and strategies to address them, including handling the fallacies of distributed computing
- How to evaluate key organizational and technical signals to assess preparedness for adopting microservices
By following these principles, you can ensure a structured and deliberate evolution of your system, prioritizing simplicity, business alignment, and long-term scalability.
In the next chapter, we will explore advanced topics, focusing on event versioning—a critical aspect of managing and maintaining consistency in event-sourced systems.