In Chapter 2 , we explored how to think about migration to a microservice architecture. More specifically, we explored whether it was even a good idea, and if it was, then how you should go about it in terms of rolling out your new architecture and making sure you’re going in the right direction.

We’ve discussed what a good service looks like, and why smaller services may be better for us. But how do we handle the fact that we may already have a large number of applications lying about that don’t follow these patterns? How do we go about decomposing these monolithic applications without having to embark on a big bang rewrite?

Throughout the rest of this chapter, we’ll explore a variety of migration patterns and tips that can help you adopt a microservice architecture. We’ll look at patterns that will work for black-box vendor software, legacy systems, or monoliths that you plan to continue to maintain and evolve. For incremental rollout to work, though, we have to ensure that we can continue to work with, and make use of, the existing monolithic software.

Tip

Remember that we want to make our migration incremental. We want to migrate over to a microservice architecture in small steps, allowing us to learn from the process and change our minds if needed.

To Change the Monolith, or Not?

One of the first things you’re going to have to consider as part of your migration is whether or not you plan (or are able) to change the existing monolith.

If you have the ability to change the existing system, this will give you the most flexibility in terms of the various patterns at your disposal. In some situations, however, there will be a hard constraint in place, denying you this opportunity. The existing system may be a vendor product for which you don’t have the source code, or it may also be written in a technology that you no longer have the skills for.

There may also be softer drivers that might divert you away from changing the existing system. It’s possible that the current monolith is in such a bad state that the cost of change is too high—as a result, you want to cut your losses and start again (although as I detailed earlier, I worry that people reach this conclusion far too easily). Another possibility is that the monolith itself is being worked on by many other people, and you’re worried about getting in their way. Some patterns, like the Branch by Abstraction pattern we’ll explore shortly, can mitigate these issues, but you may still judge that the impact to others is too great.

In one memorable situation, I was working with some colleagues to help scale a computationally heavy system. The underlying calculations were performed by a C library we were given. Our job was to collect the various inputs, pass them into the library, and retrieve and store the results. The library itself was riddled with problems. Memory leaks and horrendously inefficient API design were just two of the major causes of problems. We asked for many months for the source code for the library so we could fix these issues, but we were rebuffed.

Many years later, I caught up with the project sponsor, and asked why they hadn’t let us change the underlying library. It was at that point the sponsor finally admitted they’d lost the source code but were too embarrassed to tell us! Don’t let this happen to you.

So, hopefully, we’re in a position where we can work with, and change, the existing monolithic codebase. But if we can’t, does this mean we’re stuck? Quite the contrary—several patterns can help us here. We’ll be covering some of those shortly.

Cut, Copy, or Reimplement?

Even if you have access to the existing code in the monolith, when you start migrating functionality to your new microservices, it’s not always clear cut as to what to do with the existing code. Should we move the code as is, or re-implement the functionality?

If the existing monolithic codebase is sufficiently well factored, you may be able to save significant time by moving the code itself. The key thing here is to understand that we want to copy the code from the monolith, and at this stage, at least, we don’t want to remove this functionality from the monolith itself. Why? Because leaving the functionality in the monolith for a period of time gives you more options. It can give us a rollback point, or perhaps the opportunity to run both implementations in parallel. Further down the line, once you’re happy that the migration has been successful, you can remove the functionality from the monolith.

Refactoring the Monolith

I’ve observed that often the biggest barrier to making use of existing code in the monolith in your new microservices is that existing codebases are traditionally not organized around business domain concepts. Technical categorizations are more prominent (think of all the Model, View, Controller package names you’ve seen, for example). When you’re trying to move business domain functionality, this can be difficult: the existing codebase doesn’t match that categorization, so even finding the code you’re trying to move can be problematic!

If you do go down the route of reorganizing your existing monolith along business domain boundaries, I thoroughly recommend Working Effectively with Legacy Code by Michael Feathers (Prentice Hall, 2004). In his book, Michael defines the concept of a seam —that is, a place where you can change the behavior of a program without having to edit the existing behavior. Essentially, you define a seam around the piece of code you want to change, work on a new implementation of the seam, and swap it in after the change has been made. He features techniques to work safely with seams as a way of helping clean up codebases.

While generically Michael’s concept of seams could be applied at many scopes, the concept does fit very well with bounded contexts, which we discussed in Chapter 1 . So while Working Effectively with Legacy Code may not refer directly to domain-driven design concepts, you can use the techniques in that book to organize your code along these principles.

A modular monolith?

Once you’ve started to make sense of your existing codebase, an obvious next step that is worth considering is to take your newly identified seams and start to extract them as separate modules, making your monolith a modular monolith . You still have a single unit of deployment, but that deployed unit consists of multiple statically linked modules. The exact nature of these modules depends on your underlying technology stack—for Java, my modular monolith would consist of multiple JAR files; for a Ruby app, it might be a collection of Ruby gems.

As we touched on briefly at the start of the book, having a monolith broken into modules that can be developed independently can deliver many benefits while sidestepping many of the challenges of a microservice architecture, and can be the sweet spot for many organizations. I’ve spoken to more than one team that has started breaking its monolith apart into a modular monolith, with a view to eventually move to a microservice architecture, only to find that the modular monolith solved most of its problems!

Incremental rewrites

My general inclination is always to attempt to salvage the existing codebase first, before resorting to just reimplementing functionality, and the advice I gave in my previous book, Building Microservices , was along these lines. Sometimes teams find that they get enough benefit from this work to not need microservices in the first place!

However, I have to accept that, in practice, I find very few teams take the approach of refactoring their monolith as a precursor to moving to microservices. Instead, what seems more common is that once teams have identified the responsibilities of the newly created microservice, they instead do a new clean-room implementation of that functionality.

But aren’t we in danger of repeating the problems associated with big bang rewrites if we start reimplementing our functionality? The key is to ensure you’re rewriting only small pieces of functionality at a time, and shipping this reworked functionality to your customers regularly. If the work to reimplement the behavior of the service is a few days or weeks, it’s probably fine. If the timelines start looking more like several months, I’d be reexamining my approach.

Migration Patterns

I have seen used many techniques used as part of a microservice migration. For the rest of the chapter, we’ll explore these patterns, looking at where they may be useful and how they can be implemented. Remember, as with all patterns, these aren’t universally “good” ideas. For each one, I’ve attempted to give enough information to help you understand whether they make sense in your context.

Caution

Make sure you understand the pros and cons of each of these patterns. They are not universally the “right” way to do things.

We’ll start with looking at techniques to allow you to migrate and integrate with the monolith; we will deal primarily with where the application code lives. To start with, though, we’ll look at one of the most useful and commonly used techniques: the strangler fig application.

Pattern: Strangler Fig Application

A technique that has seen frequent use when doing system rewrites is called the strangler fig application . Martin Fowler first captured this pattern, inspired by a certain type of fig that seeds itself in the upper branches of trees. The fig then descends toward the ground to take root, gradually enveloping the original tree. The existing tree becomes initially a support structure for the new fig, and if taken to the final stages, you may see the original tree die and rot away, leaving only the new, now self-supporting fig in its place.

In the context of software, the parallel here is to have our new system initially be supported by, and wrapping, the existing system. The idea is that the old and the new can coexist, giving the new system time to grow and potentially entirely replace the old system. The key benefit to this pattern, as we’ll see shortly, is that it supports our goal of allowing for incremental migration to a new system. Moreover, it gives us the ability to pause and even stop the migration altogether, while still taking advantage of the new system delivered so far.

As we’ll see shortly, when we implement this idea for our software, we strive to not only take incremental steps toward our new application architecture, but also ensure that each step is easily reversible, reducing the risk of each incremental step.

How It Works

While the strangler fig pattern has been commonly used to migrate from one monolithic system to another, we will look to migrate from a monolith to a series of microservices. This may involve actually copying the code from the monolith (if possible), or else reimplementing the functionality in question. In addition, if the functionality in question requires the persistence of state, then consideration needs to be given to how that state can be migrated to the new service, and potentially back again. We’ll explore aspects related to data in Chapter 4 .

Implementing a strangler fig pattern relies on three steps, as outlined in Figure 3-1 . First, identify parts of the existing system that you wish to migrate. You’ll need to use judgement as to which parts of the system to tackle first, using the sort of trade-off activity we discussed in Chapter 2 . You then need to implement this functionality in your new microservice. With your new implementation ready, you need to be able to reroute calls from the monolith over to your shiny new microservice.

Showing an overview of the strangler pattern

Figure 3-1. An overview of the strangler pattern

It’s worth noting that until the call to the moved functionality is redirected, that the new functionality isn’t technically live—even if it is deployed into a production environment. This means you could take your time getting that functionality right, working on implementing this functionality over a period of time. You could push these changes into a production environment, safe in the knowledge that it isn’t yet being used, allowing us to get happy with the deployment and management aspects of your new service. Once your new service implements the same equivalent functionality as your monolith, you could then consider using a pattern like parallel run (which we explore shortly) to give you confidence that the new functionality is working as intended.

Tip

Separating the concepts of deployment from release is important. Just because software is deployed into a given environment doesn’t mean it’s actually being used by customers. By treating the two things as separate concepts, you enable the ability to validate your software in the final production environment before it is being used, allowing you to de-risk the rollout of the new software. Patterns like the strangler fig, parallel run, and canary release are among those patterns that make use of the fact that deployment and release are separate activities.

A key point of this strangler application approach is not just that we can incrementally migrate new functionality to the new system, but that we can also roll back this change very easily if required. Remember, we all make mistakes—so we want techniques that allow us to not only make mistakes as cheaply as possible (hence lots of small steps), but also fix our mistakes quickly.

If the functionality being extracted is also used by other functionality inside the monolith, you need to change how those calls are made as well. We’ll cover a few techniques for this later in the chapter.

Where to Use It

The strangler fig pattern allows you to move functionality over to your new services architecture without having to touch or make any changes to your existing system. This has benefits when the existing monolith itself may be being worked on by other people, as this can help reduce contention. It’s also very useful when the monolith is in effect a black-box system—such as third-party software or a SaaS service.

Occasionally, you can extract an entire end-to-end slice of functionality in one piece, as we see in Figure 3-2 . This simplifies the extraction greatly, aside from concerns around data, which we’ll look at later in this book.

Inventory Management can be clearly extracted as it has no downstream dependencies.

Figure 3-2. Straightforward end-to-end abstraction of Inventory Management functionality

In order to perform a clean end-to-end extraction like this, you might be inclined to extract larger groups of functionality to simplify this process. This can result in a tricky balancing act—by extracting larger slices of functionality, you are taking on more work, but may simplify some of your integration challenges.

If you do want to take a smaller bite, you may have to consider more “shallow” extractions, like those we see in Figure 3-3 . Here we are extracting Payroll functionality, despite the fact it makes use of other functionality that remains inside the monolith—in this example, the ability to send User Notifications.

Payroll has a dependency on the downstream user notifications functionality, which we want to leave inside the monolith, so we need the new microservice to call back into the monolith.

Figure 3-3. Extraction of functionality that still needs to use the monolith

Rather than also reimplementing the User Notifications functionality, we expose this functionality to our new microservice by exposing it from the monolith—something that obviously would require changes to the monolith itself.

For the strangler to work, though, you need to be able to clearly map the inbound call to the functionality you care about to the asset that you want to move. For example, in Figure 3-4 , we’d ideally like to move out the ability to send User Notifications to our customers into a new service. However, notifications are fired as a result of multiple inbound calls to the existing monolith. Therefore, we can’t clearly redirect the calls from outside the system itself. Instead, we’d need to look at a technique like the one described in the section “Pattern: Branch by Abstraction” .

Showing the notification functionality being deeper inside the existing system, with no direct calls to it from the outside world.

Figure 3-4. The strangler fig pattern doesn’t work too well when the functionality to be moved is deeper inside the existing system

You will also need to consider the nature of the calls being made into the existing system. As we explore shortly, a protocol such as HTTP is very amenable to redirection. HTTP itself has the concepts of transparent redirection built in, and proxies can be used to clearly understand the nature of an inbound request and divert it accordingly. Other types of protocols, such as some RPCs, may be less amenable to redirection. The more work you have to do in the proxy layer to understand and potentially transform the inbound call, the less viable this option becomes.

Despite these restrictions, the strangler fig application has proven itself time and again to be a very useful migration technique. Given the light touch, and easy approach to handle incremental change, it’s often my first port of call when exploring how to migrate a system.

Example: HTTP Reverse Proxy

HTTP has some interesting capabilities, among them that it is very easy to intercept and redirect in a way that can be made transparent to the calling system. This means that an existing monolith with an HTTP interface is amenable to migration through use of a strangler fig pattern.

In Figure 3-5 , we see an existing monolithic system that exposes an HTTP interface. This application may be headless, or the HTTP interface may, in fact, be being called by an upstream UI. Either way, the goal is the same: to insert an HTTP reverse proxy between the upstream calls and the downstream monolith.

An existing monolithic system being driven by calls from an up stream system or user interface

Figure 3-5. A simple overview of an HTTP-driven monolith prior to a strangler being implemented

Step 1: Insert proxy

Unless you already have an appropriate HTTP proxy in place that you can reuse, I suggest getting one in place first , as seen in Figure 3-6 . In this first step, the proxy will just allow any calls to pass through without change.

Placing a pass-through HTTP proxy between calls from the upstream system and the monolith

Figure 3-6. Step 1: Inserting a proxy between the monolith and the upstream system

This step will allow you to assess the impact of inserting an additional network hop between the upstream calls and the downstream monolith, set up any required monitoring of your new component, and basically, sit with it a while. From a latency point of view, we will be adding a network hop and a process in the processing path of all calls. With a decent proxy and network, you’d expect a minimal impact on latency (perhaps in the order of a few milliseconds), but if this turns out not to be the case, you have a chance to stop and investigate the issue before you go any further.

If you already have an existing proxy in place in front of your monolith, you can skip this step—although do make sure you understand how this proxy can be reconfigured to redirect calls later on. I suggest at the very least experimenting with the redirection to make sure it will work as intended before assuming that this can be done later on. It would be a nasty surprise to discover that this is impossible just before you plan to send your new service live!

Step 2: Migrate functionality

With our proxy in place, next you can start extracting your new microservice, as we see in Figure 3-7 .

Making incremental changes to our new service in production

Figure 3-7. Step 2: Incremental implementation of the functionality to be moved

This step itself can be broken into multiple stages. First, get a basic service up and running without any of the functionality being implemented. Your service will need to accept the calls made to the matching functionality, but at this stage you could just return a 501 Not Implemented . Even at this step, I’d get this service deployed into the production environment. This allows you to get comfortable with the production deployment process, and test the service in situ. At this point, your new service isn’t released , as you haven’t redirected the existing upstream calls yet. Effectively, we are separating the step of software deployment from software release, a common release technique that we’ll revisit later on.

Step 3: Redirect calls

It’s only once you’ve completed movement of all the functionality that you reconfigure the proxy to redirect the call, as we see in Figure 3-8 . If this fails for whatever reason, then you can switch the redirection back—for most proxies, this is a very quick and easy process, giving you a fast rollback.

A calls to payroll-related functionality are now redirected in the proxy to our new microservice

Figure 3-8. Step 3: Redirecting the call to Payroll functionality, completing the migration

You may decide to implement the redirection using something like a feature toggle, which can make your desired configuration state much more obvious. The use of a proxy to redirect the calls is also a great location to consider incremental rollout of the new functionality through a canary rollout, or even a full-blown parallel run , another pattern we discuss in this chapter.

Data?

So far, we haven’t talked about data. In Figure 3-8 , what happens if our newly migrated Payroll service needs access to data that is currently held in the monolith’s database? We’ll explore options for this more fully in Chapter 4 .

Proxy Options

How you implement the proxy is in part going to depend on the protocol used by the monolith. If the existing monolith uses HTTP, then we’re off to a good start. HTTP is such a widely supported protocol that you have a wealth of options out there for managing the redirection. I would probably opt for a dedicated proxy like NGINX, which has been created with exactly these sorts of use cases in mind, and can support a multitude of redirection mechanisms that are tried and tested and likely to perform fairly well.

Some redirections will be simpler than others. Consider redirection around URI paths, perhaps as would be exhibited making use of REST resources. In Figure 3-9 , we move the entire Invoice resource over to our new service, and this is easy to parse from the URI path.

Redirecting calls based on the resource being accessed

Figure 3-9. Redirection by resources

If, however, the existing system buries information about the nature of the functionality being called somewhere in the request body (perhaps in a form parameter), our redirection rule will need to be able to switch on a parameter in the POST—something that is possible, but more complicated. It is certainly worth checking the proxy options available to you to make sure they are able to handle this if you find yourself in this situation.

If the nature of interception and redirection is more complex, or in situations where the monolith is using a less well-supported protocol, you might be tempted to code something yourself, but you should be very cautious about this approach. I’ve written a couple of network proxies by hand before (one in Java, the other in Python), and while it may say more about my coding ability than anything else, in both situations the proxies were incredibly inefficient, adding significant lag into the system. Nowadays if I needed more custom behavior, I’d be more likely to consider adding custom behavior to a dedicated proxy—for example, NGINX allows you to use code written in Lua to add custom behavior.

Incremental rollout

As you can see in Figure 3-10 , this technique allows for architectural changes to be made via a series of small steps, each of which can be done alongside other work on the system.

You might consider the switchover to a new implementation of the Payroll functionality to still be too big, in which case you can take smaller slices of functionality. You can consider, for example, migrating only part of the Payroll functionality and diverting calls appropriately—having some of the behavior implemented in the monolith, and part in the microservice, as shown in Figure 3-11 . This can cause issues if both the functionality in the monolith and in the microservice need to see the same set of data, as this will likely require a shared database and all the problems this can bring.

No big bang, stop-the-line re-platforming required. This makes it much easier to break this work into stages that can be delivered alongside other delivery work. Rather than breaking your backlog into “feature” and “technical” stories, fold all this work together. Get good at making incremental changes to your architecture while still delivering new features!

Showing each of the steps involved in implementing HTTP-based redirection for the payroll functionality.

Figure 3-10. An overview of implementing an HTTP-based strangler

Showing each of the steps involved in implementing HTTP-based redirection for the payroll functionality.

Figure 3-11. An overview of implementing an HTTP-based strangler

Changing Protocols

You could also use your proxy to transform the protocol. For example, you may currently expose a SOAP-based HTTP interface, but your new microservice is going to support a gRPC interface instead. You could then configure the proxy to transform requests and responses accordingly, as shown in Figure 3-12 .

Using a proxy to change communication protocol as part of a strangler migration

Figure 3-12. Using a proxy to change communication protocol as part of a strangler migration

I do have concerns about this approach, primarily due to the complexity and logic that starts to build up in the proxy itself. For a single service, this doesn’t look too bad, but if you start transforming the protocol for multiple services, the work being done in the proxy builds up and up. We’re typically optimizing for independent deployability of our services, but if we have a shared proxy layer that multiple teams need to edit, this can slow down the process of making and deploying changes. We need to be careful that we aren’t just adding a new source of contention. There is the oft-stated mantra of “Keep the pipes dumb, the endpoints smart” when we discuss microservice architecture. We want to reduce how much functionality gets pushed into shared middleware layers, as this can really slow down feature development.

If you want to migrate the protocol being used, I’d much rather push the mapping into the service itself—with the service supporting both your old communication protocol and the new protocol. Inside the service, calls to our old protocol could just get remapped internally to the new communication protocol, as we see in Figure 3-13 . This avoids the need to manage changes in proxy layers used by other services and puts the service in full control over how this functionality changes over time. You can see microservices as a collection of functionality on a network endpoint. You might expose that same functionality in different ways to different consumers; by supporting different message or request formats inside this service, we’re basically just supporting the different needs of our upstream consumers.

If you want to change protocol type, consider having a service expose its capabilities over multiple types of protocol

Figure 3-13. If you want to change protocol type, consider having a service expose its capabilities over multiple types of protocol

By pushing service-specific request and response mapping inside the service, this keeps the proxy layer simple and much more generic. Additionally, by a service providing both types of endpoints, you give yourself time to migrate upstream consumers before potentially retiring the old API.

And service meshes

At Square, they adopted a hybrid approach to solve this problem. 1 They had decided to migrate away from their own homegrown RPC mechanism for service-to-service communication, in favor of adopting gRPC, a well-supported open source RPC framework with a very broad ecosystem. To make this as painless as possible, they wanted to reduce the amount of change needed in each service. To do this, they made use of a service mesh.

With a service mesh , shown in Figure 3-14 , each service instance communicates with other service instances via its own, dedicated local proxy. Each proxy instance can be configured specifically for the service instance it is partnered with. You can also provide centralized control and monitoring of these proxies by using a control plane. As there is no central proxy layer, you avoid the pitfalls regarding having a shared “smart” pipe—effectively, each service can own its own piece of the service-to-service pipe if needed. It’s worth noting that because of the way Square’s architecture had evolved, the company ended up having to create its own service mesh specific to its needs, albeit making use of the Envoy open source proxy, rather than being able to use an established solution like Linkerd or Istio.

An overview of a service mesh

Figure 3-14. An overview of a service mesh

Service meshes are growing in popularity, and conceptually I think the idea is spot on. They can be a great way to handle common service-to-service communication concerns. My worry is that despite a lot of work by some very smart people, it has taken a while for the tooling in this space to stabilize. Istio seems to be the clear leader, but it’s far from the only option in this space, and there are new tools emerging on what seems to be a weekly basis. My general advice has been to give the service mesh space a bit more time to stabilize if you can before making your choice.

Example: FTP

Although I’ve spoken at length regarding the use of the strangler pattern for HTTP-based systems, there is nothing to stop you from intercepting and redirecting other forms of communication protocols. Homegate, a Swiss real estate company, used a variation of this pattern to change how customers uploaded new real estate listings.

Homegate’s customers uploaded listings via FTP, with an existing monolithic system handling the uploaded files. The company was keen to move over to microservices, and also wanted to start to support a new upload mechanism that, rather than supporting batch FTP upload, was going to use a REST API that matched a soon-to-be-ratified standard.

The real estate company didn’t want to have to change things from the customer point of view—it wanted to make any changes seamless. This means that FTP still needed to be the mechanism by which customers interacted with the system, at least for the moment. In the end, the company intercepted FTP uploads (by detecting changes in the FTP server log), and directed newly uploaded files to an adapter that converted the uploaded files into requests to the new REST API, as shown in Figure 3-15 .

Intercepting an FTP upload and diverting it to a new listings service for Homegate

Figure 3-15. Intercepting an FTP upload and diverting it to a new listings service for Homegate

From a customer point of view, the upload process itself didn’t change. The benefit came from the fact that the new service that handled the upload was able to publish the new data much more quickly, helping customers get their adverts live much faster. Later on, there is a plan to directly expose the new REST API to customers. Interestingly, during this period, both listing upload mechanisms were enabled. This allowed the team to make sure the two upload mechanisms were working appropriately. This is a great example of a pattern we’ll explore later in “Pattern: Parallel Run” .

Example: Message Interception

So far we’ve looked at intercepting synchronous calls, but what if your monolith is driven from some other form of protocol, perhaps receiving messages via a message broker? The fundamental pattern is the same—we need a method to intercept the calls, and to redirect them to our new microservice. The main difference is the nature of the protocol itself.

Content-based routing

In Figure 3-16 , our monolith receives numerous messages, a subset of which we need to intercept.

A monolith which subscribes to messages from a queue, probably managed by a message broker.

Figure 3-16. A monolith receiving calls via a queue

A simple approach would be to intercept all messages intended for the downstream monolith, and filter the messages on to the appropriate location, as outlined in Figure 3-17 . This is basically an implementation of the content-based router pattern, as described in Enterprise Integration Patterns . 2

Using an intermediary process which filters messages to the appropriate downstream consumer, allowing us to redirect calls to our new microservice.

Figure 3-17. Using a content-based router to intercept messaging calls

This technique allows us to leave the monolith untouched, but we’re placing another queue on our request path, which could add additional latency and is another thing we need to manage. The other concern is how many “smarts” are we placing into our messaging layer? In Chapter 4 of Building Microservices , I spoke about the challenges caused by systems making use of too many smarts in the networks between your services, as this can make systems harder to understand and harder to change. Instead I urged you to embrace the mantra of “smart endpoints, dumb pipes,” something that I still push for. It’s arguable here that the content-based router is us implementing a “smart pipe”—adding complexity in terms of how calls are routed between our systems. In some situations, this is a highly useful technique, but it’s up to you find a happy balance.

Selective consumption

An alternative would be to change the monolith and have it ignore messages sent which should be received by our new service, as we see in Figure 3-18 . Here, we have both our new service and our monolith share the same queue, and locally they use some sort of pattern-matching process to listen to the messages they care about. This sort of filtering is quite a common requirement in message-based systems and can be implemented using something like a Message Selector in JMS or using equivalent technology on other platforms.

Both the microservice and monolith share the same queue, and only pick up the messages each consumer cares about.

Figure 3-18. Using a content-based router to intercept messaging calls

This filtering approach reduces the need to create an additional queue but has a couple of challenges. First, your underlying messaging technology may or may not let you share a single queue subscription like this (although this is a common feature, so I would be surprised if this was the case). Second, when you want to redirect the calls, it requires two changes to be fairly well coordinated. You need to stop your monolith from reading the calls meant for the new service, and then have the service pick them up. Likewise, reverting the call interception requires two changes to roll back.

The more types of consumers you have for the same queue, and the more complex the filtering rules, the more problematic things can become. It can be easy to imagine a situation in which two consumers start receiving the same message due to overlapping rules, or even the opposite—some messages are being ignored altogether. For this reason, I would likely consider using selective consumption with only a small number of consumers and/or with a simple set of filtering rules. A content-based routing approach is likely to make more sense as the number of types of consumers increases, although beware of the potential downsides cited previously, especially falling into the “smart pipes” problem.

The added complication with either this solution or content-based routing is that if we are using an asynchronous request-response style of communication, we’ll need to make sure we can route the request back to the client, hopefully without them realizing anything has changed. There are other options for call routing in message-driven systems, many of which can help you implement strangler fig pattern migrations. I thoroughly recommend Enterprise Integration Patterns as a great resource here.

Other Protocols

As I hope you can understand from this example, there are lots of ways to intercept calls into your existing monolith, even if you use different types of protocols. What if your monolith is driven by a batch file upload? Intercept the batch file, extract the calls that you want to intercept, and remove them from the file before you forward it on. True, some mechanisms make this process more complicated, and it’s much easier if using something like HTTP, but with some creative thinking the strangler fig pattern can be used in a surprising number of situations.

Other Examples of the Strangler Fig Pattern

The strangler fig pattern is highly useful in any context where you are looking to incrementally re-platform an existing system, and its use isn’t limited to teams implementing microservice architectures. The pattern was in use for a long time before Martin Fowler wrote it up in 2004. At my previous employer, ThoughtWorks, we often used it to help rebuild monolithic applications. Paul Hammant has authored a collated nonexhaustive list of projects where we used this pattern over on his blog. They include a trading company’s blotter, an airline booking application, a rail ticketing system, and a classified ad portal.

Changing Behavior While Migrating Functionality

Here and elsewhere in the book, I focus on patterns that I chose specifically because they can be used to incrementally migrate an existing system to a microservice architecture. One of the main reasons for this is it lets you mix in migration work with ongoing feature delivery. But there is still a problem that occurs when you want to change or enrich system behavior that is actively being migrated.

Imagine, for example, that we are going to make use of the strangler fig pattern to move our existing Payroll functionality out of the monolith. The strangler fig pattern allows us to do this in multiple steps, with each step theoretically allowing us to roll back. If we’d rolled out a new Payroll service to our customers and found an issue with it, we could divert calls to Payroll functionality back to the old system. This works well if the monolith and microservice Payroll functionality is functionally equivalent, but what if we’d changed how Payroll behaves as part of the migration?

If the Payroll microservice had a few bug fixes applied to how it works that hadn’t been back-ported to the equivalent functionality in the monolith, then a rollback would also cause those bugs to reappear in the system. This can get more problematic if you’d added new functionality to the Payroll microservice—a rollback would then require removing features from your customers.

There is no easy fix here. If you allow for changes in functionality you are moving before the migration is complete, then you have to accept that you are making any rollback harder. It’s easier if you don’t allow for any changes until the migration is complete. The longer the migration takes, the harder it can be to enforce a “feature freeze” in this part of the system—if there is a demand for part of your system to change, that demand is unlikely to go away. The longer it takes you to complete the migration, the more pressure you’ll be under to “just slip this feature in while you’re at it.” The smaller you make each migration, the less pressure you’ll be under to change the functionality being migrated before the migration has completed.

Caution

When migrating functionality, try to eliminate any changes in the behavior being moved—delay new features or bug fixes until the migration is complete if you can. Otherwise, you may reduce your ability to roll back changes to your system.

Pattern: UI Composition

With the techniques we’ve considered so far, we’ve primarily pushed the work of incremental migration to the server—but the user interface presents us with some useful opportunities to splice together functionality served in part from an existing monolith or new microservice architecture.

Many years ago, I was involved in helping move The Guardian online from its existing content management system over to a new, custom Java-based platform. This was going to coincide with the rollout of a whole new look and feel for the online newspaper to tie in with the relaunch of the print edition. As we wanted to embrace an incremental approach, the cut-over from the existing CMS to the new website served from the brand-new was phased in parts, targeting specific verticals (travel, news, culture, etc.). Even within those verticals, we also looked for opportunities to break the migration into smaller chunks.

We ended up using two compositional techniques that were useful. From speaking to other companies, it’s become clear to me over the past several years that variations on these techniques are a significant part of how many organizations adopt microservice architectures.

Example: Page Composition

With The Guardian , although we started by rolling out a single widget (which we’ll discuss shortly), the plan had always been to mostly use a page-based migration in order to allow a brand-new look and feel to go live. This was done on a vertical-by-vertical basis, with Travel being the first we sent live. Visitors to the website during this transition time would have been presented with a different look and feel when they went to the new parts of the site. Great pains were also taken to ensure that all old page links were redirected to the new locations (where URLs had changed).

When The Guardian made another change in technology, moving away from the Java monolith some years later, they again used a similar technique of migrating a vertical at a time. At this point, they made use of the Fastly content delivery network (CDN) to implement the new routing rules, effectively using the CDN much as you might use an in-house proxy. 3

REA Group in Australia, which provides online listings for real estate, has different teams responsible for commercial or residential listings, owning those whole channels. In such a situation, a page-based composition approach makes sense, as a team can own the whole end-to-end experience. REA actually employs subtly different branding for the different channels, which means that page-based decomposition makes even more sense as you can deliver quite different experiences to different customer groups.

Example: Widget Composition

At The Guardian , the Travel vertical was the first one identified to be migrated to the new platform. The rationale was partly that it had some interesting challenges around categorization, but also that it wasn’t the most high-profile part of the site. Basically, we were looking to get something live, learn from that experience, but also make sure that if something did go wrong, then it wouldn’t affect the prime parts of the site.

Rather than go live with the whole travel part of the website, replete with in-depth reportage of glamorous destinations all over the world, we wanted a much more low-key release to test out the system. Instead, we deployed a single widget displaying the top 10 travel destinations, defined using the new system. This widget was spliced into the newspaper’s old travel pages, as shown in Figure 3-19 . In our case, we made use of a technique called Edge-Side Includes (ESI), using Apache. With ESI, you define a template in your web page, and a web server splices in this content.

Apache interprets ESI statements in the page serviced from the old CMS and fetches and includes the widget from the new CMS.

Figure 3-19. Using Edge-Side Includes to splice in content from the new Guardian CMS

Nowadays, splicing in a widget purely on the server side seems less common. This is largely because browser-based technology has become more sophisticated, allowing for much more composition to be done in the browser itself (or in the native app—more on that later). This means for widget-based web UIs, the browser itself is often making multiple calls to load various widgets using a multitude of techniques. This has the further benefit that if one widget fails to load—perhaps because the backing service is unavailable—the other widgets can still be rendered, allowing for only a partial, rather than total, degradation of service.

Although in the end we mostly used page-based composition at The Guardian , many other companies make heavy use of widget-based composition with supporting backend services. Orbitz (now part of Expedia), for example, created dedicated services just to serve up a single widget. 4 Prior to its move to microservices, the Orbitz website was already broken into separate UI “modules” (in Orbitz nomenclature). These modules could represent a search form, booking form, map, etc. These UI modules were initially served directly from the Content Orchestration service, as we see in Figure 3-20 .

Before migration to microservices, Orbitz's Content Orchestration service served up all modules

Figure 3-20. Before migration to microservices, Orbitz’s Content Orchestration service served up all modules

The Content Orchestration service was in effect a large monolith. Teams that owned these modules all had to coordinate changes being made inside the monolith, causing significant delays in rolling out changes. This is a classic example of the Delivery Contention problem I highlighted in Chapter 1 —whenever teams have to coordinate to roll out a change, the cost of change goes up. As part of a drive toward faster release cycles, when Orbitz decided to try microservices, they focused their decomposition along these module lines—starting with the editorial module. The Content Orchestration service was changed to delegate responsibility for transitioned modules to downstream services, as we see in Figure 3-21 .

Modules were migrated one at a time, with the Content Orchestration Service delegating to the new backing services

Figure 3-21. Modules were migrated one at a time, with the Content Orchestration service delegating to the new backing services

The fact that the UI was already decomposed visually along these lines made this work easier to do in an incremental fashion. This transition was further helped as the separate modules already had clean lines of ownership, making it easier to perform migrations without interfering with other teams.

It’s worth noting that not all user interfaces suit decomposition into clean widgets—but when they can, it makes the work of incremental migration to microservices much easier.

And mobile applications

While we’ve spoken primarily about web-based UIs, some of these techniques can work well for mobile-based clients too. Both Android and iOS, for example, provide the ability to componentize parts of their user interfaces, making it easier for these parts of the UI to be worked on in isolation, or recombined in different ways.

One of the challenges with deploying changes with native mobile applications is that both the Apple App Store and Google Play store require applications to be submitted and vetted prior to new versions being made available. While the times for applications to be signed off by the app stores have in general reduced significantly over the last several years, this still adds time before new releases of software can be deployed. The app itself is also at this point a monolith: if you want to change one single part of a native mobile application, the whole application still needs to be deployed. You also have to consider the fact that users have to download the new app to see the new features—something you typically don’t have to deal with when using a web-based application, as changes are seamlessly delivered to the users’ browser.

Many organizations have dealt with this by allowing them to make dynamic changes to an existing native mobile application without having to resort to deploying a new version of a native application. By deploying changes on the server side, client devices can immediately see the new functionality without necessarily having to deploy a new version of the native mobile application. This can be achieved simply using things like embedded web views, although some companies use more sophisticated techniques .

Spotify’s UI across all platforms is heavily component-oriented, including its iOS and Android applications. Pretty much everything you see is a separate component, from a simple text header, to album artwork, or a playlist. 5 Some of these modules are, in turn, backed by one or more microservices. The configuration and layout of these UI components is defined in a declarative fashion on the server side; Spotify engineers are able to change the views that users see and roll that change quickly, without needing to submit new versions of their application to the app store. This allows them to much more rapidly experiment and try out new features.

Example: Micro Frontends

As bandwidth and the capability of web browsers have improved, so has the sophistication of the code running in browsers improved. Many web-based user interfaces now make use of some form of single-page application framework, which does away with the concept of an application consisting of different web pages. Instead, you have a more powerful user interface, where everything runs in a single pane—effectively in-browser user experiences that previously were available only to those of us working with “thick” UI SDKs like Java’s Swing.

By delivering an entire interface in a single page, we obviously can’t consider page-based composition, so we have to consider some form of widget-based composition. Attempts have been made to codify common widget formats for the web—most recently, the Web Components specification is attempting to define a standard component model supported across browsers. It has taken a long while, though, for this standard to gain any traction, with browser support (among other things) being a considerable stumbling block.

People making use of single-page app frameworks like Vue, Angular, or React haven’t sat around waiting for Web Components to solve their problems. Instead, many people have tried to tackle the problem of how to modularize UIs built with SDKs that were initially designed to own the whole browser pane. This has led to the push toward what some people have called Micro Frontends .

At first glance, Micro Frontends really are just about breaking down a user interface into different components that can be worked on independently. In that, they are nothing new—component-oriented software predates my birth by several years! What is more interesting is that people are working out how to make web browsers, SPA SDKs, and componentization work together. How exactly do you create a single UI out of bits of Vue and React without having their dependencies clash, but still allow them to potentially share information?

Covering this topic in depth is out of scope for this book, partly because the exact way you make this work will vary based on the SPA frameworks being used. But if you find yourself with a single-page application that you want to break apart, you’re not alone, and there are many people out there sharing techniques and libraries to make this work.

Where to Use It

UI composition as a technique to allow for re-platforming systems is highly effective, as it allows for whole vertical slices of functionality to be migrated. For it to work, though, you need to have the ability to change the existing user interface to allow for new functionality to be safely inserted. We’ll cover compositional techniques later in the book, but it’s worth noting that which techniques you can use will often depend on the nature of the technology used to implement the user interface. A good old-fashioned website makes UI composition easy, whereas single-page app technology does add some complexity and an often bewildering array of implementation approaches!

Pattern: Branch by Abstraction

For the useful strangler fig pattern , to work, we need to be able to intercept calls at the perimeter of our monolith. However, what happens if the functionality we want to extract is deeper inside our existing system? Coming back to a previous example, consider the desire to extract the Notification functionality, as seen in Figure 3-4 .

In order to perform this extraction, we will need to make changes to the existing system. These changes could be significant, and disruptive to other developers working on the codebase at the same time. We have competing tensions here. On the one hand, we want to make our changes in incremental steps. On the other hand, we want to reduce the disruption to other people working on other areas of the codebase. This will naturally drive us toward wanting to complete the work quickly.

Often, when reworking parts of an existing codebase, people will do that work on a separate source code branch. This allows the changes to be made without disrupting the work of other developers. The challenge is that once the change in the branch has been completed, these changes have to be merged back, which can often cause significant challenges. The longer the branch exists, the bigger these problems are. I won’t go into detail now as to the problems associated with long-lived source code branches, other than to say they run contrary to the principles of continuous integration. I could also throw in that data gathered from “The 2017 State of DevOps Report” shows that embracing trunk-based development (where changes are made directly on the main line and branches are avoided) and using short-lived branches contributes to higher performance of IT teams. Let’s just say that I am not a fan of long-lived branches, and I’m not alone.

So, we want to be able to make changes to our codebase in an incremental fashion, but also keep disruption to a minimum for developers working on other parts of our codebase. There is another pattern we can use that allows us to incrementally make changes to our monolith without resorting to source code branching. The branch by abstraction pattern instead relies on making changes to the existing codebase to allow the implementations to safely coexist alongside each other, in the same version of code, without causing too much disruption.

How It Works

Branch by abstraction consists of five steps:

  1. Create an abstraction for the functionality to be replaced.

  2. Change clients of the existing functionality to use the new abstraction.

  3. Create a new implementation of the abstraction with the reworked functionality. In our case, this new implementation will call out to our new microservice.

  4. Switch over the abstraction to use our new implementation.

  5. Clean up the abstraction and remove the old implementation.

Let’s take a look at these steps with respect to moving our Notification functionality out into a service, as detailed in Figure 3-4 .

Step 1: Create abstraction

The first task is to create an abstraction that represents the interactions between the code to be changed and the callers of that code, as we see in Figure 3-22 . If the existing Notification functionality is reasonably well factored, this could be as simple as applying an Extract Interface refactoring in our IDE. If not, you may need to extract a seam, as mentioned earlier. This might have you searching your codebase for calls being made to APIs that send emails, SMSs, or whatever other notification mechanism you might have. Finding this code and creating an abstraction that the other code uses is a required step.

A new abstraction is created for our existing functionality, but that abstraction is not yet used.

Figure 3-22. Step 1: Create an abstraction

Step 2: Use abstraction

With our abstraction created, we now need to refactor the existing clients of the Notification functionality to use this new abstraction point, as we see in Figure 3-23 . It’s possible that an Extract Interface refactoring could have done this for us automatically—but in my experience, it’s more common that this will need to be an incremental process, involving manually tracking inbound calls to the functionality in question. The nice thing here is that these changes are small and incremental; they’re easy to make in small steps without making too much impact on the existing code. At this point, there should be no functional change in system behavior.

Step 3: Create new implementation

With our new abstraction in place, we can now start work on our new service-calling implementation. Inside the monolith, our implementation of the Notification functionality will mostly just be a client calling out to the external service, as in Figure 3-24 —the bulk of the functionality will be in the service itself.

The key thing to understand at this point is that although we have two implementations of the abstraction in the codebase at the same time, only one implementation is currently active in the system. Until we’re happy that our new service-calling implementation is ready to send live, it is in effect dormant. While we work to implement all the equivalent functionality in our new service, our new implementation of the abstraction could return Not Implemented errors. This doesn’t stop us writing tests for the functionality we have written, of course, and this is one of the benefits of getting this work integrated as early as possible.

Incrementally, each client of the Notification functionality is refactored to use the new abstraction

Figure 3-23. Step 2: Change existing clients to use new abstraction

Create a new implementation of the abstraction

Figure 3-24. Step 3: Create a new implementation of the abstraction

During this process, we can also deploy our work-in-progress User Notification service into production, just as we did with the strangler fig pattern. The fact that it isn’t finished is fine—at this point, as our implementation of the Notifications abstraction isn’t live, the service isn’t actually being called. But we can deploy it, test it in situ, and verify the parts of the functionality we have implemented are working correctly.

This phase could last a significant amount of time. Jez Humble details the use of the branch by abstraction pattern to migrate the database persistence layer used in the continuous delivery application GoCD (at the time called Cruise). The switch from using iBatis to Hibernate lasted several months—during which the application was still being shipped to clients on a twice weekly basis.

Step 4: Switch implementation

Once we are happy that our new implementation is working correctly, we switch our abstraction point so that our new implementation is active, and the old functionality is no longer being used, as seen in Figure 3-25 .

The active implementation of our Notification functionality is switched over to use our new microservice

Figure 3-25. Step 4: Switch the active implementation to use our new microservice

Ideally, as with the strangler fig pattern, we’d want to use a switching mechanism that can be toggled easily. This allows us to quickly switch back to the old functionality if we found a problem with it. A common solution to this would be to use feature toggles. In Figure 3-26 , we see toggles being implemented using a configuration file, allowing us to change the implementation being used without having to change code. If you want to know more about feature toggles and how to implement them, then Pete Hodgson has an excellent write-up.

A configuration file being used to toggle which implementation of our notification functionality is currently active

Figure 3-26. Step 5: Using feature toggles to switch between implementations

At this stage, we have two implementations of the same abstraction, which we hope should be functionality equivalent. We can use tests to verify equivalency, but we also have the option here to use both implementations in production to provide additional verification. This idea is explored further in “Pattern: Parallel Run” .

Step 5: Clean up

With our new microservice now providing all notifications for our users, we can turn our attention to cleaning up after ourselves. At this point, our old User Notifications functionality is no longer being used, so an obvious step would be to remove it, as shown in Figure 3-27 . We are starting to shrink the monolith!

The old implementation is removed, leaving only our new service-calling implementation of Notification—although the abstraction is retained

Figure 3-27. Step 6: Remove the old implementation

When removing the old implementation, it would also make sense to remove any feature flag switching we may have implemented. One of the real problems associated with the use of feature flags is leaving old ones lying around—don’t do that! Remove flags you don’t need anymore to keep things simple.

Finally, with the old implementation gone, we have the option of removing the abstraction point itself, as in Figure 3-28 . It’s possible, however, that the creation of the abstraction may have improved the codebase to the point where you’d rather keep it in place. If it’s something as simple as an interface, retaining it will have minimal impact on the existing codebase.

The abstraction for Notifications is removed, leaving clients calling our service client directly

Figure 3-28. Step 7: (Optional) Remove the abstraction point

As a Fallback Mechanism

The ability for us to switch back to our previous implementation if our new service isn’t behaving is useful, but is there a way we could do that automatically? Steve Smith details a variation of the branch by abstraction pattern called verify branch by abstraction that also implements a live verification step—we can see an example of this in Figure 3-29 . The idea is that if calls to the new implementation fail, then the old implementation could be used instead.

Call the new implementation, and fallback to the old implementation if it fails

Figure 3-29. Verify branch by abstraction

This clearly adds some complexity, not only in terms of code but also in terms of reasoning about the system. Effectively, both implementations might be active at any given point in time, which can make understanding system behavior more difficult. If the two implementations are in anyway stateful, then we also have data consistency to consider. Although data consistency is a challenge in any situation where we are switching between implementations, The verify branch by abstraction pattern allows for us to switch back and forth between implementations on a request-by-request basis, which means you’ll need a consistent shared set of data that both implementations can access.

We’ll explore this idea in more detail in just a moment when we look at the more generic parallel run pattern.

Where to Use It

Branch by abstraction is a fairly general-purpose pattern, useful in any situation where changes to the existing codebase are likely going to take time to carry out, but where you want to avoid disrupting your colleagues too much. In my opinion, it is a better option than the use of long-lived code branches in nearly all circumstances.

For migration to a microservice architecture, I’d nearly always look to use a strangler fig pattern first, as it’s simpler in many regards. However, there are some situations, as with Notifications here, where that just isn’t possible.

This pattern also assumes that you can change the code of the existing system. If you can’t, for whatever reason, you may need to look at other options, some of which we explore in the rest of this chapter.

Pattern: Parallel Run

There is only so much testing you can do of your new implementation before you deploy it. You’ll do your best to ensure that your prerelease verification of your new microservice is done in as production-like a way as possible as part of a normal testing process, but we all understand that it isn’t always possible to think of every scenario that could occur in a production setting. But there are other techniques available to us.

Both the strangler fig pattern and branch by abstraction pattern allow old and new implementations of the same functionality to coexist in production at the same time. Typically, both of these techniques allow us to execute either the old implementation in the monolith or the new microservice-based solution. To mitigate the risk of switching over to the new service-based implementation, these techniques allow us to quickly switch back to the previous implementation.

When using a parallel run, rather than calling either the old or the new implementation, instead we call both , allowing us to compare the results to ensure they are equivalent. Despite calling both implementations, only one is considered the source of truth at any given time. Typically, the old implementation is considered the source of truth until the ongoing verification reveals that we can trust our new implementation.

This pattern has been used in different forms for decades, although typically it is used to run two systems in parallel. I’d argue this pattern can be just as useful within a single system, when comparing two implementations of the same functionality.

This technique can be used to verify not just that our new implementation is giving the same answers as the existing implementation, but that it is also operating within acceptable nonfunctional parameters. For example, is our new service responding quickly enough? Are we seeing too many time-outs?

Example: Comparing Credit Derivative Pricing

Many years ago, I was involved in a project to change the platform being used to perform calculations on a type of financial product called credit derivatives . The bank I was working at needed to make sure the various derivatives it was offering would be a sensible deal for them. Would we make money on this trade? Was the trade too risky? Once issued, market conditions would also change. So they also needed to assess the value of current trades to make sure they weren’t vulnerable to huge losses as market conditions changed. 6

We were almost entirely replacing the existing system that performed these important calculations. Because of the amount of money involved, and the fact that some people’s bonuses were based in part on the value of the trades that had been made, there was a great degree of concern over the changes. We made the decision to run the two sets of calculations side by side and carry out daily comparisons of the results. The pricing events were triggered via events, which were easy to duplicate such that both systems carried out the calculations, as we see in Figure 3-30 .

All pricing requests are sent to both the old system and the new system.

Figure 3-30. An example of a parallel run—both pricing systems are invoked, with the results compared offline

Each morning, we’d run a batch reconciliation of the results, and would then need to account for any variations in results. We actually wrote a program to perform the reconciliation. We presented the results in an Excel spreadsheet, making it easy to discuss the variations with the experts at the bank.

It turned out we did have a few issues that we had to fix, but we also found a larger number of discrepancies caused by bugs in the existing system. This meant that some of the different results were actually correct, but we had to show our work (made much easier due to surfacing the results in Excel). I remember having to sit down with analysts and explain why our results were correct by working things out from first principles.

Eventually, after a month, we switched over to using our system as the source of truth for the calculations, and some time later we retired the old system (we kept it around for a few more months in case we needed to carry out any auditing of calculations done on the old system).

Example: Homegate Listings

As we discussed earlier in “Example: FTP” , Homegate ran both its listing import systems in parallel, with the new microservice that handled list imports being compared against the existing monolith. A single FTP upload by a customer would cause both systems to be triggered. Once they had confirmed that the new microservice was behaving in an equivalent fashion, the FTP import was disabled in the old monolith.

N-Version Programming

It could be argued that a variation of parallel run exists in certain safety critical control systems, such as fly-by-wire aircraft. Rather than relying on mechanical controls, airliners increasingly rely on digital control systems. When a pilot uses the controls, rather than this pulling cables to control the rudder, instead fly-by-wire aircraft this sends inputs to control systems that decide how much to turn the rudder by. These control systems have to interpret the signals they are being sent and carry out the appropriate action.

Obviously, a bug in these control systems could be extremely dangerous. To offset the impact of defects, for some situations multiple implementations of the same functionality are used side by side. Signals are sent to all implementations of the same subsystem, which then send their response. These results are compared and the “correct” one selected, normally by looking for a quorum among the participants. This is a technique known as N-version programming . 7

The end goal with this approach is not to replace any of the implementations, unlike the other patterns we have looked at in this chapter. Instead, the alternative implementations will continue to exist alongside each other, with the alternative implementations hopefully reducing the impact of a bug in any one given subsystem.

Verification Techniques

With a parallel run, we want to compare functional equivalence of the two implementations. If we take the example of the credit derivative pricer from before, we can treat both versions as functions—given the same inputs, we expect the same outputs. But we also can (and should) validate the nonfunctional aspects, too. Calls made across network boundaries can introduce significant latency and can be the cause of lost requests due to time-outs, partitions, and the like. So our verification process should also extend to making sure that the calls to the new microservice complete in a timely manner, with an acceptable failure rate.

Using Spies

In the case of our previous notification example, we wouldn’t want to send an email to our customer twice. In that situation, a Spy could be handy. A pattern from unit testing, a Spy can stand in for a piece of functionality, and allows us to verify after the fact that certain things were done. The Spy stands in and replaces a piece of functionality, stubbing it out.

So for our Notification functionality, we could use a Spy to replace the low-level code that is used to actually send the email, as shown in Figure 3-31 . Our new Notifications service would then use this Spy during the parallel run phase to allow us to verify that this side effect (the sending of the email) would be triggered when the sendNotification call is received by the service.

Using a Spy to verify that emails would have been sent during a parallel run

Figure 3-31. Using a Spy to verify that emails would have been sent during a parallel run

Note that we could have decided to use the Spy inside the monolith, and avoid our RemoteNotification code ever making a service call. However this is likely not what you want, as you actually do want to take into account the impact of the remote calls being made—to understand if time-outs, failures, or general latency to our new Notifications service is causing us issues.

One added complexity here is the fact that our Spy is running in a separate process, which will complicate when the verification process could be carried out. If we wanted this to happen live, within the scope of the original request, we’d likely need to expose methods on the Notifications service to allow for verification to be carried out after the initial call is sent to our Notifications service. This could be a significant amount of work, and in many cases you don’t need live verification. A more likely model for verification of out-of-process spies would be to record the interactions to allow for the verification to be done out of band—perhaps on a daily basis. Obviously, if we did use the Spy to replace the call to the Notifications service, the verification gets easier, but we’re testing less! The more functionality you replace with a Spy, the less functionality is actually being tested.

GitHub Scientist

GitHub’s Scientist library is a notable library to help implement this pattern at a code level. It’s a Ruby library that allows you to run implementations side by side and capture information about the new implementation to help you understand if it is working properly. I’ve not used it myself, but I can see how having a library like this would really help in verifying your new microservice-based functionality against the existing system—ports now exist for multiple languages including Java, .NET, Python, Node.JS, and many more besides.

Dark Launching and Canary Releasing

It’s worth calling out that a parallel run is different from what is traditionally called canary releasing . A canary release involves directing some subset of your users to the new functionality, with the bulk of your users seeing the old implementation. The idea is that if the new system has a problem, then only a subset of requests are impacted. With a parallel run, we call both implementations.

Another related technique is called dark launching . With dark launching, you deploy the new functionality and test it, but the new functionality is invisible to your users. So a parallel run is a way of implementing dark launching, as the “new” functionality is in effect invisible to your users until you’ve switched over what system is live.

Dark launching, parallel runs, and canary releasing are techniques that can be used to verify that our new functionality is working correctly, and reduce the impact if this turns out not to be the case. All these techniques fall under the banner of what is called progressive delivery —an umbrella term coined by James Governor to describe methods to help control how software is rolled out to your users in a more nuanced fashion, allowing you to release software more quickly while validating its efficacy and reducing the impact of problems should they occur.

Where to Use It

Implementing a parallel run is rarely a trivial affair, and is typically reserved for those cases where the functionality being changed is considered to be high risk. We’ll examine an example of this pattern being used for medical records in Chapter 4 . I’d certainly be fairly selective about where I used this pattern—the work to implement this needs to be traded off against the benefits you gain. I’ve used this pattern myself only once or twice, but in those situations it has been hugely useful.

Pattern: Decorating Collaborator

What happens if you want to trigger some behavior based on something happening inside the monolith, but you are unable to change the monolith itself? The decorating collaborator pattern can help greatly here. The widely known decorator pattern allows you to attach new functionality to something without the underlying thing knowing anything about it. We are going to use a decorator to make it appear that our monolith is making calls to our services directly, even though we haven’t actually changed the underlying monolith.

Rather than intercepting these calls before they reach the monolith, we allow the call to go ahead as normal. Then, based on the result of this call, we can call out to our external microservices through whatever collaboration mechanism we choose. Let’s explore this idea in detail with an example from Music Corp.

Example: Loyalty Program

Music Corp is all about our customers! We want to add the ability for them to earn points based on orders being placed, but our current order placement functionality is complex enough that we’d rather not change it right now. So the order placement functionality will stay in the existing monolith, but we will use a proxy to intercept these calls, and based on the outcome decide how many points to deliver, as shown in Figure 3-32 .

When an order is placed successfully, our proxy calls out to the Loyalty service to add points for the customer

Figure 3-32. When an order is placed successfully, our proxy calls out to the Loyalty service to add points for the customer

With the strangler fig pattern, the proxy was fairly simplistic. Now our proxy is having to embody quite a few more “smarts.” It needs to make its own calls out to the new microservice and tunnel responses back to the customer. As before, keep an eye on complexity that sits in the proxy. The more code you start adding here, the more it ends up becoming a microservice in its own right, albeit a technical one, with all the challenges we’ve discussed previously.

Another potential challenge is that we need enough information from the inbound request to be able to make the call to the microservice. For example, if we want to reward points based on the value of the order, but the value of the order isn’t clear from either the Place Order request or response, we may need to look up additional information—perhaps calling back into the monolith to extract the required information as in Figure 3-33 .

When an order is placed successfully, our proxy calls out to the Loyalty Service to add points for the customer

Figure 3-33. Our Loyalty service needs to load additional order details to work out how many points to award

Given that this call could generate additional load, and arguably introduces a circular dependency, it might be better to change the monolith to provide the required information when order placement completes. This, though, would either require changing the code of the monolith, or else perhaps using a more invasive technique like change data capture.

Where to Use It

When kept simple, it is a more elegant and less coupled approach than change data capture. This pattern works best where the required information can be extracted from the inbound request, or the response back from the monolith. Where more information is required for the right calls to be made to your new service, the more complex and tangled this implementation ends up being. My gut feeling is that if the request and response to and from the monolith don’t contain the information you need, then think carefully before using this pattern.

Pattern: Change Data Capture

With change data capture , rather than trying to intercept and act on calls made into the monolith, we react to changes made in a datastore. For change data capture to work, the underlying capture system has to be coupled to the monolith’s datastore. That’s really an unavoidable challenge with this pattern.

Example: Issuing Loyalty Cards

We want to integrate some functionality to print out loyalty cards for our users when they sign up. At present, a loyalty account is created when a customer is enrolled. As we can see in Figure 3-34 , when enrollment returns from the monolith, we know only that the customer has been successfully enrolled. For us to print a card, we need more details about the customer. This makes inserting this behavior upstream, perhaps using a decorating collaborator, more difficult—at the point where the call returns, we’d need to make additional queries to the monolith to extract the other information we need, and that information may or may not be exposed via an API.

When enrolling a customer, we don't get enough information in response to know how to print their new card

Figure 3-34. Our monolith doesn’t share much information when a customer is enrolled

Instead, we decide to use change data capture. We detect any insertions into the LoyaltyAccount table, and on insertion, we make a call to our new Loyalty Card Printing service, as we see in Figure 3-35 . In this particular situation, we decide to fire a Loyalty Account Created event. Our printing process works best in batch, so this allows us to build up a list of printing to be done in our message broker.

When the monolith changes data in the database, we want to use change data capture to call our new service

Figure 3-35. How change data capture could be used to call our new printing service

Implementing Change Data Capture

We could use various techniques to implement change data capture, all of which have different trade-offs in terms of complexity, reliability, and timeliness. Let’s take a look at a couple of options.

Database triggers

Most relational databases allow you to trigger custom behavior when data is changed. Exactly how these triggers are defined, and what they can trigger varies, but all modern relational databases support these in one way or another. In the example in Figure 3-36 , our service is called whenever an INSERT is made into the LoyaltyAccount table.

After the new record is INSERTed into the loyalty_accounts table, our trigger fires, calling out to the Loyalty Card Printer service

Figure 3-36. Using a database trigger to call our microservice when data is inserted

Triggers need to be installed into the database itself, just like any other stored procedure. There may also be limitations as to what these triggers can do, although at least with Oracle they are quite happy for you to call web services or custom Java code.

At first glance, this can seem like quite a simple thing to do. No need to have any other software running, no need to introduce any new technology. However like stored procedures, database triggers can be a slippery slope.

A friend of mine, Randy Shoup, once said something along the lines of “Having one or two database triggers isn’t terrible. Building a whole system off them is a terrible idea.” And this is often the problem associated with database triggers. The more of them you have, the harder it can be to understand how your system actually works. The issue is often with the tooling and change management of database triggers—use too many, and your application can become some baroque edifice.

So if you’re going to use them, use them very sparingly.

Transaction log pollers

Inside most databases, certainly all mainstream transactional databases, there exists a transaction log. This is normally a file, into which is written a record of all the changes that have been made. For change data capture, the most sophisticated tooling tends to make use of this transaction log.

These systems run as a separate process, and their only interaction with the existing database is via this transaction log, as we see in Figure 3-37 . It’s worth noting here that only committed transactions will show up in the transaction log (which is sort of the point).

When changes are flushed to the transaction log, our call to the Loyalty Card Printer service is called

Figure 3-37. A change data capture system making use of the underlying transaction log

These tools will require an understanding of the underlying transaction log format, and this typically varies across different types of databases. As such, exactly what tools you’ll have available here will depend on what database you use. A huge array of tools exist in this space, although many of them are used to support data replication. There are also a number of solutions designed to map changes to the transaction log to messages to be placed onto a message broker; this could be very useful if your microservice is asynchronous in nature.

Restrictions aside, in many ways this is the neatest solution for implementing change data capture. The transaction log itself shows only changes to the underlying data, so you aren’t worried about working out what has changed. The tooling runs outside the database itself, and can run off a replica of the transaction log, so you have fewer concerns regarding coupling or contention.

Batch delta copier

Probably the most simplistic approach is to write a program that on a regular schedule scans the database in question for what data has changed, and copies this data to the destination. These jobs are often run using tools like cron or similar batch scheduling tools.

The main problem is working out what data has actually changed since the batch copier last ran. The schema design might make this obvious, or may not. Some databases allow you to view table metadata to see when parts of the database have changed, but this is far from universal, and may give you change timestamps at only the table level when you’d rather have information at a row level. You could start adding these timestamps yourself, but this could add significant work, and a change data capture system would handle this problem much more elegantly.

Where to Use It

Change data capture is a useful general-purpose pattern, especially if you need to replicate data (something we’ll explore more in Chapter 4 ). In the case of microservice migration, the sweet spot is where you need to react to a change in data in your monolith, but are unable to intercept this either at the perimeter of the system using a strangler or decorator, and cannot change the underlying codebase.

In general, I try to keep the use of this pattern to a minimum because of the challenges around some of the implementations of this pattern. Database triggers have their downsides, and the full-blown change data capture tools that work off transaction logs can add significant complexity to your solution. Nonetheless, if you understand these potential challenges, this can be a useful tool to have at your disposal.

Summary

As we’ve seen, a vast array of techniques allow for the incremental decomposition of existing codebases, and can help you ease into the world of microservices. In my experience, most folks end up using a mix of approaches; it’s rare that one single technique will handle every situation. Hopefully, what I’ve been able to do so far is give you a variety of approaches and enough information to work out which techniques may work best for you.

We have glossed over one of the bigger challenges in migrating to a microservice architecture—data. We can’t put it off any longer! In Chapter 4 , we’ll explore how to migrate data and break apart the databases.

1 For a more thorough explanation, see “The Road to an Envoy Service Mesh” by Snow Pettersen at Square’s developer blog.

2 Bobby Woolf and Gregor Hohpe, Enterprise Integration Patterns (Addison-Wesley, 2003).

3 It was nice to hear from Graham Tackley at The Guardian that the “new” system I initially helped implement lasted almost 10 years before being entirely replaced with the current architecture. As a reader of the website, I reflected that I never really noticed anything changing during this period!

4 See Steve Hoffman and Rick Fast, “Enabling Microservices at Orbitz” , YouTube, August 11, 2016.

5 See John Sundell, “Building Component-Driven UIs at Spotify” , published August 25, 2016.

6 Turned out we were terrible at this as an industry. I recommend Martin Lewis’s The Big Short (W. W. Norton & Company, 2010) as an excellent overview of the part that credit derivatives played in the global financial crisis of 2007–2008. I often look back at the small part I played in this industry with a great deal of regret. It turns out not knowing what you’re doing and doing it anyway can have some pretty disastrous implications.

7 See Liming Chen and Algirdas Avizienis, “N-Version Programming: A Fault-Tolerance Approach to Reliability of Software Operation,” published in the Twenty-Fifth International Symposium on Fault-Tolerant Computing (1995).