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

Building your first microservices

Knowing the patterns is not the same as having built a service. This chapter takes FlixTube, a small video-streaming app, from an empty folder to several services that run together on your laptop, with storage, a database and messaging, solving one concrete problem at each step.

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

Where we are

In chapter 25 we looked at the people side: Conway's law, ownership, platform teams and an architect who steers with principles and a paved road. Chapters 1 to 25 followed FTGO through every pattern. That left one thing open: all of it was explained, none of it was built by you.

This chapter

How do you get from an empty folder to a set of microservices that run, store data and talk to each other? You build FlixTube step by step with Node.js, Docker, Docker Compose, MongoDB and RabbitMQ. At the end you can package a service as an image, boot a multi-service app with one command, and choose between direct and indirect messaging.

Complexity grows: split it behind hard boundaries

Problem

Picture FlixTube as one program. Upload, search, viewing history and billing start as tidy modules. A year later a change to history breaks upload, because nothing stops one module from reaching into another. Every developer has to understand the whole program before touching any part of it.

Every application grows complex. Microservices do not remove that complexity. They cut it into small parts with hard boundaries, so the part you work on every day stays simple.

Tangled monolith parts versus microservices with hard boundaries Monolith: parts blur together Upload Search History Billing Microservices: hard boundaries Upload Search History Billing Both can be split into parts. Process boundaries keep microservice parts from tangling.
Solution · Microservices

Build the app as a microservices application: a distributed program made of many small microservices. Each one is an independent process with its own deployment schedule and, usually, its own data. One developer or one small team can own it and update it without touching the others.

Only a few services face users, usually through a gateway for web or mobile clients. Most are internal and are called over the network by other services. An orchestration platform, Kubernetes in this course, runs them all as a cluster on a cloud vendor.

A microservices application in a cluster Cloud vendor (Azure here) Kubernetes cluster Gateway exposed Service A Service B Service C Service D Database server may be outside File storage cloud storage Only the gateway faces users. Kubernetes starts, restarts and connects the services.
TermPlain meaning
MicroserviceA small independent process with its own deployment schedule and one owner
Microservices applicationA distributed program built from collaborating services
ClusterA group of computers presented as one pool of computing power
OrchestrationAutomated management of services (Kubernetes does it here)
Cost

A distributed program has more moving parts than one process, and every boundary is a decision. Draw the boundaries badly and the complexity comes back as network chatter between services.

What goes in each service, and how big it should be

Hard boundaries help only if they are in the right places.

Problem

Should FlixTube have one "video" service that stores, streams and recommends videos? Or ten tiny services, one per function? One big service drifts back toward a monolith. Ten tiny ones spend their time calling each other, and a single page view becomes a chain of network calls.

Designing microservices is ordinary software design. Do not over-design or future-proof, keep refactoring so the design stays simple, and let a good design emerge. Plan every iteration, but expect the plan to change.

Solution · Classic design principles plus bounded contexts

Give each service a single responsibility, keep services loosely coupled and highly cohesive, and use domain-driven design (DDD) to find the boundaries. A bounded context, a bubble in which all terms and logic fit together, maps well to one microservice.

Four principles for microservices Single responsibility Separation of concerns Loose coupling few, minimal links High cohesion belongs together Loose coupling lets you upgrade one service without ripples.

The same concept can live in two contexts with slightly different meanings. To the recommendations context, a Video is something a user liked. To the video-storage context, it is a file. That is fine, and it is the same idea as FTGO's Order meaning different things to Kitchen and Accounting in chapter 2.

Bounded contexts map to microservice boundaries Recommendations Video storage User Video Like Video File similar idea Each box is a bounded context. The same concept may live in several services.

DRY (do not repeat yourself) bends here. Sharing code across process and team boundaries is hard, and a bad shared abstraction often costs more than a little duplicated code. Share only when it clearly makes sense.

And size? There is no right answer, only a trade-off:

How much should one microservice hold Too small more chatter Right-sized follows a domain concept Too big drifts toward a monolith The smaller the services, the more they must talk, and the more complex the whole system gets.
Right-sized beats smallest. The author of the FlixTube example even dislikes the name "microservices", because it pushes people to go too small. Ask the same question you ask about a function or a class: what is one cohesive area of responsibility?
Cost

Principles do not draw the boundaries for you, and you will get some wrong. That is acceptable only if you can change the design cheaply, which means building in a way that keeps the app working while it changes.

FlixTube, built in small working steps

Design gives the target. Now we need a way to get there without breaking things on the way.

Problem

You could write all of FlixTube's services first and then try to run them together. For weeks nothing runs, and when you finally start everything, a dozen problems appear at once and you cannot tell which change caused which.

The running example is FlixTube, a small video-streaming product. Video streaming is a classic microservices use case. The finished app has a gateway that serves the UI, and services for streaming, storage, upload, metadata and viewing history.

FlixTube services at a glance Browser Gateway UI + REST Video streaming Storage Cloud Upload History viewed videos Metadata Dashed: indirect messaging. Solid: direct HTTP calls.
Solution · Iterate and keep it working

Work in small steps, keep the app working after every step, and move from simple to complex. Commit each working step to Git. If a step goes wrong, revert to the last commit and lose almost nothing.

The personal iteration loop Small change a few lines Test it see it work Commit save to Git Repeat feedback each loop Many working iterations add up to a large body of working code, with no big-bang risk.

The same rule shapes the whole hands-on track. This chapter covers the first row below; chapter 27 covers the second.

The path of the example Step 1 Node.js service Step 2 Docker image Steps 3-5 Compose, data Step 6 messaging Deploy K8s, Terraform, CD Test automated tests Run FlixTube, health Grow scaling This chapter covers the first row. Chapter 27 covers the second.

The tools:

ToolWhy it is here
Node.jsNetwork oriented, light, quick to start an HTTP server; a huge community; JavaScript runs on both front end and back end
GitCommit each working iteration so you can wind back
VS CodeEditor with a built-in terminal; later also used to browse logs and shell scripts
Docker, Compose, KubernetesIntroduced in later steps of this chapter and in chapter 19

Node.js and Azure are only examples. Docker, Kubernetes and Terraform exist precisely so you can swap the language and the cloud vendor.

Cost

Small steps feel slow at first, and you will rework early code as the app grows. But every step starts from something that runs, so the first step must be the smallest thing that runs: one service.

Step 1: a first service that streams video

FlixTube's core job is to play a video in the browser, so that is the first service.

Problem

A video file can be hundreds of megabytes. If the server reads the whole file into memory before answering, a few viewers at once exhaust its memory, and each viewer waits for the full read before playback starts.

Solution · Stream the file

Build one Express web server with a single /video route. The handler opens the file as a Node.js read stream and pipes it into the HTTP response, so bytes flow to the browser as they are read and the whole video is never in memory.

The streaming path Browser GET /video Express route handler runs Read stream video file HTTP response piped to client Node.js streams carry the bytes through a pipe. Playback starts before the file ends.

The service also needs to know which port to listen on. Hard-code 3000 and it clashes the day two services run on one machine, or the day the platform picks the port.

Solution · Configure with environment variables

Read settings from environment variables, the standard way that every tool used later supports. The service reads PORT and throws if it is missing, so a forgotten setting fails loudly at start-up instead of silently later.

Configuring the service with an environment variable Environment PORT=3000 Microservice reads process.env.PORT Listens on port Throws, will not start set missing Compose and Kubernetes later supply the same variables, so one image runs anywhere.

Two run modes come from this step and are reused in every later one. Production mode installs only the runtime dependencies and starts with the standard npm start. Development mode also installs nodemon, which restarts the service whenever you save a code change.

Production mode and development mode Production mode Install runtime deps only npm start Development mode Install dev deps (nodemon) npm run start:dev Same convention in every project, so you never need to remember the main file name.
Cost

The service runs on your machine because your machine has the right Node.js version and the right packages installed. A colleague's laptop, a test server or a cloud VM may not, and installing everything by hand on each one is slow and error-prone.

Step 2: run it anywhere with Docker

A service that runs only on the developer's laptop cannot be deployed, and every new service adds another set of things to install.

Problem

The streaming service needs Node.js and its npm packages. To run it on a server you must install the same versions there, and keep them in step every time you upgrade. With ten services in different stacks, each server becomes a fragile, hand-made snowflake.

Solution · Package the service as a container image

Put the code, its dependencies and its assets into one image, and run the image as a container on any machine that has Docker. Store images in a registry so any machine with credentials can pull them.

A container is lighter than a virtual machine. A virtual machine carries a full guest operating system; a container shares the host's operating system kernel and holds only the service and what it needs. That is why many containers fit on one computer and why running many microservices stays affordable.

Virtual machines compared with containers Virtual machines Containers Hardware and host OS VM 1 guest OS + service VM 2 guest OS + service Hardware and host OS Container service Container service Container service Heavy copies of an OS on the left, small isolated processes on the right.

Four terms carry the whole workflow. An image is a snapshot of code, dependencies and assets. A container is a running instance of an image. A Dockerfile is the script that builds the image. A registry stores images; a company with proprietary code publishes to a private registry in the cloud.

Build, publish, run Dockerfile + Node.js project Image docker build Registry docker push Container docker run Publish to a private registry in the cloud, as a company with proprietary code would.

A Dockerfile for a Node.js service has four kinds of line:

Reading a Dockerfile FROM start from a base image (a Node.js version) COPY copy package files, then the source code and assets RUN install dependencies at build time CMD what to run when a container starts (npm start) Each line adds a layer to the image. A .dockerignore file keeps junk out of the build.
CommandJob
docker buildPackage the project as an image (the -t option names it)
docker image listList local images with their tag and size
docker runStart a container from an image, mapping ports and setting environment variables
docker tag, docker login, docker pushTag the image, authenticate, and upload the image to the registry
docker container listShow running containers
A universal package manager. One useful way to think of Docker: a single package format for every tech stack, and a way to give every developer the same environment as production.
Cost

Each image is one service. FlixTube will soon have a streaming service, a storage service, a database and a message broker. Building and starting each container by hand, with the right ports and variables, every time you sit down to work, wastes a lot of time.

Step 3: start the whole app with Docker Compose

One container by hand is fine. Five containers by hand, several times a day, is not.

Problem

To test a change you run docker build and docker run for each service, remember every port mapping and environment variable, and stop them all again afterward. You forget one variable, a service refuses to start, and twenty minutes go into finding out why.

Solution · Docker Compose file

Describe the whole application as a set of containers in one YAML file. One command builds and starts them all; another stops and removes them.

docker compose up --build
docker compose down
One file, one command, many containers Compose file one YAML file docker compose up --build Service 1 Service 2 Database Containers reach each other by name: the container name is the host name.

Compose gives you what a lone service lacks: a reproducible way to boot the whole app, to drop one project and start another, and to keep several configurations for different slices of the app. Inside the Compose network, containers reach each other by name. Wrap the longer commands in small shell scripts so nobody has to remember them.

Why not use Compose in production too? Because it is built for one machine:

Docker ComposeKubernetes
Best atBooting the whole app on a laptopRunning the app in production on a cluster
Start-upOne file, one commandMany commands, many configuration files
WeightLightHeavy; a local copy eats laptop resources
Scales toOne machineMany machines
Why not Compose in production Cloud VM you create it Install Docker by hand Copy the code by hand Run Compose hard to scale Compose in production means all of this. Kubernetes automates it, so production uses Kubernetes.
Cost

Compose is a development tool, so production will need Kubernetes (chapter 27). And so far the streaming service reads a video file baked into its own folder. Real videos are uploaded by users and must live somewhere that survives a container restart.

Step 4: add storage and a database

Containers come and go. The videos and the records about them must not.

Problem

The streaming service reads its video from a local folder. If it reads straight from a cloud storage SDK instead, the service is tied to one provider, and switching from Azure to another cloud means rewriting the code that streams video. FlixTube also needs to remember things, such as which videos exist, and a container's own disk disappears when the container is replaced.

Solution · Hide storage behind its own service

Put files in cloud storage (Azure Storage here; Amazon S3 or Google Cloud Storage do the same job) and add a small video-storage microservice with a REST API in front of it. The streaming service forwards its HTTP request to video-storage and streams the answer back to the browser. Swapping providers later changes only video-storage.

Hiding the storage provider behind a microservice Browser Video streaming forwards request Video storage REST API Cloud storage private files The streaming service forwards its HTTP request and streams the answer back to the client.

Where should the bytes live: inside the cluster, on volumes, or outside it? FlixTube keeps a stateless cluster. Files and data sit outside Kubernetes, in cloud storage and a managed database. The cluster can then be destroyed and rebuilt at will without losing data, which also makes blue-green deployments possible (chapter 27).

Cloud storage versus cluster storage Stateless cluster (preferred) Services Rebuild freely Data outside: storage + managed DB State inside the cluster Services Data at risk Volumes inside the cluster Cloud storage is also simple, works in development, is cheap and managed for you.

For records, add a MongoDB server to the Compose file from a public image, and a database exists within seconds. Services find it through a host name and a database name, both given as environment variables like PORT. In production, use an external, managed database instead.

Solution · Database per microservice

Give each service its own database. One database server can host several databases, so this costs little. Data stays private to the service that owns it, exactly as chapter 8 argued for FTGO.

Database per microservice, not a shared database One database server video-streaming database history database Video streaming History Shared database services coupled through data Fragile, hard to scale One server may host many databases. One database per service keeps data private to its owner.
Per microservice, not per application. A shared database is an integration point that makes the system more fragile and less scalable. Break the rule only for a good, deliberate reason.
Cost

The app now has more containers: streaming, video-storage and MongoDB. Every code change means rebuilding an image and restarting Compose, which takes long enough to break your concentration many times a day.

Step 5: fast feedback with live reload

With several services in Compose, the build-restart loop becomes the slowest part of the day. We feel it as soon as we add the next service.

Problem

FlixTube needs a history service that records which videos a user watched, so it can later feed recommendations. While you write it, every small edit means rebuilding its image and restarting the containers. A one-line change takes a minute to try, and you try dozens a day.

The history service receives a "viewed" message from the streaming service and writes it to its own database. It is also the example for the messaging step that follows. To keep the focus on communication, the storage service is left out of this part of the app.

The viewed message Video streaming user watches "Viewed" message sent to history History records it History DB own database For this chapter the storage service is dropped to keep the focus on communication.
Solution · Separate dev and prod Dockerfiles, plus live reload

Split the single Dockerfile in two. Dockerfile-dev favors fast iteration: no code baked in, dev dependencies and nodemon. Dockerfile-prod favors performance and security: code copied in, production dependencies only. In development, Compose shares the source folder with the container, and nodemon restarts the service on every save.

Two Dockerfiles for two purposes Dockerfile-dev No code baked in Dev deps, nodemon npm run start:dev Dockerfile-prod Code copied into image Production deps only npm start Dev: source is shared from the host. Prod: everything is inside the image.
The live reload loop in Compose Edit in VS Code save a file Shared volume src in container nodemon sees the change Service restarts refresh browser Under WSL2 or a VM, nodemon needs its polling option, because file watching does not cross over.

Keep the two Dockerfiles side by side so the dev one does not drift far ahead of the prod one. And do not leave production mode until deployment day: keep a second Compose file for it and run it now and then, selecting the file with the -f option, so problems do not pile up unseen. A good rhythm is to test dev mode every few minutes and production mode every few hours.

Cost

Two Dockerfiles and two Compose files are more to maintain, and they can drift apart. With the history service running, a new question appears: how should the streaming service tell history that a video was watched?

Step 6: let services talk, directly and through RabbitMQ

Services must cooperate, and there are two styles of message. Call them direct and indirect rather than "synchronous" and "asynchronous", because those words already mean something else to programmers.

Problem

Every time a user watches a video, the streaming service must tell the history service. Next month a recommendations service will want the same news. If streaming has to know about, and call, every service that cares, each new listener means changing and redeploying streaming.

The simplest option is a direct message: an HTTP POST from streaming to history.

Direct messaging with HTTP Sender video streaming Receiver history HTTP POST "viewed" direct response Direct: the receiver is named, cannot ignore the message, and answers at once.

Direct messages over HTTP are easy: HTTP and DNS are everywhere, and in Compose the container name is the host name. One controller can orchestrate a strict sequence: send a message, wait for the reply, then send the next. The price is tight coupling, which is exactly the problem above.

Solution · Indirect messaging through a broker

Streaming publishes a "viewed" message to a message broker, RabbitMQ, and does not know or care who receives it. Any service that wants the news subscribes. Adding a listener never changes the sender.

Indirect messaging through a broker Sender Broker RabbitMQ Receiver Indirect: neither side knows the other, so there is no direct reply.
Direct (HTTP)Indirect (RabbitMQ)
TargetA named serviceA queue or exchange
ReplyImmediate responseNone; the sender may not know a receiver exists
CouplingTightLoose
ControlOne service can orchestrateBehavior emerges from the services
Good forStrict sequences, commandsNotifications and designs that must evolve

RabbitMQ is a mature broker built on the AMQP protocol. Like MongoDB, it starts in Compose from a public image. Services talk to it with the amqplib library and find it by DNS name; they never meet each other. A message goes either to a queue or to an exchange, and the choice decides who receives it.

Single-recipient messages Video streaming Viewed queue one shared queue History A History B Single recipient: each message goes to exactly one consumer, like a pool of workers.

A service "asserts" a queue: it creates the queue only if it does not exist yet, so several services can safely share it. Consumers acknowledge each message once they have handled it. With one shared queue, each message reaches exactly one consumer. That suits a pool of workers, but not our case, where history and recommendations both need every "viewed" message.

Multiple-recipient messages with an exchange Video streaming Viewed exchange fanout Queue 1 Queue 2 History Recommend Multiple recipients: each service owns an anonymous queue bound to the shared exchange.

For multiple recipients, streaming publishes to a fanout exchange. Each interested service creates its own anonymous queue and binds it to the exchange, so every service gets its own copy. Add a new consumer and the sender never changes. That is the benefit and the risk: with no central controller, the app's behavior emerges from how each service reacts to what it hears, and may emit further messages in turn. It is harder to follow than one orchestrating service, but there is no single point of failure in charge of everything.

One practical snag shows up at once. Compose starts the history service and RabbitMQ together, and history may try to connect before the broker is ready.

The start-up order problem Compose starts both history and RabbitMQ History connects early broker not ready Wait for the port a start-up delay The MongoDB library retries on its own. Chapter 27 solves this properly with Kubernetes probes.
Cost

Indirect messaging trades control for flexibility: no reply, behavior spread across services, and a broker that must be running before anyone can use it. For now, a start-up delay that waits for the broker's port is enough on a laptop. In production, services crash, restart and scale, and that needs real health checks.

Practices in this chapter

PracticeProblem it solvesWhat it costs
Right-sized services along bounded contextsOne big service drifts into a monolith; tiny ones drown in network chatterNo formula; some boundaries will be wrong at first
Iterate, keep it working, commitBig-bang builds fail in many places at onceEarly code gets reworked as the app grows
Stream the responseLarge video files exhaust memory and delay playbackStream handling instead of simple file reads
Configure with environment variablesHard-coded ports and hosts break when the environment changesEvery setting must be supplied; a missing one stops the service
Container image and registryServices run only where their stack was installed by handImages to build, store and secure
Docker Compose for developmentStarting many containers by hand is slow and error-proneOne machine only; production needs Kubernetes
Storage behind its own service, stateless clusterServices tied to one storage provider; data lost when the cluster changesAn extra service and an extra network hop
Database per microserviceA shared database couples services through their dataData shared between services must travel by messages or APIs
Dev and prod Dockerfiles with live reloadRebuilding images for every edit kills the feedback loopTwo sets of files that can drift apart
Direct messaging (HTTP)A service needs an answer now, or a strict sequence of stepsTight coupling: the sender names every receiver
Indirect messaging (RabbitMQ queues and exchanges)Every new listener forces a change to the senderNo reply; emergent behavior; a broker to run and wait for

Recap

Quick check

The streaming and history services share one database table because it is "easier". Six months later the history team wants to change the table's structure. What breaks, and what should they have done?
Show answer

The database is an integration point: the streaming service depends on the table too, so the change breaks it, and the two services can no longer change or deploy independently. The shared database also becomes a bottleneck. Give each service its own database, even if both live on one database server, and share data through messages or an API.

You publish one "viewed" message and want both history and recommendations to receive it. Queue or exchange?
Show answer

An exchange, with one anonymous queue per consuming service bound to it. A single shared queue would hand each message to only one of the two services.

Why does FlixTube keep its Kubernetes cluster stateless?
Show answer

Files and data live outside the cluster, in cloud storage and a managed database, so the cluster can be destroyed and rebuilt at will without losing data. That also makes blue-green upgrades possible.

Still open

FlixTube now runs as several services on one laptop under Docker Compose. Production is a different place: the app must be deployed to a cluster, kept healthy when services crash or start in the wrong order, and scaled as viewers arrive.

Next: 27 FlixTube in production →