Image

How do you make an architecture easier to change? Business is changing faster than ever, and software architectures need to keep up. In this chapter you’ll learn how to create a flexible architecture that can change as your business changes, scale as your business grows, and remain operational even when system failures occur. Intrigued? We hope so, because in this chapter we’re going to show you microservices —an architectural style that solves all of these problems and more. Let’s get started on our journey through microservices, bit by bit.

Are you feeling okay?

StayHealthy, Inc., is a company that specializes in medical monitoring systems for patients in hospitals. Using its systems, doctors and nurses can monitor a patient’s heart rate, oxygen levels, body temperature, blood sugar levels, and more, and even determine whether the patient is sleeping or awake. If something goes wrong, a doctor or nurse is notified right away.

Recent advances in medicine have given rise to a new set of needs for medical monitoring. As a result, StayHealthy plans to leverage newer technology to replace its current patient medical monitoring software with a new system called MonitorMe. Guess what? You’re the architect they chose for the new project.

Below are the requirements for the new system. You’ll need to figure out what kind of architecture would be best suited for the job.

Image

StayHealthy MonitorMe requirements document

  • □ The system reads inputs from StayHealthy’s patient monitoring equipment and sends the results to a single monitoring screen.

  • □ MonitorMe must analyze each patient’s vital signs and alert a medical professional if it detects a change that reaches a preset threshold.

  • □ For each vital sign, the system must record all readings and measurements for the past five minutes. A medical professional should be able to review this five-minute history.

  • □ Medical professionals select how they’d like to be notified if something goes wrong. Notifications can be sent to an assigned nurse or doctor’s cell phone or to a central nurses’ station.

  • □ MonitorMe reads inputs from eight different input sources. It is vital that if any of these fails, the other inputs will still be monitored and recorded.

  • □ The vital signs monitored by the MonitorMe system include heart rate, blood pressure, oxygen level, blood sugar, respiration rate, electrocardiogram (ECG), body temperature, and sleep status (sleep or awake).

  • □ The system can measure the vital signs of multiple patients (up to 500) within a single hospital, meaning each physical hospital location has its own copy of the complete system (including the data).

Sharpen your pencil

Image

Based on the problem domain and requirements document on the previous page, check off the top five architectural characteristics you think are critical to the MonitorMe architecture and indicate why you think they are critical.

Image

Testability (the ease and completeness of testing)

Reason: _________________________________________________

Image

Responsiveness (the time it takes to get a response to the medical professional)

Reason: _________________________________________________

Image

Deployability (the difficulty and ceremony involved in releasing changes)

Reason: _________________________________________________

Image

Abstraction (the level of isolation and knowledge between parts of the system)

Reason: _________________________________________________

Image

Scalability (the system’s ability to grow to accommodate more users or patients)

Reason: _________________________________________________

Image

Fault tolerance (the system’s ability to continue operating when parts of the system fail)

Reason: _________________________________________________

Image

Data integrity (the data is consistent and correct across the system and there is no data loss)

Reason: _________________________________________________

Image

Workflow (the system’s ability to handle complex business workflows)

Reason: _________________________________________________

Image

Concurrency (the system’s ability to process concurrent requests or operations)

Reason: _________________________________________________

Image Solution in “Sharpen your pencil Solution”

Cubicle conversation

Image

Sam: I think we can all agree that microservices is a perfect fit for the new MonitorMe system.

Mara: Hold on—what brought you to that conclusion so quickly?

Sam: It’s obvious, isn’t it? From a domain perspective, we have independent monitoring functions, and we need high fault tolerance and comprehensive testability. Microservices does all this and more.

Note

Assumptions like this are a common trap. We’ll show you how to avoid it by better understanding the microservices architectural style and its trade-offs.

Alex: Slow down a second. I’m not familiar with microservices, and I have no idea how it supports all the things you say it does.

Mara: I agree with Alex. I know that we need a distributed architecture, so microservices might be a fit here. But let’s back up and take a closer look before we jump to any conclusions.

Sam: Okay, I see your point—what might seem obvious to me might not be obvious to you. It’s important that you both understand what microservices is all about, and then together we can decide if it’s the right fit for MonitorMe. So let’s get started.

What’s a microservice?

What’s in a name? When it comes to microservices, plenty. We’ll show you what a microservice is and how it differs from other types of services.

Generally, a service is a separately deployed unit of software that performs some business or infrastructure process. For example, a single Monitor All Vital Signs service in MonitorMe might perform a lot of functions, including monitoring the patient’s heart rate, blood pressure, temperature, and so on. This service does quite a bit, but we still call it a service.

Image

The prefix micro- in microservice refers not to physical size, but to what the service does . For example, a Monitor Heart Rate service is single-purpose and does one thing really well—it monitors a heart rate. That’s the idea behind microservices. By contrast, the larger Monitor All Vital Signs service performs many vital sign monitoring functions.

Image

A microservice is a single-purpose, separately deployed unit of software that does one thing really well.

Exercise

Image

We’re having trouble determining what single-purpose means. Can you help us by checking off all the functions below that you would consider single-purpose and therefore possible microservices?

  • Image Add a movie to your personal “to watch” list

  • Image Pay for an order using your credit card

  • Image Generate sales-forecasting and financial-performance reports

  • Image Submit and process a loan application to get that new car you’ve always wanted

  • Image Determining the shipping cost for an online order

Image Solution in “Exercise Solution”

It’s my data, not yours

Another feature that makes microservices special is that they own their own data. In other words, each microservice is the only one that can directly access its data.

Image

Why? The primary reason is to manage change control . Say you have 50 microservices, all sharing the same data. If one microservice changes the structure of its data, which the other 49 microservices are also accessing, all of those other services will need to change at the same time . (Is your head exploding yet?)

Physically associating a microservice with its data is known as creating a physical bounded context . Physical bounded contexts help manage change and coupling. If other microservices need access to data they don’t own, they must ask the owning service for it.

Note

A physical bounded context includes the microservice and all of its data.

Image

In the example above, the Monitor Heart Rate microservice is asking for the data rather than directly accessing the data. This way, even if the Sleep Status data structures change, the Monitor Heart Rate microservice doesn’t have to. This is the whole idea behind physical bounded contexts.

Sharpen your pencil

Image

We created the following services for an ecommerce site, but we need your help in figuring out the data ownership and bounded contexts. Can you associate the database tables below with the corresponding microservices that should own the data?

Image

Image Solution in “Sharpen your pencil Solution”

How micro is “micro”?

Figuring out how big or small a microservice should be is hard. By now you know that a microservice is a single-purpose service that’s separately deployed . But how do you determine the scope of that single purpose?

As an example, let’s take a look at the MonitorMe functionality for blood pressure. Monitoring a vital sign involves capturing the input from the medical device attached to the patient, recording the input, analyzing the measurements, and alerting a nurse or doctor if something is wrong. We can model this functionality in one of three ways:

  • • Option 1: Create a single monitoring microservice that performs all monitoring and alerting functions.

  • • Option 2: Create two separate microservices—one that captures and records vital signs data, and one that analyzes the data and alerts staff if necessary.

  • • Option 3: Create four separate microservices, each one performing a specific blood pressure monitoring function.

Image

Image

Image

Relax

Image

You don’t have to choose yet. At this point, we’re only showing you the different options you can choose from to create a microservice. Keep reading to find out how to make the right choice for your situation.

Image

No, granularity is not a guessing game.

G ranularity —the scope of what a microservice does—is an important factor when identifying microservices. Microservices that are too fine-grained tend to communicate more with each other to complete business functions, leading to high levels of coupling, poor performance, and overall reliability issues. This is commonly referred to as the Grains of Sand antipattern, in which services are so small that they start to resemble sand on a beach. However, microservices that are too coarse -grained are harder and more expensive to maintain, test, and scale (which defeats the whole purpose of using microservices).

So how do you determine the most appropriate level of granularity for a microservice? By applying forces called granularity disintegrators and granularity integrators. Granularity disintegrators are forces that tell you to make your service smaller (meaning it’s doing less work), whereas granularity integrators are forces that tell you to make the service bigger (meaning it’s doing more work). Let’s see how these forces work.

Image

Granularity disintegrators

Granularity disintegrators are forces that help you decide whether you should break a service apart into several smaller ones. To show you how these forces can influence your decision to break a service apart, we’ll take a look at MonitorMe ’ s Monitor Basic Vital Signs functionality.

The three basic vital signs are blood pressure, temperature, and heart rate. Since they’re all related, we could put them all in the same microservice or create separate microservices, one for each basic vital sign.

Image

Let’s analyze each of these forces to see how it might help you decide whether to break the monitoring functionality into separate microservices.

Why should you make microservices smaller?

Cohesion

Image

A single-purpose microservice has functionality that is highly cohesive —meaning all the things it does are closely related to each other. If the functionalities of a microservice lack cohesion, then it might be a good idea to break that microservice apart.

Fault tolerance and availability

Image

Do certain functions in a microservice frequently produce fatal errors? In larger microservices, all functionalities become unavailable when a part of the microservice fails. However, if the faulty functionality is in its own separate microservice, it won’t affect other functions.

Access control

Image

The larger the service, the more difficult it is to control access to sensitive information. For example, a Patient Profile microservice containing functionality to access medical history might inadvertently allow unauthorized staff to access this sensitive (and protected) information.

Moving sensitive functionalities (like access to medical history) into their own microservices isolates them, making it easier to control access to that information.

Code volatility

Note

This is also referred to as “volatility-based decomposition.”

Image

Does one part of the microservice change faster than others? Constant changes to one part of a large microservice mean you have to test the entire microservice, including functionalities you didn’t change. That’s a lot of extra work.

Moving a frequently changing function into its own separate microservice isolates those changes from other functions, making it much easier to maintain and test functionality.

Scalability and throughput

Image

Do some parts of the microservice need more scalability than others? If so, breaking the service apart allows better control over which portions need to scale and which do not.

For example, suppose the heart rate monitoring function accepts sensor readings every second, but the temperature monitoring function accepts sensor readings once every 5 minutes. Separating these monitoring functions into distinct services allows each one to accommodate a different throughput rate.

Note

Smaller microservices start up much faster than larger ones, making much-needed functionality available to the user sooner.

Granularity integrators

Granularity integrators work in the opposite direction from disintegrators—they help you decide when to make services bigger and combine their functionalities. We’ll use the same Monitor Basic Vital Signs microservice we broke apart earlier to illustrate why you might want to consider combining separate microservices into one larger microservice.

Image

Let’s analyze each of these forces to see how they might help you determine whether you should put all this monitoring functionality into a single larger microservice.

Why should you make microservices bigger?

Database transactions

Image

When requests involve multiple microservices, you can’t perform a single database commit or rollback for all updates. Since each microservice update is in its own separate transaction, it must instead be committed or rolled back separately.

If data consistency and integrity are more important than any of the disintegrator forces, then it makes sense to combine the functionality into a single microservice so that operations take place in a single database transaction.

Data dependencies

Note

Data dependencies are one of the most common integration drivers.

Image

When you break a microservice apart, you also have to break its data apart. However, if the data is highly coupled , it will be very difficult to break it apart and form new physical bounded contexts.

An example of data coupling is when one database table refers to the key of another database table (known as a foreign key constraint ). Another example of data coupling is when an entity (like customer information ) is spread across multiple tables.

If your data is highly coupled and functions in the microservice need to share that data, it makes sense to keep the microservice large and combine the functions.

Workflow and choreography

Image

If a single business request requires separate microservices to communicate with each other, that’s coupling . Too much coupling between microservices can have many negative effects on the system.

For example, performance is affected by network, security, and data latency. Scalability is affected because each microservice in the call chain must scale as the other microservices scale (something that is hard to coordinate). Fault tolerance is affected because if one of the microservices in the chain becomes unresponsive or unavailable, the request cannot be processed.

If your workflow involves a lot of coordination between your microservices and these characteristics are important to you, consider combining them.

Image

It’s all about balance

Determining the appropriate level of granularity for a microservice isn’t easy. You have to balance the trade-offs associated with each granularity disintegrator and integrator, and determine which trade-offs are more important. This usually involves collaborating with your product owner or business stakeholder, particularly if the trade-offs are significant.

Make it Stick

Image

How small should a microservice be?

Use this tip and you will see.

Keep them coarse-grained when you begin,

Then move to fine-grained for the win!

Image

Exercise

Image

Now it’s your turn to apply granularity disintegrators and granularity integrators to decide whether to implement the Monitor Basic Vital Signs functionality (which covers blood pressure, temperature, and heart rate) as a single microservice or three separate services. Here is some additional information:

  • * A patient’s heart rate and blood pressure are the two most critical basic vital signs to monitor. If something should go wrong with temperature monitoring, heart rate and blood pressure monitoring must continue to work.

  • * All three basic vital signs share an alert functionality to notify medical professionals if something goes wrong.

  • * The heart rate monitoring functionality accepts sensor readings once a second, whereas the temperature and blood pressure monitoring functions only accept sensor readings once every 5 minutes.

  • * Each basic vital sign’s data is recorded and stored separately, as simple JSON name/value pairs in a single document database. For example, the heart rate readings are stored as follows:

Image

Image

Which of the two options would you choose, and why? ____________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

___________________________________________________________________

Image Solution in “Exercise Solution”

Image

You can still share code in microservices.

Code reuse is a necessary part of software development. Without it, you would have duplicate functionality almost everywhere in your system. Functions like logging, metrics streaming, user authorization, and basic utilities like transforming date formats are common in most (if not all) systems.

In monolithic systems, this is easy—you write the common functionality once and use it everywhere in the system, because it’s all compiled together as one unit. But in distributed architectures like microservices, it’s not that easy. That’s because each microservice is a separately deployed unit of software.

So where does all that common functionality go in microservices? Usually into either a shared library or a shared service . In the following pages, we’ll show you the trade-offs between these choices.

Sharing functionality

All of MonitorMe’s vital-sign monitoring microservices have shared functionality to alert a medical professional if something is wrong with the patient. Let’s look at the code:

Image

Let’s say we create three separate microservices for monitoring blood pressure, temperature, and heart rate. Each one needs this common alert functionality.

Image

Where should the source code for the common alert functionality go? We could replicate the code in each microservice, but that would lead to issues if anyone changed it to fix a bug or add new functionality. That leaves us with two choices for where to put the code: in a shared service or in a shared library. Let’s look at both options.

Note

“Replication” means that each microservice has its own copy of the source code. This is only useful for truly static source code.

Sharpen your pencil

Image

Besides alerting a medical professional, can you list other common functionalities that the MonitorMe services might need?

Image Solution in “Sharpen your pencil Solution”

Code reuse with a shared service

A shared service is a separate microservice that contains a shared functionality that other microservices can call remotely.

If we put the MonitorMe alert functionality in its own separate shared service, each monitoring microservice will need to call that shared service if it detects something wrong with the patient.

Image

Like everything in software architecture, shared services have advantages and disadvantages.

Image

Code reuse with a shared library

A more common approach to shared functionality is to put it in a custom shared library. A shared library is an independent artifact (like a JAR file in Java or a DLL in C#) that is included with each microservice at compile time. This means that once the microservice is deployed, each microservice has all of the shared functionality available to it.

Note

Most platforms and programming languages have their own shared-library file formats.

Let’s see how the shared MonitorMe alerting functionality might look if we were to use a shared library rather than a shared service.

Image

Do you see how the shared alert functionality is included as part of each microservice’s deployment unit? This means each microservice can simply use the shared code to alert a medical professional, without having to make a remote call to a separate service.

Image

Fireside Chats

Image

Tonight’s talk: A shared service and a shared library answer the question: “Who’s cooler?

Shared ServiceShared Library
Hey there, “old school.” You still around?
“Old school?” Let me tell you something—not only am I still around, I’ll outlive you by a long shot.
Not a chance, bud. Don’t you get it? In the distributed architecture world, I’m king. Everything is services— including me, the shared functionality. Need to reauthorize a user? Need to alert a nurse that the patient is having issues? Just call me. What could be easier?
Right. And when you aren’t around, what then? You see, unlike you, I’m always around, right by each microservice’s side.
Fine, you got me there. But when I have to change, I just do it. No one else has to be involved. When you change, every service you’re attached to has to retest and redeploy. How disruptive you are!
Oh please! I can clone myself into multiple versions. That makes me a lot safer to change. You, on the other hand, are full of risk—you can break the entire system when you redeploy! You really like to live dangerously, don’t you?
At least I’m not a conformist. Face it—for every programming language in your environment, you have to replicate yourself. I, on the other hand, am independent. I can be implemented in any language or platform because I don’t have the same attachment problem you have.
Attachment problem? Really? Listen—my attachment to services means I’m faster, more available, more scalable, and more reliable than you.
Whatever. Later, conformist—I’m gonna go find someone to hang out with who appreciates me.
And... now you’re not available. See what I mean?

Sharpen your pencil

Image

Now that you’ve seen the two main options for sharing functionality in the microservices architectural style, it’s your turn to decide—should the alert functionality in MonitorMe be a shared library or a shared service? Make sure you consider external forces (like the problem domain) in addition to the pros and cons of each option, and justify your choice.

Image

Note

Put your decision and reasoning here.

Image Option 1: Shared service

Image Option 2: Shared library

Reason: ________________________________________

________________________________________________

________________________________________________

________________________________________________

________________________________________________

________________________________________________

Image Solution in “Sharpen your pencil Solution”

Image

Yes, you can! This is called workflow management.

A workflow is when fulfilling a single business request—a task request that comes from a user interface—needs more than one microservice. You can manage a workflow in microservices by using either of two techniques: orchestration or choreography . In the next couple of pages, we’ll show you how these work and discuss their pros and cons.

there are no Dumb Questions

Q: If I make a request involving a workflow that needs multiple microservices to give me an answer, why break those microservices apart? Wouldn’t it be better to make a single service and avoid workflows in the first place?

A: Great question. Remember the granularity disintegrators from several pages ago? Some of those factors—like scalability, fault tolerance, code volatility, and better, more secure access control—might be important enough to warrant keeping the microservices separate, even if it means you’ll have to add a bit of complexity later to tie those services together with a workflow.

Managing workflows

A workflow is required when two or more microservices are needed to complete a single business request. The request might be a nurse (say, Juan) asking “How is the patient doing today?” To answer, the system must gather information about the patient’s temperature, heart rate, and blood pressure. This means calling multiple microservices, one for each vital sign.

However, Juan doesn’t want to make three separate requests to the MonitorMe system. He would like to make a single request to get all the vital signs information. This means the three monitoring microservices need to be coordinated in a workflow.

Let’s look at how to make this happen in microservices by using either orchestration (centralized workflow management) or choreography (decentralized workflow management).

Image

Exercise

Image

Can you think of any workflows involving multiple microservices that might exist for the MonitorMe patient vital signs monitoring system? List them in the space below.

Get the status of a patient’s basic vital signs (temperature, blood pressure, and heart rate).

Note

We did this one for you.

Image Solution in “Exercise Solution”

Orchestration: Conducting microservices

When you go to a symphony concert, who do you see in the front, leading all the musicians? The conductor, of course. This is a great way to think about orchestration in microservices.

Orchestration is about coordinating all the microservices needed for a workflow. A centralized microservice—the orchestrator —does this, very much like a conductor coordinates all the musicians performing in a symphony orchestra.

An orchestration service is a separate microservice that is responsible for calling all the microservices involved in the workflow. It also handles errors and passes consolidated data back to the caller (usually the user interface).

Image

Image

Job Posting: Microservices Orchestrator

Looking for a microservices orchestrator to manage monitoring a patient’s basic vital signs. Duties and responsibilities include:

  • Call the right microservices in the right order.

  • Always know the current state of the workflow and what happens next.

  • Consolidate all the data from each microservice.

  • Handle errors if any of the microservices fails.

Note

That’s a lot to manage. I hope the job pays well.

Like everything, orchestration has trade-offs. Let’s be positive and start with the good.

The good...

Image

Centralized workflow

Request workflows are centralized and well understood. You only need to go to the orchestrator to understand the complete workflow.

Workflow state

Since the orchestrator always knows where the request is in the workflow, if there’s a failure, restarting the request where the workflow left off is much easier.

Note

Sort of like a GPS—it always knows where you are.

Error handling

Error handling is consolidated into the orchestrator, so each microservice doesn’t need to worry about what to do if an error occurs—the orchestrator handles it.

Workflow changes

It’s easy to change the workflow because all changes occur in one central place.

The bad...

Image

Performance

Orchestration tends to be slowed by communication between the orchestrator and the microservices, and because the orchestrator typically saves the workflow state to a database each time something changes.

Scalability

The central orchestrator can become a bottleneck as requests increase, because every request must go through it before reaching any microservices.

Tight coupling

Because the orchestrator and microservices need to communicate constantly, orchestration tends to be highly coupled.

Availability

If the conductor leaves the orchestra, the concert is over. Similarly, if the orchestration microservice is unavailable, the request cannot be processed. This single point of failure is usually addressed by creating multiple instances of the orchestrator.

Note

Sort of like having an understudy conductor backstage in case the conductor gets sick.

Choreography: Let’s dance

Whereas orchestras are conducted, dances are choreographed . Rarely do you see a conductor leading a group of classical or modern dancers—instead, the dancers learn their parts and then communicate with each other. This is a great way to think about choreography in microservices.

Let’s say the MonitorMe system’s blood pressure monitoring functionality is separated into four separate microservices, which communicate to complete the workflow of the monitoring operation.

Image

Image

Like dancers, the microservices communicate with each other. Each performs its function, then calls the next microservice to perform its function, until the workflow is complete.

Watch it!

Image

Don’t lead the dancers!

When using choreography, make sure you don’t fall into the trap of turning one of the microservices into an orchestrator. This is known as the Front Controller pattern. This pattern is useful for orchestration, but not for choreography.

Image

Guess what? Choreography has trade-offs as well.

The good...

Image

Responsiveness

Since there’s no central orchestrator to communicate with continually, responsiveness and performance tend to be better.

Loose coupling

Since microservices don’t depend on a central orchestration service to direct them, the system tends to be less coupled.

Scalability

Each microservice can scale to meet its throughput demands, independent of other microservices in the workflow.

Note

Fast, scalable systems usually use choreography. However, watch out for the trade-offs.

The bad...

Image

Error handling

Each microservice is responsible for managing the error workflow if an error occurs. This can lead to too much communication between services.

Recoverability

When a user retries a request that has failed or is still in progress, it’s really hard for the system to know where to restart. That’s because no single service is responsible for directing the request to a specific microservice in the workflow—each one only sends it to the next microservice in the call chain.

State management

It’s hard to know what state the workflow is in when using choreography, because there’s no central conductor controlling the workflow. Usually, one of the microservices (typically the first one in the call chain) is designated the state owner, and other microservices send it their state.

Note

Be careful—state management can lead to the Front Controller pattern, described in the “Watch it!” box on the previous page.

Exercise

Image

StayHealthy, Inc., stands behind MonitorMe and its monitoring devices and display screens. If a problem occurs with any software or physical hardware, someone from the medical facility can go online and create a trouble ticket. A field technician will receive the trouble ticket on their mobile phone, come to the medical facility, fix the problem, and mark the ticket as fixed.

It’s up to you: Would you manage the microservices for the trouble ticket system workflow using orchestration or choreography? Be sure to include the reasons for your choice.

Image

Image Solution in “Exercise Solution”

Image

You’re right—the microservices architectural style is complex. But it’s also powerful.

Using microservices helps us address complex business problems. Not only does this architectural style excel at supporting operational characteristics such as scalability, reliability, availability, and fault tolerance, but it also allows the system to respond quickly to changes in both business and technology (known as agility ).

That said, the microservices architectural style may not be a fit for every system. In the next few pages we’ll show you some of the superpowers of microservices as well as its weaknesses.

Microservices architecture superpowers

Every architectural style has its superpowers. Here are some reasons to use the microservices architectural style.

Image

Maintainability

Image

Because microservices are single-purpose and separately deployed, you can more easily locate code that needs to change for a particular function.

Testability

A microservice’s testing scope is much smaller than that of a larger monolithic application or a system with large services. This limited scope makes it easier to fully test a microservice’s functionality.

Deployability

Image

Because microservices are deployed as separate units of software, there are fewer risks involved with releasing a microservice than with large monolithic systems. You can also deploy microservices more frequently—sometimes daily.

Evolvability

It’s relatively easy to add functionality to a microservices architecture: you create a new service, test it, and deploy it alongside other existing microservices in your system.

Scalability

Microservices scale at a function level rather than a system level. This means that you scale only the functionalities you need to meet increased user load and demand, saving resources and lowering costs.

Fault tolerance

If a particular microservice fails, it doesn’t bring down the entire system—only that function. Users can continue to use other functions.

Image

Microservices architecture kryptonite

Are there reasons not to use the microservices architectural style? You bet there are. Just like kryptonite diminishes a superhero’s powers, certain business and architectural characteristics diminish the case for using microservices. Watch out for them!

Image

Image

Complexity

Microservices is one of the most complex architectural styles. It involves so many hard decisions—about granularity, transactions, workflow, contracts, shared code, communication protocols, team topologies, and deployment strategies, just to name a few.

Performance

The more microservices communicate with each other, the worse their performance will be. They may have to wait for the network, undergo additional security checks, and make extra database calls.

Image

Complex workflows

Workflows occur when you need to call multiple microservices for a single business request. If the functionality of your system is too tightly coupled, breaking it into separately deployed services will only result in a big ball of distributed mud. Yuck!

Monolithic databases

Each microservice must own its own data and form a physical bounded context. If your data can’t be broken apart for whatever reason, stay away from this architectural style.

Note

Remember—a physical bounded context includes the microservice as well as all of its data.

Image

Technically partitioned teams

Does your organization consist of siloed teams of user interface developers, backend developers, and database people? If so, microservices won’t work for you (a reflection of Conway’s Law). Microservices architecture requires cross-functional teams. Each team owns its own group of microservices, all the way from the user interface to the database.

Microservices star ratings

Below is a useful chart for understanding what microservices architecture is good at and what it’s not so good at. One star means that the architectural characteristic is not well supported; five stars means the characteristic is very well supported.

Note

Just like movie reviews.

Image

As you can see, the microservices architectural style is pretty good in terms of agility (maintainability, testability, and deployability) and operational characteristics. However, it’s not so great when it comes to performance, simplicity, and cost.

You might be wondering about the low performance rating. This is because of latency as services communicate with each other. This latency takes on three forms: network latency (the time it takes the request to get to the service), security latency (the time it takes to reauthorize a user, for example), and data latency (since each microservice makes its own database calls).

Exercise

Image

Which of the following systems might be well suited for the microservices architectural style, and why? Hint: Take into account microservices’ superpowers, its kryptonite, and the problem domain.

Image

Image Solution in “Exercise Solution”

Wrapping it up

Congratulations! The MonitorMe system is up and running, and it’s a success. It’s all thanks to your understanding of microservices and what types of systems this approach is good for.

You’ve learned that while microservices can be a complicated architectural style, it also has superpowers that can help solve complex business problems (like the MonitorMe system we’ve been working on). Let’s close this chapter by reviewing some key points about microservices.

Bullet Points

  • A microservice is a single-purpose, separately deployed unit of software that does one thing really well.

  • A physical bounded context means that a microservice owns its own data and is the only microservice that can access that data. If a microservice needs data that is owned by another microservice, it must ask for it.

  • The granularity of a microservice is a measure of its size—not physically, but the scope of what it does.

  • Forces that guide you to make your microservices smaller are called granularity disintegrators .

  • Forces that guide you to make your microservices bigger are called granularity integrators .

  • Balance granularity disintegrators and integrators to find the most appropriate level of granularity for a microservice.

  • You can make microservices coarse-grained to start with, then finer-grained as you learn more about them.

  • Two techniques for sharing functionality in microservices are shared services and shared libraries .

  • A shared service is a microservice that contains a functionality shared by multiple microservices. It’s deployed separately and each microservice calls it remotely. Shared services are more agile overall and are good for heterogeneous environments. However, they are not good for scalability, fault tolerance, or performance.

  • A shared library is an independent artifact (like a JAR or DLL file) that is bound to a microservice at compile time. Shared libraries offer better operational characteristics, like scalability, performance, and fault tolerance, but make it harder to manage dependencies and control changes.

  • A workflow is when multiple microservices are needed for a single business request or business process.

  • Workflows that use orchestration require a central orchestrator microservice, which works like a conductor in a symphony orchestra.

  • In workflows that use choreography, the services talk to each other, like dancers performing together.

  • Scalability, fault tolerance, evolvability, and overall agility (maintainability, testability, and deployability) are the superpowers of the microservices architectural style.

  • Performance, complexity, cost, monolithic databases that can’t be broken apart, and high semantic coupling are kryptonite to microservices.

  • Microservices should be as independent as possible; too much communication between them will degrade the benefits of this architectural style.

Microservices Crossword

Images

Ready to have some fun and test your knowledge about what you’ve learned?

Image

Across

1. Microservices make it easier for a system to do this

5. When you make a service smaller, you make it more _____

7. Each microservice _____ its own data

11. Workflow where microservices communicate with each other

14. A _____service does one thing really well

15. Microservices is this type of architecture

17. _____ tolerance keeps a problem from bringing down the whole system

18. Microservices are _____-purpose

19. When you need more than one microservice to do the job, it’s a _____

Down

1. _____ handling is part of an orchestrator’s job

2. Kind of component found within a microservice

3. Kind of force that pushes you to make a microservice bigger

4. Watch out for the _____ Controller pattern

6. Each microservice is a separately deployed _____ of software

8. Code resource that’s often shared

9. A context that restricts data access

10. Workflow where one microservice rules all the others

12. Type of bounded context or architecture diagram

13. Good security includes restricting _____ to data

16. A bad design pattern is an _____pattern

Image Solution in “Microservices Crossword Solution”

From “Sharpen your pencil”

Sharpen your pencil Solution

Image

Based on the problem domain and requirements document in “StayHealthy MonitorMe requirements document” , check off the top five architectural characteristics you think are critical to the MonitorMe architecture and indicate why you think they are critical.

Image

From “Exercise”

Exercise Solution

Image

We’re having trouble determining what single-purpose means. Can you help us by checking off all the functions below that you would consider single-purpose and therefore possible microservices?

Image

From “Sharpen your pencil”

Sharpen your pencil Solution

Image

We created the following services for an ecommerce site, but we need your help in figuring out the data ownership and bounded contexts. Can you associate the database tables below with the corresponding microservices that should own the data?

Image

From “Exercise”

Exercise Solution

Image

Now it’s your turn to apply granularity disintegrators and granularity integrators to decide whether to implement the Monitor Basic Vital Signs functionality (which covers blood pressure, temperature, and heart rate) as a single microservice or three separate services. Here is some additional information:

  • * A patient’s heart rate and blood pressure are the two most critical basic vital signs to monitor. If something should go wrong with temperature monitoring, heart rate and blood pressure monitoring must continue to work.

  • * All three basic vital signs share an alert functionality to notify medical professionals if something goes wrong.

  • * The heart rate monitoring functionality accepts sensor readings once a second, whereas the temperature and blood pressure monitoring functions only accept sensor readings once every 5 minutes.

Each basic vital sign’s data is recorded and stored separately, as simple JSON name/value pairs in a single document database. For example, the heart rate readings are stored as follows:

Image

From “Sharpen your pencil”

Sharpen your pencil Solution

Image

Besides alerting a medical professional, can you list other common functionalities that the MonitorMe services might need?

Observability—streaming service response times, errors, uptime, and other metrics and measurements

Logging—reporting on errors and other service functionality alerts

Auditing—recording when an alert was sent and which medical professional received it

Security—restricting access to a monitoring service to authorized medical professionals only

From “Sharpen your pencil”

Sharpen your pencil Solution

Image

Now that you’ve seen the two main options for sharing functionality in the microservices architectural style, it’s your turn to decide—should the alert functionality in MonitorMe be a shared library or a shared service? Make sure you consider external forces (like the problem domain) in addition to the pros and cons of each option, and justify your choice.

Image

From “Exercise”

Exercise Solution

Image

Can you think of any workflows involving multiple microservices that might exist for the MonitorMe patient vital signs monitoring system? Here are our ideas.

Get the status of a patient’s basic vital signs (temperature, blood pressure, and heart rate)

Find out which vital signs are being monitored for a given patient (requires queries to multiple monitoring services)

Register a new patient to be monitored—lots of different information is gathered, like name, identity, demographics, medical history, and so on, all of which could be separate microservices

From “Exercise”

Exercise Solution

Image

StayHealthy, Inc., stands behind MonitorMe and its monitoring devices and display screens. If a problem occurs with any software or physical hardware, someone from the medical facility can go online and create a trouble ticket. A field technician will receive the trouble ticket on their mobile phone, come to the medical facility, fix the problem, and mark the ticket as fixed.

It’s up to you: would you manage the microservices for the trouble ticket system workflow using orchestration or choreography? Be sure to include the reasons for your choice.

Image

From “Exercise”

Exercise Solution

Image

Which of the following systems might be well suited for the microservices architectural style, and why? Hint: Take into account microservices’ superpowers, its kryptonite, and the problem domain. Here are our answers.

Image

Microservices Crossword Solution

Image

From “Microservices Crossword”

Image