Chapter 27 of 27 · Part 12: Hands-on: FlixTube

FlixTube in production

FlixTube runs on one laptop, but no customer can use it, nobody can see it fail, and it cannot grow. This chapter finishes the app and takes it to production: deploy it in safe steps, keep it healthy and reliable, scale it, and change it without breaking it.

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

Where we are

In chapter 26 we built FlixTube's first services: video streaming over HTTP, packaged with Docker, booted with Docker Compose, with storage, MongoDB and RabbitMQ messaging. That left one problem open: the app runs only on a laptop, and production needs deployment, health and scale.

This chapter

What turns a working prototype into an app people can rely on? By the end you can deploy FlixTube to Kubernetes by hand and automatically, keep it observable and fault tolerant, scale the team and the load, ship changes safely, and judge how far to take microservices at all.

Six services that all look alike

Problem

FlixTube can stream a video and record the view, but it cannot accept new videos and has no page to browse them. Each service also grew its own way, so switching from history to metadata means first hunting for its start script, tests and Dockerfile.

The finished app adds a gateway that serves the UI and an upload service. With the services from chapter 26, that makes six, plus a stand-in for development.

FlixTube services in the cluster Browser Gateway UI + REST API Video streaming Azure storage cloud files Video upload History viewed videos Metadata video details One database server hosts a database per service. RabbitMQ carries the indirect messages.
ServicePurpose
GatewayEntry point that serves the web UI and a REST API
Video streamingStreams videos from storage to the viewer
Azure storageStores and retrieves videos in external cloud storage
HistoryRecords the viewing history
MetadataRecords details about each video
Video uploadOrchestrates the upload of new videos
Mock storageDevelopment stand-in for Azure storage that uses the local disk
Solution · One layout, one monorepo

Give every service the same folder layout and keep them all in one repository, with one deployment pipeline per service folder.

Project structure: service and monorepo One microservice folder Dockerfile-dev, Dockerfile-prod package.json (scripts) src/index.js, index.test.js jest.config.js, .dockerignore The monorepo gateway/ video-streaming/ ... scripts/ (local, production, cd) .github/workflows/ (one per service) docker-compose.yaml, fixtures/ Every service has virtually the same layout. All of them live in one repository.

A monorepo used to defeat the point of microservices, because everything in it deployed together. A GitHub Actions workflow scoped to each subfolder fixes that: each service deploys on its own schedule.

Cost

One repository suits a small team and gets crowded as it grows (we split it later). And six services raise a question at once: which of them does the browser talk to?

One door in: the gateway and the request paths

Problem

Without a gateway the browser would call metadata for the video list, streaming to play, upload to add and history for past views. Every service would need a public address, and any internal change would break the web page.

Solution · API gateway

One door at the edge of the cluster serves the UI and a REST API and forwards each request inward. Authentication belongs here too.

This is the gateway from chapter 12. If web, mobile and admin frontends need different things, each can get its own gateway on its own host name (backends for frontends).

Backends for frontends Web Mobile Admin Gateway: web Gateway: mobile Gateway: admin Services inside the cluster Keep one gateway if you can. Add more only when frontends truly differ.

The UI is deliberately plain: Express renders Handlebars templates on the server, with vanilla JavaScript and Tailwind CSS. The home route fetches the video list from metadata. A real product would probably use a single-page framework.

To play a video, the HTML video element requests a gateway route. Each of three services pipes the stream it receives into its own response, so the video moves byte by byte from cloud storage to the page. Upload is the mirror image: the body of an HTTP POST is piped from the upload page through the gateway and the upload service into storage.

Streaming path through FlixTube Cloud storage blob Azure storage GET /video Video streaming pipes stream Gateway /api/video The HTML video element requests the gateway route and receives the same stream.

While it streams, video streaming broadcasts a "video viewed" message over RabbitMQ and history records it. A new consumer can subscribe later without any change to streaming.

Cost

Every request now passes through the gateway, so its failures are everyone's. And both paths end in Azure storage, so every developer who tries upload needs a cloud account and a network.

Develop without the cloud: Compose, mocks and fixtures

Problem

Two developers test upload against the same Azure account and see each other's test videos. On a train, nothing works. Every manual test starts from whatever data is in the local MongoDB, so a bug seen once cannot be seen again.

The loop from chapter 26 still applies. Boot one service alone with npm install and npm start. Boot the whole app with docker compose up --build, wait for the gateway to print that it is online, then upload a video, watch it and check the history page.

Solution · Mock service

Replace a whole service with a simpler one behind the same HTTP interface. Mock storage keeps videos on the local disk through a shared Docker volume, and no other service can tell.

Replacing cloud storage with a mock service Developer computer Video streaming Mock storage same HTTP interface Local files Docker volume Same contract as the Azure service, so nothing else changes.
Solution · Database fixtures

Load a named set of realistic data before each test, manual check or demo, so every run starts from the same state.

Fixtures are JSON for static data or JavaScript for generated data. During Playwright tests a small REST API beside the app loads the fixture each test asks for.

Loading a database fixture Named fixture e.g. two-videos Fixture REST API loads the data Database realistic content Test or demo known data A meaningful fixture name tells you at a glance what state the app starts from.

Testing reuses chapter 14 and chapter 15, with one convention: npm test always runs the tests, whatever framework is behind it.

Command and placeWhat runsScope
npm test in the metadata folderJest unit tests, database library mockedOne service
npm test at the repository rootPlaywright, in three browsersWhole running app
npm run test:watchJest in live reload modeWhile coding
Cost

A mock can drift from the real service, so real storage must still be exercised somewhere. And all of this runs on a laptop: no customer has watched a video yet.

Get it to production in three steps

Production runs on Kubernetes, not Compose, as chapter 19 explained.

Problem

You write one GitHub Actions workflow that builds, pushes and deploys all six services to a cloud cluster. It fails. Is it the Kubernetes YAML, the registry login, or the pipeline? With everything new at once, you cannot tell.

Solution · Deploy in stages

Go from local Kubernetes to a manual production deploy to automatic deployment. If a step fails, go back to the easier one: you cannot automate what you cannot do by hand.

Three stages of deployment 1 Local Kubernetes mock storage, no registry 2 Manual production registry + cloud cluster 3 Automatic CD push to deploy For daily development Compose is still simpler. Local Kubernetes is for practice.
  1. Local. A script builds each image and applies each service's YAML to the Kubernetes bundled with Docker Desktop. The gateway appears on a NodePort at or above 30000. No registry is needed, and a delete script removes it all.
  2. Manual production. Log in to the private registry, set its address as an environment variable, and run the deploy script. It builds and pushes each image, fills in the templated YAML with envsubst, and pipes the result to kubectl.
  3. Automatic. One workflow per service, scoped to its folder, redeploys only what changed. Each can also be started by hand from the GitHub UI.
One CD pipeline per microservice Git push to main GitHub Actions gateway/** only Build + push image to registry kubectl apply deploy to cluster Secrets: container registry, registry user and password, base64 kube config One workflow file per service. Only services whose folder changed are redeployed.

Shell scripts driven by environment variables do the work, so they run the same on a laptop and in the pipeline. MongoDB and RabbitMQ rarely change, so an infrastructure script deploys them once, by hand. A real product should use an external managed database.

Cost

The pipeline now holds secrets. And FlixTube runs where you cannot see it: when it breaks at 3 a.m., there is no terminal to look at.

See it, restart it, debug it

A healthy service is not crashing, not buggy and not starved of CPU or memory. Keeping it so starts with seeing it, as in chapter 17.

Problem

A viewer reports an empty home page. RabbitMQ restarted overnight, and the metadata service lost its connection. It is still running, but useless, and nobody knows where to look.

Solution · Logs in one place

Services write normal events to standard output and errors to standard error. Docker or Kubernetes captures the streams, and a collector gathers them so you can search and alert.

The path of a log line Service console output Docker or K8s captures streams Collector one place to read You search, alert, act Standard output carries normal events. Standard error carries errors.
WhereHow to read the logs
One service in developmentTerminal output
Docker ComposeOne merged stream; pipe it through tee to also save a file
Kuberneteskubectl logs with the pod name; a pod can have several containers
A growing clusterInstall an aggregator; Kubernetes has none built in

Log meaningful events and whether important operations succeeded. Never log secrets or personal details. Lean towards more logging: you cannot add it after the problem. Enterprise stacks (Fluentd, Elasticsearch and Kibana for logs; Prometheus and Grafana for metrics) are powerful but heavy, so do not rush to adopt them. Observability goes further: services emit rich telemetry (OpenTelemetry is the standard), and a tool such as Honeycomb follows one request across services to the span that failed.

Seeing a failure is half the fix. Exceptions, bad input and broken dependencies are unavoidable, so decide in advance how a service reacts.

Solution · Abort and restart, with probes

On an unexpected error, log it, exit with a nonzero code and let Kubernetes start a fresh process. Probes let Kubernetes spot a service that is running but not healthy.

Abort and restart Unhandled error uncaught exception Log it seen by ops Exit nonzero abort the process K8s restarts fresh instance Watch for repeated restarts: they signal a bug that still needs fixing.

Use resume instead only where aborting loses work, such as uploads in progress. The metadata service did not crash, though. The readiness probe route says a service can take requests; the liveness probe route says it still works, and Kubernetes restarts it if not. Probes also fix chapter 26's start-up ordering problem and the case where RabbitMQ restarts later.

Readiness and liveness probes Kubelet agent on each node Service: /ready Service: /alive ready to accept traffic? still healthy? restart if not A 200 response means yes. Rolling updates also wait for readiness (see below).

Some faults survive a restart. In a distributed app they hide among many processes, so debug with a repeatable routine:

The seven debugging steps Triage worst first Evidence logs, metrics Mitigate protect users Isolate which service Reproduce ideally a test Fix the root cause Reflect prevent the class A failing test that reproduces the bug also proves when it is fixed.
Symptom in productionFirst move
Service crashedkubectl logs for the pod, and for the previous instance
Pod in error or restartingkubectl get pods for status and restart count
Image pull errorsCluster cannot reach the registry: check the connection and image name
Cannot find the problemExperiment in production only if you cannot reproduce it elsewhere
Cost

Restarts can hide a recurring bug, and a restart takes time: while the only instance is down, every user who needs it gets an error.

Keep serving while parts fail

Restarting repairs a failure afterwards. Users need the app to work while it happens. Chapter 18 has the full patterns; here is FlixTube's minimum.

Problem

A corrupt file crashes the single upload instance. The gateway calls upload with Axios, which waits forever by default, so gateway requests pile up and the home page hangs too. One bad file has taken down the site.

Start inside each service with defensive programming (expect bad input, hidden bugs and unreliable dependencies) and defensive testing that attacks the code to check that errors are reported and recovered from. Protect source data above all: an uploaded video matters more than a thumbnail you can regenerate. Automate backups, practice restoring, keep capture code small and tested, and never write code that overwrites or deletes source data.

Solution · Replication

Run at least three instances behind a load balancer, so others serve while Kubernetes restarts a failed one. It is one field in the deployment YAML: replicas: 3.

Replicas behind a load balancer Load balancer Replica 1 Replica 2 Replica 3 Replicas set to 3. One request goes to one replica; the dashed one may be restarting.

Still investigate every failure. And replicas do not help when every one of them meets the same bad file.

Solution · Fault isolation

Contain a failure where it happens. The gateway catches upload's error, says upload is unavailable, and keeps serving the rest. This is the bulkhead idea: lose one feature, keep the app.

Containing a fault at the gateway Without isolation Upload Gateway User sees error With isolation Upload Gateway catches Notice, rest OK Graceful degradation: lose one feature, keep the application.
Fault tolerance toolbox Timeout give up after wait Retry try again Job queue smooth heavy work Circuit breaker fail fast when down Axios waits forever by default, so set a timeout. Failing fast beats failing slowly.

A timeout and a retry stop the gateway hanging on upload. A job queue stores heavy work, such as a thumbnail per video, in a database-backed queue: workers pull one job when free, jobs survive a crash and failed jobs run again, spreading load over time. A circuit breaker already knows a service is failing, so it fails at once without waiting.

Cost

Three replicas of everything triple the compute bill, and every fallback is code to test. FlixTube now survives failure, but one person built it. The next problems come from growth.

Scale the team and the load

Problem

Three developers join. Every push to main deploys straight to customers, and two developers keep breaking each other's work in the shared repository. A month later a video goes viral, and video streaming runs at full CPU while the other services idle.

Service boundaries are natural seams for splitting the work: each team owns its services from development to production (chapter 25).

Solution · Repository per service, environment per branch

Split the monorepo into a repository per service plus one for infrastructure, and give each environment a branch whose merges deploy to it.

From monorepo to repository per service Monorepo All services + infrastructure One pipeline per service folder Independent repositories gateway history metadata infrastructure (Terraform) Splitting: git init for each folder, or keep history with git filter-branch.

A meta-repo (the meta tool and a .meta file) ties the repositories back into one virtual repository, so cloning and running everything feels like a monorepo again. Each team can keep one for its own services.

Environments and branches Developer own computer Development integrate daily Test weekly merge Production 1 to 2 weeks One branch per environment. A merge triggers deployment to that environment.

Each environment comes from the Terraform code of chapter 19, parameterized by environment name, with its state in cloud storage. A push to the development branch runs the CI tests from chapter 21 and deploys to development. Shorter gaps between merges mean fewer integration surprises. A separate configuration repository can also record which version of each service is deployed: the service pipeline publishes an image, and a change to that repository deploys it.

Do not split early. A configuration repository adds steps and errors, such as typing an older version number. Use it only to promote one version between environments, see history in one place, or restrict access.

Now the viral video. Microservices let you add capacity to one part, as chapter 22 showed.

Solution · Measure, then scale the lightest way

Find the bottleneck in the Kubernetes dashboard or cloud portal, then use the lightest fix. Most are a one-line change in Terraform or YAML.

Ways to scale Cluster, vertical bigger VMs Cluster, horizontal more VMs Service, horizontal more replicas Cluster, elastic autoscaler with min/max Service, elastic replicas follow demand Database split, then shard Many small VMs usually cost less than a few big ones.

Raise the VM size or the node count of the cluster, or raise the streaming service's replicas, the same field that gave redundancy. Elastic scaling does it automatically: the cluster autoscaler grows the node pool, and a horizontal pod autoscaler grows one service, each between a minimum and a maximum, so you pay only for the load you have. For data, keep one database per service so no shared database becomes the bottleneck; later spread them over more servers, then shard huge data sets.

Do not scale too early. You cannot predict how you will need to scale, so future-proofing often blocks the scaling you need. Keep it simple and scale when real load demands it.
Cost

More repositories, branches and environments mean more pipelines to maintain. And every scaling change is itself a change to production that can break the cluster.

Change it without breaking it

Problem

A developer merges a gateway change that crashes at start-up. The pipeline deploys it to every gateway pod, and every viewer sees an error. The same week, someone finds MongoDB and RabbitMQ, opened during early experiments, still reachable from the internet.

Solution · Layers of change protection

Catch a bad change as early, and as cheaply, as possible: in a pull request, in a test environment, during rollout, or by switching a whole environment.

Layers of change protection Pull request tests + review Test environment shake it down Rolling update one by one Blue-green whole new stack Branch protection forbids direct pushes to the production branch.

A rolling update replaces replicas one by one and moves on only when the new one passes its readiness probe. The broken gateway would stop at its first pod while the old pods keep serving, and you roll back. maxSurge and maxUnavailable cap how many extra and missing pods are allowed at once.

For risky infrastructure changes, such as the scaling changes above, use blue-green deployment: build a second environment from Terraform, test it, repoint DNS, and point it back if it misbehaves. A stateless cluster makes this safe.

Blue-green deployment Blue customers use it Green new stack, risky work Switch DNS blue to green If green misbehaves, flip DNS back. Works best when the cluster holds no data.

The open ports call for basic security (chapter 16 has the patterns).

Solution · Small attack surface, secrets out of code

Expose only the gateway. Add authentication there and HTTPS. Keep passwords, tokens and API keys in GitHub secrets, Kubernetes secrets or a tool such as Vault.

Think like an attacker: how would someone break this? Keep it simple; simple systems hide fewer flaws.

Trust models Internal trust Gateway authenticates Services trust each other Zero trust Gateway authenticates Authenticate every call Start with internal trust. Zero trust suits higher needs or several clusters.
Cost

Each layer slows the path to customers a little, and blue-green briefly doubles the infrastructure. All of it also assumed FlixTube was built as microservices from day one. Most teams start elsewhere.

Starting from a monolith instead

Problem

A team with a large monolith, like FTGO in the rest of this course, decides to rewrite it all as microservices at once. Months later nothing new has shipped, the rewrite is half done, and the old system still needs care.

Solution · Small, tested steps along natural seams

Convert the way FlixTube was built: small tested steps that keep the system working while features ship. First ask whether you need microservices at all.

Chapter 23 showed the strangler approach for FTGO. The practical sequence:

Refactoring a monolith step by step Plan shared vision, team Know the code tests, risks Automate deploy and test Platform cluster, template Find seams natural components Prioritize most benefit first Extract + test keep it working Repeat often for years If you cannot afford automation, you probably cannot afford microservices.

Carve along natural seams, components that already look like services; without them, refactor inside the monolith first, under tests. Extract first what changes most or gains most in speed or scale. Returns diminish: later extractions bring less, and services that are too small cost more than they give. It is fine to stop.

The spectrum from monolith to functions Spectrum of possibilities Monolith one big process Hybrid monolith + helpers Microservices many services Functions many tiny processes There is no right place on the line. Pick what suits your team, business and customers.

The hybrid, a monolith with a few helper services for jobs like thumbnails, is a sensible default when unsure. If you go all the way, start cheaply:

Microservices on a budget
A monorepo with one CD pipeline per service; a meta-repo after splitting
One database server, with one database per service
A one-VM cluster, one instance per service, simple pipelines
External file storage and database, so the cluster stays stateless
Without automated tests, a fast scripted boot with Compose and fixtures; automate deployment early
Cost

Two architectures run side by side, often for years, and automation must exist before the first extraction pays off.

Practices in this chapter

PracticeProblem it solvesWhat it costs
Shared layout, monorepo, pipeline per serviceServices organized differently; joint deploysCrowded as the team grows
API gatewayThe browser would need every serviceOne more hop on every request
Mock service and fixturesDevelopment needs the cloud; tests start from unknown dataMocks drift; fixtures to maintain
Deploy in stagesA failing pipeline with too many new partsSecrets in the pipeline
Logs, observability, probesUnseen and half-broken servicesTooling; restarts can hide bugs
Replication and fault isolationOne failure takes down a feature or the siteCompute; fallbacks to test
Timeout, retry, job queue, circuit breakerHanging calls and bursts of heavy workTuning; delayed work
Repository per service, environment per branchA growing team ships untested, clashing codeMore repositories and pipelines
Measured, elastic scalingOne service overloaded by demandScaling changes are risky changes
Rolling update, blue-green, small attack surfaceBad releases and exposed internals hit everyoneSlower rollouts; a second environment
Incremental refactoring, hybridA big-bang rewrite stalls deliveryTwo architectures for a long time

Recap

Quick check

FlixTube's upload service crashes on a corrupt file, and the gateway calls it with Axios and no timeout. What do viewers see, and what fixes it?
Show answer

Upload fails, and because Axios waits forever by default, gateway requests pile up until other pages hang too. Set a timeout, and let the gateway catch the error and report that upload is unavailable while serving everything else (fault isolation). Several replicas of upload keep it available while Kubernetes restarts the crashed one.

A rollout of the gateway shows that its first new replica never becomes ready. What happens?
Show answer

A rolling update waits for readiness, so it stops after the first replica. The old replicas keep serving, and you debug and roll back.

Why can a one-VM cluster with one replica per service still be a sound start?
Show answer

Early on you rarely need redundancy or extra performance, and it costs little. A stateless cluster with a database per service can later scale by changing replica and node counts, without a redesign.

Still open

This is the end of the course. You followed FTGO from monolithic hell to dozens of services and built FlixTube from one service to production. What stays open is your own system: which patterns it needs, and in what order. The pattern map lists every pattern with the problem it solves, so you can start from your own pain.

Explore the pattern map →

Back to the course home →