Refactoring the Database

In the previous chapters, we explored how to use CQRS and event sourcing to break apart a monolithic application, allowing services to align with specific bounded contexts in a microservices architecture. However, while separating application logic is a crucial step, the database itself often remains a bottleneck, tightly coupled and shared across services. For a true transition to microservices, database refactoring is essential to ensure that each service has control over its own data and operates independently.

In this chapter, you’ll learn about the primary patterns for database refactoring, each addressing different strategies for managing and partitioning database tables to support service-specific ownership. We are going to cover how to do the following:

  • Clearly identify and align domain boundaries to support independent service evolution
  • Apply common table ownership strategies to manage data shared across multiple services effectively
  • Implement single table ownership for assigning exclusive data control to individual services
  • Navigate joint table ownership scenarios, ensuring distinct services clearly define their data boundaries
  • Gradually migrate stored procedures into your application code, reducing coupling and enhancing testability and maintainability

Additionally, many legacy systems rely on stored procedures to handle complex logic within the database. While stored procedures can be efficient, they also create a tight coupling between the application code and the database, making them difficult to maintain and test in a microservices context. This chapter will also guide you through patterns for migrating stored procedures into your code base, ensuring cleaner service boundaries and improved maintainability.

By the end of this chapter, you’ll have a strong foundation in database refactoring strategies, enabling you to move confidently toward a fully decoupled microservices architecture.

The complete code for this chapter can be found in the 01-monolith_legacy branch within the book’s GitHub repository: https://github.com/PacktPublishing/Domain-driven-Refactoring/tree/01-monolith\_legacy .

Modular services and the need for database refactoring

Modular services form the core of the transformation from a monolithic architecture to a more flexible, maintainable, and scalable system. As you already learned in previous chapters, modular services are built around specific business domains and function as independent units that can evolve separately. This independence fosters agility, allowing teams to make changes in one service without having to worry about impacting other services. Each service owns its data, logic, and specific responsibilities, making it easier to manage complexity.

In practice, modular services are often designed around the principles of DDD, where each service represents a bounded context —a clearly defined area of the business. By aligning the database schema with these bounded contexts, we can significantly reduce the coupling between different parts of the system and ensure that each service interacts only with the data it needs. This eliminates the need for complex joins and relationships that are typical in monolithic databases and makes the services more autonomous.

For example, consider our ERP system where Orders , Customers , and Warehouses each represent a distinct bounded context. In a monolithic setup, a single database might store tables for all these domains, with intricate foreign key relationships linking them together. In a modular architecture, however, each of these domains could have its own service with its own database or schema. The Orders service would handle only order data, while the CustomerManagement service would manage customer-related data independently. This separation means that changes in customer information do not directly impact order processing, and vice versa, minimizing the risk of cascading failures.

Another key aspect of modular services is data ownership and autonomy. Each service should be responsible for the data it needs to fulfill its role. This ownership is critical in ensuring that services remain loosely coupled and can operate independently of each other. In our previous example, WarehouseService is the only service that has the authority to modify beer’s availability. OrdersService can inform WarehouseService of an order event, but it cannot directly modify inventory data. This separation of concerns helps maintain clear boundaries and prevents unintended side effects that are common in tightly coupled systems.

By understanding and implementing modular services effectively, the database refactoring process becomes much more manageable. The database is refactored to align with individual service domains, reducing complexity and making future changes more straightforward. Each modular service becomes a self-contained unit, capable of evolving without introducing significant risks to the overall system. This approach ultimately sets the foundation for a distributed system, where each service can scale, be updated, or even be replaced independently, providing a robust pathway toward microservices if the business needs to evolve in that direction.

As our software architecture evolves from a monolithic legacy system to a modular monolith with CQRS and event sourcing, the role of the underlying database becomes increasingly critical. The transformation toward a modular architecture inevitably demands that the database structure evolve as well, aligning more closely with new, separated application components. This chapter focuses on why refactoring the database is crucial during this transition, and how the database itself must shift to reflect the changes made at the application level.

While we frequently reference SQL databases in our discussions, the same principles apply to NoSQL systems—simply think in terms of collections instead of tables, and you’ll find that most patterns remain just as relevant.

Monolithic databases, which are typically characterized by tightly coupled tables, global relationships, and shared schemas, often grow in complexity as the system evolves, leading to poor maintainability, significant technical debt, and increased fragility. As application components move toward a more modular design—decoupling responsibilities through CQRS and implementing event sourcing to handle state transitions—the underlying database needs to follow suit. Without corresponding changes to the database structure, the benefits of a modular application layer are limited. The persistence layer remains a bottleneck, restricting the flexibility and independence that modular services need.

Hidden business rules in the data schema

Legacy databases commonly embed business logic implicitly within the data schema, particularly through constraints such as foreign keys. For instance, a foreign key constraint between an order table and a customer table often enforces business rules, such as ensuring an order cannot exist without a valid customer. While technically useful, these constraints represent embedded business logic that can make changes or refactoring difficult, as the business rules are maintained implicitly and scattered throughout the database structure. This implicit embedding of business logic can significantly hinder refactoring efforts.

The purpose of refactoring the database is twofold: to maintain consistency with the refactored modular application, and to reduce the coupling and complexity that often plague monolithic databases. For instance, in the previous chapter, the refactoring we carried out allowed application components to function independently, using CQRS to separate read and write responsibilities and event sourcing to provide a more traceable and resilient state mechanism. Now, our challenge is to ensure that the database schema and architecture adequately reflect these changes—enabling modularity at both the data and application levels.

The database refactoring must tackle several key areas:

  • Aligning domain boundaries : The goal is to ensure the database aligns with the DDD boundaries we defined during the modularization process. Tables and other database structures that originally spanned multiple business contexts may need to be broken down or reorganized to reflect new, more granular services. As an example, imagine a table called SalesOrders that stores not only the order information but also customer details such as address and contact information. In a modular approach, customer information belongs in a separate domain, such as CustomerManagement , while SalesOrders focuses purely on order data. Thus, the SalesOrders table should be split into two tables: one for SalesOrders and another for CustomerDetails , which reside in separate schemas aligned with their respective domains.
  • Managing data consistency across services : In a modular architecture, data that was previously centralized might now belong to multiple separate domains. It is critical to identify how to manage consistency across these domains while avoiding overly tight coupling—a challenge especially pertinent when moving toward CQRS and distributed data models. To be more clear, consider the situation where you need to ensure consistency between Warehouse and SalesOrders . In a monolithic database, these might have been joined directly in queries. Now, with modular services, Warehouse and SalesOrders are separate services, potentially with different data stores. To maintain consistency, you could use an event-driven approach where a SalesOrderCreated event triggers WarehouseService to update stock levels, ensuring eventual consistency without tightly coupling the services.
  • Transitioning while ensuring performance : During the transition period, the legacy monolith must continue to serve existing business operations without a drop in performance or reliability. This often means supporting a dual schema—maintaining parts of the old schema while introducing the new one, until the transition is complete. For example, suppose we have refactored a Payments table to separate payment processing from payment history. During the transition, both Payments (original) and PaymentProcessing (new) tables may coexist. Any updates to the payment data need to be synchronized across both tables until all dependent services are updated to use the new PaymentProcessing structure. This could be achieved using database triggers or a background synchronization script.

By addressing the database refactoring alongside the refactoring of the application components, we can ensure that our modular monolith is truly modular from top to bottom—paving the way for easier maintenance, greater agility in responding to changing requirements, and a smoother path forward to future service extraction or migration to a fully distributed system.

Finally, it is crucial to clearly communicate these choices to the business, as their need for real-time updates can often be met with eventual consistency. As architects, it is our responsibility to explain these choices and collaboratively decide with business experts which approach to adopt, ensuring a smooth trans ition.

Principles of database refactoring and identifying domain boundaries

A shared database introduces strong coupling across different bounded contexts, limiting flexibility, and making each change ripple across the entire system. While this approach simplifies consistency management by offloading it to the database rather than handling it directly in code, in legacy applications, this structure often leads to unintended side effects whenever updates or changes are made to accommodate new requirements. For example, if a new feature needs to be added to the warehouse context in our ERP, altering the database schema may inadvertently disrupt the sales context, causing errors or requiring additional refactoring.

This entanglement between contexts opposes the principle of modularity central to DDD. By splitting the database into smaller, context-specific databases, each subdomain can evolve independently. Each bounded context should manage its own data model, enabling each team to independently refine, extend, and optimize their database structures without impacting others.

We are confident that many of you have heard this sentence at least once:

“ I assumed the database structure would be thoroughly defined and finalized from the beginning. ”

In traditional development, teams often start with a fixed, predefined database schema and then they build code on top of it. This approach assumes that database requirements will remain static, which rarely aligns with real-world project dynamics. The principles of DDD challenge these dynamics by emphasizing that system design should evolve, starting with deep collaboration with stakeholders and using the Ubiquitous Language that reflects the business context. DDD recommends iterating the design of both the code and the database, evolving the system in small steps to stay aligned with changing requirements and insights.

This approach requires us to move away from a rigid database schema toward what is known as evolutionary database development .

Evolutionary database development

This concept was introduced by Pramod J. Sadalage and Scott W. Ambler in their book Refactoring Databases – Evolutionary Database Design . The approach adapts Agile and test-driven development practices, traditionally used in software development, to the database layer. Just as software code is continuously refactored and tested, the database can be incrementally designed and updated to mirror the ongoing evolution of the application and its requirements.

With evolutionary database development, teams can adapt the database structure as the project progresses, aligning it more closely with the actual needs of each bounded context. This avoids the common pitfall of early, rigid database decisions that constrain flexibility and force developers to work around outdated structures. This approach also encourages using techniques such as database migration, automated tests, and version control for the database schema. Together, these tools make it safer and simpler to modify the database incrementally without breaking the system. By evolving the database alongside the code, teams can respond to change more effectively, ensuring that both the application and the database remain relevant, efficient, and aligned with the business goals over time.

Adopting this evolutionary approach in database development offers multiple benefits. Its key advantages include the following:

  • Minimizing waste : Avoids unnecessary work on detailed requirements and design artifacts that may become obsolete as requirements evolve
  • Reducing rework : Enables early identification of major issues without prematurely diving into minor details, thereby lowering the risk of costly rework
  • Ensuring functionality : Frequent deployment of working versions, even in demo environments, helps teams consistently validate that the system operates as expected, reducing project risk
  • Enhancing database quality : Regular, incremental database refactoring ensures the schema evolves and maintains high-quality design over time
  • Aligning with developers’ workflow : An evolutionary approach ensures data professionals work compatibly with developers using Agile methods
  • Reducing effort : Focuses only on essential, immediate tasks, avoiding unnecessary work and lowering overall development effort

Of course, because you are an architect and you know the first architecture law (there is always a trade-off), here are some disadvantages to evolutionary database development:

  • Cultural barriers : Many data professionals are accustomed to a sequential approach, preferring detailed, upfront data modeling. However, modern methodologies favor an agile, evolutionary approach, which some professionals, particularly those trained in older methods, may resist.
  • Learning curve : Shifting from a serial to an evolutionary mindset requires time and a willingness to learn new techniques.
  • Limited tool support : While refactoring tools for code are widely available, similar tools for database refactoring are still developing, though efforts such as the Eclipse Data Tools Platform ( https://projects.eclipse.org/projects/tools.datatools) aim to bridge this gap.

Before introducing the patterns you can use in database refactoring, it’s important to remember that the goal is to improve the structure while preserving the database’s behavioral and informational semantics. That means database refactoring is conceptually more challenging than code refactoring because it requires maintaining not only behavioral consistency but also informational accuracy. This complexity is compounded by the high degree of coupling often present in database architectures, where multiple parts of the system depend on shared data structures. Achieving what we explained requires treating database structure changes with the same rigor as code changes, following principles of testing, versioning, and incremental updates.

The benefits can be summarized as follows:

  • Thorough testing : Both data teams and developers should thoroughly test schema changes to ensure stability and compatibility. If an ORM tool is used, fitness functions (introduced in Chapter 6 , Transitioning from Chaos ) can be helpful for keeping schema mappings in sync with database structures.
  • Version control : Database schemas should be versioned in sync with the code that depends on them, as each relies on the other to function correctly. Separating code and schema management often introduces unnecessary complexity and inefficiencies.
  • Incremental updates : Like code, schema changes should be gradual and incremental to support system evolution. Automated migration tools are favored for updating schemas, avoiding the risks and delays associated with manual changes.

As you should already know, it is important to understand and analyze the problem before attempting to refactor the database. For example, if multiple services or applications access your database, you cannot refactor it and then deploy all of these services simultaneously. You need a transition period, called deprecation mode , until the schema changes take place in all the services. For a detailed explanation, you can read the paper The Agile Database: Tutorial Notes , by Pramod Sadalage and Peter Schuh (2002).

Figure 8 .1 shows three typical scenarios to consider before splitting the database.

Figure 8.1 – Database splitting

Figure 8 .1 – Database splitting

Patterns for database refactoring

There are at least three key patterns you can apply during database refactoring, each with its own advantages and limitations. The following explanations highlight these essential patterns, showcasing how each offers a targeted approach to improving database design and functionality:

  • Common table ownership : In this situation, multiple services access the same table for both reading and writing data. Before separating the table, it is important to clarify which module, or bounded context, has responsibility for write operations and which modules have read-only access.
  • Single table ownership : This is the simplest scenario, where only one service accesses the table for all read and write operations. Here, you can move the table into a dedicated database that aligns with this bounded context, as there are no conflicting ownership issues.
  • Joint table ownership : In this scenario, different services are responsible for managing different sets of properties within the same table. To split the table, you need to follow domain-specific rules and patterns, separating properties according to the responsibilities of each module.

Common table ownership is the scenario you will frequently find in projects, and it is also used in our ERP. Figure 8 .2 shows the starting step of our refactoring process and where it is used as an integration point.

Figure 8.2 – The database as an integration point

Figure 8 .2 – The database as an integration point

As you can see in Figure 8 .2 , Sales and Warehouse use the same database, but what if their features start to diverge so much that the database will become a burden?

In the book Refactoring Databases , by Pramod Sadalage and Scott Ambler, the authors suggest using the expand/contract pattern . Figure 8 .3 represents this pattern.

Figure 8.3 – The expand/contract pattern

Figure 8 .3 – The expand/contract pattern

With this approach, developers start with an initial state and move to a final state, keeping both the previous and updated states available during the transition. This intermediate state supports backward compatibility and allows other services within the system adequate time to adapt to changes. There isn’t a constraint on the duration of this transition. It could be a few days or several months.

During the Start phase, developers implement the refactoring; in the Transition phase, both schemas, old and new, exist, and finally, in the End phase, the refactoring is completed.

Firstly, in the Start phase, both Sales and Warehouse bounded contexts access the same Availability collection in the same database. Warehouses owns the collection, but Sales needs read access to check availability when processing an order.

Secondly, during the Transition phase, we duplicate the Availability table (or collection if using a NoSQL database) into two distinct databases and Sales still reads data from the table in the original database.

Finally, during the End phase, Sales is refactored to read the Availability data from its own database (the one we created during the Transition phase). At the end of this phase, only the Warehouse bounded context retained ownership of the Availability table. Figure 8 .4 shows the result of our refactoring in which you can notice that there are two different databases, with the same table, but with different responsibilities.

Figure 8.4 – Two databases with eventual consistency

Figure 8 .4 – Two databases with eventual consistency

As you can see, after the End phase, only the Warehouse bounded context has ownership of the Availability table of the original database. The same table, in the Sales database, is eventually consistently updated, and the Sales bounded context can just be read from it.

After applying this operation, you need to synchronize data from the original database to the newly created one. For this purpose, Data Duplication through Event-Based Data Synchronization is the recommended pattern. We’ll go deeply into it in the next chapter.

An essential aspect of database refactoring involves reworking stored procedures, which are written in the database’s native SQL. While stored procedures offer a powerful and efficient way to manipulate data, they are challenging to test and often lead to tight coupling between modules because separating behaviors across them is difficult.

To address this, the native SQL code should be migrated into the module’s application code. You must use the same Extract/Contract pattern applied before. Figure 8 .5 shows the steps to follow.

Figure 8.5 – Steps to extract stored procedures

Figure 8 .5 – Steps to extract stored procedures

As you learned with table extraction, extracting a stored procedure isn’t as simple as moving the script directly into your code base. This process requires a step-by-step approach, with thorough testing at each stage to ensure stability and accuracy before proceeding. Here’s an explanation of the pattern applied to stored procedures to guide you through this careful extraction process:

  1. Start : At the beginning, the layer used to access the database calls the stored procedure directly within the database. It is a common scenario in many legacy systems. Your goal is to remove this stored procedure.
  2. Expand : It is impossible to move the stored procedure’s script directly in your code in just one step. That’s because you don’t know how many services are calling it. So, you prepare your code in SalesOrderDomainService and move the calls to the database into this new domain service, without removing the stored procedure.
  3. Contract : Finally, when no services are calling the stored procedure, you can safely remove it from the database.

This operation often requires additional refactoring, especially when the data in question is no longer housed in a single database. In such cases, processing mechanisms such as the saga pattern may be necessary to coordinate actions across modules, but we’ll explore this in more detail in the next chapter.

Extracting services and managing data consistency

Going back to the 01-monolith_legacy branch, you can observe the original database used in our ERP. Figure 8 .6 shows the original database with both the SalesOrder and Availability collections:

Figure 8.6 – Common table ownership

Figure 8 .6 – Common table ownership

As you can see, in the beginning, we had a situation where multiple services relied on a single database to store and access all the collections they needed—for instance, services such as SalesQueryService or AvailabilityQueryService in the ERP code base. In this scenario, any of these services can modify the data in each collection, which creates several risks. Because all services have direct access to the same collections, there is a high risk of tight coupling.

Just as all collections are in the same database, all the services are in the same code base. In our ERP, we have just one module that is responsible for updating all the collections, BrewUp.DomainModel . Figure 8 .7 shows the project with all the necessary services.

Figure 8.7 – All the services are in the same module

Figure 8 .7 – All the services are in the same module

In this scenario, when a new order is processed, we check for the availability of the beer using warehouseRepository , which is an implementation of IRepository for the Availability collection. Because all the collections rely on the same database, we can have multiple implementations in the same modules. The side effect is that we are creating tight coupling inside the CreateSalesOrderAsync method:

public sealed class SalesOrderService(
    [FromKeyedServices("sale")] IRepository saleRepository,
    [FromKeyedServices("warehouse")] IRepository warehouseRepository) : ISalesOrderService
{
    public async Task CreateSalesOrderAsync(SalesOrderId salesOrderId, SalesOrderNumber salesOrderNumber, OrderDate orderDate,
       CustomerId customerId, CustomerName customerName, IEnumerable<SalesOrderRowJson> rows, CancellationToken cancellationToken)
    {
       List<SalesOrderRowJson> beersAvailable = new();
       foreach (var row in rows)
       {
          var availability = await warehouseRepository.GetByIdAsync<Entities.Warehouses.Availability>(row.BeerId.ToString(), cancellationToken);
          if (availability!=null)
             beersAvailable.Add(row);
       }
       var aggregate = SalesOrder.CreateSalesOrder(salesOrderId, salesOrderNumber, orderDate, customerId, customerName, beersAvailable);
       await saleRepository.InsertAsync(aggregate.MapToReadModel(), cancellationToken);
    }
}

In a simple example such as this one, it is not a big problem, but when the application grows, the number of services in this module will grow, and adding new features will be increasingly complicated.

To avoid this scenario, we moved the Availability collection within the Warehouse module, and of course, in a separate database. At the end of the migration, the solution will look like the one shown in Figure 8 .8 .

Figure 8.8 – Solution after migrating the collection and services

Figure 8 .8 – Solution after migrating the collection and services

Having the Availability collection in two different databases implies the problem of keeping them synchronized. Warehouse is the bounded context that has the ownership of this data, but Sales needs to read the availability when processing a new order. We applied the Data Duplication through Event-Based Data Synchronization pattern introduced in the previous section. When the Warehouse domain receives a command to update Availability , because the beer production is over, it raises the AvailabilityUpdatedDueToProductionOrder domain event. As this is a domain event, it has be to managed inside the Warehouse bounded context. We have two event handlers for this purpose within the BrewUp.Warehouses.ReadModel project: the first one has the responsibility to update the read model, and the second one has to publish the AvailabilityUpdatedForNotification integration event. This event is caught by the Sales bounded context, inside the anti-corruption layer represented by the BrewUp.Sales.Acl project, and used to update the copy of the data into the Availability collection of the BrewUpSales database.

Here is the code to publish the integration event:

namespace BrewUp.Warehouses.ReadModel.EventHandlers;
public class AvailabilityUpdatedDueToProductionOrderFor
IntegrationEventHandler(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);
    }
}

As you can see, this handler in the BrewUp.Warehouses namespace receives the AvailabilityUpdatedDueToProductionOrder domain event and publishes the AvailabilityUpdatedForNotification integration event.

Moving to the BrewUp.Sales bounded context, you can find the BrewUp.Sales.Acl anti-corruption layer project with the following handler:

namespace BrewUp.Sales.Acl;
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);
    }
}

The responsibility of the preceding piece of code is to receive the integration event and prepare the command to update the internal read model.

Using different events, as in this example, is a best practice to avoid coupling between the bounded contexts. In this way, you can modify the domain event to introduce new features into the Warehouse bounded context, without changing the integration event used to communicate with the other bounded contexts. Figure 8 .9 shows the solution on the Warehouse side after the refactor:

Figure 8.9 – The Warehouse bounded context after the refactor

Figure 8 .9 – The Warehouse bounded context after the refactor

The solution’s organization highlights the separation of concerns inside the bounded context itself.

Figure 8 .10 shows the same solution for the Sales bounded context:

Figure 8.10 – The Sales bounded context after the refactor

Figure 8 .10 – The Sales bounded context after the refactor

In the preceding figure, you can see the anti-corruption layer implemented via the BrewUp.Sales.Acl project. This layer aims to translate the language used by the Warehouse bounded context into the language used inside the Sales bounded context. This is the ACL pattern, which we introduced in Chapter 3 , Strategic Patterns .

Transitioning to the new architecture and ensuring performance

Now that we have made the first attempt to divide the database into smaller ones more aligned with our modules (or bounded contexts), we should start thinking about the various performance considerations involved during the transition from a monolithic database into a modular architecture, especially in distributed systems where asynchronous communication and eventual consistency are implemented. The challenge lies in optimizing performance while ensuring that the system’s data remains consistent, particularly in scenarios where certain services are loosely coupled and rely on asynchronous operations for updates. Let’s break down the steps involved in analyzing performance bottlenecks and implementing optimizations with the SalesOrder and Warehouse services.

We can summarize the potential performance bottlenecks as follows:

  • Network latency : Direct service-to-service calls across the network add latency
  • Data synchronization delays : Ensuring consistent data across services can be complex, particularly with asynchronous updates
  • Scalability issues : Some patterns may scale poorly if data volumes or update rates increase

By identifying these bottlenecks, we can select appropriate optimization strategies tailored for performance in distributed systems.

Distributed data access patterns

To ensure the SalesOrder and Warehouse services operate efficiently with access to inventory data, three distributed data access patterns can be considered: replicated caching, synchronous interservice communication, and column schema replication.

Replicated caching

The replicated caching pattern uses an in-memory cache where each service maintains a synchronized cache of essential data, such as stock levels. The Warehouse service manages inventory data, while SalesOrder holds a read-only replica, updated asynchronously, as shown in Figure 8 .11 .

Figure 8.11 – Replicated caching architecture

Figure 8 .11 – Replicated caching architecture

This pattern minimizes network calls, reduces latency, and allows SalesOrder to remain operational even if Warehouse experiences downtime. Replicated caching is optimal for relatively static or low-frequency data updates but may struggle with high update rates.

Synchronous interservice communication

The synchronous interservice communication pattern is used in scenarios where immediate inventory accuracy is essential, where SalesOrder may query Warehouse directly. This is probably the most common pattern for accessing data in a distributed system. When a service needs to read data that it cannot access directly, it asks the owning service for it by using a remote access protocol (i.e., RPC or REST). However, this approach introduces latency from network roundtrips and dependency on Warehouse availability. It could also introduce security latency depending on the security level of the endpoint being accessed. Lastly, do not forget the data latency that you could have due to multiple database calls to retrieve the data requested.

So, while straightforward, this pattern scales poorly under high loads and tight consistency requirements due to its synchronous nature.

Column schema replication

Column schema replication is a strategy for services requiring high data responsiveness, where specific fields (or columns), such as availability , are duplicated from one service’s database into the local tables of SalesOrder to enable immediate access without remote calls. This approach trades consistency for performance and requires a mechanism to synchronize changes from Warehouse via events or queues.

There are different solutions to achieve this async alignment between services. The first one is the event-based pattern . With event sourcing, the Warehouse service broadcasts stock updates asynchronously whenever the inventory changes, which SalesOrder listens to and updates locally. This pattern ensures that SalesOrder is eventually consistent with the latest stock levels while keeping performance high due to the decoupled nature of event handling. Figure 8 .10 shows the event stream that originates from Warehouse and is subscribed by SalesOrder .

Figure 8.12 – Event-based pattern

Figure 8 .12 – Event-based pattern

The alternative is to go with Background Synchronization . For scenarios where immediate consistency is less critical, background synchronization processes can periodically update inventory records in SalesOrder . This method minimizes the real-time load on Warehouse but introduces a lag between updates, making it suitable for non-critical stock-level data.

Lastly, the Orchestrated Request-Based Pattern involves an orchestrator service that manages transactions between SalesOrder and Warehouse . This synchronous pattern ensures consistency but can become a bottleneck if the orchestrator’s performance degrades under heavy loads. As such, this pattern is best suited for critical operations where strict data integrity is required.

Optimizing query performance with caching and indexing

There are other simple steps to consider in maintaining high performance that are often overlooked (at least in our experience). These are as follows:

  • Caching : Utilize in-memory caches for frequently accessed data
  • Indexing : Carefully index frequently queried fields, such as stock levels, in SalesOrder
  • Data duplication : For critical data, duplication allows SalesOrder to function independently without frequent remote calls

By adopting a combination of distributed access patterns, eventual consistency, and strategic synchronization methods, the transition from monolithic to modular architecture becomes smoother and more performant. These strategies ensure that SalesOrder and Warehouse remain loosely coupled, maintain performance, and support the agility required in modular architecture.

Testing and deployment

As we transition to a modular architecture, testing and deploying the database becomes critical in ensuring that refactored services and their data schemas function correctly and remain resilient. In a distributed system with a refactored database, this process is more complex than in a monolithic setup. Each module’s data is now independently managed and synchronized, requiring careful testing for consistency, reliability, and performance across services. Deployment practices must also ensure smooth updates without downtime or data loss.

Keep in mind that testing a distributed database in a modular architecture involves validating both the data integrity and the behavior of services that interact with it. With each bounded context now managing its own data, testing must account for consistency, failover handling, and compatibility.

Testing strategies

So, let’s look at some strategies for effectively testing and deploying the database during this transition, ensuring stability as we move toward a fully modular and distributed system:

  • Unit testing for schema integrity and changes : Each service should include unit tests that validate its individual schema, ensuring that changes to one module’s schema do not inadvertently impact others. Unit tests should verify that tables are correctly indexed, have the right constraints, and adhere to the designed schema structure. For instance, tests on the SalesOrder service schema can ensure that fields such as orderId and availability maintain their expected data types and relationships.
  • Integration testing with mocked services : Since multiple services may rely on data from other modules, integration tests are essential for verifying interactions between SalesOrder , Warehouse , and other related services. By using mocks or stubs for external services, we can isolate and verify database behavior within each service’s context, simulating the full data flow without impacting live data. For example, integration tests should verify that SalesOrder can read stock levels accurately from the Warehouse cache or database replica.
  • Eventual consistency testing : For services employing eventual consistency, tests should ensure that delays in data synchronization do not introduce inconsistencies. In a test environment, simulate conditions such as network latency or temporary unavailability of the Warehouse service and verify that SalesOrder still functions as expected. Test scenarios should include both typical synchronization periods and high-load situations to ensure data consistency is maintained under varying conditions.
  • Contract testing for interservice communication : Contract testing ensures that communication between services, such as SalesOrder and Warehouse , remains reliable. These tests validate that each service can correctly handle and interpret data or events from the other. For example, if SalesOrder receives an AvailabilityUpdated event from Warehouse , contract tests should confirm that SalesOrder processes it correctly and updates its local inventory cache.
  • Performance and load testing for database scalability : Load testing is critical in understanding how the database will perform under high concurrency. By simulating heavy read and write loads, load tests reveal bottlenecks in schema design, indexing, and caching strategies. These tests can simulate high-traffic scenarios where SalesOrder frequently checks stock levels, helping to tune the database for optimal performance.

Deployment strategies for modular databases

Deploying a database in a modular architecture requires a strategy that minimizes downtime, preserves data integrity, and allows smooth updates across services. Since each module now operates independently, deployment processes must ensure that schema changes, migrations, and updates occur without disrupting interdependent services. The following are some strategies to consider:

  • Blue-green deployments for zero downtime : Use a blue-green deployment strategy for database changes, where two environments (blue and green) run concurrently. Changes are applied to the blue environment while green continues to serve production traffic. Once testing confirms the new schema, traffic is switched to the updated environment, ensuring zero downtime and a quick rollback if issues arise.
  • Schema migration patterns (expand/contract) : The expand/contract pattern (explained in detail in the Principles of database refactoring and identifying domain boundaries section) helps manage schema changes in a modular database. When refactoring shared data between SalesOrder and Warehouse , expand the schema to support both the old and new structures, maintaining compatibility during the transition. Only after all services are compatible with the new schema should the old schema be removed:
    • Expand : Add new fields or tables for the refactored data
    • Contract : Update services to use the new schema, then deprecate the old fields/tables
  • Versioned migrations for incremental updates : Database version control tools such as Flyway or Liquibase can manage schema changes as versioned migrations. Each migration is tested individually, applied incrementally, and rolled back if issues arise. This approach allows for phased updates where schema changes are compatible across versions until full deployment.
  • Data duplication for a seamless transition : During refactoring, use data duplication to ensure data availability across services. For example, duplicate stock data in SalesOrder and Warehouse to prevent dependencies from causing downtime. Event-based data duplication patterns ensure data consistency without requiring immediate updates in each service.
  • Feature flags for gradual rollout : For complex deployments, use feature flags to control new features that depend on schema changes. By enabling or disabling features per service or environment, you can test schema updates gradually and ensure stable operation across services. This strategy is especially helpful when deploying new data models or migrating to a distributed data source.

Feature flags

A feature flag , or feature toggle , is a powerful software development concept that allows you to enable or disable specific features without deploying new code. Feature flags serve different purposes, and it is essential, as a software architect, to consider these categories when creating and maintaining toggles. While they add flexibility, they also increase complexity, which is why it is wise to limit the number of toggles in your system to keep things manageable. You can use feature flags for the following:

  • Accelerated releases : Safely deploy new features to production and manage risk by hiding unfinished features until they are ready
  • A/B testing : Test new features with a subset of users to gather feedback and assess performance before a full rollout
  • Rollbacks made easy : Quickly disable problematic features without needing to roll back the entire deployment

Generally speaking, feature flags help you develop and deliver features faster, safer, and with more flexibility. By using them, you can focus on building, refactoring, testing, and refining.

  • Deployment pipeline with continuous integration and testing : Automated pipelines ensure that every schema change or deployment passes through CI/CD stages with automated testing. Incorporating database tests, schema migrations, and performance tests in the CI/CD pipeline allows for faster feedback, reducing the risk of deployment errors.

Let’s apply the preceding strategies to deploy changes to the SalesOrder and Warehouse services in a way that ensures continuous availability and smooth transitions:

  1. Blue-green deployment : Set up a blue environment to apply and test schema changes (e.g., duplicating availability data across SalesOrder and Warehouse ). Traffic remains routed to the green environment, which operates with the stable version (once the blue environment is stable for production it becomes the new green).
  2. Expand/contract : Expand the schema by adding new tables to store inventory in the local database of SalesOrder . Update SalesOrder to access this new schema gradually. Once validated, apply the contract step by step, deprecating old fields in Warehouse and re-routing stock-level queries to SalesOrder .
  3. Event-driven data synchronization : Use event-based updates to keep SalesOrder and Warehouse inventory data consistent. An Availability event triggers SalesOrder to update its local stock cache, achieving eventual consistency without high-latency synchronous queries.
  4. Continuous deployment with feature flags : Enable feature flags on SalesOrder to selectively access the new inventory data from its local schema. Feature flags control access to both old and new schemas during testing, allowing a gradual transition.

Testing and deploying a distributed database in a modular architecture requires a thoughtful blend of testing strategies, schema migration patterns, and deployment practices. By ensuring that schema updates are incremental, tested, and reversible, we can achieve a stable deployment pipeline that supports modular service independence without sacrificing data integrity or performance. These practices allow the architecture to evolve flexibly, providing a foundation for future scalability and resilience as services continue to decouple and scale.

Summary

In this chapter, you learned how to refactor your database, exploring fundamental patterns to help achieve this goal. Database refactoring is never an easy task, nor is it one that an architect can tackle alone—it requires collaboration with a database administrator. The primary challenge often lies not in the technical approach, but in overcoming resistance from stakeholders and DBAs who may be reluctant to split the database. However, if your goal is to move toward a microservices architecture, database separation becomes essential.

First, you need to identify which tables in the original database are relevant to each service’s responsibilities. Previous chapters introduced patterns such as bounded contexts and aggregates to help guide this process. Once you’ve defined these responsibilities, you can apply one of the patterns explored throughout our journey in the database world.

Lastly, many legacy systems rely heavily on stored procedures. While efficient, this approach creates tight coupling between applications and the database, making it challenging to test and maintain. As with tables, you can’t simply migrate stored procedures to the code base in one step; instead, you must proceed gradually, testing at each stage.

At the end of this chapter, you have now gained the skills to do the following:

  • Split tables from the original database to the new, service-specific databases
  • Migrate stored procedures into your code base
  • Use incremental, carefully tested steps to ensure data integrity and maintain system behavior

With these skills, you’re now equipped to transition from a monolithic solution to a microservices architecture, where each bounded context or microservice is responsible for its own database.

However, database splitting introduces additional complexity, particularly in managing long and intricate processes. When moving tables and services from a monolithic system to microservices, you may need to implement logic to coordinate processes across distributed systems. Chapter 12 , Orchestrating Complexity , will introduce the saga pattern, a solution for handling these challenges in a microservices environment.

Before that, in the next chapter, we will cover DDD patterns for CI/CD and learn how to harness the power of automation, modularity, and iterative design to deliver high-quality software that serves your domain effectively.