The Hardest Part About Microservices: Your Data
Microservices only work if we shed our dependencies — having multiple processes sitting on a single database is not microservices.
Join the DZone community and get the full member experience.Join For Free
continuing on with my series about microservices implementations (see " why microservices should be event driven ," " three things to make your microservices more resilient ," and " carving the java ee monolith: prefer verticals, not layers " for background) we're going to explore probably the hardest problem when creating and developing microservices. your data. using spring boot/dropwizard/docker doesn't mean you're doing microservices. taking a hard look at your domain and your data will help you get to microservices.
of the reasons we attempt a microservices architecture, chief among them is allowing your teams to be able to work on different parts of the system at different speeds with minimal impact across teams. so we want teams to be autonomous, capable of making decisions about how to best implement and operate their services, and free to make changes as quickly as the business may desire. if we have our teams organized to do this, then the reflection in our systems architecture will begin to evolve into something that looks like microservices.
to gain this autonomy, we need to "shed our dependencies," but that's a lot easier to say than do. i've seen folks refer to this idea in part, trivially, as "each microservice should own and control its own database and no two services should share a database." the idea is sound: don't share a single database across services because then you run into conflicts like competing read/write patterns, data-model conflicts, coordination challenges, etc. but a single database does afford us a lot of safeties and conveniences: acid transactions, single place to look, well-understood (kinda?), one place to manage, etc. so when building microservices, how do we reconcile these safeties with splitting up our database into multiple smaller databases?
let's see. first, for an "enterprise" building microservices, we need to make the following things clear:
- what is the domain? what is reality?
- where are the transactional boundaries?
- how should microservices communicate across boundaries?
- what if we just turn the database inside out?
what is the domain?
this seems to be ignored at a lot of places but is a huge difference between how internet companies practice microservices and how a traditional enterprise may (or may fail because of neglecting this) implement microservices.
before we can build a microservice, and reason about the data it uses (produces/consumes, etc), we need to have a reasonably good, crisp understanding about what that data is representing. for example, before we can store information into a database about "bookings" for our ticketmonster and its migration to microservices , we need to understand "what is a booking." just like in your domain, you may need to understand what is an account, or an employee, or a claim, etc.
to do that, we need to dig into what is "it" in reality? for example, "what is a book?" try to stop and think about that, as it's a fairly simple example. try to think what a book is. how would we express this in a data model?
is a book something with pages? is a newspaper a book? it has pages. so maybe a book has a hard cover? or is not something that's released/published every day? if i write a book (which i did — microservices for java developers ) the publisher may have an entry for me with a single row representing my book. but a bookstore may have 5 of my books. is each one a book? or are they copies? how would we represent this? what if a book is so long it has to be broken down into volumes? is each volume a book? or all of them combined a book? what if many small compositions are combined together? is the combination the book? or each individual one? so basically i can publish a book, have many copies of it in a bookstore, each one with multiple volumes. so what is a book then?
the reality is there is no reality. there is no objective definition of "what is a book" with respect to reality so to answer any question like that, we have to know "who's asking the question and what is the context." context is king. we as humans can quickly (and even unconsciously) resolve the ambiguity of this understanding because we have a context in our heads, in the environment, and in the question. but a computer doesn't. we need to make this context explicit when we build our software and model our data. using a book is to illustrate this is simplistic. your domain (an enterprise) with its accounts, customers, bookings, claims, etc. is going to be far more complicated and far more conflicting/ambiguous. we need boundaries.
where do we draw the boundaries? the work in the domain driven design community helps us deal with this complexity in the domain. we draw a bounded context around entities, value objects, and aggregates that model our domain. stated another way, we build and refine a model that represents our domain and that model is contained within a boundary that defines our context. and this is explicit. these boundaries end up being our microservices, or the components within the boundaries end up being microservices, or both. either way, microservices are about boundaries, and so is ddd.
our data model (how we wish to represent concepts in a physical data store — note the explicit difference here) is driven by our domain model, not the other way around. when we have this boundary, we know, and can make assertions about what is "correct" in our model and what is incorrect. these boundaries also imply a certain level of autonomy. bounded context "a" may have a different understanding of what a "book" is than bounded context "b" (e.g., maybe bounded context "a" is a search service that searches for titles where a single title is a "book"; maybe bounded context "b" is a checkout service that processes a transaction based on how many books (titles plus copies) you're buying, etc).
you may stop and say "wait a minute, netflix doesn't say anything about domain driven design, neither does twitter, nor linkedin. why should i listen to this about ddd?"
well here's why:
"people try to copy netflix, but they can only copy what they see. they copy the results, not the process" — adrian cockcroft, former netflix chief cloud architect
the journey to microservices is just that: a journey. it will be different for each company . there are no hard and fast rules, only tradeoffs. copying what works for one company just because it appears to work at this one instant is an attempt to skip the process/journey and will not work. and the point to make here is that your enterprise is not netflix. in fact, i'd argue that for however complex the domain is at netflix, it's not as complicated as it is at your legacy enterprise. searching for and showing movies, posting tweets, updating a linkedin profile, etc. are all a lot simpler than your insurance claims processing systems. these internet companies went to microservices because of the speed to market and the sheer volume/scale (posting a tweet to twitter is simple. posting tweets and displaying tweet streams for 500 million users is incredibly complex). enterprises today are going to have to confront complexity in both the domain as well as scale. so, accept the fact that this is a journey that balances domain, scale, and organizational changes . it will be different for each organization. don't ignore it.
what are the transactional boundaries?
back to the story. we need something like domain driven design to help us understand the models we'll use to implement our systems and draw boundaries around these models within a context. so, we accept that a customer, account, booking, etc. may mean different things to different bounded contexts, but at the end of the day, we may end up with these related concepts distributed around our architecture, and we need some way to reconcile changes across these different models when changes happen. we need to account for this, but first we need to identify our transactional boundaries.
unfortunately, we as developers still seem to approach building distributed systems all wrong: we still look through the lens of one, single, relational, acid database. we also ignore the perils of an asynchronous, unreliable network. to wit, we do things like write fancy frameworks that keep us from having to know anything about the network (including rpc frameworks — database abstractions that also ignore the network) and try to implement everything with point-to-point synchronous invocations (rest, soap, other corba like object serialization rpc libraries, etc.). we build systems without regard to authority vs. autonomy and end up trying to solve the distributed data problem with things like a two-phase commit across lots of independent services. or we ignore these concerns all together. this mindset leads to building very brittle systems that don't scale, and it doesn't matter if you call it soa, microservices, miniservices, whatever.
so what do i mean by transactional boundaries? i mean the smallest unit of atomicity that you need with respect to the business invariants. whether you use a database's acid properties to implement the atomicity or a two-phase commit, it doesn't really matter. the point is we want to make these transactional boundaries as small as possible (ideally a single transaction on a single object: vernon vaughn has a series of essays describing this approach with ddd aggregates ) so we can scale. when we build our domain model, using ddd terminology, we identify entities, value objects, and aggregates. aggregates in this context are objects that encapsulate other entities/value objects and are responsible for enforcing invariants (there can be multiple aggregates within a bounded context).
for example, let's say we have the following use cases:
- "allow customers to search for flights."
- "allow a customer to pick a seat on a particular flight."
- "allow customer to book a flight."
we'd probably have three bounded contexts here: search, booking, and ticketing (we'd likely have lots more like payments, loyalty, standby, upgrades, etc. but we'll keep it narrowed to these three). search is responsible for showing flights for specific routes and itineraries for a given time frame (range of days, times, etc.). booking will be responsible for teeing up the booking process with customer information (name, address, frequent flyer number, etc.), seat preferences, and payment information. ticketing would be responsible for actually settling the reservations with the airline and issuing a ticket. within each bounded context, we want to identify transactional boundaries where we can enforce constraints/invariants. we will not consider atomic transactions across bounded contexts (we'll discuss this in the next section).
how would we model this considering we want small transaction boundaries (this is a very simplified version of booking a flight, by the way)? maybe a flight aggregate that encapsulates values like time, date, route, and entities like customers, planes, and bookings? this seems to make sense: a flight has a plane, seats, customers, and bookings. the flight aggregate is responsible for keeping track of planes, seats, etc. for the purposes of creating bookings. this may make some sense from a data model standpoint inside of a database (nice relational model with constraints and foreign keys, etc.), or make a nice object model (inheritance/composition) in our source code, but let's look at what happens.
are there really invariants across all bookings, planes, flights, etc. just to create a booking? that is, if we add a new plane to the flight aggregate, should we really include customers and bookings in that transaction? probably not. what we have here is an aggregate built with compositional and data model conveniences in mind. however, the transactional boundaries are too big. if we have lots of changes to flights, seats, bookings, etc., we'll have a lot of transactional conflicts (whether using optimistic or pessimistic locking won't matter). and that obviously doesn't scale (never mind failing orders all the time just because a flight schedule is changing being a terrible customer experience).
what if we broke the transactional boundaries a little smaller.
maybe booking, seatavailability, and flights are their own independent aggregates. a booking encapsulates customer information, preferences, and maybe payment information. the seatavailability aggregate encapsulates planes and plane configurations. the flights aggregate is made up of schedules, routes, etc., but we can proceed with creating bookings without impacting transactions on flight schedules and planes/seatavailability. from a domain perspective, we want to be able to do that. we don't need 100% strict consistency across planes/flights/bookings, but we do want to correctly record flight schedule changes as an admin, plane configurations as a vendor, and bookings from customers. so how do we implement things like "pick a particular seat" on a flight?
during the booking process, we may call into the seatavailability aggregate and ask it to reserve a seat on a plane. this seat reservation would be implemented as a single transaction, for example, (hold seat 23a) and return a reservation id. we can associate this reservation id with the booking and submit the booking knowing the seat was at one point "reserved." each of these (reserve a seat, and accept a booking) are individual transactions and can each proceed independently without any kind of two-phase commit or two-phase locking.
note that using a "reservation" here is a business requirement. we don't do seat assignment here, we just reserve the seat. this requirement would need to be fettered out potentially through iterations of the model because the language for the use case at first may simply say "allow a customer to pick a seat." a developer could try to infer that the requirement means "pick from the remaining seats, assign this to the customer, remove it from inventory, and don't sell more tickets than seats." this would be extra, unnecessary invariants that would add additional burden to our transactional model which the business doesn't really hold as an invariant. the business is certainly okay taking bookings without complete seat assignments and even overselling the flight.
this is an example of allowing the true domain guide you toward smaller, simplified, yet fully atomic transactional boundaries for the individual aggregates involved. but the story cannot end here because we now have to rectify the fact that there are all these individual transactions that need to come together at some point. different parts of the data are involved (i.e., i created a booking and seat reservations, but these are not settled transactions with regard to getting a boarding pass/ticket, etc.).
how should microservices communicate across boundaries?
we want to keep the true business invariants in tact. with ddd, we may choose to model these invariants as aggregates and enforce them using single transactions for an aggregate. there may be cases where we're updating multi-aggregates in a single transaction (across a single database or multiple databases) but those scenarios would be the exception. we still need to maintain some form of consistency between aggregates (and eventually between bounded contexts), so how should we do this?
one thing we should understand is that distributed systems are finicky. there are very few guarantees if any we can make about anything in a distributed system in bounded time (things will fail, things are non-deterministically slow or appear to have failed, systems have non-synchronized time boundaries, etc.), so why try to fight it? what if we embrace this and bake it into our consistency models across our domain? what if we say "between our necessary transactional boundaries we can live with other parts of our data and domain to be reconciled and made consistent at some later point in time?"
as we've been saying, we value autonomy for microservices. we value being able to make changes independent of other systems (in terms of availability, protocol, format, etc.). this decoupling of time and any guarantees about anything between services in any bounded time allows us to truly achieve this sort of autonomy ( this is not unique to computer systems… or any systems for that matter ).
so i say, between transaction boundaries and between bounded contexts, use events to communicate consistency. events are immutable structures that capture an interesting point in time that should be broadcast to peers. peers will listen to the events in which they're interested and make decisions based on that data, store that data, store some derivative of that data, update their own data based on some decision made with that data, etc.
continuing the flight booking example i somehow started (instead of using my ticketmonster example. that's what happens when i start writing!), when a booking is stored via an acid-style transaction, how do we end up ticketing that?
that's where the aforementioned ticketing bounded context comes in. the booking bounded context would publish an event like "newbookingcreated" and the ticketing bounded context would consume that event and proceed to interact with the backend (potentially legacy) ticketing systems. this obviously requires some kind of integration and data transformation, which something apache camel would be great at. it also brings up some other questions. how do we do a write to our database and publish to a queue/messaging appliance atomically? and what if we have ordering requirements/causal requirements between our events? and what about one database per service?
ideally our aggregates would use commands and domain events directly (as a first class citizen — that is, any operation is implemented as commands, and any response is implemented as reacting to events) and we could more cleanly map between the events we use internal to our bounded context and those we use between contexts.
we could just publish events (ie, newbookingcreated) to a messaging queue and then have a listener consume this from the queue and insert it idempotently into the database without having to use xa/2pc transactions instead of inserting into the database ourselves. we could insert the event into an dedicated event store that acts like both a database and a messaging publish-subscribe topic (this is probably the preferred route). or you can just continue to use an acid database and stream changes to that database to a persistent, replicated log like apache kafka using something like debezium and deduce the events using some kind of event processor/steam processor. either way, the point is we want to communicate between boundaries with immutable point in time events.
this comes with some great advantages:
- we avoid expensive, potentially impossible transaction models across boundaries.
- we can make changes to our system without impeding progress of other parts of the system (timing and availability).
- we can decide how quickly or slowly we want to see the rest of the outside world and become eventually consistent.
- we can store the data in our own databases however we'd like using the technology appropriate for our service.
- we can make changes to our schema/databases at our leisure.
- we become much more scalable, fault tolerant, and flexible.
- you have to pay even more attention to cap theorem and the technologies you chose to implement your storage/queues.
notably, this comes with disadvantages:
- it's more complicated.
- difficult to debug.
- since you have a delay when seeing events, you cannot make any assumptions about what other systems know (which you cannot do anyway, but it's more pronounced in this model).
- more difficult to operationalize.
- you have to pay even more attention to cap theorem and the technologies you chose to implement your storage/queues.
i listed "paying attention to cap, et al" in both columns because although it places a bit more of a burden on you, it's imperative that you do so anyway! it's imperative that we always pay attention to the different forms of data consistency and concurrency in our distributed data systems! relying on "our database in acid" is no longer acceptable (especially when that acid database most likely defaults to some weak consistency anyway. so much for your acid properties).
another interesting concept that emerges from this approach is the ability to implement a pattern known as "command query separation responsibility," where we separate our read model and our write models into separate services. remember, we lamented that internet companies don't have very complex domain models. this is evident in their write models being simple ( insert a tweet into a distributed log , for example).
however, their read models are crazy complicated because of their scale. cqrs helps separate these concerns. on the flip side, in an enterprise, the write models might be incredibly complicated while the read models may be simple flat select queries and flat dto objects. cqrs is a powerful separation of concerns pattern to evaluate once you've got proper boundaries and a good way to propogate data changes between aggregates and between bounded contexts.
so what about a service has only one database and doesn't share with any other service? in this scenario, we may have listeners that subscribe to the stream of events and may insert data into a shared database that the primary aggregates might end up using. this "shared database" is perfectly fine. remember, there are no rules, just tradeoffs. in this instance we may have multiple services working in concert together with the same database and so long as we (our team) owns all the processes, we don't negate any of our advantages of autonomy. thusly when you hear someone say "a microservice should have its own database and not share it with anything else" you can respond "well, kinda."
what if we take the concepts in the previous section to its logical extreme? what if we just say we'll use events/streams for everything and also persist these events forever? what if we say databases/caches/indexes are really just materialized views of a persistent log/stream of events that happened in the past, and the current state is a left fold over all of those events?
this approach brings even more benefits that you can add to the benefits of communicating via events (listed above):
- now you can treat your database as a "current state" of record, not the true record.
- you can introduce new applications and re-read the past events and examine their behaviors in terms of "what would have happened."
- you can perfect audit logging for free.
- you can introduce new versions of your application and perform quite exhaustive testing on it by replaying the events.
- you can more easily reason about database versioning/upgrades/schema changes by just replaying the events into the new database.
- you can migrate to completely new database technology (i.e., maybe you find you've outgrown your relational database and you want to switch to a specialized database/index).
for more information on this, take a look at martin kleppmann's talk/blog post titled " turning the database inside-out with apache samza ."
when you book a flight on aa.com, delta.com, or united.com, you're seeing some of these concepts in action. when you choose a seat, you don't actual get assigned it, you reserve it. when you book your flight, you don't actually have a ticket. you get an email later telling you you've been confirmed/ticketed. have you ever had a plane change and be assigned a different seat for the actual flight? or been to the gate and heard them ask for volunteers to give up their seat because they oversold the flight? these are all examples of transactional boundaries, eventual consistency, compensating transactions, and even apologies at work.
moral of the story
the moral of the story here is that data, data integration, data boundaries, enterprise usage patterns, distributed systems theory, timing, etc., are all the hard parts of microservices (because microservices are really just distributed systems!). i'm seeing too much confusion around technology ("if i use spring boot, i'm doing microservices," "i need to solve service discovery and load balancing in the cloud before i can do microservices," "i must have a single database per microservice") and useless "rules" regarding microservices. don't worry. once the big vendors have come and sold you all the fancy suites of products (mmm… soa ring a bell?), you'll still be left to do the hard parts listed above.
Published at DZone with permission of Christian Posta, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.