Chapter 1. Escaping monolithic hell
Figure 1.1. The FTGO application has a hexagonal architecture. It consists of business logic surrounded by adapters that implement UIs and interface with external systems, such as mobile applications and cloud services for payments, messaging, and email.
Figure 1.2. A case of monolithic hell. The large FTGO developer team commits their changes to a single source code repository. The path from code commit to production is long and arduous and involves manual testing. The FTGO application is large, complex, unreliable, and difficult to maintain.
Figure 1.3. The scale cube defines three separate ways to scale an application: X-axis scaling load balances requests across multiple, identical instances; Z-axis scaling routes requests based on an attribute of the request; Y-axis functionally decomposes an application into services.
Figure 1.4. X-axis scaling runs multiple, identical instances of the monolithic application behind a load balancer.
Figure 1.5. Z-axis scaling runs multiple identical instances of the monolithic application behind a router, which routes based on a request attribute. Each instance is responsible for a subset of the data.
Figure 1.6. Y-axis scaling splits the application into a set of services. Each service is responsible for a particular function. A service is scaled using X-axis scaling and, possibly, Z-axis scaling.
Figure 1.7. Some of the services of the microservice architecture-based version of the FTGO application. An API Gateway routes requests from the mobile applications to services. The services collaborate via APIs.
Figure 1.8. The microservices-based FTGO application consists of a set of loosely coupled services. Each team develops, tests, and deploys their services independently.
Figure 1.9. The visual representation of different types of relationships between the patterns: a successor pattern solves a problem created by applying the predecessor pattern; two or more patterns can be alternative solutions to the same problem; one pattern can be a specialization of another pattern; and patterns that solve problems in the same area can be grouped, or generalized.
Figure 1.10. A high-level view of the Microservice architecture pattern language showing the different problem areas that the patterns solve. On the left are the application architecture patterns: Monolithic architecture and Microservice architecture. All the other groups of patterns solve problems that result from choosing the Microservice architecture pattern.
Figure 1.11. There are two decomposition patterns: Decompose by business capability, which organizes services around business capabilities, and Decompose by subdomain, which organizes services around domain-driven design (DDD) subdomains.
Figure 1.12. The five groups of communication patterns
Figure 1.13. Because each service has its own database, you must use the Saga pattern to maintain data consistency across services.
Figure 1.14. Because each service has its own database, you must use one of the querying patterns to retrieve data scattered across multiple services.
Figure 1.15. Several patterns for deploying microservices. The traditional approach is to deploy services in a language-specific packaging format. There are two modern approaches to deploying services. The first deploys services as VM or containers. The second is the serverless approach. You simply upload the service’s code and the serverless platform runs it. You should use a service deployment platform, which is an automated, self-service platform for deploying and managing services.
Figure 1.16. The rapid, frequent, and reliable delivery of large, complex applications requires a combination of DevOps, which includes continuous delivery/deployment, small, autonomous teams, and the microservice architecture.
Chapter 2. Decomposition strategies
Figure 2.1. The 4+1 view model describes an application’s architecture using four views, along with scenarios that show how the elements within each view collaborate to handle requests.
Figure 2.2. An example of a hexagonal architecture, which consists of the business logic and one or more adapters that communicate with external systems. The business logic has one or more ports. Inbound adapters, which handled requests from external systems, invoke an inbound port. An outbound adapter implements an outbound port, and invokes an external system.
Figure 2.3. A possible microservice architecture for the FTGO application. It consists of numerous services.
Figure 2.4. A service has an API that encapsulates the implementation. The API defines operations, which are invoked by clients. There are two types of operations: commands update data, and queries retrieve data. When its data changes, a service publishes events that clients can subscribe to.
Figure 2.5. A three-step process for defining an application’s microservice architecture
Figure 2.6. System operations are derived from the application’s requirements using a two-step process. The first step is to create a high-level domain model. The second step is to define the system operations, which are defined in terms of the domain model.
Figure 2.7. The key classes in the FTGO domain model
Figure 2.8. Mapping FTGO business capabilities to services. Capabilities at various levels of the capability hierarchy are mapped to services.
Figure 2.9. From subdomains to services: each subdomain of the FTGO application domain is mapped to a service, which has its own domain model.
Figure 2.10. The Order god class is bloated with numerous responsibilities.
Figure 2.11. The Delivery Service domain model
Figure 2.12. The Kitchen Service domain model
Figure 2.13. The Order Service domain model
Chapter 3. Interprocess communication in a microservice architecture
Figure 3.1. The client’s business logic invokes an interface that is implemented by an RPI proxy adapter class. The RPI proxy class makes a request to the service. The RPI server adapter class handles the request by invoking the service’s business logic.
Figure 3.2. An API gateway must protect itself from unresponsive services, such as the Order Service.
Figure 3.3. The API gateway implements the GET /orders/{orderId} endpoint using API composition. It calls several services, aggregates their responses, and sends a response to the mobile app. The code that implements the endpoint must have a strategy for handling the failure of each service that it calls.
Figure 3.4. Service instances have dynamically assigned IP addresses.
Figure 3.5. The service registry keeps track of the service instances. Clients query the service registry to find network locations of available service instances.
Figure 3.6. The platform is responsible for service registration, discovery, and request routing. Service instances are registered with the service registry by the registrar. Each service has a network location, a DNS name/virtual IP address. A client makes a request to the service’s network location. The router queries the service registry and load balances requests across the available service instances.
Figure 3.7. The business logic in the sender invokes a sending port interface, which is implemented by a message sender adapter. The message sender sends a message to a receiver via a message channel. The message channel is an abstraction of messaging infrastructure. A message handler adapter in the receiver is invoked to handle the message. It invokes the receiving port interface implemented by the receiver’s business logic.
Figure 3.8. Implementing asynchronous request/response by including a reply channel and message identifier in the request message. The receiver processes the message and sends the reply to the specified reply channel.
Figure 3.9. A service’s asynchronous API consists of message channels and command, reply, and event message types.
Figure 3.10. The services in brokerless architecture communicate directly, whereas the services in a broker-based architecture communicate via a message broker.
Figure 3.11. Scaling consumers while preserving message ordering by using a sharded (partitioned) message channel. The sender includes the shard key in the message. The message broker writes the message to a shard determined by the shard key. The message broker assigns each partition to an instance of the replicated receiver.
Figure 3.12. A consumer detects and discards duplicate messages by recording the IDs of processed messages in a database table. If a message has been processed before, the INSERT into the PROCESSED_MESSAGES table will fail.
Figure 3.13. A service reliably publishes a message by inserting it into an OUTBOX table as part of the transaction that updates the database. The Message Relay reads the OUTBOX table and publishes the messages to a message broker.
Figure 3.14. A service publishes messages inserted into the OUTBOX table by mining the database’s transaction log.
Figure 3.15. The Order Service invokes other services using REST. It’s straightforward, but it requires all the services to be simultaneously available, which reduces the availability of the API.
Figure 3.16. The FTGO application has higher availability if its services communicate using asynchronous messaging instead of synchronous calls.
Figure 3.17. Order Service is self-contained because it has replicas of the consumer and restaurant data.
Figure 3.18. Order Service creates an order without invoking any other service. It then asynchronously validates the newly created Order by exchanging messages with other services, including Consumer Service and Restaurant Service.
Chapter 4. Managing transactions with sagas
Figure 4.1. The createOrder() operation updates data in several services. It must use a mechanism to maintain data consistency across those services.
Figure 4.2. Creating an Order using a saga. The createOrder() operation is implemented by a saga that consists of local transactions in several services.
Figure 4.3. When a step of a saga fails because of a business rule violation, the saga must explicitly undo the updates made by previous steps by executing compensating transactions.
Figure 4.4. Implementing the Create Order Saga using choreography. The saga participants communicate by exchanging events.
Figure 4.5. The sequence of events in the Create Order Saga when the authorization of the consumer’s credit card fails. Accounting Service publishes the Credit Card Authorization Failed event, which causes Kitchen Service to reject the Ticket, and Order Service to reject the Order.
Figure 4.6. Implementing the Create Order Saga using orchestration. Order Service implements a saga orchestrator, which invokes the saga participants using asynchronous request/response.
Figure 4.7. The state machine model for the Create Order Saga
Figure 4.8. A saga consists of three different types of transactions: compensatable transactions, which can be rolled back, so have a compensating transaction, a pivot transaction, which is the saga’s go/no-go point, and retriable transactions, which are transactions that don’t need to be rolled back and are guaranteed to complete.
Figure 4.9. The design of the Order Service and its sagas
Figure 4.10. OrderService creates and updates Orders, invokes the OrderRepository to persist Orders, and creates sagas, including the CreateOrderSaga.
Figure 4.11. The OrderService’s sagas, such as Create Order Saga, are implemented using the Eventuate Tram Saga framework.
Figure 4.12. Eventuate Tram Saga is a framework for writing both saga orchestrators and saga participants.
Figure 4.13. The sequence of events when OrderService creates an instance of Create Order Saga
Figure 4.14. The sequence of events when the SagaManager receives a reply message from a saga participant
Figure 4.15. OrderCommandHandlers implements command handlers for the commands that are sent by the various Order Service sagas.
Chapter 5. Designing business logic in a microservice architecture
Figure 5.1. The Order Service has a hexagonal architecture. It consists of the business logic and one or more adapters that interface with external applications and other services.
Figure 5.2. Organizing business logic as transaction scripts. In a typical transaction script–based design, one set of classes implements behavior and another set stores state. The transaction scripts are organized into classes that typically have no state. The scripts use data classes, which typically have no behavior.
Figure 5.3. Organizing business logic as a domain model. The majority of the business logic consists of classes that have state and behavior.
Figure 5.4. A traditional domain model is a web of interconnected classes. It doesn’t explicitly specify the boundaries of business objects, such as Consumer and Order.
Figure 5.5. Structuring a domain model as a set of aggregates makes the boundaries explicit.
Figure 5.6. References between aggregates are by primary key rather than by object reference. The Order aggregate has the IDs of the Consumer and Restaurant aggregates. Within an aggregate, objects have references to one another.
Figure 5.7. A transaction can only create or update a single aggregate, so an application uses a saga to update multiple aggregates. Each step of the saga creates or updates one aggregate.
Figure 5.8. An alternative design defines a Customer aggregate that contains the Customer and Order classes. This design enables an application to atomically update a Consumer and one or more of its Orders.
Figure 5.9. An aggregate-based design for the Order Service business logic
Figure 5.10. The result of an event-storming workshop that lasted a couple of hours. The sticky notes are events, which are laid out along a timeline; commands, which represent user actions; and aggregates, which emit events in response to a command.
Figure 5.11. The design of Kitchen Service
Figure 5.12. The design of the Order Service. It has a REST API for managing orders. It exchanges messages and events with other services via several message channels.
Figure 5.13. The design of the Order aggregate, which consists of the Order aggregate root and various value objects.
Figure 5.14. Part of the state machine model of the Order aggregate
Chapter 6. Developing business logic with event sourcing
Figure 6.1. The traditional approach to persistence maps classes to tables and objects to rows in those tables.
Figure 6.2. Event sourcing persists each aggregate as a sequence of events. A RDBMS-based application can, for example, store the events in an EVENTS table.
Figure 6.3. Applying event E when the Order is in state S must change the Order state to S'. The event must contain the data necessary to perform the state change.
Figure 6.4. Processing a command generates events without changing the state of the aggregate. An aggregate is updated by applying an event.
Figure 6.5. Event sourcing splits a method that updates an aggregate into a process() method, which takes a command and returns events, and one or more apply() methods, which take an event and update the aggregate.
Figure 6.6. A scenario where an event is skipped because its transaction A commits after transaction B. Polling sees eventId=1020 and then later skips eventId=1010.
Figure 6.7. Using a snapshot improves performance by eliminating the need to load all events. An application only needs to load the snapshot and the events that occur after it.
Figure 6.8. The Customer Service recreates the Customer by deserializing the snapshot’s JSON and then loading and applying events #104 through #106.
Figure 6.9. The architecture of Eventuate Local. It consists of an event database (such as MySQL) that stores the events, an event broker (like Apache Kafka) that delivers events to subscribers, and an event relay that publishes events stored in the event database to the event broker.
Figure 6.10. The main classes and interfaces provided by the Eventuate client framework for Java
Figure 6.11. Using an event handler to reliably create a saga after a service creates an event sourcing-based aggregate
Figure 6.12. How the event sourcing-based Accounting Service participates in Create Order Saga
Figure 6.13. How an event sourcing-based saga orchestrator sends commands to saga participants
Chapter 7. Implementing queries in a microservice architecture
Figure 7.1. The findOrder() operation is invoked by a FTGO frontend module and returns the details of an Order.
Figure 7.2. The API composition pattern consists of an API composer and two or more provider services. The API composer implements a query by querying the providers and combining the results.
Figure 7.3. Implementing findOrder() using the API composition pattern
Figure 7.4. Implementing API composition in a client. The client queries the provider services to retrieve the data.
Figure 7.5. Implementing API composition in the API gateway. The API queries the provider services to retrieve the data, combines the results, and returns a response to the client.
Figure 7.6. Implement a query operation used by multiple clients and services as a standalone service.
Figure 7.7. API composition can’t efficiently retrieve a consumer’s orders, because some providers, such as Delivery Service, don’t store the attributes used for filtering.
Figure 7.8. On the left is the non-CQRS version of the service, and on the right is the CQRS version. CQRS restructures a service into command-side and query-side modules, which have separate databases.
Figure 7.9. The design of Order History Service, which is a query-side service. It implements the findOrderHistory() query operation by querying a database, which it maintains by subscribing to events published by multiple other services.
Figure 7.10. The design of a CQRS view module. Event handlers update the view database, which is queried by the Query API module.
Figure 7.11. The DeliveryPickedUp and DeliveryDelivered events are delivered twice, which causes the order state in view to be temporarily out-of-date.
Figure 7.12. The design of OrderHistoryService. OrderHistoryEventHandlers updates the database in response to events. The OrderHistoryQuery module implements the query operations by querying the database. These two modules use the OrderHistoryDataAccess module to access the database.
Figure 7.13. Preliminary structure of the DynamoDB OrderHistory table
Figure 7.14. The design of the OrderHistory table and index
Chapter 8. External API patterns
Figure 8.1. The FTGO application’s services and their clients. There are several different types of clients. Some are inside the firewall, and others are outside. Those outside the firewall access the services over the lower-performance internet/mobile network. Those clients inside the firewall use a higher-performance LAN.
Figure 8.2. A client can retrieve the order details from the monolithic FTGO application with a single request. But the client must make multiple requests to retrieve the same information in a microservice architecture.
Figure 8.3. The API gateway is the single entry point into the application for API calls from outside the firewall.
Figure 8.4. An API gateway often does API composition, which enables a client such as a mobile device to efficiently retrieve data using a single API request.
Figure 8.5. An API gateway has a layered modular architecture. The API for each client is implemented by a separate module. The common layer implements functionality common to all APIs, such as authentication.
Figure 8.6. A client team owns their API module. As they change the client, they can change the API module and not ask the API gateway team to make the changes.
Figure 8.7. The Backends for frontends pattern defines a separate API gateway for each client. Each client team owns their API gateway. An API gateway team owns the common layer.
Figure 8.8. The architecture of an API gateway built using Spring Cloud Gateway
Figure 8.9. The API gateway’s API consists of a graph-based schema that’s mapped to the services. A client issues a query that retrieves multiple graph nodes. The graph-based API framework executes the query by retrieving data from one or more services.
Figure 8.10. The design of the GraphQL-based FTGO API Gateway
Figure 8.11. GraphQL executes a query by recursively invoking the resolver functions for the fields specified in the Query document. First, it executes the resolver for the query, and then it recursively invokes the resolvers for the fields in the result object hierarchy.
Chapter 9. Testing microservices: Part 1
Figure 9.1. The goal of a test is to verify the behavior of the system under test. An SUT might be as small as a class or as large as an entire application.
Figure 9.2. Each automated test is implemented by a test method, which belongs to a test class. A test consists of four phases: setup, which initializes the test fixture, which is everything required to run the test; execute, which invokes the SUT; verify, which verifies the outcome of the test; and teardown, which cleans up the test fixture.
Figure 9.3. Replacing a dependency with a test double enables the SUT to be tested in isolation. The test is simpler and faster.
Figure 9.4. The test quadrant categorizes tests along two dimensions. The first dimension is whether a test is business facing or technology facing. The second is whether the purpose of the test is to support programming or critique the application.
Figure 9.5. The test pyramid describes the relative proportions of each type of test that you need to write. As you move up the pyramid, you should write fewer and fewer tests.
Figure 9.6. Some of the interservice communication in the FTGO application. Each arrow points from a consumer service to a producer service.
Figure 9.7. Each team that develops a service that consumes Order Service’s API contributes a contract test suite. The test suite verifies that the API matches the consumer’s expectations. This test suite, along with those contributed by other teams, is run by Order Service’s deployment pipeline.
Figure 9.8. The API Gateway team writes the contracts. The Order Service team uses those contracts to test Order Service and publishes them to a repository. The API Gateway team uses the published contracts to test API Gateway.
Figure 9.9. An example deployment pipeline for Order Service. It consists of a series of stages. The pre-commit tests are run by the developer prior to committing their code. The remaining stages are executed by an automated tool, such as the Jenkins CI server.
Figure 9.10. Unit tests are the base of the pyramid. They’re fast running, easy to write, and reliable. A solitary unit test tests a class in isolation, using mocks or stubs for its dependencies. A sociable unit test tests a class and its dependencies.
Figure 9.11. The responsibilities of a class determine whether to use a solitary or sociable unit test.
Chapter 10. Testing microservices: Part 2
Figure 10.1. Integration tests must verify that a service can communicate with its clients and dependencies. But rather than testing whole services, the strategy is to test the individual adapter classes that implement the communication.
Figure 10.2. Integration tests are the layer above unit tests. They verify that a service can communicate with its dependencies, which includes infrastructure services, such as the database, and application services.
Figure 10.3. The contracts are used to verify that the adapter classes on both sides of the REST-based communication between API Gateway and Order Service conform to the contract. The consumer-side tests verify that OrderServiceProxy invokes Order Service correctly. The provider-side tests verify that OrderController implements the REST API endpoints correctly.
Figure 10.4. The contracts are used to test both sides of the publish/subscribe interaction. The provider-side tests verify that OrderDomainEventPublisher publishes events that confirm to the contract. The consumer-side tests verify that OrderHistoryEventHandlers consume the example events from the contract.
Figure 10.5. The contracts are used to test the adapter classes that implement each side of the asynchronous request/response interaction. The provider-side tests verify that KitchenServiceCommandHandler handles commands and sends back replies. The consumer-side tests verify KitchenServiceProxy sends commands that conform to the contract, and that it handles the example replies from the contract.
Figure 10.6. A component test tests a service in isolation. It typically uses stubs for the service’s dependencies.
Figure 10.7. The component tests for Order Service use the Cucumber testing framework to execute tests scenarios written using Gherkin acceptance testing DSL. The tests use Docker to run Order Service along with its infrastructure services, such as Apache Kafka and MySQL.
Figure 10.8. End-to-end tests are at the top of the test pyramid. They are slow, brittle, and time consuming to develop. You should minimize the number of end-to-end tests.
Chapter 11. Developing production-ready services
Figure 11.1. A client of the FTGO application first logs in to obtain a session token, which is often a cookie. The client includes the session token in each subsequent request it makes to the application.
Figure 11.2. When a client of the FTGO application makes a login request, Login Handler authenticates the user, initializes the session user information, and returns a session token cookie, which securely identifies the session. Next, when the client makes a request containing the session token, SessionBasedSecurityInterceptor retrieves the user information from the specified session and establishes the security context. Request handlers, such as OrderDetailsRequestHandler, retrieve the user information from the security context.
Figure 11.3. The API gateway authenticates requests from clients and includes a security token in the requests it makes to services. The services use the token to obtain information about the principal. The API gateway can also use the security token as a session token.
Figure 11.4. An API gateway authenticates an API client by making a Password Grant request to the OAuth 2.0 authentication server. The server returns an access token, which the API gateway passes to the services. A service verifies the token’s signature and extracts information about the user, including their identity and roles.
Figure 11.5. A client logs in by POSTing its credentials to the API gateway. The API gateway authenticates the credentials using the OAuth 2.0 authentication server and returns the access token and refresh token as cookies. A client includes these tokens in the requests it makes to the API gateway.
Figure 11.6. Order History Service uses Apache Kafka and AWS DynamoDB. It needs to be configured with each service’s network location, credentials, and so on.
Figure 11.7. When the deployment infrastructure creates an instance of Order History Service, it sets the environment variables containing the externalized configuration. Order History Service reads those environment variables.
Figure 11.8. On startup, a service instance retrieves its configuration properties from a configuration server. The deployment infrastructure provides the configuration properties for accessing the configuration server.
Figure 11.9. The observability patterns enable developers and operations to understand the behavior of an application and troubleshoot problems. Developers are responsible for ensuring that their services are observable. Operations are responsible for the infrastructure that collects the information exposed by the services.
Figure 11.10. A service implements a health check endpoint, which is periodically invoked by the deployment infrastructure to determine the health of the service instance.
Figure 11.11. The log aggregation infrastructure ships the logs of each service instance to a centralized logging server. Users can view and search the logs. They can also set up alerts, which are triggered when log entries match search criteria.
Figure 11.12. The Zipkin server shows how the FTGO application handles a request that’s routed by the API gateway to Order Service. Each request is represented by a trace. A trace is a set of spans. Each span, which can contain child spans, is the invocation of a service. Depending on the level of detail collected, a span can also represent the invocation of an operation inside a service.
Figure 11.13. Each service (including the API gateway) uses an instrumentation library. The instrumentation library assigns an ID to each external request, propagates tracing state between services, and reports spans to the distributed tracing server.
Figure 11.14. Metrics at every level of the stack are collected and stored in a metrics service, which provides visualization and alerting.
Figure 11.15. A service reports exceptions to an exception tracking service, which de-duplicates exceptions and alerts developers. It has a UI for viewing and managing exceptions.
Figure 11.16. A microservice chassis is a framework that handles numerous concerns, such as exception tracking, logging, health checks, externalized configuration, and distributed tracing.
Figure 11.17. All network traffic in and out of a service flows through the service mesh. The service mesh implements various functions including circuit breakers, distributed tracing, service discovery, and load balancing. Fewer functions are implemented by the microservice chassis. It also secures interprocess communication by using TLS-based IPC between services.
Chapter 12. Deploying microservices
Figure 12.1. Heavyweight and long-lived physical machines have been abstracted away by increasingly lightweight and ephemeral technologies.
Figure 12.2. A simplified view of the production environment. It provides four main capabilities: service management enables developers to deploy and manage their services, runtime management ensures that the services are running, monitoring visualizes service behavior and generates alerts, and request routing routes requests from users to the services.
Figure 12.3. The deployment pipeline builds an executable JAR file and deploys it into production. In production, each service instance is a JVM running on a machine that has the JDK or JRE installed.
Figure 12.4. Deploying multiple service instances on the same machine. They might be instances of the same service or instances of different services. The overhead of the OS is shared among the service instances. Each service instance is a separate process, so there’s some isolation between them.
Figure 12.5. Deploying multiple services instances on the same web container or application server. They might be instances of the same service or instances of different services. The overhead of the OS and runtime is shared among all the service instances. But because the service instances are in the same process, there’s no isolation between them.
Figure 12.6. The deployment pipeline packages a service as a virtual machine image, such as an EC2 AMI, containing everything required to run the service, including the language runtime. At runtime, each service instance is a VM, such as an EC2 instance, instantiated from that image. An EC2 Elastic Load Balancer routes requests to the instances.
Figure 12.7. A container consists of one or more processes running in an isolated sandbox. Multiple containers usually run on a single machine. The containers share the operating system.
Figure 12.8. A service is packaged as a container image, which is stored in a registry. At runtime the service consists of multiple containers instantiated from that image. Containers typically run on virtual machines. A single VM will usually run multiple containers.
Figure 12.9. A Docker orchestration framework turns a set of machines running Docker into a cluster of resources. It assigns containers to machines. The framework attempts to keep the desired number of healthy containers running at all times.
Figure 12.10. A Kubernetes cluster consists of a master, which manages the cluster, and nodes, which run the services. Developers and the deployment pipeline interact with Kubernetes through the API server, which along with other cluster-management software runs on the master. Application containers run on nodes. Each node runs a Kubelet, which manages the application container, and a kube-proxy, which routes application requests to the pods, either directly as a proxy or indirectly by configuring iptables routing rules built into the Linux kernel.
Figure 12.11. Istio consists of a control plane, whose components include the Pilot and the Mixer, and a data plane, which consists of Envoy proxy servers. The Pilot extracts information about deployed services from the underlying infrastructure and configures the data plane. The Mixer enforces policies such as quotas and gathers telemetry, reporting it to the monitoring infrastructure servers. The Envoy proxy servers route traffic in and out of services. There’s one Envoy proxy server per service instance.
Figure 12.12. The routing rule for Consumer Service, which routes all traffic to the v1 pods. It consists of a VirtualService, which routes its traffic to the v1 subset, and a DestinationRule, which defines the v1 subset as the pods labeled with version: v1. Once you’ve defined this rule, you can safely deploy a new version without routing any traffic to it initially.
Figure 12.13. Deploying Restaurant Service as AWS Lambda functions. The AWS API Gateway routes HTTP requests to the AWS Lambda functions, which are implemented by request handler classes defined by Restaurant Service.
Figure 12.14. The design of the AWS Lambda-based Restaurant Service. The presentation layer consists of request handler classes, which implement the lambda functions. They invoke the business tier, which is written in a traditional style consisting of a service class, an entity, and a repository.
Figure 12.15. The design of the request handler classes. The abstract superclasses implement dependency injection and error handling.
Chapter 13. Refactoring to microservices
Figure 13.1. The monolith is incrementally replaced by a strangler application comprised of services. Eventually, the monolith is replaced entirely by the strangler application or becomes another microservice.
Figure 13.2. A new feature is implemented as a service that’s part of the strangler application. The integration glue integrates the service with the monolith and consists of adapters that implement synchronous and asynchronous APIs. An API gateway routes requests that invoke new functionality to the service.
Figure 13.3. Splitting the frontend from the backend enables each to be deployed independently. It also exposes an API for services to invoke.
Figure 13.4. Break apart the monolith by extracting services. You identify a slice of functionality, which consists of business logic and adapters, to extract into a service. You move that code into the service. The newly extracted service and the monolith collaborate via the APIs provided by the integration glue.
Figure 13.5. The Order domain class has a reference to a Restaurant class. If we extract Order into a separate service, we need to do something about its reference to Restaurant, because object references between processes don’t make sense.
Figure 13.6. The Order class’s reference to Restaurant is replaced with the Restaurant’s primary key in order to eliminate an object that would span process boundaries.
Figure 13.7. Minimize the scope of the changes to the FTGO monolith by replicating delivery-related data from the newly extracted Delivery Service back to the monolith’s database.
Figure 13.8. When migrating a monolith to microservices, the services and monolith often need to access each other’s data. This interaction is facilitated by the integration glue, which consists of adapters that implement APIs. Some APIs are messaging based. Other APIs are RPI based.
Figure 13.9. The adapter that implements the CustomerContactInfoRepository interface invokes the monolith’s REST API to retrieve the customer information.
Figure 13.10. The integration glue replicates data from the monolith to the service. The monolith publishes domain events, and an event handler implemented by the service updates the service’s database.
Figure 13.11. A service adapter that invokes the monolith must translate between the service’s domain model and the monolith’s domain model.
Figure 13.12. An event handler must translate from the event publisher’s domain model to the subscriber’s domain model.
Figure 13.13. The login handler is enhanced to set a USERINFO cookie, which is a JWT containing user information. API Gateway transfers the USERINFO cookie to an authorization header when it invokes a service.
Figure 13.14. The design of Delayed Delivery Service. The integration glue provides Delayed Delivery Service access to data owned by the monolith, such as the Order and Restaurant entities, and the customer contact information.
Figure 13.15. The integration glue provides Delayed Delivery Service with access to the data owned by the monolith.
Figure 13.16. Delivery management is entangled with order management within the FTGO monolith.
Figure 13.17. The high-level view of the FTGO application after extracting Delivery Service. The FTGO monolith and Delivery Service collaborate using the integration glue, which consists of APIs in each of them. The two key decisions that need to be made are which functionality and data are moved to Delivery Service and how do the monolith and Delivery Service collaborate via APIs?
Figure 13.18. The entities and fields that are accessed by delivery management and other functionality implemented by the monolith. A field can be read or written or both. It can be accessed by delivery management, the monolith, or both.
Figure 13.19. The design of the Delivery Service’s domain model
Figure 13.20. The design of the Delivery Service integration glue. Delivery Service has a delivery management API. The service and the FTGO monolith synchronize data by exchanging domain events.
Figure 13.21. The first step is to define DeliveryService, which is a coarse-grained, remotable API for invoking the delivery management logic.
Figure 13.22. The second step is to change the FTGO monolith to invoke delivery management via the DeliveryService interface.
Figure 13.23. The final step is to implement DeliveryService with a proxy class that sends messages Delivery Service. A feature toggle controls whether the FTGO monolith uses the old implementation or the new Delivery Service.