Modular Monolith: Integration Styles

This post is part of articles series about Modular Monolith architecture:

1. Modular Monolith: A Primer
2. Modular Monolith: Architectural Drivers
3. Modular Monolith: Architecture Enforcement
4. Modular Monolith: Integration Styles (this)

Introduction

No module or application in a larger system works in 100% isolation. In order to deliver business value, individual elements must somehow integrate with each other. Let me write here a quote from the book “Thinking in Systems: A Primer”, where Donella H. Meadows defines the system concept in general:

A system is an interconnected set of elements that is coherently organized in a way that achieves something. If you look at that definition closely for a minute, you can see that a system must consist of three kinds of things: elements, interconnections, and a function or purpose.

The concept of systems integration is defined as follows (wiki):

process of linking together different computing systems and software applications physically or functionally, to act as a coordinated whole.

As you can see from the definitions above, in order to provide a system that fulfills its purpose, we must integrate elements to form a whole. In previous articles in this series, we discussed the attributes of these elements which are, in our terminology, called modules.

In this post, I would just like to discuss the missing part – Integration Styles for modules in Modular Monolith architecture.

Enterprise Integration Patterns book

The title of this post is not accidental. It sounds exactly like Chapter 2 of Gregor Hohpe and Bobby Wolf great book Enterprise Integration Patterns. This book is considered a bible of information about systems integration and messaging. This article takes some knowledge from this chapter and relates it to the monolithic and modular architecture.

In any case, everyone interested in the topic of integration, I invite you to read the book or materials that are available online at https://www.enterpriseintegrationpatterns.com/ site.

Integration Styles

Integration Criteria

Like everything in nature, each Integration Style has its pros and cons. Therefore, we must define criteria on the basis of which we will compare all styles. Then, based on that criteria, we will decide on the method of integration in the future.

We can distinguish the following criteria: Coupling, Complexity, Data Timeliness.

1. Coupling

Coupling is a measure of the degree to which 2 modules are dependent on each other (wiki):

coupling is the degree of interdependence between software modules; a measure of how closely connected two routines or modules are; the strength of the relationships between modules.

If you’ve read the previous posts in the series, you already know that one of the most important attributes of modular design is independence. Therefore, it will be easy to guess that coupling is one of the more important criteria in terms of integration style.

2. Complexity

The second criterion for evaluating the Integration Style is its level of complexity. Some integration methods are simple – require little work, are easy to understand and use. However, others are more complicated, require more commitment, knowledge, and discipline.

3. Data Timeliness

The last criterion is the length of time between when one module decides to share some data and other modules have that data. This means how soon after a state change in a given module, the rest of the modules concerned will take this change into account. Of course, the shorter this time, the better.

Now that we know all the most important criteria, let’s move on to the ways of integrating our modules. Let’s discuss 4 Integration Styles: File Transfer, Shared Database Data, Direct Call and Messaging.

File Transfer

The first option is to integrate our modules using a regular file. Such a file must be exported from the source module and imported into the target module. This can happen in 3 ways:
– manual, where the user manually imports/exports
– automatic, where files are imported and exported automatically by systems
– hybrid, where the file is imported/exported automatically on one side and vice versa on the other

Modular Monolith Integration Styles - File Transfer
File Transfer

One of the main tasks of this type of integration is to determine the format of a given file. What is important, it is the only dependency that two modules integrating in this way have. You can visualize it as a really huge message that is carried over by the filesystem. For this reason, it can be assumed that the coupling is very low in this case.

As for the level of complexity of this approach, it can be evaluated as an average. On the one hand, generating a file in a specific format is not difficult in these times. On the other hand, uploading to a shared resource, managing files, handling duplicates, and so on is more complicated and time-consuming.

From a timeliness point of view, modules integration via files is slow (not to mention manual export/import). Most often it is performed in larger batches at some time intervals (so-called batches), often at night. For this reason, the delay can be a day, a week or more.

To be honest, I’ve seen file-sharing integration many, many times between systems, and probably never in a monolith – which is rather understandable. This Integration Style I have described for the sake of completeness of this topic. The most popular integration method for monoliths is the Shared Database Data.

Shared Database Data

In the EIP book, this method of integration is called Shared Database, but I believe that it is not quite the right name. Sharing the database does not always have to mean sharing data, because modules can store its data in separate tables (most often it is done through database schemas). Therefore, in my opinion, Shared Database Data is a better term.

Modular Monolith Integration Styles - Shared Data
Integration Style: Shared Data

In Shared Database Data modules share a certain set of data in the database. In this way, the data are always integrated and consistent with each other because, generally speaking, they are the same data. If module A writes data to table X, module B can read the data immediately after the database transaction is completed.

The level of complexity of such a solution is very small. Nowadays every application/module needs a database, so there is no need to add anything extra with this approach.

The solution looks perfect at first glance. However, its biggest disadvantage is a very high coupling. By sharing data, modules share their state which couples them together. The high coupling means no autonomy for the module. In addition, one little change to database structure or even data itself can break another module without notice. It implies that each change to the database must be consulted and coordinated. This way database becomes bottle-neck of changes. The whole solution is not evolutionary anymore.

The shared state has another significant disadvantage – it is very hard or even impossible to create one, unified data model which will ensure that the requirements of all modules are met. The attempt to unify most often ends with a very weak, ambiguous model that is difficult to understand, develop and maintain.

To reduce coupling while still maintaining the same level of data timeliness we can use Direct Call.

Direct Call

The third option is to directly call the method of the module we’re integrating with. In this case, we use the encapsulation mechanism. The module exposes only what is needed. The whole behavior is closed in a method. In this way, the state of our module is not exposed to the outside as it is in the case of the Shared Database Data approach. Thanks to this, the caller is not able to break anything from the outside.

Modular Monolith Integration Styles - Direct Call
Integration Styles – Direct Call

Not sharing the data implies that each module has its own data set. It can be the same database broken down by schemas or each module can have even a separate database created in different technology. In a scenario with one database, it is important to keep the data really in isolation. It means no constrains between tables from separate modules and no transactions between them.

Both the caller and the callee should treat each other as external. Both modules will use a different language and have different concepts modeled. Therefore, the Anti-Corruption Layer (ACL) should be applied. On the caller side, it could just be a gateway, on the callee side a facade. Thanks to this, modules encapsulation are kept.

In the case of a distributed system, the Direct Call is known as Remote Procedure Invocation/Call (RPI/RPC). Unfortunately, this technique is very often used in Microservice architecture and can lead to the so-called Distributed Monolith anti-pattern architecture. As the call is always synchronous, we are dealing with temporal coupling. Both caller and calle must be available in the same time. In the case of a monolith, it is not a problem because this is its nature, in the case of microservices it is much worse – it reduces architecture quality attributes like autonomous development and deployment. Read other article in this series about architectural drivers for more details.

The Direct Call Integration Style seems to be a very good choice when it comes to integrating our modules, but has some drawbacks too. First, the call is synchronous, so the caller has to wait for the result. Second, the calling module needs to know about the module it is calling, it has to have a direct dependency. Moreover, it has to know the intent of what it wants to do. Coupling is lower than in Shared Database Data, but still exists. If we want to avoid these drawbacks, we can use the last integration style: Messaging

Messaging

The File Transfer integration style has a great advantage – it does not create dependencies between modules. However, it has a big drawback – the data timeliness in most cases is unacceptable. Messaging does not have this disadvantage. The data timeliness is not so good as in the case of Direct Call because it is asynchronous communication, but it can be safely said that it is very good and acceptable in most cases.

Modular Monolith Integration Styles - Messaging - in memory
Integration Styles – Messaging (in memory)
Modular Monolith Integration Styles - Messaging - separate process
Integration Styles – Messaging (separate process)

Appropriate use of Messaging for the implementation of Event-Driven Architecture causes no dependency between modules. Modules integrate through events. However, these are not Domain Events because a domain event is local and should be encapsulated in a given Bounded Context. Integration Events contain only as much as needed to avoid the so-called Fat Events. Integration Events should be as small as possible, as they are part of the contract made available by the given module. As you know, the smaller the contract, the more stable it is -> the less frequently other modules have to change.

In addition, asynchronous processing, that causes Eventual Consistency, on the other hand supports performance advantages, scales better and it is more reliable.

What are the disadvantages of Messaging? First, due to the nature of asynchronicity, the state of our entire system can be eventually consistent as described above. That is why it is so important to have the boundaries of the modules well defined. This is almost as important as in Microservices architecture, but the advantage of the Modular Monolith architecture is that it is much easier to change these boundaries.

The second disadvantage of Messaging is that it is more complex. To provide asynchronous processing and Event-Driven Architecture, we’re going to need some sort of Event Bus. It can be an in-memory broker or a separate component (eg RabbitMQ). In addition, we will also need job processing mechanisms for internal processing – outbox, inbox, internal commands messages. There is need to write some of this infrastructure code. Fortunately, this is a generic problem – we do it only once and there are a lot of libraries and frameworks which support this.

Comparison

Below I present a comparison of all 3 Integration Styles taking into account 3 criteria – Coupling, Data Timeliness and Complexity.

Comparison - Coupling vs Complexity
Comparison – Coupling vs Complexity
Comparison - Coupling vs Data Timeliness
Comparison – Coupling vs Data Timeliness

What can we deduce from these diagrams? First of all, there is no one perfect style. Fortunately, we can see some heuristics:

1. If the system is very, very simple (essential complexity is low) and you do not care about modularity: choose simplicity and use Shared Database Data style.
2. If the system is complex (essential complexity is high) you must care about modularity. Options are:
– choose Messaging if you prefer highest level of autonomy and eventual consistency between modules is acceptable
– choose Messaging if you care a lot about performance, reliability, scalability
– choose Direct Call if you must have strong consistency, don’t need maximum level of modules autonomy or Data Timeliness is the primary factor.

Additionally, you can mix different styles. Most often, when we are talking about modular architecture, it is best to use Direct Call and Messaging together. Some modules can communicate synchronously and some asynchronously, depending on the need.

Summary

As I mentioned at the beginning, no module, component, or system lives in complete isolation. We must follow the “Divide and Conquer” principle so we divide our solution into smaller parts, but finally – we have to integrate these parts together to create a system.

Let’s summarize all 4 styles again:

File transfer – provides low coupling but has almost always unacceptable data timeliness so it is impractical in the monolith
Shared Database Data – the simplest, quick, but couples modules together
Direct Call – provides lower coupling than Shared Database Data, encapsulates modules, relatively simple
Messaging – ensures the lowest coupling, modularity, autonomy but at the cost of complexity

Which Integration Style to choose? Everything, as usual, “it depends”. However, I hope that I managed to at least to some extent explain what it depends on. No silver bullet, again.

Related Posts

1. Modular Monolith: A Primer
2. Modular Monolith: Architectural Drivers
3. Modular Monolith: Architecture Enforcement
4. How to publish and handle Domain Events
5. Handling Domain Events: Missing Part
6. Processing multiple aggregates – transactional vs eventual consistency

The Outbox Pattern

Introduction

Sometimes, when processing a business operation, you need to communicate with an external component in the Fire-and-forget mode. That component can be, for example:
– external service
– message bus
– mail server
– same database but different database transaction
– another database

Examples of this type of integration with external components:
– sending an e-mail message after placing an order
– sending an event about new client registration to the messaging system
– processing another DDD Aggregate in different database transaction – for example after placing an order to decrease number of products in stock

The question that arises is whether we are able to guarantee the atomicity of our business operation from a technical point of view? Unfortunately, not always, or even if we can (using 2PC protocol), this is a limitation of our system from the point of latency, throughput, scalability and availability. For details about these limitations, I invite you to read the article titled It’s Time to Move on from Two Phase Commit.

The problem I am writing about is presented below:

After execution of line 24 transaction is committed. In line 28 we want to send an event to event bus, but unfortunately 2 bad things can happen:
– our system can crash just after transaction commit and before sending the event
– event bus can be unavailable at this moment so the event cannot be sent

Outbox pattern

If we cannot provide atomicity or we don’t want to do that for the reasons mentioned above, what could we do to increase the reliability of our system? We should implement the Outbox Pattern.

Outbox pattern

The Outbox Pattern is based on Guaranteed Delivery pattern and looks as follows:

Outbox pattern

When you save data as part of one transaction, you also save messages that you later want to process as part of the same transaction. The list of messages to be processed is called an Outbox, just like in e-mail clients.

The second element of the puzzle is a separate process that periodically checks the contents of the Outbox and processes the messages. After processing each message, the message should be marked as processed to avoid resending. However, it is possible that we will not be able to mark the message as processed due to communication error with Outbox:

Outbox messages processing

In this case when connection with Outbox is recovered, the same message will be sent again. What all this means to us? Outbox Pattern gives At-Least-Once delivery. We can be sure that message will be sent once, but can be sent multiple times too! That’s why another name for this approach is Once-Or-More delivery. We should remember this and try to design receivers of our messages as Idempotents, which means:

In Messaging this concepts translates into a message that has the same effect whether it is received once or multiple times. This means that a message can safely be resent without causing any problems even if the receiver receives duplicates of the same message.

Ok, Enough theory, let’s see how we can implement this pattern in .NET world.

Implementation

Outbox message

At the beginning, we need to define the structure of our OutboxMessage:

What is important, the OutboxMessage class is part of the Infrastructure and not the Domain Model! Try to talk with business about Outbox, they will think about the outlook application instead of the messaging pattern. πŸ™‚ I didn’t include ProcessedDate property because this class is only needed to save message as part of transaction so this property always will be NULL in this context.

Saving the message

For sure I do not want to program writing messages to the Outbox every time in each Command Handler, it is against DRY principle. For this reason, the Notification Object described in the post about publishing Domain Events can be used. Following solution is based on linked article with little modification – instead of processing the notifications immediately, it serializes them and writes them to the database.

As a reminder, all Domain Events resulting from an action are processed as part of the same transaction. If the Domain Event should be processed outside of the ongoing transaction, you should define a Notification Object for it. This is the object which should be written to the Outbox. The code looks like:

Example of Domain Event:

And Notification Object:

First thing to note is Json.NET library usage. Second thing to note are 2 constructors of CustomerRegisteredNotification class. First of them is for creating notification based on Domain Event. Second of them is to deserialize message from JSON string which is presented in following section regarding processing.

Processing the message

The processing of Outbox messages should take place in a separate process. However, instead of a separate process, we can also use the same process but another thread depending on the needs. Solution which is presented below can be used in both cases.

At the beginning, we need to use a scheduler that will periodically run Outbox processing. I do not want to create the scheduler myself (it is known and solved problem) so I will use one the mature solution in .NET – Quartz.NET. Configuration of Quartz scheduler is very simple:

Firstly, scheduler is created using factory. Then, new instance of IoC container for resolving dependencies is created. The last thing to do is to configure our job execution schedule. In case above it will be executed every 15 seconds but its configuration really depends on how many messages you will have in your system.

This is how ProcessOutboxJob looks like:

The most important parts are:
Line 1 – [DisallowConcurrentExecution] attribute means that scheduler will not start new instance of job if other instance of that job is running. This is important because we don’t want process Outbox concurrently.
Line 25 – Get all messages to process
Line 30 – Deserialize message to Notification Object
Line 32 – Processing the Notification Object (for example sending event to bus)
Line 38 – Set message as processed

As I wrote earlier, if there is an error between processing the message (line 32) and setting it as processed (line 38), job in the next iteration will want to process it again.

Notification handler template looks like this:

Finally, this is view of our Outbox:

Outbox view

Summary

In this post I described what are the problems with ensuring the atomicity of the transaction during business operation processing. I’ve raised the topic of 2PC protocol and motivation to not use it. I presented what the Outbox Pattern is and how we can implement it. Thanks to this, our system can be really more reliable.

Source code

If you would like to see full, working example – check my GitHub repository.

Additional Resources

Refactoring Towards Resilience: Evaluating Coupling – Jimmy Bogard
Asynchronous message-based communication – Microsoft

Related posts

Domain Model Encapsulation and PI with Entity Framework 2.2
Simple CQRS implementation with raw SQL and DDD
How to publish and handle Domain Events