Chapter 19 of 27 · Part 9: Deployment and scaling

Deployment patterns and Kubernetes

A monolith is deployed a few times a year by hand. Dozens of services, each released every week, cannot be. This chapter shows how FTGO packages, runs and releases its services automatically, without downtime and without betting every release on all its customers.

key idea / coordinator service / good path in progress / watch out problem / failure neutral

Where we are

In chapter 18 we made FTGO's services survive slow, failed and buggy neighbors with time-outs, retries, circuit breakers, bulkheads and redundancy. That left one problem open: surviving failure is not enough. The team must ship dozens of services, each with its own fixes and settings, to production safely and often.

This chapter

How does FTGO get a new version of a service into production, many times a week, without hand work, downtime or a risky big bang? By the end you can choose a deployment pattern, explain what Kubernetes does for you, create infrastructure from code, and release a new version to a few users before everyone.

Release night does not scale

Problem

FTGO's monolith was released four times a year. On release night the operations team logged into each server, copied the new WAR file, edited config files by hand and restarted. Now there are a dozen services, each with several instances, and every team wants to release weekly. Release night lasts until dawn, the servers have drifted apart because each was fixed by hand, and nobody dares touch the one that "just works".

Servers that are named, hand-configured and nursed back to health when they get sick are often called pets. The industry has moved toward cattle: identical, throwaway machines created and replaced by automation. Each step in that history hid more of the machine.

From pets to cattle 1990s physical servers 2006 virtual machines 2013 Docker containers 2014 serverless Servers went from hand-cared pets to throwaway, automated infrastructure.
Solution · Automated deployment to a production platform

Automate every step of a deployment, and run services on a production environment that does the routine work for you. Developers deploy through an API, not by logging into servers.

Whatever platform FTGO picks, the production environment must provide four things:

What production must provide Production environment Management API deploy, update Runtime mgmt keep N running Monitoring logs, metrics Routing users to services

A management API to deploy and update services. Runtime management that keeps the right number of instances running. Monitoring that gathers the logs and metrics from chapter 17. Routing that sends each user request to a healthy instance.

Automation is what makes many services workable at all. In a side example, the online retailer Gilt had about 10 services a year after starting with microservices, and over 450 by 2014. Tooling that let developers create and deploy services themselves drove that growth.

Cost

Automation needs a unit to automate. "Copy a JAR to a server" is easy to script, but the scripts still put several services on shared machines, and that creates its own trouble.

Noisy neighbors: package each service in isolation

The first decision is what exactly gets deployed: the shape of the package.

Problem

To save machines, Kitchen Service and Order Service are deployed as JAR files on the same host. Kitchen's nightly report job has a memory leak. At 7 p.m. it eats the host's memory, and Order Service, which did nothing wrong, slows to a crawl in the dinner rush. The ops team cannot even tell which service is using the CPU.

Isolated execution Many services per host Noisy neighbors steal CPU Hard to monitor each one Gilt hit this early on Isolated instances Own CPU, memory, filesystem Failures stay local VM or container each One host is simpler for the ops team, but the side effects add up.
Solution · Isolated execution

Run each service instance in its own isolated environment, a virtual machine or a container, with its own CPU and memory limits and its own filesystem. A leak in Kitchen Service then hurts only Kitchen Service.

There are four deployment patterns. Each step down the table hides more of the machine from you:

PatternBenefitsDrawbacks
Language package (JAR/WAR)Fast deploy, shares resourcesNo isolation, no resource limits, ops must know the runtime
Virtual machine (AMI)Stack encapsulated, isolated, mature cloudHeavy, minutes to build and boot, patch the OS
Container (Docker)Encapsulated, isolated, limited, starts fastYou patch images and run the platform
Serverless (Lambda)No servers, elastic, pay per requestCold starts, limited to short functions

A virtual machine image, such as an Amazon Machine Image (AMI), packages the service with its whole operating system. Isolation is strong, but each instance carries a full OS and takes minutes to build and boot. A container packages the service and its libraries but shares the host's kernel, so it builds in seconds and starts fast, while still getting its own IP address, filesystem and CPU and memory limits.

VM versus container Virtual machine Whole OS per instance Strong isolation Slow to build and boot Container Shares the host kernel Own IP, filesystem, CPU/RAM limits Builds in seconds, starts fast

FTGO chooses containers with Docker. A Dockerfile names a base image, copies in the service's JAR and sets the command to start it. docker build turns it into an image, docker push stores the image in a registry, and docker run starts a container from it on any machine.

Docker in four steps Dockerfile base + JAR + CMD docker build makes image docker push to a registry docker run a container Push sends only the layers that changed. Compose runs several containers on one machine.

The fourth pattern, serverless, hides the machine completely. It gets its own chapter next.

Cost

FTGO must now keep its base images patched and run a container platform. And containers on their own are just processes on machines. With forty of them spread over eight hosts, someone still has to decide where each one runs and restart it when it dies.

Who restarts the containers at 2 a.m.? Kubernetes

Docker runs one container on one machine. FTGO needs something that runs many containers across many machines.

Problem

At 2 a.m. one of the eight hosts fails. The three Order Service containers and two Kitchen containers on it are gone. The on-call engineer has to find hosts with free memory, start replacement containers by hand, and update the load balancer, all while orders fail.

Solution · Desired state management (Kubernetes)

Declare what you want, such as "three instances of Order Service", and let an orchestrator decide where they run and keep that state true. When reality drifts, because an instance dies or a host fails, the platform notices and fixes it.

Desired state management Desired state 3 instances Reality changes one instance dies Platform notices actual differs Self-heal starts a new one You state the goal. The platform works out where and how to keep it true.

Kubernetes is the orchestration framework that won this space. It turns many machines into one pool. The master holds the control plane: the API server that kubectl talks to, etcd for the cluster state, the scheduler that picks a node for each pod, and the controller manager that keeps the desired state equal to the actual state. Each node runs the kubelet, which starts pods, and kube-proxy, which handles networking.

Kubernetes architecture A master runs the API server, etcd, scheduler and controller manager. Each node runs kubelet, kube-proxy and pods. Master API server kubectl talks here etcd cluster state Scheduler picks a node Controller mgr desired = actual Node (one of many) Kubelet runs pods Kube-proxy networking Pod containers Pod containers Pod containers Pods share one IP per pod and are created and replaced by the master.
You declare the desired state; Kubernetes keeps making it true.

You describe the desired state as objects in YAML files and send them with kubectl apply. A pod is one or more containers sharing an IP address; usually one container per pod, sometimes with a helper container beside it (the sidecar pattern). A bare pod is not enough for production, because nothing replaces it when it dies. A deployment keeps the chosen number of pod replicas running, and a service gives them one stable DNS name and address. ConfigMaps and Secrets carry the externalized configuration from chapter 16.

The objects you write in YAML Kubernetes objects Pod containers + IP Deployment N replicas Service stable DNS name ConfigMap settings Secret passwords

Most of FTGO's services should be reachable only inside the cluster. The API Gateway is the exception: customers must reach it from outside. The service's type decides this:

Service types (how the API gateway is exposed) ClusterIP Default inside the cluster only NodePort Port on every node 30000–32767 LoadBalancer Cloud load balancer easiest from outside
Cost

Kubernetes is a large system with many concepts to learn. And the cluster itself, with its nodes, network and container registry, has to come from somewhere. If someone builds it by clicking in a cloud portal, FTGO is back to a hand-made pet, just a bigger one.

A cluster nobody can rebuild: infrastructure as code

Kubernetes keeps the services in their desired state. The infrastructure under it needs the same treatment.

Problem

An engineer created FTGO's production cluster and registry by clicking through the cloud provider's portal. The staging cluster was made a month later, by someone else, with slightly different settings. A bug appears only in production. Nobody can say how the two differ, and nobody could rebuild production if the account were lost.

Solution · Infrastructure as code

Describe the infrastructure in machine-readable files kept in source control, and let a tool create it. Every environment is built from the same code, every change is reviewed and recorded, and the code is documentation that cannot go out of date.

Version control gives an audit trail and lets you recreate an environment as it was on a given date. That matters more than it sounds: one company had to spend months rebuilding an old system for a court case because nobody had recorded how it was set up.

The road from a developer's laptop to a running FTGO service has the same four steps every time:

The road to production Dockerfile builds the image Registry private, versioned Deployment pods, replicas Service stable address A deploy.yaml file describes pod, deployment and service. kubectl apply sends it.

Different environments need different tools along that road:

ToolUsed for
Docker ComposeRun the whole app on your computer while developing and testing. It simulates the cluster without the weight.
Local Kubernetes (Docker Desktop)Learn and rehearse a deployment: switch it on, apply, test, delete.
Managed Kubernetes (for example on Azure)Production. A few clicks, or better Terraform code, give you a cluster with a container registry attached.

Terraform is a language and a tool for describing cloud infrastructure. terraform init downloads the providers, terraform apply creates or updates resources to match the code, Terraform's state file tracks what exists, and terraform destroy tears it all down.

The Terraform cycle init get the providers apply create or update State tracks resources destroy tear it all down Providers plug in each cloud (Azure, AWS), so one skill works across vendors.

Grow the code in small steps: a resource group first, then the container registry, then the Kubernetes cluster, sharing settings through variables. Outputs expose values such as the registry address. Do not output passwords: they land in plain text in the state file.

Alternatives: Pulumi describes infrastructure in ordinary programming languages, and AWS CloudFormation and the AWS CDK work only on AWS. A cross-platform tool such as Terraform, kept in version control next to the service, is a sound default.

The same idea reaches the cluster's contents through GitOps: the desired state of the cluster lives in a Git repository, and a tool in the cluster watches the repository and applies every change. Deploying becomes a reviewed commit.

GitOps Git repository desired state as code GitOps tool Flux watches the repo Cluster changes are applied A tool such as Flux does not give you these ideas by itself: you still have to adopt them.

Whether a CD workflow (for example in GitHub Actions) runs kubectl apply or a GitOps tool pulls the change, no one logs into a server anymore. Chapter 21 builds that pipeline.

Cost

The infrastructure code must be written, reviewed and kept in step with reality, and the Terraform state file must be stored safely because it can hold secrets. With deployment now easy, the team deploys Order Service v2 in the middle of lunch, and finds out what a deployment does to the requests in flight.

Deploy without an outage: rolling updates

Automated deployment makes releases frequent. Each release must therefore be invisible to customers.

Problem

The first automated deploy of Order Service v2 stops all v1 instances, then starts the v2 ones. For about ninety seconds no instance is ready, and every order placed in that window fails. The team goes back to deploying at 3 a.m., which defeats the point of deploying often.

Solution · Zero-downtime deployment (rolling update)

Replace instances a few at a time. Start a new v2 pod, wait until its readiness probe says it can serve traffic, then remove one v1 pod, and repeat until all pods run v2. Consumers never see a gap, so teams can deploy during working hours.

Zero-downtime rolling update v1 pods serving traffic New v2 pod starting Ready? readiness probe Old pod gone repeat to the end Liveness probe restarts a stuck pod. Readiness probe decides if it gets traffic. kubectl rollout undo reverts.

The probes are the health checks from chapter 17. If something goes wrong, kubectl rollout undo rolls back to the previous version. A Kubernetes deployment does a rolling update by default.

Zero downtime is easier for some services than others. A service that receives work through a message broker, like Kitchen Service consuming order events, is easy: messages simply wait in the broker while instances are swapped. For synchronous services, use rolling updates or blue-green deployment (below). Adopting Kubernetes only to get zero-downtime deploys is overkill.

Cost

Old and new versions run side by side during the rollout, so they must be compatible with each other and with their consumers. And the readiness probe only proves that a pod started. A bug that shows up only under real traffic passes the probe, and the rollout spreads it to every pod within minutes.

Deploy is not release: progressive delivery

A rolling update replaces pods safely. It does not limit how many customers a bad version reaches.

Problem

Consumer Service v2 passes its tests and its readiness probe. But it fails for customers with more than one saved address. The rolling update finishes in four minutes, and from then on every such customer gets an error on checkout. The SLO alert fires, but by then every customer is on v2.

Solution · Separate deployment from release

Deployment installs a version in production. Release lets users reach it. Deploy v2 with no traffic, test it, then shift real users to it a little at a time, and switch back at once if the metrics turn bad. This is progressive delivery: continuous delivery with fine control over the blast radius.

Service mesh: separate deployment from release Deploy v2 no traffic yet Test users routed to v2 Shift 5% real users 100% v2 remove v1 Deploy = running in production. Release = users get it. Istio's Envoy sidecars route the traffic.

A service mesh such as Istio, from chapter 16, makes this routing possible without code changes. An Envoy proxy runs as a sidecar beside each service and follows routing rules. For Consumer Service, a rule first sends requests that carry a test-user header to v2, and everyone else to v1. Once the testers are happy, the weights move from 95/5 toward 0/100, and finally v1 is deleted.

Routing rules in Istio API gateway Envoy sidecar Consumer v1 Consumer v2 GET /consumers/1 normal user → v1 header testuser test user → v2 Then weight 95/5 → 0/100, then delete v1.

Routing by weight is one technique. There are several, and they combine:

TechniqueIdeaNote
Blue-greenRun the new version beside the old, check it, then switch all traffic at onceSimple zero-downtime option; switching back is just as fast
Feature toggleDeploy code hidden behind a switch, and turn it on laterSupports trunk-based work. Start with a config file.
Canary releaseA small subset of users sees the new version, then widenTools such as Spinnaker can ramp up automatically based on error rates
Parallel runSend each request to both versions and compare the resultsOnly the old version's result is used

A parallel run suits risky rewrites, such as a new way to calculate delivery fees: the old version stays the source of truth, and the differences tell you whether the new one is right before any customer depends on it.

A parallel run Request from a user Router copies the call Old version source of truth New version result ignored Compare diff results Guard side effects: do not send two real order updates. The user sees only the old result.
Cost

A mesh adds proxies and routing rules to run. Feature toggles pile up and must be removed once a feature is fully released. Parallel runs need care so that two versions do not both charge a card or both send a ticket to the kitchen. On top of all this sits a large platform that someone has to own.

Is Kubernetes worth it?

FTGO now has containers, a cluster, infrastructure as code and progressive delivery. Time to look at what running that platform costs.

Problem

Six FTGO teams share one cluster. The Delivery team's load test fills the nodes and the Order team's pods cannot be scheduled. Teams can see each other's resources more than they should. Two engineers now spend most of their time upgrading the cluster and installing tools such as Kafka into it, instead of working on food delivery.

Kubernetes deliberately left strong multitenancy (many teams safely sharing one cluster) out of its core, so organizations work around it:

Sharing clusters between teams One shared cluster Best use of capacity Weak tenant controls Platform on top Rich access controls Vendor layer to learn Federated clusters Strong separation Hard to move capacity Multitenancy was left out of Kubernetes on purpose, so organizations work around it.

For installing and running third-party software in the cluster, the ecosystem offers three tools:

ToolRole
HelmA package manager: install third-party software such as Kafka
OperatorManages the ongoing life cycle, such as upgrades. Can be used with Helm.
CRDCustom resource definition: extend the Kubernetes API with your own object types
Solution · Use the least platform you need

Running your own cluster is a big job, so prefer a fully managed one. In the public cloud, first ask whether you need Kubernetes at all: a platform as a service (PaaS) or function as a service (FaaS) offering may hide the complexity completely. Expect Kubernetes to become a layer beneath higher-level platforms such as Knative.

Cost

Managed services and higher-level platforms trade control for convenience, and tie FTGO more closely to one vendor. For some services, such as Restaurant Service's rarely changing menus, even a managed cluster may be more machinery than the job needs.

Patterns in this chapter

PatternProblem it solvesWhat it costs
Automated deploymentHand-run release nights that cannot keep up with many servicesA production platform and tooling to build
Language-specific packageGetting a service onto a server quicklyNo isolation or resource limits between services
Service as a virtual machineNoisy neighbors; the stack must travel with the serviceHeavy images, slow to build and boot, OS to patch
Service as a containerIsolation with fast builds and startsImages to patch and a container platform to run
Desired state management (Kubernetes)Placing and restarting many containers on many machines by handA large system to learn and operate; weak multitenancy
Infrastructure as code and GitOpsHand-made environments that drift and cannot be rebuiltCode to maintain; state files that can hold secrets
Zero-downtime rolling updateEvery deployment causes a short outageOld and new versions must be compatible; bugs still reach every pod
Blue-green deploymentSwitching versions safely, with a fast way backTwo full environments during the switch
Canary release with a service meshA bad version reaches every user at onceA mesh and routing rules to run
Feature toggleDeployed code that is not ready for usersToggle debt to clean up
Parallel runNot knowing whether a rewrite gives the same answersDouble work, and side effects to guard

Recap

Quick check

Rolling updates already wait for the readiness probe. Why add Istio?
Show answer

Readiness only shows that the pod started. A bug that appears under real traffic would still spread to every pod. Istio lets you send test users to v2 first, then shift real traffic slowly and revert at once.

FTGO runs Kitchen Service and Order Service as JAR files on the same hosts. Kitchen's batch job starts using all the memory every evening. What breaks, and which pattern fixes it?
Show answer

Order Service slows down or fails because it shares the host with a noisy neighbor, and it is hard to see which service is to blame. Isolated execution fixes it: deploy each instance as a container (or VM) with its own CPU and memory limits, so Kitchen's leak only hurts Kitchen.

What is the difference between deploying and releasing, and why does it matter?
Show answer

Deploying installs a version in production; releasing lets users reach it. Keeping them apart lets the team test a new version in production with no or few users, widen it gradually, and switch back quickly if it misbehaves.

Still open

FTGO can now ship any service safely, many times a week. But it still owns a cluster, nodes, images and a mesh, and someone must patch and upgrade them all. What if FTGO did not have to manage servers at all?

Next: 20 Serverless deployment →