Image

There’s more than one way to build a monolith. So far, you’ve encountered the layered architecture, which aligns things technically . You can go a long way with a layered monolith, but when changes begin to involve lots of communication and coordination between different teams, you might need a little more horsepower under the hood—and perhaps even a different architectural style.

This chapter looks at the modular monolith architectural style, which divides applications up by business concerns as opposed to technical concerns. You’ll learn what this means, what to look out for, and all the trade-offs associated with this style. Let’s take the modular monolith for a spin, shall we?

Image

As a reminder, Naan & Pop’s sandwich shop has a small development team, and its requirements haven’t changed a whole lot since the team built their layered application in Chapter 6 . The competition is stiff, and time to market remains a concern. The system should remain simple.

Note

Be sure to review Chapter 6 if you need to refresh your memory.

Exercise

Image

Cast your mind back to the layered architecture we built for Naan & Pop in Chapter 6 . The following diagram shows its layers and logical components. Adding a new category to the menu (say, pizza) means changing a bunch of moving parts. Grab a marker and put a triangle ( Images ) next to everything this new requirement will affect.

Image

Images Solution in “Exercise Solution”

Cubicle conversation

Image

Alex: Pfft! This is easy . We’ve already delivered a working and extensible system. Let’s get to it.

Mara: Hold your horses. This might be our first rodeo with such a change, but I doubt it’ll be our last.

Sam: So what? We’ve built an extensible system. Why are you being so reticent?

Mara: Let’s think this through—we have to add pizzas to the menu. Not only will we have to add new recipes and ingredients, but we’ll also need to allow patrons to order pizzas online. So where will we have to make changes?

Sam : Lots of places! It’ll at least affect ordering and recipe management. I still don’t see a concern.

Alex: I think I do. We’ve built a layered architecture, and we have specialists working on each layer. A change like this means coordinating changes across all of those folks.

Mara: Bingo! The layered architecture smears the domain across all the layers. So, implementing anything that changes the domain can be arduous.

Alex: You’re telling me that choosing the layered architecture was a mistake?

Mara: The layered architecture was simple and quick to build. It allowed us to launch quickly. But now we need to think about maturing the architecture to support modularity, so changes like these will be easier in the future.

Alex: So where do we start?

Mara: Allow me to introduce you to the modular monolith. Rather than partitioning by technical concern, we’ll partition by business domain , using modules—hence the word modular . I’ll show you what this looks like as I explain it.

Sam: Ooh, I’m so excited. Let’s do it!

Modular monolith?

A modular monolithic architecture, like a layered architecture, is deployed as a single unit, usually with its own database.

Note

Think back to Chapter 5 . Architectural styles can be separated by how the code is partitioned and by deployment model.

Image

That’s where the similarity ends. In a modular monolith, rather than partitioning your application by technical concerns, you partition it by functionality . Every business operates within a certain domain—like banking, education, or retail. Online stores usually have several subdomains , like Order Placement, Payment, and Inventory Management. Together, they make up the Online Store domain. You organize your application according to these subdomains, separating them into modules.

Note

Heads up—you’ll find the terms domain and subdomain used interchangeably. As long as you understand that both terms represent business concerns, you’re good.

Image

What is a module ? At a high level, it’s just how you organize your code. In some languages, you might have support like packages or namespaces. But it doesn’t start or stop there.

Partitioning your code using modules has implications for how you’ll go about separating concerns between modules and how modules will interact with each other. We have a lot more to say about this, so stay tuned. For now, we just want you to be able to distinguish between the layered and modular monolith architectural styles.

there are no Dumb Questions

Q: Can you explain more about what you mean when you say module ?

A: A module is a software design element representing an independent unit that fulfills one piece of functionality. Technically, every layer in a layered architecture is a module—these modules just happen to be divided by technical concern.

In a modular monolith, on the other hand, each module represents a particular piece of the domain—that is, a subdomain . Each module contains all the business functionality needed for that particular subdomain.

Who Does What?

Identifying which components should belong to a particular module can be tricky. In this game of “Who Does What?”—or rather, “What Goes Where?”—we’d like you to match each component to the module where it fits best. Multiple components can belong to one module.

Image

Images Solution in “Who Does What? Solution”

Domain ~pains~ changes

Naan & Pop wants to add a new food category (pizza) to the menu. Which parts of the architecture need to change to make this happen? Let’s take a look.

Image

Introducing a new menu category primarily affects the Order domain. The menu needs to allow customers to order pizzas and customize their toppings. That might require changing or adding new business rules to support customization and perhaps delivery, since pizzas need to be delivered hot. It could also change how the system stores orders (since customers may ask for customizations.)

As you can see, introducing new menu items can affect multiple components across multiple layers. This is because, as mentioned in the previous chapter, in a technically partitioned architecture the business domain gets “smeared” across multiple layers. This is great if you’re implementing a technical change, like changing the view technology or swapping out the database. But it’s not so great if the change affects the domain—you’ll have to round up folks from multiple teams to figure out how to implement it.

Note

No one ever woke up and said, “How can I add yet another meeting to my calendar?”

This is where modular monoliths can really help.

Geek Note

Image

It’s not unusual for teams to start with a layered architecture, then refactor it into a modular monolith over time as the application grows.

Why modular monoliths?

When you eat a burger (or a veggie burger!), do you take a bite of the top bun first, then bite into the gooey cheese, then take a bite of the patty? Or do you take one bite that slices vertically through every layer of the burger? The latter, right?

Note

Every layer in a burger serves a specific purpose—so it tastes best if you bite through all the layers together.

Note

Yum!

That’s exactly how you can think of a modular monolith. You don’t organize the application in horizontal layers separated by technical concern, but in vertical slices scoped by business concern. Each vertical slice aligns with a piece of the domain and is encapsulated in a module. Every module contains a set of business functions—for example, order placement, order completion, and order delivery would all be part of the Order Placement module.

Image

What does this mean? Changes to the domain that affect many or all layers require lots of coordination between different teams. You’ll need to ensure that everybody’s changes work with everybody else’s.

Now, rather than having teams that specialize in the presentation layer or the persistence layer, you have cross-functional teams , each specializing in a domain . The result? It’s far easier to coordinate domain changes when one team takes full ownership.

Note

This isn’t business-word bingo! It’s not always easy to build out cross-functional teams that work in multiple different technical stacks.

Image

How astute of you! You’re absolutely right that each module here still consists of layers—but they don’t have to. The important thing is that your application is organized by domain.

Your system still needs to process and respond to each request, though. So you’ll need an entry point (presentation layer), some business processing (workflow layer), and maybe a data store to write to (persistence layer). Even within a modular architecture, it makes sense to separate those responsibilities, much like the layered architecture does.

However, if you zoom out and look at the whole architecture, you’ll see that the application is carved up into subdomains. The fact that each module is composed of a bunch of technically partioned layers becomes an implementation detail, as opposed to an architectural concern. In other words, how a module is laid out internally isn’t how the architecture is partitioned . Modular monoliths are domain-partitioned.

Let’s get a bit more concrete by seeing what this looks like in code.

Show me the code!

You’ve probably recognized that modular monoliths solve the problem you are working on differently from a layered architecture, by organizing applications by domain rather than technical concern. But how does this translate to your code?

Let’s first talk about the modules themselves. They represent parts of the domain. Naan & Pop’s namespaces look like this:

Image

Remember, we’re still working with a monolith—that is, it’s still one deployment. Typically, one deployment would translate to one codebase, with the code organized in different namespaces. Each namespace represents a separate module, like so:

Image

Image

Exercise

Image

A critical piece of successfully developing modular monoliths is understanding the domain well enough that you can break it into individual modules. One way to do that (and there are many) is to really listen to your business experts.

Say you are working for a startup that’s creating an expense-tracking app for small to medium-sized businesses. Here are the business requirements:

  • There are users and auditors. Users add expenses, and auditors review expense reports to ensure they align with policy guidelines.

  • When a user adds an expense, it is recorded in the database for that user.

  • The app creates an audit trail that the auditors can use to ensure that everything is in order.

    Can you identify the subdomains that should make up this application? Hint: Not everything your business users say will translate into a module.

Images Solution in “Exercise Solution”

Cubicle conversation, continued...

Image

Alex: I get it. We’re increasing the modularity of the codebase because our application is divided up by modules.

Sam: That sounds great in theory, but it’s not like they can all work independently of each other. Doesn’t the ordering side of things need to know what ingredients we have in our inventory? God forbid the kitchen should run out of mushrooms!

Mara: You’re both right. Splitting the application up by business concern means we’re increasing its modularity. But on the flip side, different parts of the application might also need to talk to each other.

Alex: But it’s one codebase. I can just have the ordering side make an API call to the inventory module, right?

Sam: Oh, brilliant. I can already see the big ball of mud forming! Soon every module will be talking to every other module, and then there goes our modularity.

Mara: Right. If you just start making calls between modules willy-nilly, soon enough there won’t be any boundaries left. Everything will just start referencing everything else. And that would be, well, a big ball of mud.

Alex: So how do we maintain separate modules, but still have them talk to one another?

Mara: Let me show you.

Keeping modules modular

Modular monoliths are, well, monoliths, so they’re generally contained in one codebase. That makes it easy for someone working in one module to inadvertently reach into another module and end up coupling the two modules together.

Note

The auto-import feature in your IDE is not your friend here! It’s way too easy to accidentally reference another module without realizing it.

Image

The philosophy of the modular monolith centers on partitioning by domain within a monolithic deployment model . Your objective should be to create loosely coupled modules so that changing one doesn’t affect others. So how do you avoid the big ball of mud? Read on.

Note

You got it! Callback to Chapter 5 .

Brain Power

Image

Can you think of any mechanisms to help you ensure that one part of your application won’t accidentally access another? For example, does your favorite programming language provide any support at compile time to keep modules separate? Jot down any ideas that come to mind here. You can see some of our ideas at the end of the chapter.

Images Solution in “Exercise Solution”

From a code design perspective, it’s best to think of each module as a separate service . Just to be clear, though, they aren’t really separate—they all still constitute one monolithic deployment. Each “service” exposes a public API while shielding its internal implementation from the other modules.

Image

As long as modules only talk to one another through their public APIs, you can safely change one module without affecting others—thereby reducing their coupling.

Of course, this sounds like a great idea in theory . But how can you maintain module boundaries so well that you can sleep peacefully at night? Let’s look at a few possibilities.

there are no Dumb Questions

Q: Dividing my application into modules sure seems like a lot of trouble. Are modular monoliths really the better option?

A: We’ve said this before, and we’ll say it again—we don’t like words like better . It’s always about trade-offs. So far, we’ve tried to highlight some of the benefits of modular monoliths (and we aren’t done yet), while also pointing out some of the challenges.

Do modular monoliths require more thought and discipline, and maybe even more tooling (as we’ll see in a minute)? Absolutely.

But the trade-off is a much more modular architecture that allows cross-functional teams to work independently and thus move faster.

Keeping modules modular (last time!)

Keeping your modules modular isn’t as easy as it seems, but don’t lose hope just yet. You have options, depending on your technical stack—especially if you apply some creative thinking and elbow grease.

Image

Some languages, like Java, have built-in support to build modules. The Java Platform Module System (JPMS) allows you to build modules that are isolated from one another. The .NET platform, meanwhile, offers namespaces that use the internal keyword for this purpose.

Image

Another approach is to break up your project code so that each module is a separate folder in your repository. These subprojects (or, as many build systems call them, multimodule projects ) force isolation by virtue of being different projects. You might even consider creating different repositories to contain individual modules, then stitching the complete application together at build time.

Note

Gradle, the Java build tool, supports subprojects.

Of course, you are still deploying a monolith, so you’ll probably need to bring all the modules together using your build tool of choice. A monolithic deployment model doesn’t have to mean a monolithic codebase!

Image

Architectural governance tools, like ArchUnit for Java projects and ArchUnitNET for the .NET platform, can help maintain module boundaries as a project grows.

Note

Check out ts-arch for TypeScript and JavaScript projects!

And none of these options needs to stand alone: you can use one or more together.

there are no Dumb Questions

Q: Am I way off base here, or could these techniques be useful even for layered architectures?

A: Give us a moment to wipe away the tears—you’ve grown up so fast! Absolutely; they can be useful whether your project is partitioned technically or by domain. It’s a great idea to use tools (like ArchUnit) and language features (like JPMS) to enforce module boundaries, regardless of architectural style.

Image

That would be the logical end of modularization, wouldn’t it? Modularizing the code may not be enough. If all your data is still intertwined, then you’ve just moved your ball of mud into the database!

Before we go further, a caveat: most developers are not used to thinking vertically along business concern lines or breaking up their code into separate modules. Extending that modularity all the way to the database sounds like a great idea— it is —but it may be too much to take on all at once. Feel free to evolve your architecture over time when needed, rather than trying to get it all right the first time around.

Put all the lessons you’ve learned in this book at work. Do your architectural characteristics push you to pick the modular monolith architecture? If so, start by modularizing your code first. Once your team gets the hang of thinking modularly, then see if it helps to take that approach all the way into the database.

Next, let’s see what modularizing your database might look like.

Taking modularity all the way to the database

The modular monolith is still a monolithic deployment, typically with a monolithic database backing it. There is a lot of power here: having a single database can make things a lot simpler. You don’t have to worry about transactions or eventual consistency, and most developers are very comfortable working with just one database. However, if you intend to maintain modularity at all levels, then you should consider modularizing your data.

The rule is simple: every module should access only its own tables. Here’s how you’d accomplish this for Naan & Pop:

Image

For every module in your application, you define a schema and a set of tables. Any and all data that belongs to a particular module will reside only in the tables for that module.

As you can see, you can extend modularity all the way to the database by separating data that belongs to different modules into different tables (and maybe even different schemas).

Brain Power

Image

Take a few moments and think about the implications of modularizing your database. What pros and cons can you think of?

Sharpen your pencil

Image

Take a look at the following table names and see if you can identify which tables belong to the schemas we’ve identified for the Naan & Pop database. Draw an arrow from each table to its schema.

Image

Images Solution in “Sharpen your pencil Solution”

Beware of joins

Keeping different tables, perhaps even in different schemas, does partition the data belonging to different modules—but it’s easy to slip up and accidentally perform a SQL join across tables that belong to different modules. Then you’re back to tight coupling!

It’s OK to store the IDs of records that belong to one module in another module’s tables. For example, the Naan & Pop Order domain is allowed to store “recipe item” IDs in its tables within the order_schema. If it ever needs more information about a particular item, it calls the Recipe module’s API and provides it with the recipe item’s ID.

Note

Read that again! This is not a foreign key reference.

Image

And there you have it. Now, as we’ve done before, we’ll show you some of the strengths and weaknesses of modular monoliths, followed by our star rating chart.

Modular monolith superpowers

Here are some good reasons to use modular monoliths:

Image

Image

Domain partitioning

Architects can design components around domain concerns, then build teams that specialize in one or more of these domains (as opposed to a technical specialization). Domain partitioning is the key superpower of this architectural style.

Domain-based alignment

Modular monoliths encourage crossfunctional teams, which are better aligned with the domain than the technically partitioned teams used in layered architectures.

Image

Performance

Performance is usually very good, like for most monolithic architectures. There are no network calls between modules, and all data processing happens in a single place.

Maintainability

Modular monoliths separate business concerns from one another, with crossfunctional teams each specializing in a subdomain. This makes it easier to maintain the code, as long as changes don’t cross into other domains.

Testability

Since the scope of changes is limited to one module, testing is much easier. And since a cross-functional team’s members understand their subdomain really well, they can build out an entire testing suite, including integration, smoke, and end-to-end tests.

Image

Modular monolith kryptonite

Of course, there are always trade-offs. Here are some reasons not to use a modular monolith architecture:

Image

Hard to reuse

Modular organization makes it hard to reuse logic and utilities across modules. For example, you can’t share common functionality between modules without extracting it as a dependency, increasing the coupling between the modules.

Image

(Still) a single set of architectural characteristics

Even though modular monoliths are organized by modules, you still get a single set of architectural characteristics for the entire application—even if one business concern has a different set of needs than others.

Image

Modularity can be fragile

It’s easy to dilute module boundaries accidentally. Avoiding the big ball of mud takes a lot of governance—and the database is even harder to govern.

Note

It’s particularly hard to avoid joins in SQL via tooling.

Operational characteristics

Despite its focus on business concerns, a modular monolith is still, well, a monolith. And as with any monolith, operational characteristics like elasticity and fault tolerance tend to be hard to attain.

Image

Modular monolith star ratings

We’ve created a star rating chart for modular monoliths, just like the one we showed you for layered architectures in the previous chapter. One star means that the architectural characteristic is not well supported; five stars means it’s very well supported.

Note

Just like movie reviews.

Image

You’ll notice that our ratings for modular monoliths’ operational characteristics aren’t all that different from those for layered architectures. From a process perspective (that is, in terms of maintainability, testability, and deployability), however, the modular monolith does a lot better than the layered architecture. That’s because changes to a particular module only affect that module and can be tested in isolation, which reduces the risks involved in deploying software.

Modular monoliths cost a little more than layered architectures because they require the team to be vigilant. They also involve additional governance and tooling to maintain module boundaries.

Exercise

Image

Which of the following systems might be well suited for the modular monolith architectural style, and why? Hint: Take into account its superpowers, its kryptonite, and the problem domain.

Image

Images Solution in “Exercise Solution”

Naan & Pop is delivering pizza!

The development team has finally grokked modular monoliths! With a modular codebase and a modular database, they now feel ready for any other big changes to Naan & Pop’s menu. Rumor has it that the owners plan to introduce a full Mediterranean menu next. We can’t wait, and we wish them a lot of luck!

Image

Bullet Points

  • A modular monolith is a monolithic architectural style that is partitioned by domains and subdomains that reflect business concerns, not technical concerns.

  • Each subdomain makes up one module of the application. Each module can contain multiple business use cases.

  • Each module can be made up of layers to provide better organization. A module may be technically partitioned as a means to organize its functionality.

  • Avoid having code in one module directly access any functionality in other modules. Allowing this can reduce or eliminate the boundaries between modules.

  • Each module should have a public API that communicates with other modules while shielding the module’s internal implementation from the rest of the world.

  • Avoiding intermodule communication allows modules to change internally without affecting other modules.

  • It takes time and effort to ensure that the modules in a modular monolith remain separate and distinct.

  • You can govern a modular monolith using a variety of techniques. Some languages have built-in support for building modules.

  • Another approach is to physically break up the codebase into separate subprojects or even different repositories. This usually involves using a build tool to bring all the modules back together when you build the monolith.

  • Third-party tools can also help with architectural governance.

  • You may choose to use several techniques in combination to ensure the boundaries of individual modules are maintained.

  • You can extend modularity all the way to the database, keeping the data for each module separate.

  • Watch that you don’t accidentally couple modules when inserting or fetching data (for example, when using a SQL join statement across tables that belong to different modules).

Modular Monolith Crossword

Image

Modular monoliths are about separating business concerns. Take a look at these separate clues and test your knowledge about this architectural style.

Image

Across

1. Java _____ Module System

6. _____ to one module don’t require _____ to the others

8. The Recipes _____ interface is part of the Recipes domain

9. Each module exposes a public _____

10. Modular monoliths are good when many teams need to _____ their work

13. Monoliths generally have one big _____base

15. Highly rated characteristic in most monolithic architectures

18. Each domain in this style represents a _____ concern

19. With a modular monolith, _____ are often cross-functional

20. Smaller bits of functionality can reside in their own _____ domains

21. It’s important to maintain _____ between modules

22. Style of monolithic architecture first used in this system

23. Databases can show modularity by representing an entity via a _____

Down

1. The latest addition to Naan and Pop’s menu

2. In a domain-partitioned architecture, each domain gets its own _____

3. If something is an implementation _____, it’s not an architectural concern

4. If technical concerns are like horizontal “slices” of a monolith, business concerns are ____ slices

5. “Spaghetti code” is too closely ____

7. This system is for ____ & Pop

11. A challenging kind of architectural characteristic for monoliths

12. Modules use ID references in ____ to look things up

14. Monolithic and distributed are two kinds of deployment ____

16. Example of a language that supports creating modules

17. Modules communicate indirectly, through their ____ APIs

19. Databases build schemas from related ____

Images Solution in “Exercise Solution”

From “Exercise”

Exercise Solution

Image

Cast your mind back to the layered architecture we built for Naan & Pop in Chapter 6 . The following diagram shows its layers and logical components. Adding a new category to the menu (say, pizza) means changing a bunch of moving parts. Grab a marker and put a triangle ( Images ) next to everything this new requirement will affect.

Image

Here’s some space for you to explain your thought process:

Offering pizzas probably means the menu will need a new listing. We might need to allow for customized toppings, which would affect the presentation layer and the associated pricing and could introduce new rules. There might be time constraints on deliveries (no one wants a cold pizza). The customizations might also affect how we persist pizza orders (as opposed to other kinds of orders).

However, the recipe and inventory domains won’t be affected. A recipe is a recipe is a recipe—a list of ingredients with a set of steps to follow. And while there may be new ingredients, the inventory domain will manage them just like it would any other ingredients .

From “there are no Dumb Questions”

Who Does What? Solution

Identifying which components should belong to a particular module can be tricky. In this game of “Who Does What?”—or rather, “What Goes Where?”—we’d like you to match each component to the module where it fits best. Multiple components can belong to one module.

Image

From “Exercise”

Exercise Solution

Image

A critical piece of successfully developing modular monoliths is understanding the domain well enough that you can break it into individual modules. One way to do that (and there are many) is to really listen to your business experts.

Say you are working for a startup that’s creating an expense-tracking app for small to medium-sized businesses. Here are the business requirements:

  • There are users and auditors. Users add expenses, and auditors review expense reports to ensure they align with policy guidelines.

  • When a user adds an expense, it is recorded in the database for that user.

  • The app creates an audit trail that the auditors can use to ensure that everything is in order.

    Can you identify the subdomains that should make up this application? Hint: Not everything your business users say will translate into a module.

    Image

From “Brain Power”

Brain Power

Image

Can you think of any mechanisms to help you ensure that one part of your application won’t accidentally access another? For example, does your favorite programming language provide any support at compile time to keep modules separate? Jot down any ideas that come to mind here.

  • • <insert your favorite programming language> feature

  • • Repository structure

  • • Build tool capabilities

  • • Third-party libraries and governance frameworks

From “Sharpen your pencil”

Sharpen your pencil Solution

Image

Take a look at the following table names and see if you can identify which tables belong to the schemas we’ve identified for the Naan & Pop database. Draw an arrow from each table to its schema.

Image

From “Exercise”

Exercise Solution

Image

Which of the following systems might be well suited for the modular monolith architectural style, and why? Hint: Take into account its superpowers, its kryptonite, and the problem domain.

Image

Modular Monolith Crossword Solution

Image

From “Modular Monolith Crossword”

Image