Foundation Architecture
It seems that every book that discusses software architecture in any way attempts to define software architecture. Some examples from other sources follow.
The software architecture of a program or computing system is the structure or structures of the system, which comprise software elements, the externally visible properties of those elements, and the relations among them. [ Software Architecture in Practice ]
The fundamental organization of a system embodied in its components, their relationships to each other, and to the environment, and the principles guiding its design and evolution. [ ISO 47010 ]
All architecture is design, but not all design is architecture. Architecture represents the significant design decisions that shape the form and function of a system, where significant is measured by the cost of change. Every software-intensive system has an architecture: some are intentional; a few are accidental; most are emergent. All meaningful architecture springs from a living, vibrant process of deliberation, design, and decision.
—Grady Booch
Okay, these are good. There are probably some ideas that are implied, but not explicitly stated. Maybe another attempt is worthwhile. The following is the authors’ attempt to freshen the older definitions. This one reflects what this book discusses, and has been used for several years.
There are at least three major sets of statements that help define software architecture. (1) Architecture is the result of team communication that leads to a shared understanding of business goals, how to balance the goals of various stakeholders, and how to understand and address the quality attributes–related impactful features; that is, there cannot be effective architecture without a purpose, and purpose cannot be well understood without socializing intent through communication. (2) The architectural intent is captured and articulated as a set of current and future decisions for the whole system and individual services by specifying purposeful flexibility and constraints that support the software’s initial and ongoing development. (3) The architectural intent and decisions are spoken, rendered into visual form—graphical and/or textual—and expressed in software artifacts that have modular structure and well-defined component-to-component protocols.
Note that there’s a lot of communication going on within all three parts of this definition, and it seems to be communication that is lacking in the more traditional definitions. Sound architecture cannot be developed in a vacuum. No part of the definition suggests specific tooling or formats, which should be chosen by the teams involved. That’s all part of socializing the software’s intent through communication, and the best way to capture and articulate that intent should be determined by those who create it. Accepting feedback is an invaluable skill to be developed.
The authors also recommend reading another book in the Vaughn Vernon Signature Series—namely, Continuous Architecture in Practice by Murat Erder, Pierre Pureur, and Eoin Woods. It provides in-depth advice on how to apply a continuous approach to software architecture and contains in-depth guidance for addressing key quality attributes and cross-cutting concerns, such as security, performance, scalability, resilience, data, and emerging technologies, all illustrated using a start-to-finish case study [ Continuous-Architecture ].
It’s not uncommon for software architecture to be thrown under the bus, dismissed as some sort of formal and useless rite of common programmers seeking a higher pay grade. There are indeed overengineered architectures, but those come from the immature. Here’s the point:
If you think that good architecture is expensive, try bad architecture.
—Brian Foote [ BBoM ]
You can pay for architecture now, or you can pay for it later. The authors suggest now would be best. All the same, there is no need for good architecture to be expensive. This chapter backs up that claim and throws overengineered architectures under the bus.
We’ll consider a number of architectural styles and architecture patterns that specifically support events-first systems. This is where the understanding gained from previous chapters that feature business drivers now point toward making wise decisions based on how the overall software architecture will support the business goals. There is clearly a danger of selecting among a broad collection of arbitrary architectural choices just because they seem useful, or even cool, as if a potpourri of architecture decisions will automatically produce benefits. Again, the purpose of architecture decisions is to achieve the quality attribute requirements, such as flexibility, security, performance, and scalability. Without those requirements, architecture decisions are meaningless and often harmful. Deep details are out of scope for the book, but are provided in our follow-on implementation book, Implementing Strategic Monoliths and Microservices (Vernon & Jaskuła, Addison-Wesley, forthcoming).
Next up on our agenda are a selection of modern architecture options, each of which is described in terms of its overall definition, but also qualified according to its strengths and weaknesses. As with everything involved in software development, the architectural decisions made by teams will tend to have both positive and negative consequences.
Architectural Styles, Patterns, and Decision Drivers
To reiterate, not every architecture style and pattern will suit any set of arbitrary business, technical, scale, performance, or throughput constraints. The specific set of constraints will drive a purposeful architecture. Likewise, not every Bounded Context is equally important in terms of business strategic goals, which has an important influence on architectural decisions.
The architectures discussed here include those at both the system level and the service/application level. A system-level architecture defines how various subsystems work together to address the quality attributes related to shared impactful features, including software collaboration and integration. A service/application architecture defines how a single subsystem (service/application) addresses the quality attributes related to its own impactful features.
Chapter 2 , “ Essential Strategic Learning Tools ,” discussed Architecture Decision Records (ADRs) as a means to determine the business and technical drivers around each decision made regarding software architecture. ADRs are used by teams to help explain why various styles and patterns are helpful, but they also highlight the potential negative consequences of applying those choices in a given solution.
Ports and Adapters (Hexagonal)
One of the most versatile architecture styles is Ports and Adapters, also known as Hexagonal. This style inherits concepts from the traditional Layers architecture [ POSA1 ], but it emphasizes different strengths and has much less overhead. Some of the highlighted strengths are based on contemporary software drivers, such as tests and loose coupling.
Allow an application to equally be driven by users, programs, automated tests, or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases. [ PortsAdapters ]
Sometimes problems are encountered due to the fundamental differences between the external devices and other mechanisms used to interact with a software service or application. These mechanisms might be a browser, a mobile phone or tablet, another service or application, a streaming or messaging mechanism, batch processing, tests, or other computing resources. The service or application should not be exposed directly to the interactions with the outside world because that will interfere with the technology-independent business logic and processing.
To sidestep the potential problems of coupling the service or application to various kinds of input–output devices and mechanisms, create a layer of adapters between the two sets of concerns. As Figure 8.1 illustrates, the Ports and Adapters architecture style defines such a separation by considering one part of the architecture as the outside and the other as the inside. On the outside left are a number of driver types, also called primary actors : HTTP, externally called procedures or functions, and flowing streams or messages. On the outside right are a number of driven types, also called secondary actors : payment gateways, databases, procedure or function outward calls, and flowing streams of messages. The locations of the ports are shown by the bold border around the inside circular Application area.
Figure 8.1 Ports and Adapters architecture, also known as Hexagonal, Clean, and Onion. 1
- Some consider Onion architecture to be closer to Layers, which does not distinguish the outside and inside in terms of adapters. Some consider Onion to be synonymous with Layers. Rather than have several thousand people complain about the omission of Onion, it is mentioned here, along with a potential caveat (or at least a specific nuance).
Note
The outside-left driver actors send input requests or notifications. The outside-right driven actors are driven by the application inside to fulfill use cases: Some are bidirectional, providing both requests and responses; others receive one-way notifications. The outside-left adapters are needed to adapt incoming requests or notifications to data types that the Application can consume to carry out its supported use cases. The Application uses adapters on the outside right to persist and query, as well as to deliver notifications. Only the outside left is aware of the existence of use cases on the inside. The outside-right driven actors are oblivious to use cases.
Figure 8.1 does not contain an exhaustive set of incoming and outgoing adapter types. Any given adapter type is not limited to creating a single instance. The adapters shown are those typically used by services and applications. There need not be a single database type or instance, for example, or a single stream source and sink, or one messaging topic. The elements in Figure 8.1 are only representative of the large number of possibilities.
Some of the distinct advantages of Ports and Adapters are as follows:
-
Each of the two main layers can be tested in isolation; that is, any adapter can be tested without the need for a specific application implementation, and the application may be tested without any given adapter implementation.
-
All device adapters can be backed by both mocks/fakes and with actual mechanisms. (This does not mean that the concrete adapters aren’t tested, because they always are. Rather, mocks/fakes are used to test units that are dependent on the adapters.)
-
Each actual mechanism might have multiple types (e.g., Postgres, MariaDB, HSQLDB, AWS DynamoDB, Google Cloud Bigtable, or Azure Cosmos DB).
-
New adapter types can be introduced as needed without big upfront architecture/design; that is, the team can employ an #agile and emergent architectural design.
-
Multiple outside adapters can use the same inside Application layer facilities.
-
The application remains completely isolated from the device-level technology details.
There can also be disadvantages, depending on decisions regarding integration with external mechanisms:
-
The use of data mappers, such as object-relational mapping tools, might cause complexity. However, this disadvantage is due to the choice of persistence integration, not because Ports and Adapters itself forces these choices.
-
The domain model can make use of integrations with remote services and applications through an interface. The interface implementation can leak underlying implementation details, such as exceptions and errors caused by network and service failures. This can be avoided by a few means, including those discussed in this chapter and Chapter 9 . For example, using Functional Core with Imperative Shell keeps the domain model entirely isolated from external remote integrations. The Imperative Shell must do all integration work separately and not involve the Functional Core. The Functional Core provides only pure, side-effect-free functions.
-
Other disadvantages may include additional complexity by requiring more layers; creation and maintenance cost; and lack of guidance on organizing code (directories and layers). The authors have not experienced these claims in the least, and wonder if those who cite these so-called problems have read the literature and understand Ports and Adapters at all. Experience has shown us that a basic, well-structured architecture can be constructed in a matter of minutes, with far fewer layers than a typical N -tier application requires. The chosen mechanisms and related adapters can increase the system’s complexity, but those have nothing to do with the architecture style. Such a system would have at least the same complexity without the use of a Ports and Adapters architecture.
The Ports and Adapters architecture isolates the inside Application layer from the details of device input–output. The Application is focused solely on business-driven use cases. Multiple outside-left adapter types may effectively reuse Application ports to perform operations rather than a separate port type being required for every adapter type.
This architectural design can employ the Dependency Inversion Principle [ SOLID ], in which the infrastructure becomes dependent on the Application, rather than the Application being dependent on the infrastructure. The Application can steer clear of concrete device dependencies because any such dependencies on the outside-right secondary actor types are managed through adapter interfaces. The adapter interfaces are provided to the Application by means of its service constructors/initializers or possibly container-based dependency injection.
Adapters should adhere to the Single Responsibility Principle [ SOLID ], meaning that a single adapter should focus on adapting input–output that it is designated to support and no more. No adapter should depend on another adapter.
Some have claimed that Ports and Adapters is an unnecessarily heavyweight style of architecture, but frankly this criticism is both unfounded and unsubstantiated when one considers the facts. As Figure 8.1 illustrates, a Ports and Adapters software architecture includes exactly the number and kinds of adapters needed for a given input and output port—no more, no less. There are also only two primary layers.
Certainly any architecture style and pattern can suffer from overengineering. Don’t expect Ports and Adapters to, on its own, prevent such poorly executed implementations. As Figure 8.2 shows, the nature of the Application inside is quite versatile; that is, the pattern doesn’t define how the Application inside should work. What is more, not even one of the four natures shown is at all complex, although each has its advantages (as described in the sections that follow).
Figure 8.2 Ports and Adapters architecture with varying Application types.
Service Layer with Transaction Scripts
A Service Layer is described as follows:
Defines an application’s boundary and its set of available operations from the perspective of interfacing client layers [i.e., port adapters]. It encapsulates the application’s business logic, controlling transactions and coordinating responses in the implementation of its operations. [Fowler-PEAA]
A Service Layer supplies application-specific services, typically known as Application Services, as depicted in the first two variants, from left to right, in Figure 8.2 . At the top left of this figure is a Service Layer composed of only Application Services. This example uses some form of Transaction Scripts, Active Record, or Data Access Objects [Fowler-PEAA]. These three patterns are used for Create-Read-Update-Delete (CRUD) operations without incurring the overhead of a domain model. They are all useful when the Bounded Context is mainly focused on data collection and performs simple creates and updates, and occasional deletes. There is no business-driven complexity. In terms of Cynefin—as explained in Chapter 2 , in the section “ Using Cynefin to Make Decisions ”—this is clear/obvious/simple. The primary work lies in using the Application Services for writing and reading, with possible encapsulation of data accesses to and from a database, but any such access encapsulation is purposely kept trivial.
Service Layer with Domain Model
In the top-right Service Layer in Figure 8.2 , the Application Services are accompanied by a domain model at the heart of the software below the Application Layer. A domain model is used when (as described in Chapter 7 ) domain 2 complexity needs to be solved in an innovative, core, differentiating business software initiative. In the system depicted in Figure 8.2 , the Application Services are used to manage the use case coordination and database usage, including transactions. 3
-
Here again, domain means a sphere of knowledge.
-
Use cases and transactions may be managed by other means, such as in the adapters, negating the Service Layer. Even so, you should be careful not to place too many responsibilities on adapters.
Domain Model of Actors
The Actor Model is a form of message-driven object model that provides specialized and well-insulated capabilities in a highly concurrent and scalable compute environment, as further described in Chapter 9 , “ Message- and Event-Driven Architectures .” 4 The incoming adapters dispatch directly into the domain model objects. Although there are no Application Services, the domain model might provide actor-based Domain Services.
- This is different from the Service Layer with Domain Model because the underlying actor platform is designed to take this burden off of application developers, rather than to move it elsewhere in the team’s code.
This implementation of Ports and Adapters provides the simplest and most concise rendering of this architecture style, packing tremendous power into a small form factor. 5 An actor, by design, is physically isolated from other actors—which emphasizes even more strongly the sound distinction between business logic and infrastructure concerns.
- Although typically a hardware term, form factor seems appropriate here because individual actors in an Actor Model have been referred to as tiny computers.
Functional Core with Imperative Shell
Functional Core with Imperative Shell bridges the gap between Ports and Adapters and Functional Programming. Although inspired by functional programming principles, Functional Core is readily applicable even with programming paradigms that are not purely functional. For example, the fundamental strengths of functional programming can be achieved with object-oriented programming languages such as Java and C#. The idea behind this approach is to write pure functional code for the domain model, while moving the side effects 6 of imperative code to the surrounding environment, known as the Imperative Shell. The Functional Core is thus predictable, more easily testable, and used where it counts most.
- A side effect is the modification of some state variable value(s) outside its local environment; in other words, the operation has an observable effect besides returning a value (the main effect) to the invoker of the operation. For example, execution of an I/O operation such as a network call or database call is a side effect.
The predictability comes from the fact that a pure function always returns the same result for the same input and never causes observable side effects. Likewise, pure functions are easier to test, because the focus is on meaningful inputs and outputs. There is no need to create mocks or stubs, so no knowledge of unit test internals is needed. Actually, avoiding mocks altogether is one of the goals of Functional Core with Imperative Shell.
Another advantage is that this approach decreases the risk of leaking technical concerns when domain code calls a side-effectful domain service through an interface. For example, error handling can be problematic. Using a REST-over-HTTP endpoint can result in not just expected kinds of errors, such as 404 Resource Not Found , but also unexpected errors, such as network failures. Error-handling logic can be challenging to test and, unless extreme caution is used, can propagate throughout the whole of the domain model. Deep details of this issue are beyond the scope of this book but are provided in the follow-on implementation book.
Ports and Adapters Architecture Nature Comparison
Table 8.1 compares the four natures described here and outlines how they differ in usefulness, complexity, model isolation, evolvability, quality attributes, and testability.
Table 8.1 Comparison of Different Architectural Approaches to Domain Model Implementation and Their Impacts
| Service Layer with Transaction Scripts | Service Layer with Domain Model | Domain Model of Actors | Functional Core with Imperative Shell | |
|---|---|---|---|---|
| Isolated domain model | No; focused on data updates | Yes | Yes | Yes |
| Business complexity | Low; not many or no business rules, mainly data focused | High | High | High |
| Domain model isolation from infrastructure | Low technical overhead, but the domain model is not present, so it involves mainly data access encapsulation. Very close to infrastructure concerns, which pose a risk for long-term maintenance. | Domain model is well isolated from infrastructure but requires constant effort to keep the isolation free of infrastructure concerns. It may require application services for coordination. | Domain model is very well isolated from infrastructure concerns. Isolation is embedded in the underlying Actor Model implementation, which helps to maintain domain models while keeping them free of any infrastructure concerns. | Domain model is very well isolated from infrastructure concerns because it is based on pure functions. This design prevents pure functions from interacting with infrastructure and directly causing side effects, which is guaranteed to keep the domain model isolated. |
| Evolvability | Low. The lack of a domain model makes it difficult to evolve toward more complex business scenarios. | Medium to high. Depends on how the domain model is kept isolated from other infrastructural concerns. | Very high. It is very simple to add business behavior. | Very high. It is very simple to add new business behavior. |
| Scalability, performance, and concurrency | Very low. | Low to high. It may require implementation of technical code around the domain model to keep up with scalability and concurrency requirements. The domain model itself is not geared toward concurrency so the surrounding code has to take care of it. | Very high. The Actor Model implementation guarantees the scalability, performance, and concurrency out of the box. | High. The domain model is based on pure functions, which means it is concurrency enabled. However, the Imperative Shell code may require some tenacity to make it more scalable and performant. |
| Testability | Low. May be difficult based on how infrastructure concerns are managed. | High. Domain model is well isolated, so it is simple to test. | High. Every aspect is testable. | High. The domain model is very simple to test. However, the Imperative Shell is not easily tested except through integration tests. |
Modularization
The importance of modularity has already been established, and we’ve even provided a few examples of it. This section applies an architectural focus to modularization. Figure 8.3 provides an example of a modular Monolith.
Figure 8.3 Monolith container with five Bounded Contexts as modules.
The container itself is not necessarily special in its own right. It’s just a way to deploy a body of executable software. It might be a Docker container, and might even have a Kubernetes Pod around it for a co-located, co-scheduled, and shared runtime context. Yet, the focus in the Monolith container is on the five major modules inside. Each of these modules represents a Bounded Context. As previously noted, a Monolith is a great place to start early in software architecture development, and possibly even a long-term solution.
The fact that the five modules are deployed together in a single container is not an excuse for the Bounded Context modules to be tightly coupled or to have any strong, infiltrating dependencies between them. That is absolutely not acceptable, in the same way that it is unacceptable to have such dependencies between Microservices. The loose coupling between Bounded Contexts can be achieved using Context Maps, like those described in Chapter 6 , “ Mapping, Failing, and Succeeding—Choose Two .” Figure 8.3 indicates the formation of Published Languages among the contexts. Moreover, the related events might be communicated across contexts using an asynchronous messaging mechanism, which is practical even in a Monolithic solution, but a lightweight choice rather than heavyweight component.
Inside each of the five Bounded Context modules are internal modules specific to the respective Ubiquitous Language. Each internal module shown encompasses cohesive model components, with no dependencies on other modules, or perhaps acyclic ones.
Over time, it is observed that two of the major modules, Risk and Rate, have a tendency to change at a pace that is significantly faster than the rate of change for the other three modules; the Risk and Rate modules also changes in ways that are different from each other. As a result of this observation, the teams determine that it would be best to split the Risk and Rate modules off into two independent Microservices. Figure 8.4 shows the outcome. The solution has now become three outer containers, which have a similar or identical nature as the original Monolith container. Possibly each is a Docker container, and each of those might have a respective Kubernetes Pod containing it.
Figure 8.4 A Monolith container and two Microservice containers with five total Bounded Contexts.
The three separate containers have a network in between them, which introduces the challenges associated with distributed systems. Even so, if care was taken early on in the process of creating the original Monolithic architecture, having a messaging mechanism between modularized contexts should have forced each message publisher and subscriber to design around concerns related to nondeterministic latency, unsequenced order, and multiplicity of deliveries. As previously stated, the original introduction of a messaging mechanism for the Monolith could be lightweight, but now this would be replaced with a more robust mechanism. There will likely be some challenges beyond these when a cloud network and other infrastructure are involved, but they should not be major surprises—unlike when networks are perceived as a “free lunch.”
All of the aforementioned rate-of-change and nondeterministic messaging drivers demonstrate that the system architecture serves a purpose, rather than the system becoming the host of an architecture that meets the desires and curiosities of its architects.
REST Request–Response
The REST architecture style and pattern supports requests and responses generated during the exchange of application resources. The exchanges of application state generally use non-native representations (e.g., digital data is rendered in a text-based format). The industry-standard implementation of REST is HTTP, which is not only a network transport protocol but also a protocol for exchanging and modifying information. HTTP even supports application workflows by means of hypermedia, meaning that links to related data are embedded in the resource exchanges. The requests are made using verb-based methods, four of which are considered the bare minimum: POST, GET, PUT, and DELETE. These methods are meant to operate on full entity-based resources.
REST is most often used for client–server communication, such as between a browser and a server. REST is often considered useful only for Create-Read-Update-Delete (CRUD) applications, but it is actually far more versatile. For example, this architecture style can be used to provide integration between Bounded Contexts. This chapter discusses the browser-to-server use case. Chapter 9 focuses on integration between Bounded Contexts.
Although only four methods are considered the minimum, as mentioned earlier and shown in Table 8.2 , the authors promote the use of the fifth verb method, PATCH. This method supports partial updates—which allow for pinpointing the specific changes made to an entity-based resource. With PATCH, the CRUD acronym is extended to CRUUD; there is now a second Update option that is implemented for partial entity changes only.
Table 8.2 Including PATCH for Partial Updates Forms CRUUD Rather Than CRUD
| POST | Create |
|---|---|
| GET | Read |
| PUT | Update |
| PATCH | Update, Partial |
| DELETE | Delete |
In a PUT-based update, the intention is to replace the entire entity state. When doing so, if only a small portion of the entity is actually modified, it is difficult for the server-side application to determine what specific update occurred. If the use case implementation is to produce an event-based outcome, it’s overly complicated to identify what the fine-grained event should be. This results in events being very coarse-grained. When the entire state of the entity is packed into a single event, and that event is named, for example, Application Updated , both everything and nothing are communicated at the same time. The consumer of the event must perform some sort of difference comparison based on an older state; otherwise, it might apply the full state in a destructive or error-inducing way.
As indicated by Figure 8.5 , cumbersome state modification determination is not the case when using PATCH. With a partial update, it is straightforward to determine what the fine-grained event-based outcome is for the use case, because it is clear exactly what changed. A key advantage of the architecture shown in Figure 8.5 is that subsequent risk reassessment and rate recalculation can be performed more quickly because only the limited amount of data changed is precisely communicated by a specific event.
Figure 8.5 Performing CRUUD partial updates makes pinpointing event types and their content simple.
Note
Something similar to PATCH can be accomplished using PUT, but the submitted entity must indicate what in the full payload has changed. Using PUT reduces the number of exposed URIs that are required by PATCH, 7 and it may be considered a way to reduce the client’s awareness of additional URIs. Yet, if the team is employing the ideas of HATEOAS, 8 there is no need for the client to hard-code access to resources.
-
PUT creates overhead: The full entity payload must cross the network twice; the client must understand how to indicate a partially changed entity; and the server must know how to dispatch by means of the indicator.
-
Hypertext As The Engine Of Application State (HATEOAS): This acronym, which many don’t know how to pronounce, represents the idea that once a client uses GET on a top-level, “minted” URI, all other resources are available through links provided in the response payload. This continually guides the client through everything the service/application makes available to that client.
Chapter 9 discusses how REST supports message- and event-driven architectures.
Quality Attributes
The foundation architecture includes quality attributes. Among the many possible quality attributes, we have chosen to discuss here a subset that we consider to be the most salient: Security, Privacy, Performance, Scalability, Resilience, and Complexity. The sections that follow discuss the trade-offs involved in each of these.
Note
Readers interested in learning more about addressing quality attributes can refer to Continuous Architecture in Practice [Continuous-Architecture], a book in the Vaughn Vernon Signature Series.
Security
Nowadays, it is difficult to imagine a company not handling at least a part of its business activities using online technologies. Exposing the business enterprise to even partially open access can be dangerous, though. Whether it relies on a publicly accessible website, HTTP APIs, or diverse integration endpoints with partners reaching in through private networks or VPNs, open access poses multiple threats to business security.
For example, data might be stolen or corrupted. General computing resources running day-to-day operations might be infected with viruses and compromised. There is also the possibility that various attacks and infiltrations might require considerable time to detect, and might even go unnoticed until severe damage is done. In the worst of cases, the damage might bring the whole business down. Such potential threats can cause security team members to “sleep with one eye open.”
Consider one of the most devastating cyber-attacks ever [ CyberAttack ]. Within hours of its first appearance, the malware known as NotPetya wormed its way beyond a small Ukrainian software business to countless devices around the world. It paralyzed global shipping corporations, including FedEx, TNT Express, and Maersk, for several weeks, causing more than $10 billion in damages. Not every cyber-attack has such extensive penetration or such dramatic consequences, but according to data collected by Juniper Research [Juniper] and Forbes , cyber-crimes accounted for $2 trillion in losses in 2019 alone. Further, it is estimated that total losses could reach three times that number sometime in 2021. The University of Maryland found recently that a cyber-attack takes place every 39 seconds, while security firm McAfee reported 480 new high-tech threats are introduced every minute. According to one research reference, a large percentage of data breaches are caused by application security problems, rather than by infrastructure [Verizon-SEC].
That it is essential to develop systems with thoroughly designed security features might be the understatement of a decade. Security must be a design goal [ Secure-By-Design ] and it must be complete [ Agile-SEC ]. Otherwise, a breach of business assets might lead to extreme financial losses and damage to a firm’s reputation via headline news. Far too often, security is implemented or strengthened only as an afterthought, leading to exposure of the system to would-be attackers through unknown gaps.
Note that Microservices have different attack surfaces that can make threats more serious due to the myriad opportunities for exploiting them. These opportunities are generally due to the services’ distributed state, network access, and distributed security mechanisms. A Monolithic architecture can use an in-process security context that is naturally available to the whole application. In contrast, because Microservices are composed of multiple distributed services, the security context has to be passed from one service to another.
The most prominent example of inter-service security dependencies is seen with establishing and verifying user identity. In a Monolithic system, user identity can be established once when a user signs in, and remains available to every module until the user finally signs out. When architecting a Microservice-based system, it is inconceivable that users be required to sign in to every service that is required to fulfill the business system’s operations.
When working within the constraints of a Microservices architecture, it can be quite challenging to correctly implement viable security. This leads to legitimate fears of getting it wrong amidst the challenges and unknowns related to which aspects might be vulnerable. Yet, companies have a wealth of industry standards and tools on which they can rely. Modern application developers must implement at least two aspects of security:
-
Authentication: The process of verifying the identity of a human or another software component attempting to access a Monolith or Microservice. The main goal is to verify the user’s credentials, such as a user identity and password, or a secret key that provides access to an API. Many different kinds of authentication protocols exist, but the most commonly used is OpenID Connect, which employs Access Tokens (JWT) as proof of authentication.
-
Authorization: The process of verifying that the authenticated user is allowed to perform a requested operation in a specific business context and on specific data. Most of the time, this involves a combination of role-based security along with associated access control lists (ACLs) or permissions, which support fine-grained authorization. The former grants broad permission for legitimate users to access certain high-level business functionality. The latter grants authentic users authorized access to specific operations on specialized components by ensuring each plays the necessary user role and has the required permissions to do so.
Modern authentication and authorization protocols rely heavily on the use of security access and bearer tokens, and system security architectures should require tokens to be included in specific HTTP, RPC, and messaging requests. Access/bearer tokens are highly secure and are retrieved through authentication. A token carries enough information to prove user authenticity and authority to use a given service offering. Tokens might expire after a standard time frame but can be renewed through regeneration. The regeneration ensures that appropriate access is still available to the user while preventing attackers from breaking the token’s secret encoding by limiting its lifetime. That’s accomplished by making the security mechanisms’ cryptography a moving target.
The following practices can be incorporated very early on in the development process to design systems with security as a central concern:
-
Design for security: Security must not be an afterthought, as that lackadaisical approach results in designs that are brittle, are fragile, and lack optimal security.
-
Use HTTPS by default: Transport Layer Security (TLS) is designed to ensure privacy and data integrity between computer applications. HTTPS requires a certificate. Certificates can be generated through a cloud provider. A certificate grants permissions to use encrypted communication via the Public Key Infrastructure (PKI), and also authenticates the identity of the certificate’s holder.
-
Encrypt and protect secrets: Applications will likely have secrets that they use for communication. These secrets might be an API key, or a client secret, or credentials for basic authentication. All of these secrets should be encrypted and should be stored and managed by third-party cloud services. The Azure Key Vault is one example of a key manager.
-
Security checks as part of the deployment pipeline 9 : Static Application Security Testing (SAST) tools are designed to analyze source code or compiled versions of code to help find security flaws. Proactively use these SAST tools to uncover flaws through invaluable, immediate feedback; don’t rely on late discovery of vulnerabilities.
- These techniques are helpful and good to use, but tools are lacking, which can make it challenging to accomplish the intended aims fully. SAST reveals only limited types of security flaws. Thus, it is necessary to perform a number of other security tests, both automated and manual.
-
Don’t create your own security mechanisms or crypto code: Not everyone is a security expert. Rely on external tools and libraries that are battle tested through use by many thousands of developers, systems, and individual services.
There are many other points to consider when implementing systems and individual services, whether using Monoliths, Microservices, or both together. Taking into account the points outlined here will certainly contribute to improved security. The follow-on book provides detailed information on architecting and implementing security.
Privacy
Disk storage has become very inexpensive. That being so, many businesses desire to capture and store as much information as possible, even when that information has undetermined value and may potentially be discarded later. Data has become known as the most valuable business asset, so incurring the limited expense of storing data, even though it potentially has no value seems, worthwhile. Useful knowledge about customers, competitors, and markets can be gained through crunching huge amounts of data by means of machine learning (ML) algorithms that yield opportunities to transform data into business intelligence. In this effort, businesses always collect some data that could be used to derive information about individual humans. Although potentially valuable, care must be taken when storing and processing such personal information.
Storing copious amounts of data about individuals can be a double-edged sword. One downside is that snatching vast amounts of personal information, or even small amounts of high-value personal information, is often the aim of those who launch security attacks. Indeed, theft of sensitive data is one of the greatest motivations of malicious individuals. One can cite many examples of credit card numbers being stolen, even from tech giants such as Apple. Storing the bare minimum of data required for a business to operate eliminates this security threat, since it reduces the business’s value as a target.
In some countries, governmental policies define how personal data can be collected, stored, and used. The most well-known policy is the “General Data Protection Regulation’’ [ GDPR ]. Its primary aim is to give individuals control over their personal data. GDPR guarantees individuals the right to erase any of their personal data, such as their email address, government-issued identity, IP address, name, street address, date of birth, age, and gender. This law is aimed at all businesses operating within the territories of countries that belong to the European Union (EU), but other personal data protection policies have been established in other countries outside the EU. In all such cases, businesses functioning within the jurisdiction of the policies must comply if they want to operate within those markets.
Figure 8.6 illustrates how events that must reference privacy data can do so from a distance, so that the events remain unchanged and the privacy data exists only until it must be deleted.
Figure 8.6 Store the bare minimum of anonymized and separated private data that can be deleted.
In addition to the elements illustrated in Figure 8.6 , additional procedures can be considered that will save a lot of work when taking into account data related to personal privacy. Consider the following as the minimum steps needed:
-
Store the bare minimum of private data. The less data that is stored that could be personally identifiable, the less work the business must undertake to comply with privacy protection policies, such as GDPR. Individuals within the EU territory can at any time request that their personal data be deleted, and businesses are required to comply. This reduces the threat that those individuals’ sensitive data will be stolen.
-
Involve the legal team. Work with the legal team on privacy requirements and understand the privacy policy under which users will be signing up.
-
Understand the purpose. Make sure the purpose of storing every piece of data is well understood.
-
Have a retention plan. Ensure there is a well-defined data retention policy and implement it.
-
Know which data is identifiable and destroyable. There must be an established way to find and delete all privacy data relating to a specific individual on demand, per GDPR requirements.
-
Anonymize and separate private data. Some data cannot be easily deleted, or it might be necessary to retain for legal, auditing, or historical reasons. When using Event Sourcing, for example, some Domain Events might tend to contain user information that is protected by a private data protection policy. In such cases, it is advisable to design data privacy as an application feature rather than considering it to be a patch. All personal data that is obligatory to store for a long time must be anonymized, and no personal information can be derived from what is anonymized. To correlate anonymized data with streaming data, such as Domain Events, replace the actual user personal data with a global unique identity, such as a universally unique identifier (UUID) token. The unique identity points to a highly secure storage record. All records holding private data can then be scrubbed upon request. It might be that the unique identity will continue to exist, but will point to data devoid of sensitive information. All that remains is data without any meaningful user information.
People everywhere are demanding freedom from uninvited intrusion and surveillance. Systems should be designed for privacy, even in countries, such as the United States, where privacy laws are a tough sell [ WP-Privacy ]. This is even more so the case when US and other non-EU businesses expect to succeed in markets beyond their national borders.
Transparency in how businesses collect, manage, and protect private data is vital to building trust and accountability with customers and partners who expect privacy. Unfortunately, many companies have learned the importance of privacy the hard way. Ensuring their data privacy demonstrates that the company is operating in the best interests of its customers. To be successful in that endeavor, data protection processes and procedures must be considered fundamental to the design of systems architectures.
Performance
The most salient aspect of performance is latency . With Microservices, the fact that the physical network is involved in the communication between services increases latency. Marshalling and unmarshalling data as well as sending bytes over the network takes time. The speed of light is very fast. No matter how quickly data is transmitted, relatively short distances require time for light to travel over a fiber network. Light travels at top speed in a vacuum, and fiber-optic networks aren’t vacuums. Consider the example round-trip times in Table 8.3 [ Fiber-Latency ].
Table 8.3 Routes on Optical Fiber with Round-Trip Times in Milliseconds
| Route | Optical Fiber Round-Trip |
|---|
| New York to San Francisco | 42 | ms |
| New York to London | 56 | ms |
| New York to Sydney | 160 | ms |
Further, a few or several milliseconds (i.e., less than one second) at observable human scale are indivisible and thus seemingly nonexistent. Computers operate on a much tighter time scale, one characterized by extremely small fractions of a second. It’s common to measure computer operations in nanoseconds, where one nanosecond is one billionth of a second. To better visualize how latency affects processing, we can express computing time at the human scale. Brendan Gregg, in the book Systems Performance: Enterprise and the Cloud [ SysPerformance ], scaled the relative time of various computer operations by making a single CPU cycle equivalent to one second. As Table 8.4 illustrates, the results were stunning.
Table 8.4 Computing Time with Nanoseconds Scaled Up to Seconds
| Event | Actual Latency | Human-Scale Latency |
|---|
| One CPU cycle | 0.4 | ns | 1 | s |
| Level 1 cache access | 0.9 | ns | 2 | s |
| Level 2 cache access | 2.8 | ns | 7 | s |
| Level 3 cache access | 28 | ns | 1 | min |
| Main memory access (DDR DIMM) | ~100 | ns | 4 | min |
| Intel Optane memory access | <10 | μs | 7 | hr |
| NVMe SSD I/O | ~25 | μs | 17 | hr |
| SSD I/O | 50–150 | μs | 1.5–4 | days |
| Rotational disk I/O | 1–10 | ms | 1–9 | months |
| Internet operation: San Francisco to New York City | 65 | ms | 5 | years |
| Internet operation: San Francisco to Hong Kong | 141 | ms | 11 | years |
Network operations, shown at the bottom of Table 8.4 , when expressed as human-scale latencies, require years to complete. That’s because there are many billions of nanoseconds in 65 milliseconds and 141 milliseconds.
It is inaccurate to say that the latency of every network operation between Microservices accumulates linearly. Assuming asynchronous messaging is used for at least some inter-service communications, all of those asynchronous message requests run in parallel. With the publish–subscribe (i.e., fanout) pattern, one message sent by a producer can be delivered to a virtually unlimited number of consumers.
Latency can also be mitigated by services keeping copies of data from other services locally, thereby eliminating the network operations needed to constantly retrieve that specific data. Yet, when non-owners cache data, other problems can occur, such as when the data becomes stale. What happens when the service that caches non-owned data acts upon that data after it becomes stale? It depends on the data in use and whether the service contracts are based on accuracy, assuming someone realizes the need to think of that point during contract negotiations. Some service contracts can be fuzzy, whereas others must be precise. Problems can be avoided by evicting stale data, refreshing it on a just-in-time basis, or not caching data that has a high sensitivity to time and service demands for the sake of accuracy.
Total latency is reduced as more operations execute simultaneously. Executing in parallel all operations that are required to solve a given problem yields the completed result in the amount of time required for the slowest of all those parallel operations. The Monolith has no network latency, other than what’s required for database access and a possible messaging mechanism, because all normal operations are in-process. Even in a perfectly parallelizable world, Monoliths will still be faster and have higher throughput, especially for workloads that cannot be easily scaled to multiple machines.
Additionally, performance is closely related to scalability. One affects the other in an opposite way; that is, they have an inverse relationship.
Scalability
Before delving into the scalability property of Monolithic and Microservices architectures, it’s helpful to consider the potential demand on computing resources. Given:
-
Both a Monolith and a set of Microservices are assigned the same work
-
Each Microservice is:
-
– Run in a Docker container
-
– Orchestrated by cluster management tools such as Kubernetes
-
– Uses log aggregation and monitoring
-
Even without digging through and surfacing exact figures, it is safe to assume that the way Microservices are run will require some processing overhead not required by a Monolith. Despite that, Microservices are capable of providing smarter resource usage. Because the cluster manager can allocate specific computing resources based on demand for use of specific components, the overall resource utilization can be much lower for the Microservices that are less heavily used. With Monoliths, the opposite is true. Because a small portion of the overall Monolith code requires the greatest number of resources, demand-based scaling carries a disproportionate cost. Thus, Microservices can independently scale the resource-intensive parts of the code, while every instance of a Monolith must have access to the peak number of resources demanded by its most resource-intensive part.
Although Monoliths are not easily scaled, there are ways around that limitation. As explained in the section “ Serverless and Function as a Service ,” in Chapter 9 , it’s possible to deploy a cloud-native modular Monolith as serverless 10 and reap all the benefits of infinite scale for the least possible financial cost on the cloud. Although that approach isn’t free, it is attainable. The system must be well designed and meet a few cloud-native design requirements. In fact, running both modular Monoliths and Microservices in a serverless fashion yields equal benefits.
- We don’t mean to suggest that a legacy Big Ball of Mud would be deployed as a serverless entity. The Monolith spoken of here would be designed to be serverless, with a cloud-native nature. The key benefit of deploying a well-designed Monolith as serverless is the decreased operational complexity, which would be incurred if the system were instead designed as hundreds of small Function as a Service (FaaS) components. There will be some size limitations to serverless solutions, however. At the time of this book’s writing, an AWS Lambda must run in 10 GB of memory. This is a lesser limitation than the previous 3 GB.
Resilience: Reliability and Fault Tolerance
Resilience is a software quality that is resistant to cascading failure when small components inevitably fail. There is a big difference between a modularized Monolith and a Big Ball of Mud Monolith. The modularized Monolith can be designed with reliability and fault tolerance in mind, similarly to Microservices, but with less technical overhead. Running in the same process doesn’t require complex mechanisms to guarantee reliability. In contrast, the Big Ball of Mud Monolith is unreliable because testing the application thoroughly is very difficult, and quality tests rarely exist. The lack of extensive tests means that bugs can easily make their way into production. It is generally quite difficult to augment a Big Ball of Mud Monolith with effective reliability measures as an afterthought. These points have been well established, and obviously this book’s concern and focus is on architecting, designing, and developing modularized Monoliths.
Microservices are also difficult to test extensively because each individual service might interact with and/or depend on functionality provided by other Microservices. Making these work well together by testing their collaboration and integration is a challenging undertaking. It’s not unusual for defects to be found in production rather than during testing.
As previously established, operations that occur inside modular Monoliths are in-process and direct. Any network failure cannot impede such operations because the network is not involved. Even if network operations are guaranteed to be 99.9% 11 reliable, 0.1% of the time there will be issues. An uptime Service Level Agreement (SLA) of 99.9% means that the system will be down 8.77 hours per year, 43.83 minutes per month, 10.08 minutes per week, and 1.44 minutes every single day. It should be abundantly obvious that the more nines in the availability criterion, the better. Nonetheless, a full-day outage that falls outside the SLA, as an unexpected anomaly, will certainly have the greatest impact of all. Using the network less rather than more has a very big advantage.
- Availability is usually expressed as a percentage of uptime in a given year within the SLA. It is usually expressed as “ N nines,” such as 99.9%, or “three nines” ( https://en.wikipedia.org/wiki/High_availability ).
Even if a modularized Monolith has much to offer, unlike Microservices, it cannot easily guarantee fault isolation. If an unhandled exception occurs in one module—or worse yet, an unrecoverable exception such as an out-of-memory condition due to a memory leak—it can potentially crash the whole process that is running all services. With Microservices, just one service is lost when it crashes, but only if attention is given to the measures noted in the section “ Mental Preparation with Resolve ,” in Chapter 11 , “ Monolith to Microservices Like a Boss .” As stated there, failure supervision can prevent widespread system crashes.
Microservices should be designed with network and other kinds of failure in mind. When a service experiences a network outage or a full crash, the resource manager (e.g., Kubernetes or a cloud-provider–specific program) can rapidly bring the service down and spin up another service instance.
Another way to ensure fault tolerance is through the purposeful creation of chaos as a test. Netflix developed a test tool, ChaosMonkey, which randomly terminates a service so as to ensure that fault tolerance is properly achieved [ ChaosMonkey ]. The assertions for proper recovery include (1) a new service instance replaces the downed service; (2) network calls are rerouted; and (3) the overall architecture is reliable and continues to run as expected.
Complexity
Whole-system complexity embodies a number of challenging aspects. It stems from the complexity of deployments, the complexity of code under development, the complexity of running the whole system in production, and the ongoing challenge of monitoring and observing the system. From the perspective of the codebase, the Monolith application code is often kept in a single repository, known as a mono-repo. The inter-module communication between services is easier to trace with this setup, and with the help of an integrated development environment (IDE) static analysis, the processing flow can be quickly discovered.
We don’t mean to imply that Microservices cannot make use of the mono-repo 12 feature. On a practical level, though, Microservices may be built by mixing languages and technologies, which increases the overall system complexity. Additionally, dealing with different libraries and frameworks, and different versions of each across services, is quite complex.
- A mono-repo is a single source code revision tracking repository that holds all the source code for potentially many projects in a large system. For more information, see https://en.wikipedia.org/wiki/Monorepo .
Deployments and auto-scalability of the system can be very complex as well. Monoliths are simple to deploy because they are self-contained and the company likely has decades of accumulated experience in deploying business software to a single machine. Scaling Monoliths is a matter of spinning up a new instance of one deployment unit. By comparison, deployments and scalability are much more complex with Microservices. Deployments to different computer nodes can be quite complex to coordinate, and tools used for scaling, such as Kubernetes, require real expertise.
And then there’s the challenge of running the system in production. Logging and monitoring may be less or more complex depending on the use of Monoliths or Microservices, respectively. When running a Monolith in production, there is generally only one or a few log files to search and inspect, making debugging issues much less complex. It’s a different story with Microservices: Tracking an issue might involve checking multiple, even many, log files. Not only is it necessary to find all the relevant log output, but it’s also critical to aggregate and merge all of the logs in the correct order of operational occurrence. Often, tools such as Elasticsearch are used to aggregate and find all the relevant log output across services.
Applying the Tools
Architecture decisions should not be pushed abruptly into concrete. It might be too early, and the team might not know enough, for a sound decision to be made on any given architectural concern. It’s never wrong to wait until the decision is actually required, rather than making decisions based on speculation. Making a decision without a confirmation of need is irresponsible and potentially harmful. Recall that all decisions should be made at the last responsible moment.
Part IV of this book demonstrates the application of the specific architectures and patterns discussed in Part III .
Modules First
A fair question is, would it make sense to promote the internal modules (Intake, Processing, Policy, Renewals) to top-level modules of their own? That’s a possibility to consider in time, and there might be advantages to doing so. But let’s fall back on the earlier advice that in essence asserts, “The team doesn’t yet have enough information to accept that decision.” It would be irresponsible to go there now. Future conversations might lead in that direction, but jumping to a conclusion now doesn’t make sense.
Summary
This chapter began by reviewing some of the many definitions of software architecture, then proposed a fresh definition with new insights. A number of architectural styles and architecture patterns were considered that specifically support events-first systems. In particular, the Ports and Adapters (Hexagonal) architectural style can be adapted to high-level architecture decisions, supporting variety at lower levels. A significant benefit of Ports and Adapters is its support for just-in-time decisions. It is a sound and versatile architecture on which to base additional architecture decisions and their respective implementations. In summary, the chapter made the following key points:
-
Ports and Adapters can be expressed in several ways, including Service Layer with Transaction Scripts; Service Layer with a Domain Model; compressed layers with a Domain Model of Actors; and Functional Core with Imperative Shell.
-
Modularization is key to adaptive architectures, where Monoliths lead to a blend of both Monolith and Microservices, or to entirely Microservices, depending on the purpose served.
-
The REST architecture is often used for limited CRUD applications, but can be extended to domain-driven and event-driven architectures by using CRUUD-based partial updates.
-
The purpose of architecture decisions is to achieve quality attribute requirements, such as flexibility, security, privacy, performance, scalability, and resilience, while reducing complexity.
-
Not every architecture style and pattern is suitable for all system and subsystem constraints.
-
Some architecture decisions meant to address certain quality attributes can work against others, requiring trade-offs to be made.
References
[Agile-SEC] Laura Bell, Rich Smith, Michael Brunton-Spall, and Jim Bird. Agile Application Security: Enabling Security in a Continuous Delivery Pipeline. Sebastopol, CA: O’Reilly Media, 2017.
[BBoM] http://laputan.org/mud/
[ChaosMonkey] https://github.com/netflix/chaosmonkey
[Continuous-Architecture] Murat Erder, Pierre Pureur, and Eoin Woods. Continuous Architecture in Practice. Boston, MA: Addison-Wesley, 2021.
[CyberAttack] https://www.wired.com/story/notpetya-cyberattack-ukraine-russia-code-crashed-the-world/
[Fiber-Latency] https://hpbn.co/primer-on-latency-and-bandwidth/
[GDPR] https://en.wikipedia.org/wiki/General_Data_Protection_Regulation
[ISO 47010] ISO 47010; was IEEE Standard 1471; https://en.wikipedia.org/wiki/IEEE_1471
[PortsAdapters] https://alistair.cockburn.us/hexagonal-architecture/
[POSA1] Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, and Michael Stal. Pattern-Oriented Software Architecture Volume 1: A System of Patterns. Hoboken, NJ: Wiley, 1996.
[Secure-By-Design] https://www.manning.com/books/secure-by-design
[Software Architecture in Practice] Len Bass, Paul Clements, and Rick Kazman. Software Architecture in Practice , 3rd ed. Boston, MA: Addison-Wesley, 2013.
[SOLID] https://en.wikipedia.org/wiki/SOLID
[SysPerformance] Brendan Gregg. Systems Performance: Enterprise and the Cloud , 2nd ed. Boston, MA: Addison-Wesley, 2021.
[Verizon-SEC] https://enterprise.verizon.com/resources/reports/dbir/
[VLINGO-XOOM] https://vlingo.io
[WP-Privacy] Washington Post. https://www.washingtonpost.com/news/powerpost/paloma/the-cybersecurity-202/2018/05/25/the-cybersecurity-202-why-a-privacy-law-like-gdpr-would-be-a-tough-sell-in-the-u-s/5b07038b1b326b492dd07e83/