Low-Risk Monolith to Microservice Evolution: Part I
Check out this detailed explanation and guide to a low-risk move from a monolith to a distributed system of microservices.
Join the DZone community and get the full member experience.Join For Free
as part of a two-day microservices workshop i'm putting together, i've been thinking a lot about how to explain monolith-application decomposition and what a transition to microservices might look like. this is a small subset of that material, but i want to share with you to get feedback (in the workshop we go into more detail about whether you should even break up your monolith!). this is based on my own tried and true real-life experience as well as my work with the many red hat customers i've met over north america for the last few years. part i explores the architecture while the second part (to be released shortly) will cover some technology that can greatly help in this area. follow along ( @christianposta ) on twitter or http://blog.christianposta.com for the latest updates and discussion.
before we dig in, let's set up some assumptions.
- microservices architecture is not appropriate all the time (to be discussed in length)
- if we find we should go to a microservices architecture, we have to decide what happens with the monolith
- in rare cases, we'll want to break out parts of the monolith as is; in most other cases we'll want to either build new features or re-implement existing business processes around the monolith (in a strangler fashion)
- in the cases where we need to break out functionality or re-implement, we cannot ignore the fact the monolith is currently in production taking load and probably bringing lots of business value
- we need a way to attack this problem with very little disruption to the overall business value of the system
- since the monolith is the monolith, it will be very difficult / nearly impossible to make changes to the data model / database underneath it
- the approach we take should reduce the risk of the evolution and may take multiple deployments and releases to make it all happen
if you dig into the conference/blog posts this topic, often times you'll find it offers these words of advice:
- organize around nouns
- do one thing and one thing well
- single responsibility principle
- it's hard
i'm afraid this advice is quite useless.
the more useful material discusses an approach that at times look something like this:
- identify modules (either existing or new ones to write)
- break out tables that correspond to those modules and wrap with a service
- update the code that once relied on the db tables directly to call this new service
- rinse and repeat
let's take a closer look:
step 1: identify modules
you start off with some nasty monolith. in the image above i've simplified this to denote the different modules and database tables that may be involved here. we identify which modules we wish to break out of the monolith and figure out which tables are involved and then go from there. of course, the reality is monoliths are far more entangled with modules conflated with each other (if any modules). more on that in a bit.
the next step is to identify which tables are used by the
module and break those out into its own service. this service is now the only thing that can access those foo tables. no more sharing tables! this is a good thing. and anything that once did refer to
must now go through the api of the newly created service. in the above image, we update the
service to now refer to
service whenever it needs
step 3: rinse and repeat
the last step is to repeat this effort until you're left with no more monolith. in the above image, we've done the same thing for the
service and you can see that we're moving to an architecture where services own their data and expose apis - sounding similar to what we hear about microservices.
while this approach is generally a decent set of guidelines, it misses a lot of the fidelity that we really need when going down this path . for example, this approach glosses over the fact that we cannot just stop the world to remove tables from databases. also:
- rarely do monoliths lend themselves to nice and neat modularization
- the relationships between tables can be highly normalized and exhibit tight coupling/integrity constraints among entities
- we may not fully understand what code in the monolith uses which tables
- just because we've extracted tables to a new service doesn't mean the existing business processes stop so we can migrate everyone to use the service
- there will be some ugly migration steps that cannot just be wished away
- there is probably a point of diminishing returns where it doesn't make sense to break things out of the monolith
- etc, etc.
let's take a look at a concrete example and what the approach/pattern would look like and the options we may have as we go.
this example comes from the aforementioned workshop. i'll be adding some color around the splitting of the services, but there are more detailed guidelines around domain driven design, coupling models, and physical/logical architecture that we go into for the workshop that we'll leave out for now. this approach on the surface appears to deal with decomposition of existing monolith functionality but applies equally well to adding new functionality around the monolith; this may be the more likely case since making changes to the monolith can be quite risky.
meet the monolith
this is the
that we'll be exploring. it's based on the
. that tutorial explores building a typical java ee application and ends up being a good example: it's not too overly complicated but has enough meat to it we can use it to illustrate key points. in part two of this blog post we'll actually go deeper into the technology frameworks/platforms.
from this image, we're illustrating that the
has all modules/components/ui co-deployed talking to a single monlithic database. whenever we need to make a change, we need to deploy all of it. you can imagine for a moment that the application is 10+ yrs old and is now very difficult to change (for all the technical reasons but also team/organization structure reasons). we would like to break out the ui and key services that will allow the business to make changes faster and independently from each other to experiment with delivering new customer/and/or/business value.
- monolith (code and database schema) is hard to change.
- changes require complete re-deployment and high coordination between teams.
- we need to have lots of tests in place to catch regressions.
- we need a fully automated way to deploy.
extract the ui
in this step, we're going to decouple the
. actually in this architecture, we don't actually remove anything from the
. we start to reduce risk by just adding a new deployment which contains the ui. the new ui component in this architecture should be very close to the same ui (exactly?) that's in the
and just calls back to the
's rest api... of course this implies the monolith has a reasonable api that an external ui could use. we may very well find that this is not the case: typically this type of api may resemble more of an "internal" api at which point we'd need to think about some integration between the separate ui component and the backend monolith and what a more consumable public-facing api might look like.
we can deploy this new
component into our architecture and use our platform to slowly route traffic to it while still routing to the old monolith. this way we can introduce it without taking downtime. again, in the second part of the blog post we'll see how to do this in more detail; however the concept of dark launch/canary release/rolling release are all very important here (and for subsequent steps).
- don't modify the monolith for this first step; just copy/past ui into separate component
- we need to have a reasonable remoting api between the ui and monolith - this may not always be the case
- security surface increases
- we need a way to route/split traffic in a controlled manner to the new ui and/or the monolith directly to support dark launch/canary/rolling release
drop the ui from the monolith
in the previous step, we introduced a
and slowly rolled over traffic to the new
(which communicated directly with the
). in this step we do a similar deployment strategy, except now we slowly release a new deployment of the monolith with the ui removed. we can slowly bleed traffic over and slop/rollback if we see issues. once we have all traffic going to our monolith without the ui (termed
from here on) we can remove the
deployment completely. by separating out the ui, we've now made a small decomposition to our monolith and reduced our risk by relying on dark launches/canaries/rolling releases.
- we are removing the ui component from the monolith.
- this requires (hopefully) minimal changes to the monolith (deprecating/removing/disabling the ui).
- again we use a controlled routing/shaping approach to introduce this change without downtime.
introduce a new service
in the next step, and skipping the detail of coupling, domain driven design, etc. we're introducing a new service: the
service. this is a critical service that the business wants to change more frequently than the rest of the application and has a fairly complicated write model. we may also explore architectural patterns like cqrs with this model, but i digress.
we want to focus on the boundary and api of the
service in terms of the existing implementation in the
. in reality, this implementation is more likely to be a re-write than a port of existing code, but the idea/approach here is the same either way. notice in this architecture, the
service has its own database. this is good; we're shooting for a complete decoupling - however we're not there yet. there are a few more steps we need to consider/undertake.
this step would also be a good time to consider how this service plays in the overall service architecture by focusing on the events it may emit or consume. now is a great time to do an activity like event storming and think through the events we should publish as we start to take transactional workloads. these events will come in handy when we try to integrate with other systems and even as we evolve the monolith.
- we want to focus on the api design/boundary of our extracted service
- this may be a re-write from what exists in the monolith
- once we have the api decided, we will implement a simple scaffolding/placeholder for the service
- the new orders service will have its own database
- the new orders service will not be taking any kind of traffic at this point
connect the api with an implementation
at this point, we should be continuing to evolve the service's api and domain model and how it's implemented in code. this service will store any new transactional workloads into its own database and keep it separate from any other services. services needing access to this data would have to go through an api.
one thing we will not be able to ignore: our new service and its data is intimately related (if not exactly the same in some areas) to the data in the monolith. this is highly inconvenient, actually. as we start to build the new service, we'll need existing data from the
service's database. this could get really tricky because of the normalization/fk constraints/relationships in the data model. re-using an existing api on the monolith/backend may be too coarse grained and we'd have to re-invent a lot of gymnastics to get the data in the shape we want.
what we want to do is get access to the data from the
in read-only mode through a lower-level api and have a way to shape the data/data-model into the model that fits better with the domain model in our new service. in this architecture, we're going to temporarily connect up to the
database directly and query the data directly as we need. for this step, we do need a consistency model that reflects a direct database access.
some of you may cringe initially at this approach. and you should. however, the plain fact is this approach is totally valid and has been used successfully in highly critical systems - and more importantly - is not the end-state architecture (if you think this may end up being end-state architecture, just stop and do not do this). you may also point out that connecting up to the
database, querying data, and massaging into the right shape we need for our new service's domain model involves a lot of nasty integration/boiler plate. i'd argue since this is temporary in our evolution of the monolith, it's probably okay: ie, use technical debt to your advantage and then quickly pay it down. however, there is a better way. i'll discuss this in part 2 of this blog post.
alternatively, some of you might be saying "well, just stand up a rest api in front of the
database that gives lower-level data access and have the new service call that". this is also a viable approach but not without its own drawbacks. again, will discuss this in more detail in part 2.
- the extracted/new service has a data model that has tight coupling with the monolith's data model by definition.
- the monolith most likely does not provide an api at the right level to get this data.
- shaping the data even if we do get it requires lots of boilerplate code.
- we can connect directly to the backend database temporarily for read-only queries.
- the monolith rarely (if ever) changes its database.
start sending shadow traffic to the new service (dark launch)
in our next step of this approach/pattern, we need a way to actually direct traffic to our new service. the key thing here, however, is we don't want to do a big-bang release. we don't want to just throw this into our production traffic (especially considering that this example uses an "order" service which takes orders! we don't want to introduce any issues with taking orders!). although we cannot easily change the underlying monolith database, if there's hope, you may be able to carefully make changes to the monolith application to call our new orders service. i highly recommend michael feather's "working effectively with legacy code" if you're unsure of how best to do this. there are patterns like the sprout method/class and/or wrap method/class that could help here.
when we make a change to our monolith/backend, we don't want to replace the old code path. we want to put in just enough code to allow both the old or the new code path to run, potentially even in parallel, as deemed fit. ideally, the new version of the monolith with this change will allow us to, at runtime, control whether we're sending to the new orders service, the old monolith code path, or both. in any combination of call paths, we want to instrument heavily to understand any potential deviations between the old and new execution path.
another thing to note. if we enable the monolith to send the execution to both the old code path as well as calling our new service, we need a way to flag this transaction/call to the new service as a "synthetic" call. if your new service is less critical than in this example, an order service, and you can deal with duplicates, then maybe this synthetic-request identification is less important. if your new service tends to serve more read-only traffic, again you may not worry as much about identifying synthetic transactions. in the case of a synthetic transaction, however, you want to be able to run the entire service end-to-end including storing into the database. you may take options here to either store the data with a "synthetic" flag or just rollback the transaction if your data store supports that.
the last thing to note here is when we make our change to the monolith/backend, we want to again use a dark launch/canary/rolling release approach. we will need our infrastructure to support this. we will look closer at this in the second part.
at this point, we're forcing the traffic back through the monolith. we're trying not to perturb the main call flow as much as possible so we can quickly roll back in the event a canary doesn't go well. on the other hand, it may be useful to deploy a gateway/control component that can more fine-grain control the call to the new service instead of forcing to the monolith. in this case, the gateway would have the control logic whether to send the transaction to the monolith, to the new service, or both.
- introducing the new orders service into the code path introduces risk.
- we need to send traffic to the new service in a controlled manner.
- we want to be able to direct traffic to the new service as well as the old code path.
- we need to instrument and monitor the impact of the new service.
- we need ways to flag transactions as "synthetic" so we don't end up in nasty business-consistency problems.
- we wish to deploy this new functionality to certain cohorts/groups/users.
canary/rolling release to the new service
if we find that the previous step does not introduce negative impacts to our transaction path and we have high confidence through our testing and initial experimentation in production with shadowing the traffic, we can now configure the monolith to not shadow and actually send traffic over to the new service. in this case, we need to be able to specify certain cohorts/groups/users to always go to the new service. in this case, we're slowly draining the real production traffic that goes through the old code path. we can increase the rolling release of our
service until all of our users are on the new orders microservice.
one point of risk we need to make concrete: once we start rolling live traffic (non-shadow/synthetic traffic) over to the new service, we're expecting users that match the cohort group to always be going to this new service. we're not able to switch back and forth between old and new code paths. in this case, if we do need to rollback, this will involve more coordination to move any new transactions from the new service back to a state that the old monolith could use. hopefully, this doesn't happen, but is something to note and plan for (and test!).
- we can identify cohort groups and send live transaction traffic to our new microservice.
- we still need the direct database connection to the monolith because there will be a period of time where transactions will still be going to both code paths.
- once we've moved all traffic over to our microservice, we should be in position to retire the old functionality.
- note that once we're sending live traffic over to the new service, we have to consider the fact a rollback to the old code path will involve some difficulty and coordination.
offline data etl/migration
at this point we should have our
microservice taking live production traffic. the
is still around handling other concerns, but we have successfully migrated service functionality out of the monolith. our immediate pressing concern now is to pay off the technical debt we've borrowed when we created a direct database connection between our new microservice and the
service. most likely this would involve some kind of one-time etl from the monolith database to the new service. the monolith may be required to still keep that data around in a read-only mode (think: regulatory compliance, etc). if this is shared reference data (i.e., read-only) this should be okay. we must make sure that the data in the monolith and the data in the new microservice is not some shared mutable data. if the data is shared/mutable then we can end up in divergent data/data ownership problems.
ordersmicroservice is now in the last throws of becoming fully autonomous.
we need to pay down the technical debt we borrowed when we connected the
ordersservice database to the
we will have a one-time etl for the data that should reside in the
- we need to be mindful of divergent data problems.
disconnect/decouple the datastores
once we've completed the previous step, we should have our new
microservice independent and ready to participate in a services architecture. the steps presented here all have their own considerations, pros, and cons. we should aim to satisfy all of the steps and not leave technical debt to accrue interest. of course, there will be variations on this pattern, but the approach is sound.
in the next blog post, i'll show how to do these steps with the example service i've referred to previously and dig deeper into some of the tools, frameworks, and infrastructure that helps assist. we'll look at things like kubernetes , istio , feature-flag frameworks, data-view tools, and test frameworks. stay tuned!
Published at DZone with permission of Christian Posta, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.