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
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.
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
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.
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.
| Term | Plain meaning |
|---|---|
| Microservice | A small independent process with its own deployment schedule and one owner |
| Microservices application | A distributed program built from collaborating services |
| Cluster | A group of computers presented as one pool of computing power |
| Orchestration | Automated management of services (Kubernetes does it here) |
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.
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.
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.
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.
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:
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.
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.
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 same rule shapes the whole hands-on track. This chapter covers the first row below; chapter 27 covers the second.
The tools:
| Tool | Why it is here |
|---|---|
| Node.js | Network oriented, light, quick to start an HTTP server; a huge community; JavaScript runs on both front end and back end |
| Git | Commit each working iteration so you can wind back |
| VS Code | Editor with a built-in terminal; later also used to browse logs and shell scripts |
| Docker, Compose, Kubernetes | Introduced 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.
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.
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.
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 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.
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.
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.
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.
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.
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.
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.
A Dockerfile for a Node.js service has four kinds of line:
| Command | Job |
|---|---|
docker build | Package the project as an image (the -t option names it) |
docker image list | List local images with their tag and size |
docker run | Start a container from an image, mapping ports and setting environment variables |
docker tag, docker login, docker push | Tag the image, authenticate, and upload the image to the registry |
docker container list | Show running containers |
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.
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.
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
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 Compose | Kubernetes | |
|---|---|---|
| Best at | Booting the whole app on a laptop | Running the app in production on a cluster |
| Start-up | One file, one command | Many commands, many configuration files |
| Weight | Light | Heavy; a local copy eats laptop resources |
| Scales to | One machine | Many machines |
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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 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.
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.
| Direct (HTTP) | Indirect (RabbitMQ) | |
|---|---|---|
| Target | A named service | A queue or exchange |
| Reply | Immediate response | None; the sender may not know a receiver exists |
| Coupling | Tight | Loose |
| Control | One service can orchestrate | Behavior emerges from the services |
| Good for | Strict sequences, commands | Notifications 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.
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.
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.
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
| Practice | Problem it solves | What it costs |
|---|---|---|
| Right-sized services along bounded contexts | One big service drifts into a monolith; tiny ones drown in network chatter | No formula; some boundaries will be wrong at first |
| Iterate, keep it working, commit | Big-bang builds fail in many places at once | Early code gets reworked as the app grows |
| Stream the response | Large video files exhaust memory and delay playback | Stream handling instead of simple file reads |
| Configure with environment variables | Hard-coded ports and hosts break when the environment changes | Every setting must be supplied; a missing one stops the service |
| Container image and registry | Services run only where their stack was installed by hand | Images to build, store and secure |
| Docker Compose for development | Starting many containers by hand is slow and error-prone | One machine only; production needs Kubernetes |
| Storage behind its own service, stateless cluster | Services tied to one storage provider; data lost when the cluster changes | An extra service and an extra network hop |
| Database per microservice | A shared database couples services through their data | Data shared between services must travel by messages or APIs |
| Dev and prod Dockerfiles with live reload | Rebuilding images for every edit kills the feedback loop | Two sets of files that can drift apart |
| Direct messaging (HTTP) | A service needs an answer now, or a strict sequence of steps | Tight coupling: the sender names every receiver |
| Indirect messaging (RabbitMQ queues and exchanges) | Every new listener forces a change to the sender | No reply; emergent behavior; a broker to run and wait for |
Recap
- Microservices manage complexity by splitting it into small processes with hard boundaries, and right-sized services that follow a bounded context beat the smallest possible ones.
- FlixTube is built in small, working, committed steps that move from simple to complex, so a mistake costs only the last step.
- The first service streams video instead of loading it into memory, reads its configuration from environment variables, and has a production mode (
npm start) and a development mode with nodemon. - Docker packages each service as an image built from a Dockerfile and stored in a registry, and Docker Compose boots the whole app on a laptop with one command, while production uses Kubernetes.
- Files sit in cloud storage behind a video-storage service, data sits outside a stateless cluster, and each service gets its own database; separate dev and prod Dockerfiles with a shared source folder give live reload.
- Direct HTTP messages are simple and allow orchestration but couple services, while indirect RabbitMQ messages through queues or fanout exchanges are loose and let behavior emerge.
Quick check
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.
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.
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.
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.