DevOps Kit Lessons Lesson 8 of 18

Checking your sign-in…

🔒

This lesson is in Phase 1 — ₹399, one-time

Pay once with UPI, card or netbanking. Keep it forever. Your progress saves, so you can stop and come back.

← Back to all lessons

End-to-End Lab — One Fake Order, All the Way Through

Phase 1 · The Data Tier

What this is and why it matters

This lab is the whole pipeline: one fake order travelling through five tools, on one machine, with one start. Then the main database dies mid-flow, and the standby takes over. A new order still flows through.

Think of a small stationery shop. A customer places an order — a notebook, a pen, a mug. The order is a small file. That file travels like a parcel through a chain of workers:

  1. The file lands in a folder called incoming/.
  2. A program called ingest sees it, stores a copy of the file in the file cupboard, and sends the order as a message.
  3. A program called worker reads the message, saves the order as a row in the database, and adds 1 to a counter.
  4. The file moves to a folder called processed/ — done.
  5. Meanwhile, a traffic guard spreads visitors across three copies of the shop front.
  6. The database copies every change to its standby, live, so the standby is always ready.

In real systems, the pieces only prove themselves together. The real test is when the main database dies mid-flow. That is what Steps 5 to 8 test: kill the main database, promote the standby to main, and send one more order through.

All names, items and amounts are made up for this lab. Nothing here is a real order, a real customer, or real money.

Your level in Whole System & On-Call
Step 1 · Beginner→✓ Step 2 · Intermediate→✓ Step 3 · Advanced ← You are here
After this lesson you can: Break a multi-part setup on purpose and fix it.
This is the last step of the Whole System & On-Call ladder.
Advanced challenge: An order stuck after the worker stopped — start the worker, watch it catch up, check the count. — try it in End-to-End.

Test status

Syntax-checked only (20 November 2026). The compose file, the two Python programs and the shell script were checked for correct syntax. The Python files also compile cleanly. This lab was not run end-to-end on this machine, because this machine has no Docker. Follow it on your own machine with Docker. No step here is promised to work on a real machine — if a step fails, read the error first. That is the real skill.

v2 (20 November 2026): fixed the four faults found in the EC2 demo — the backends now use an image that works on ARM64, the database setup file is readable, the Kafka client works on Python 3.12, and the object store is now Moto (MinIO's free images are gone). Still syntax-checked only, not run end to end.

Words you need here

Read this list first. Every word below is used in the steps. Nothing here is used before it is defined.

  • Docker — a tool that runs small sealed boxes on your machine. Each box holds one program and everything that program needs. You need Docker running before Step 1.
  • Container — one sealed box run by Docker. In this lab there are eleven boxes. Each box does one job.
  • Image — the recipe Docker uses to build a box. A box is a running image.
  • Service — one named job in the file docker-compose.yml. Each service becomes one container. The eleven services here are kafka, postgres-primary, postgres-replica, redis, moto, lb, web1, web2, web3, ingest, and worker.
  • docker-compose.yml — a recipe file. It lists the eleven services, what image each one uses, and how they talk to each other. It lives in the folder phase1/end-to-end.
  • Pipeline — a chain of tools where each tool does one job and hands the work to the next tool. Like a factory line: each station does one thing, then passes the item on.
  • Ingest — the program that takes new order files in. Its box is called ingest. It watches the folder incoming/ for new files, stores a copy of each file in the file cupboard, and sends the order to Kafka. Its code is in the file ingest.py in the folder phase1/end-to-end.
  • Worker — the program that does the saving. Its box is called worker. It reads orders from Kafka, saves each one in PostgreSQL, and adds 1 to the counter in Redis. Its code is in the file worker.py in the same folder.
  • Object store (Moto) — a big file cupboard. You store a file by a name and ask for it back by the same name. Moto is a free stand-in for Amazon S3, a paid file-cupboard service. Moto speaks the same S3 language, so what you learn here transfers. Moto keeps everything in memory: stop the lab and the files are gone. The cupboard's box here is called moto, and it holds one bucket called incoming.
  • Bucket — a named box inside the file cupboard. Files live in buckets. This lab uses one bucket called incoming.
  • Kafka — a message queue. It carries messages between programs. One program sends a message in, another program reads it out. The messages here are orders. Orders travel on a channel called a topic, and this lab's topic is called orders. Kafka's box is called kafka.
  • Topic — one named channel inside Kafka. Messages on the same topic are about the same thing. This lab uses one topic, called orders.
  • PostgreSQL — a database. It stores rows in tables. Say it "post-gres-Q-L". This lab's database is called practice, and its table is called orders. Each order becomes one row: id, item, amount, buyer.
  • Table — a grid inside a database. Columns are the fields (id, item, amount, buyer). Rows are the records (one order per row).
  • Row — one record in a table. Order 101 is one row.
  • Primary / main database — the database that takes writes. Its box is called postgres-primary. When it dies, the standby takes over.
  • Replica / standby — a live copy of the main database. Its box is called postgres-replica. The main database copies every change to it, live. "Replica" and "standby" mean the same thing here: the spare copy, waiting.
  • Failover — the spare taking over when the main fails. The standby is promoted to main, and work continues.
  • Promote — turn the standby into the main database. After promotion, the standby takes writes. The command for it is in Step 6.
  • Redis — a very fast store for small values, like counters. Its box is called redis. This lab uses it for one counter: a key called orders:count that holds the number of orders saved so far.
  • Key — a name that holds one value in Redis. orders:count is a key. Its value is a number: 3 after three orders, 4 after four.
  • Load balancer (lb) — a traffic guard. It stands in front of copies of the shop front and sends each visitor to a different copy. NGINX is the program that does this job here. The guard's box is called lb.
  • Backend — one copy of the shop front, behind the guard. The three backends are called web1, web2, and web3. Each one answers with its own name, so you can see which one answered.
  • Round robin — taking turns. Backend 1, then 2, then 3, then 1 again. That is how the guard shares the work by default.
  • Port — a door number on a machine. The doors used here, on your machine: Kafka 9092, main database 5432, standby database 5433, Redis 6379, file cupboard 9000, guard 8080. You do not need to open these doors yourself — the recipe file opens them. The numbers are listed here so you recognise them if they appear in an error.
  • localhost — a name that means "this machine". http://localhost:8080/ means "the web page served by my own machine, on door 8080".
  • curl — a small tool that asks a web page for its content and prints the answer in your terminal.
  • Terminal — the black window where you type commands. Every command in this lab is typed in the terminal, then you press Enter. Steps 7 and 8 need TWO terminals open at once — that is explained in Step 7.
  • JSON — a plain-text way of writing one record. It uses curly brackets, quoted names, and commas. Example: {"id": 101, "item": "notebook", "amount": 250, "buyer": "Asha"}. Read it as: id 101, item notebook, amount 250, buyer Asha. You do not need to learn JSON — you only copy the pattern in Step 4.
  • Folder / directory — the same thing. A folder holds files. This lesson says "folder" every time.

What you need first

  • Docker running on your machine. The lesson points to Phase 2, zero-cost-lab.md, for setting Docker up. Do that first if Docker is not installed yet.
  • How to tell Docker is running: open your terminal and type docker ps, then press Enter. docker is the tool. ps means "show the boxes that are running". If Docker is running, you see a list — even an empty list — with no error.
  • The single-topic labs (Kafka, PostgreSQL, Redis, object store, load balancer) done first. This lab uses all of them at once. If you have not done them, do them first — each tool is explained in its own lab, and this lesson only recaps each tool in one line. The recap is in "Words you need here" above: Kafka carries messages, PostgreSQL saves rows, Redis counts, Moto holds files, NGINX guards the front door.
  • The files in the folder phase1/end-to-end. That folder holds docker-compose.yml, Dockerfile, requirements.txt, ingest.py, worker.py, nginx.conf, a folder called postgres/ with 01-replicator.sql and replica-entrypoint.sh, a folder called incoming/ with three fake orders (order-001.json, order-002.json, order-003.json), and an empty folder called processed/. All of these paths were checked to exist on disk.
  • requirements.txt is the list of Python helper packages the two programs need. You never install them yourself — the Dockerfile builds them into the image.
  • postgres/01-replicator.sql is the setup file the main database runs once, to create the user the standby uses to copy data. postgres/replica-entrypoint.sh is the standby's start-up script — it copies the main database's data once, then follows it live. You never run either file yourself.
  • order-map-worksheet.txt also sits in this folder. It is the same fill-in-the-map exercise from the "Fill in the map" section below.

Getting into the right folder

Every command in this lab is run from inside the folder phase1/end-to-end.

  • What: cd means "change folder". It moves your terminal into a folder.
  • Why: the commands below look for docker-compose.yml in the folder your terminal is sitting in. If you are in the wrong folder, they fail.
  • How: open your terminal in the folder phase1/end-to-end on your machine. If your terminal opens somewhere else, type this command, then press Enter:

`` cd phase1/end-to-end ``

Type it exactly as shown, from the folder that holds phase1. cd means "change folder" — it moves your terminal into the folder named after it.

  • Check you are in the right place: type ls and press Enter. ls means "list the files here". You should see docker-compose.yml, ingest.py, worker.py, incoming, and postgres in the list. If you do not see them, you are in the wrong folder. Move again until ls shows them.

The fake shop, in plain words

A small online shop sells stationery — notebooks, pens, mugs, pen stands, rulers. A customer places an order. The order is a small file like this:

Try it Yourself »Open the practice terminal and run it yourself — nothing installs. Included with Phase 1. Simulation — practice version. Run the real lab with Docker to do it for real.
Command
{"id": 101, "item": "notebook", "amount": 250, "buyer": "Asha"}

Read it as: order number 101, a notebook, 250, bought by Asha. The amount has no currency sign — it is a made-up number for practice.

The order travels like this:

  1. The file lands in incoming/.
  2. ingest sees it, stores a copy of the file in the object store (Moto, bucket incoming), and sends the order to Kafka (topic orders).
  3. worker reads the order from Kafka, saves it in PostgreSQL (table orders), and adds 1 to the counter in Redis (orders:count).
  4. The file moves to processed/ — done.
  5. Meanwhile, the load balancer (lb) spreads visitors across three backends (web1, web2, web3).
  6. PostgreSQL copies every change to its standby, live.

Step 1 — Start everything with one command

What this step does: first it fixes the permissions on the database setup file, then it starts all eleven boxes with one command.

Why the permission fix comes first: the database runs as its own user inside its box. That user cannot read a file that is private to you on your machine. The setup file postgres/01-replicator.sql must be readable by everyone, or the database cannot read it when it starts. One command fixes that for the whole folder.

The permission command, word by word, before you run it:

Command
chmod -R a+r .
  • chmod — change a file's permissions. Permissions are the rules for who may read, write, or run a file.
  • -R — do it for this folder AND everything inside it, including the postgres/ folder. Short for "recursive", meaning "go down through all the folders inside".
  • a+r — add read permission for everyone. a means "all users". +r means "add read". Read means "may open and look at the file".
  • . — a single dot. It means "this folder" — the folder your terminal is sitting in, which should be phase1/end-to-end.

Run it now, from inside the folder phase1/end-to-end.

What you should see: nothing. chmod prints nothing when it works. Silence means it worked here. That is normal.

If it breaks: "No such file or directory" means you are in the wrong folder — run ls and check you are inside the end-to-end folder, then try again.

Then — start everything. The command, word by word:

Command
docker compose up -d --build
  • docker — the tool that runs boxes.
  • compose — read the recipe file docker-compose.yml and run everything it lists.
  • up — start everything in the recipe.
  • -d — run in the background. Short for "detached". It means: start the boxes and give me my terminal back, so I can type the next command.
  • --build — build the small Python image first, from the Dockerfile, before starting. Needed on the first run. The image holds the ingest and worker programs and the helper packages listed in requirements.txt.

What you should see: the build lines for the small Python image, then the services start, one line each. The first start builds the small Python image and downloads the others, so it takes a few minutes. Wait until the lines stop.

How to tell it worked: run the check command below.

The check command, word by word:

Command
docker compose ps
  • docker compose — the tool, reading the recipe file.
  • ps — show the boxes from this recipe and their state.

What you should see: eleven boxes with STATUS "Up". "Up" means the box is running.

Command
NAME                 STATUS
kafka                Up
postgres-primary     Up
postgres-replica     Up
redis                Up
moto                 Up
lb                   Up
web1                 Up
web2                 Up
web3                 Up
ingest               Up
worker               Up

The real table has more columns than this. What matters is all eleven names, each with STATUS "Up".

  • kafka carries the messages. postgres-primary is the main database. postgres-replica is the standby copy. redis holds the counter. moto is the file cupboard. lb is the guard. web1, web2, web3 are the three shop-front copies. ingest takes new order files in. worker saves the orders.

If it breaks: if any box shows "Exited", that box stopped. "Exited" means it ran and then stopped, usually because of an error. Read its diary with:

Command
docker compose logs <name>
  • docker compose logs — show the diary lines for one box. A log is the box's diary — lines it printed while it ran.
  • <name> — replace this with the real box name, for example worker. So the real command is docker compose logs worker. Look for the error line.

The most common cause on the first run is a slow download — wait a minute and run docker compose up -d again.

Step 2 — Watch the three orders flow

What this step does: you read the diaries of the two programs — first ingest, then worker — and watch the three fake orders travel through.

Why: the orders should flow by themselves within seconds. The diaries are the only way to see it happen. There is no web page to watch.

The incoming/ folder already holds three fake orders: order-001.json, order-002.json, and order-003.json. The ingest program should pick them up within seconds.

First — watch ingest. The command, word by word:

Command
docker compose logs ingest
  • docker compose logs — show the diary lines for one box.
  • ingest — the box that takes new order files in.

What you should see: lines like these:

Command
Connected to Kafka.
Connected to the object store.
Watching /incoming for new order files...
Sent order-001.json: {'id': 101, 'item': 'notebook', 'amount': 250, 'buyer': 'Asha'}
Sent order-002.json: {'id': 102, 'item': 'pen', 'amount': 40, 'buyer': 'Ravi'}
Sent order-003.json: {'id': 103, 'item': 'mug', 'amount': 350, 'buyer': 'Meena'}

Line by line:

  • Connected to Kafka. — ingest reached the message queue. Good.
  • Connected to the object store. — ingest reached the file cupboard. Good.
  • Watching /incoming for new order files... — ingest is now watching the folder /incoming inside its box. That folder is shared with the incoming/ folder on your machine, so a file you drop in incoming/ is seen at once.
  • Sent order-001.json: {...} — ingest sent order 101 (notebook, 250, Asha) to Kafka. "Sent" here means two things already happened: the file was stored in the cupboard first, then the order was sent as a message. Ingest only prints "Sent" after it has stored the file. So the three "Sent" lines mean all three files are in the cupboard.
  • The next two Sent lines are orders 102 (pen, 40, Ravi) and 103 (mug, 350, Meena).

Now — watch the worker. The command, word by word:

Command
docker compose logs worker
  • worker — the box that saves the orders.

What you should see: lines like these:

Command
Connected to PostgreSQL.
Connected to Redis.
Connected to Kafka. Waiting for orders...
Saved order 101: notebook (250)
Saved order 102: pen (40)
Saved order 103: mug (350)

Line by line:

  • Connected to PostgreSQL. — worker reached the database. Good.
  • Connected to Redis. — worker reached the counter store. Good.
  • Connected to Kafka. Waiting for orders... — worker reached the message queue and is waiting for orders to arrive.
  • Saved order 101: notebook (250) — worker saved order 101 in the database and added 1 to the counter. The next two lines are orders 102 and 103.

If it breaks: if the worker says "Waiting for PostgreSQL..." for more than two minutes, the database is not up yet — check docker compose ps. If the ingest diary shows no "Sent" lines, check the incoming/ folder still holds the files — run ls incoming/. If the files are gone but nothing was saved, read the worker diary from the top — the error line is usually about a connection, meaning one box cannot reach another box.

Step 3 — Prove it in four places

What this step does: you check the same three orders in four places: the database, the counter, the file cupboard, and the guard. Each check proves one hop of the journey.

Why: one check could lie. Four checks, all agreeing, prove the whole pipeline works.

Check 1 — the database

The command, word by word, before you run it:

Command
docker compose exec postgres-primary psql -U learner -d practice -c "SELECT * FROM orders ORDER BY id;"
  • docker compose exec — run a command inside one box from this recipe. exec means "run this inside the box".
  • postgres-primary — the box to run inside. The main database box. We run inside it because the database tool lives there.
  • psql — the database command tool. It talks to PostgreSQL.
  • -U learner — connect as the user called learner. -U means "user". learner is the practice user name written in the recipe file.
  • -d practice — use the database called practice. -d means "database".
  • -c "SELECT * FROM orders ORDER BY id;" — run this one database question, then stop. -c means "run this command". The question is written in SQL, the database's question language:
  • SELECT * FROM orders — show me everything from the table called orders. SELECT means "show me". * means "all columns".
  • ORDER BY id — sort the rows by the id column, smallest first.
  • ; — end of the question.

What you should see:

Command
 id  |   item   | amount | buyer
-----+----------+--------+-------
 101 | notebook |    250 | Asha
 102 | pen      |     40 | Ravi
 103 | mug      |    350 | Meena
(3 rows)

Line by line:

  • The first line is the column names: id, item, amount, buyer. Columns are separated by |.
  • The second line is a divider made of - and + signs. It separates the names from the rows.
  • The next three lines are the three orders, one row each.
  • (3 rows) means the answer has three rows. Three orders, three rows. Correct.

Check 2 — the counter

The command, word by word:

Command
docker compose exec redis redis-cli GET orders:count
  • docker compose exec redis — run a command inside the redis box.
  • redis-cli — the Redis command tool. It talks to Redis.
  • GET orders:count — show me the value held under the key orders:count. GET means "fetch". orders:count is the counter's name.

What you should see:

Command
"3"

The counter says 3. Three orders saved, counter at 3. The quotes around the 3 are part of how Redis prints a value — the value is the number 3.

Check 3 — the file cupboard

There is no separate list command in this step. The proof is the ingest diary from Step 2: ingest only prints "Sent ..." after it has stored the file, so the three "Sent" lines mean all three files are in the cupboard (bucket incoming). Moto has no web page to open, so the diary is the check.

This lab has no box that holds the aws file tool, so you cannot run a list command against the cupboard from inside this lab. The object-store lab shows you how the list command works, with its own store names — use that lab's command as the pattern for how the command is shaped, not as a copy-paste: this lab's cupboard box is called moto, not moto-a, and there is no awscli box here.

Check 4 — the guard

The command, word by word:

Command
for i in 1 2 3 4 5 6; do curl -s http://localhost:8080/ | grep Hostname; done
  • for i in 1 2 3 4 5 6; do ... ; done — a loop. It means "do the thing inside, six times". i is a counting name that goes 1, 2, 3, 4, 5, 6. do starts the repeated part. done ends it.
  • curl -s http://localhost:8080/ — fetch the front page from the guard. curl fetches a web page. -s means "silent": hide the progress lines. http://localhost:8080/ is the guard's page on your own machine, door 8080.
  • | — a pipe. It means "take the output of the command on the left and feed it into the command on the right".
  • grep Hostname — keep only the lines that contain the word Hostname, and throw the rest away. grep means "search lines for this word". The Hostname line names the backend that answered.

What you should see: the Hostname line change between the backends — web1, web2, web3, then again:

Command
Hostname: web1
Hostname: web2
Hostname: web3
Hostname: web1
Hostname: web2
Hostname: web3

That is the guard sharing the work — round robin, taking turns.

If it breaks: if the database shows fewer than 3 rows, wait 30 seconds and try again — the worker may still be catching up. If the counter shows less than 3, same fix. If the files are missing from the cupboard, check the ingest diary — it prints a line for every file it sends.

Step 4 — Add a fourth order yourself

What this step does: you write a new order file by hand, drop it in incoming/, and watch it flow through the whole pipeline by itself.

Why: the first three orders were already there when the lab started. This one proves the pipeline is alive and watching — a new file in, a new row out, with nobody touching the programs.

The command, word by word, before you run it:

Command
cat > incoming/order-004.json << 'EOF'
{"id": 104, "item": "pen stand", "amount": 120, "buyer": "Kumar"}
EOF

This looks strange, so here it is in pieces:

  • cat — a tool that prints files. Here it is used backwards: instead of printing a file, it writes what you type into a file.
  • > — send the output into a file instead of onto the screen. It overwrites the file if the file already exists.
  • incoming/order-004.json — the file to write. It goes in the folder incoming/ in phase1/end-to-end. Its name is order-004.json.
  • << 'EOF' — a "here-document". It means: "the text I am about to type, up to a line that says only EOF, is the file's content". EOF stands for "end of file". The quotes around 'EOF' mean "use the text exactly as typed, do not change anything in it".
  • The middle line {"id": 104, "item": "pen stand", "amount": 120, "buyer": "Kumar"} is the order itself, in JSON: order 104, a pen stand, 120, bought by Kumar. Copy it exactly — the quotes and commas matter.
  • The last line EOF on its own ends the file. Type it and press Enter.

What you should see: nothing — the file is written silently. That is normal. Silence means it worked here.

Wait 10 seconds, then check the database again with the Check 1 command from Step 3:

Command
docker compose exec postgres-primary psql -U learner -d practice -c "SELECT * FROM orders ORDER BY id;"

See Step 3 for the word-by-word breakdown: run psql inside the main database box, as user learner, in database practice, and ask for all rows from the orders table sorted by id.

What you should see: 4 rows now, including order 104:

Command
 id  |   item    | amount | buyer
-----+-----------+--------+-------
 101 | notebook  |    250 | Asha
 102 | pen       |     40 | Ravi
 103 | mug       |    350 | Meena
 104 | pen stand |    120 | Kumar
(4 rows)

The fourth row is the new order. (4 rows) means four orders saved.

And the counter:

Command
docker compose exec redis redis-cli GET orders:count

See Step 3 for the breakdown: run redis-cli inside the redis box and fetch the key orders:count.

What you should see:

Command
"4"

The counter says 4. A new order flows through the whole pipeline by itself — file in, database row out.

If it breaks: if the database still shows 3 rows, wait 30 seconds and try again — the worker may still be catching up. If order 104 is still missing, run ls incoming/ and check order-004.json is there. If the file is gone from incoming/ — it should have moved to processed/ — but no row was saved, read the worker diary from the top with docker compose logs worker. Also check the file moved: run ls processed/ and you should see the order files there. processed/ is the "done" folder. ls means "list the files here".

Step 5 — Kill the main database

What this step does: you stop the main database, and check the standby still has all the data.

Why: this is the failure the whole lab is built around. In real work, a database dies mid-flow. The question is: does the copy have everything, and can work continue?

The command, word by word:

Command
docker compose stop postgres-primary
  • docker compose stop — stop one box from this recipe, but keep it around so it can be started again later. Different from down, which stops AND removes the boxes.
  • postgres-primary — the box to stop. The main database.

What you should see:

Command
✔ Container postgres-primary  Stopped

One line. Stopped means the box is off but still exists.

If it breaks: "No such container" means the name is wrong — run docker compose ps and use the name it shows.

What happens next is correct, not a failure: the worker will crash — it cannot reach the database any more — and Docker will restart it. It will keep printing "Waiting for PostgreSQL..." — that is correct. It is waiting for a database that is gone. The worker's box is set to restart by itself when it crashes (the recipe file says restart: unless-stopped for the worker — that line means "restart this box unless someone stopped it on purpose"). Do not panic at the crash lines. They mean the worker is doing its job: waiting for a database.

Check the standby still has the data. The command, word by word:

Command
docker compose exec postgres-replica psql -U learner -d practice -c "SELECT * FROM orders ORDER BY id;"

This is the same database question as Step 3, except it runs inside the box postgres-replica — the standby — instead of postgres-primary. Everything else is the same: psql, user learner, database practice, show all rows from orders sorted by id.

What you should see: all 4 rows:

Command
 id  |   item    | amount | buyer
-----+-----------+--------+-------
 101 | notebook  |    250 | Asha
 102 | pen       |     40 | Ravi
 103 | mug       |    350 | Meena
 104 | pen stand |    120 | Kumar
(4 rows)

The standby has its own copy. Every change the main database made was copied to it live, before the main database died.

If it breaks: if the standby shows fewer than 4 rows, wait 10 seconds and try again — the copy takes a moment.

Step 6 — Promote the standby

What this step does: you turn the standby into the main database, with one database command.

Why: a standby only takes reads — it does not take writes. To take over, it must be promoted. Promotion is the failover: the spare becomes the main.

The command, word by word:

Command
docker compose exec postgres-replica psql -U learner -d practice -c "SELECT pg_promote();"
  • docker compose exec postgres-replica psql -U learner -d practice -c — run one database question inside the standby box, as user learner, in database practice. See Step 3 for the full breakdown.
  • SELECT pg_promote(); — the question itself. pg_promote() is a built-in database function — a small program inside PostgreSQL. It means "promote this database: stop being a standby and become the main database". SELECT runs it and shows the answer. () means "run this function". ; ends the question.

What you should see: t, short for true:

Command
 pg_promote
------------
 t
(1 row)

Line by line: the column name is pg_promote. The divider line separates the name from the answer. t means true — yes, the promotion happened. (1 row) means the answer has one row.

Check it is no longer a standby. The command, word by word:

Command
docker compose exec postgres-replica psql -U learner -d practice -c "SELECT pg_is_in_recovery();"
  • Same wrapper as before: run one question inside the standby box.
  • SELECT pg_is_in_recovery(); — ask the built-in function pg_is_in_recovery(). "Recovery" is the database's word for "catching up as a standby". The function asks: "are you still a standby catching up?" It answers true or false.

What you should see: f, short for false:

Command
 pg_is_in_recovery
-------------------
 f
(1 row)

f means false — no, it is NOT in recovery any more. It is now the main database. t would have meant it was still a standby. f is the answer you want here.

If it breaks: if pg_promote() shows f, the standby was already promoted — check with SELECT pg_is_in_recovery();. If that shows f, you are done. The promotion already happened, probably because you ran the command twice.

Step 7 — Point a worker at the new main database

What this step does: you stop the old worker — it is still waiting for the dead database — and start a fresh worker that talks to the new main database (the promoted standby).

Why: the old worker was told at start-up to talk to postgres-primary. That box is dead. A worker cannot change its database while it runs. You need a fresh worker that is told, from the start, to talk to postgres-replica instead.

First — stop the old worker. The command, word by word:

Command
docker compose stop worker
  • docker compose stop — stop one box, but keep it around.
  • worker — the old worker box.

What you should see:

Command
✔ Container worker  Stopped

If it breaks: "No such container" means the worker is already stopped — that is fine, move on.

Next — start a fresh worker. In one sentence, the command below means: start a throwaway worker that talks to the new main database, and clean up after itself. You do not need to understand every flag to run it — just paste the whole line, press Enter, and read the flag-by-flag plain-words list under it afterwards. The command, word by word, before you run it:

Command
docker compose run --no-deps --rm -e PG_HOST=postgres-replica worker
  • docker compose run — start a one-off box from a service in the recipe. Different from up, which starts the long-running boxes, and different from exec, which runs a command inside a box that is already running. run makes a NEW box from the service's image and runs it now.
  • --no-deps — do not start this service's dependencies. Dependencies are the other boxes this service normally needs — for the worker, that includes the dead main database. Without this flag, Compose would restart the dead main database too. With it, only the worker starts.
  • --rm — remove this box when it stops. Because this worker is temporary, its box should clean itself up when you stop it with Ctrl+C.
  • -e PG_HOST=postgres-replica — set one setting for this box. -e means "environment setting". PG_HOST is the setting's name — it tells the worker which database machine to talk to. postgres-replica is the value — the promoted standby. The normal worker uses postgres-primary here; this fresh one uses postgres-replica.
  • worker — the service to run. The worker program.

This runs in your terminal, not in the background. There is no -d here, so the box holds your terminal and you see its diary live. That is on purpose — you need to see the next order arrive.

What you should see:

Command
Connected to PostgreSQL.
Connected to Redis.
Connected to Kafka. Waiting for orders...

The same three lines as Step 2: connected to the database (now the promoted standby), connected to Redis, connected to Kafka and waiting.

Leave that terminal open. It is now the live worker. Do not close it, and do not press Ctrl+C yet.

If it breaks: if it prints "Waiting for PostgreSQL..." for more than a minute, the new main database is not up — check with docker compose ps that postgres-replica shows "Up".

Step 8 — Send a fifth order through the new main database

What this step does: in a SECOND terminal, you write a fifth order file. In the FIRST terminal, you watch the fresh worker save it. Then you check the new main database holds all five orders.

Why: this is the proof that failover worked. The order flows through the standby that is now the main database. If it lands as row 5, the pipeline survived the death of its main database.

Open a second terminal. A terminal is one black window. You need two at once now: the first terminal is busy running the fresh worker, and a busy terminal cannot take new commands. Open a new terminal window — in most systems, open your terminal app again, or open a new tab in the same terminal app. Move the second terminal into the same folder. Type this, then press Enter:

Command
cd phase1/end-to-end

Type it exactly as shown, from the folder that holds phase1. Check with ls — you should see docker-compose.yml, ingest.py, worker.py, incoming, and postgres.

In the second terminal, make the new order. The command, word by word:

Command
cat > incoming/order-005.json << 'EOF'
{"id": 105, "item": "ruler", "amount": 60, "buyer": "Divya"}
EOF

See Step 4 for the full breakdown: cat writes what you type into a file; > sends it into the file; incoming/order-005.json is the file; << 'EOF' means "the text up to a line that says only EOF is the content". The order is: id 105, a ruler, 60, bought by Divya. Copy it exactly.

What you should see: nothing — the file is written silently. That is normal.

Wait 10 seconds. In the first terminal (the worker), you should see:

Command
Saved order 105: ruler (60)

One line. The fresh worker saved order 105. The order flowed through the standby that is now the main database.

If it breaks: if the worker shows nothing after 30 seconds, the temporary worker from Step 7 is not running — go back and start it again.

Check the new main database, in the second terminal. The command, word by word:

Command
docker compose exec postgres-replica psql -U learner -d practice -c "SELECT * FROM orders ORDER BY id;"

Same database question as Step 3, run inside the box postgres-replica — the new main database. See Step 3 for the full breakdown.

What you should see: 5 rows:

Command
 id  |   item    | amount | buyer
-----+-----------+--------+-------
 101 | notebook  |    250 | Asha
 102 | pen       |     40 | Ravi
 103 | mug       |    350 | Meena
 104 | pen stand |    120 | Kumar
 105 | ruler     |     60 | Divya
(5 rows)

Five orders, five rows, including order 105. The order flowed through the standby that is now the main database. Failover done — end to end.

Stop the temporary worker: go to the first terminal and press Ctrl+C. Hold the Ctrl key and press C. That stops the program in the terminal. The --rm flag from Step 7 removes the worker's box when it stops.

Save your proof

The proof for this lab is the 5-row order table and the counter at 5. Save both with these commands, run from inside the folder phase1/end-to-end after Step 8.

First — make the proof folder, word by word:

Command
mkdir -p ../portfolio/proof
  • mkdir — make a folder. Short for "make directory".
  • -p — make the parent folders too if they are missing, and do not complain if the folder already exists.
  • ../portfolio/proof — the folder to make. .. means "go up one folder" — from phase1/end-to-end up to phase1. Then portfolio/proof is the folder inside phase1/portfolio. The full path is phase1/portfolio/proof, and it holds the proof files. That folder was checked to exist on disk.

Second — save the 5-row table:

Command
docker compose exec postgres-replica psql -U learner -d practice -c "SELECT * FROM orders ORDER BY id;" > ../portfolio/proof/end-to-end-trace.txt

This is the Step 3 database question, run against the new main database (postgres-replica), with one extra piece at the end:

  • > — send the output into a file instead of onto the screen. It overwrites the file if the file already exists.
  • ../portfolio/proof/end-to-end-trace.txt — the file to write into. A plain text file.

Third — add the counter to the same file:

Command
docker compose exec redis redis-cli GET orders:count >> ../portfolio/proof/end-to-end-trace.txt
  • >> — send the output into the same file, but ADD it at the end instead of overwriting. Two > signs mean "append". One > sign means "overwrite". That is the only difference between the second and third commands.

What you should see: nothing in the terminal when you run the save commands. That is correct — the table and the counter went into the file, not the screen. Silence means it worked here.

Check the file: open phase1/portfolio/proof/end-to-end-trace.txt and check it shows 5 rows, including order 105, and the counter "5".

Then add the hostnames by hand. The lesson says to use the template file phase1/portfolio/proof/end-to-end-trace-TEMPLATE.txt. That template file was checked to exist on disk. Open it. It shows the shape the finished proof file should have: the 5-row table, the counter, and the hostnames from the guard's curl loop. Open your saved file end-to-end-trace.txt next to it. Copy the hostnames you saw from the curl loop in Step 3 — the six lines starting with Hostname: — and type them into your saved file, in the place where the template shows them. Save the file. That file is your proof.

If it breaks: if the file shows fewer than 5 rows, Step 8 did not finish yet — wait 30 seconds, then run the save commands again.

Step 9 — The honest part

What this step does: it tells you the truth about what is left broken, and gives you the simple way back.

Why: failover is not a magic undo. The old main database is still stopped, and it still has the old data — 4 orders, not 5. It cannot rejoin by itself. In real work, you rebuild it from the new main database with a tool called pg_basebackup. pg_basebackup is a PostgreSQL tool that copies a whole database from one machine to another, to build a fresh standby. That is the same way the standby was first built in this lab. Teaching that rebuild is beyond this lab.

For this lab, the simple way back is to wipe everything and start fresh:

Command
docker compose down -v

Word by word:

  • docker compose down — stop all the boxes in the recipe and remove them.
  • -v — also delete the volumes. A volume is a named storage area Docker keeps on your machine so data survives a restart. The database rows and the Redis counter live in named volumes — pg-primary-data, pg-replica-data, and redis-data in the recipe file — so they survive a plain down. Adding -v deletes those volumes too, so the data is gone. Without -v, the data would come back on the next start. With -v, you start truly fresh.

What you should see: all eleven services stop and the data is deleted. The lines name each box as it stops.

If it breaks: "No such container" means the services are already stopped — nothing to do.

That stops all services and deletes the data. The data was fake.

Clean up

This is the same command as Step 9. If you already ran Step 9, you are done — do not run it twice. If you skipped Step 9, run it now, from inside the folder phase1/end-to-end:

Command
docker compose down -v

You should see: all eleven services stop and the data is deleted.

If it breaks: "No such container" means the services are already stopped — nothing to do.

What you can now say, truthfully

"I built a pipeline where a fake order file flows through an object store, Kafka, PostgreSQL and Redis, behind a load balancer — then I killed the main database, promoted the standby, and a new order still flowed through."

What this lab does NOT cover

  • Real pipelines run each part on its own machines, not all on one machine. The ideas are the same; the setup is bigger.
  • Moto keeps files in memory only. If you stop the lab, the files are gone. The database rows and the Redis counter live in named volumes, so they survive a restart — the files do not. A volume is a named storage area Docker keeps on your machine. A plain docker compose down keeps the volumes; docker compose down -v deletes them.
  • This lab has no automatic failover. "Automatic failover" would mean the standby promotes itself the moment the main dies, with nobody typing a command. There is no Patroni here — Patroni is a tool that does automatic failover, and it is shown in the Patroni part of the PostgreSQL lab. The promotion in Step 6 is by hand.
  • The load balancer here serves three tiny backends. A real app behind it is a bigger setup — but the guard works the same way.
  • The Advanced section at the end of this lesson now covers the replication-lag check before promoting, split-brain, consumer offsets and duplicate delivery, and ingest store-then-send.

Fill in the map

Draw the order flow from memory. Each blank is one hop: what travels, and which tool holds it. Write your answers on paper or in a text file, then check them at the end of this section. The same exercise is in the file phase1/end-to-end/order-map-worksheet.txt.

Command
A customer places a fake order.

  incoming/order-005.json
  (a small file: id, item, amount, buyer)
            |
            v
  1. ___ holds a copy of the file
            |
            v
  2. ___ carries the order as a message
            |
            v
  3. ___ saves the order as a row
            |
            v
  4. ___ counts the orders (orders:count)
            |
            v
  The order is saved, and the counter says 5.

Meanwhile, on the front door:

  visitor --> 5. ___ --> web1 / web2 / web3

Fill in each blank with the tool name:

  1. ___ — which tool holds the copy of the file?
  2. ___ — which tool carries the order as a message?
  3. ___ — which tool saves the order as a row?
  4. ___ — which tool counts the orders?
  5. ___ — which tool spreads visitors across the three backends?

Answers (no peeking)

  1. Object store (Moto, bucket incoming) — ingest stores a copy of the file there.
  2. Kafka (topic orders) — ingest sends the order there, and the worker reads it from there.
  3. PostgreSQL (table orders) — the worker saves the order as a row there.
  4. Redis (key orders:count) — the worker adds 1 to the counter there each time an order is saved.
  5. Load balancer (NGINX, the lb service) — it spreads visitors across web1, web2 and web3.

Sources

Studied to check how the ideas are explained elsewhere, then rewritten here in plain words. No text was pasted from these pages.

  1. roadmap.sh/devops — the whole DevOps path in one picture, so you can see where each tool in this pipeline sits: https://roadmap.sh/devops
  2. PostgreSQL docs — the people who make PostgreSQL explain replication and failover in the "High Availability" chapter: https://www.postgresql.org/docs
  3. Apache Kafka docs — the people who make Kafka explain topics, producers and consumers: https://kafka.apache.org/documentation

Advanced — Before you promote, split-brain, duplicates, and store-then-send

This section is for the reader who already did the lab above. It covers the four things the review of this kit flagged as missing for advanced readers: a replication-lag check before promoting, split-brain, consumer offsets and duplicate delivery, and ingest store-then-send atomicity. Every claim here is checked against the lab's own code — worker.py, ingest.py, and docker-compose.yml in the phase1/end-to-end/ folder. Read those files beside this section; the advanced material is the explanation of what they already do.

Advanced 1 — Check replication lag BEFORE you promote

What this is: replication lag is how far behind the standby is: the writes it has not received yet, or has received but not replayed yet. Why it matters: the lab's Step 6 promotes the standby without checking lag. If the standby is a minute behind, promoting it loses a minute of orders — silently. In real work, you never promote without reading the lag first.

Check it on the primary, before you touch anything:

Command
docker compose exec postgres-primary psql -U learner -d practice -c "SELECT client_addr, state, sync_state, replay_lag FROM pg_stat_replication;"

Word by word: pg_stat_replication is the status view that shows, for each standby, how it is doing. client_addr is the standby's address. state should say streaming — the standby is following live. sync_state says whether this standby is the one the primary waits for (sync or async — this lab is async, so the primary never waits). replay_lag is the delay: how far the standby's replay is behind the primary, as a time. What you should see: replay_lag of a few milliseconds on a healthy lab. The rule: if replay_lag is large, or state is not streaming, wait. Do not promote. The orders that have not arrived yet are lost the moment you promote.

On the standby itself, the two checks the lab already taught still apply: SELECT pg_is_in_recovery(); must show t (it is still a standby). Then read the standby's position — the last change it replayed — with a full command of its own. Run this from inside the folder phase1/end-to-end:

Command
docker compose exec postgres-replica psql -U learner -d practice -c "SELECT pg_last_wal_replay_lsn();"

Word by word: pg_last_wal_replay_lsn() means "the position of the last change this standby replayed". A position here is a WAL location — a code like 0/16B1978 that marks one exact point in the change log. What you should see: one code, like 0/16B1978. Your code will be different. Now get the primary's current position the same way:

Command
docker compose exec postgres-primary psql -U learner -d practice -c "SELECT pg_current_wal_lsn();"

Word by word: pg_current_wal_lsn() means "the primary's current position in the change log". What you should see: one code, like 0/16B1978. How to compare the two codes: if they match exactly, the standby is caught up — nothing is waiting. If the standby's code is behind the primary's, the standby is lagging. Do not subtract the codes yourself — they are hexadecimal positions, not plain numbers, and subtracting them gives an error. Measure the gap in bytes instead, on the primary, pasting in the standby's code from the last step:

Command
docker compose exec postgres-primary psql -U learner -d practice -c "SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), '0/16B1978');"

Replace '0/16B1978' with the standby's code you just read (keep the single quotes around it). Word by word: pg_wal_lsn_diff means "the difference between two positions, in bytes". What you should see: a number of bytes. 0 means caught up. A small number on a busy lab is normal — the standby is a moment behind. A large number, or one that keeps growing, means wait. Do not promote. The orders that have not arrived yet are lost the moment you promote.

If it breaks: ERROR: recovery is in progress after pg_current_wal_lsn() means you ran it on the standby by mistake — that function only works on the primary, because a standby is always in recovery. Swap the container name to postgres-primary and run again. The reverse mistake is quieter: pg_last_wal_replay_lsn() on the primary gives no error, but the number is stale — it is where the primary finished its own startup recovery long ago, and it says nothing about the standby. If the two codes look unrelated, check you ran each command on the right container. The promotion command in Step 6 is unchanged; the advanced step is the check you run before it.

Advanced 2 — Split-brain: two primaries, both taking writes

What this is: split-brain means two databases both think they are the main one, and both take writes. Why it matters: after a failover, the old primary is still alive — it was only stopped, not deleted. If it comes back and starts taking writes again while the new primary also takes writes, you have two different sets of orders, and there is no automatic way to merge them. One of them has to lose.

How it happens in this lab: promote the replica in Step 6, then start the old primary again without rebuilding it. It wakes up believing it is still the primary. It will take writes. The new primary will also take writes. Both are "right" from their own point of view.

Prevention, in order: (1) fence the old primary before you promote — "fence" means stop it from taking writes, by stopping the container or blocking its traffic, before the new primary starts. (2) Never let the old primary rejoin as a primary: it rejoins as a replica, rebuilt from the new primary. Patroni does both by itself: its leader lock in etcd means only one node can be leader, and use_pg_rewind (in the Patroni settings file — see the PostgreSQL lab's Advanced section) rewinds the old leader's files to the point where the histories split, so it can rejoin as a replica instead of being rebuilt from scratch. The manual lab has no fencing and no lock, so the human must do it: stop the old primary first, promote second, and never start the old one again until it has been rebuilt.

If split-brain already happened: stop writes on one side at once, compare the row counts and the newest rows on both sides, pick the copy with the true data, and rebuild the other side from it with pg_basebackup. Do not try to merge the two by hand — you will get duplicate order numbers and missing rows.

Advanced 3 — Consumer offsets and duplicate delivery on worker restart

What this is: the worker reads orders from Kafka as a member of the consumer group order-workers. An offset is the group's bookmark (see the Kafka lab's Advanced section). Duplicate delivery means Kafka hands the worker the same order twice — which happens whenever the worker restarts, because Kafka's promise is "at least once", never "exactly once". Why it matters: a worker that saves the same order twice double-counts the money.

Read the lab's own worker.py and you will see the whole story:

  • The consumer is built with enable_auto_commit=True. That means the worker tells Kafka "I have read up to here" on a timer, in the background — whether or not the database save finished. Two failure shapes follow. If the worker crashes after saving an order but before the timer commits, it re-reads that order after restart: a duplicate. If the timer commits before the database save lands, and the worker then crashes, that order is never re-read: a loss. Auto-commit is simple and wrong in both directions.
  • The safety net is the next line: the worker saves each order with INSERT INTO orders (...) VALUES (...) ON CONFLICT (id) DO NOTHING. ON CONFLICT DO NOTHING means "if an order with this number already exists, skip it quietly". A re-delivered order is ignored. And the Redis counter only moves when cur.rowcount == 1 — that is, only when a row was really inserted — so the count stays right even when duplicates arrive. The pair is the lesson: at-least-once delivery plus an idempotent write (a write that is safe to repeat) is the correct design. Either half alone is not enough.

What to check after a worker restart: the group's lag, and the counts. Lag first:

Command
docker compose exec kafka /opt/kafka/bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group order-workers

Read LAG per partition (see the Kafka lab's Advanced section). Then compare the two counts: the rows in PostgreSQL against the Redis counter. They must agree — if the counter is higher than the rows, a duplicate slipped past the guard; if it is lower, an order was lost. The fix in real work is to commit the offset only after the database save succeeds (manual commit, not auto-commit) — and to keep the ON CONFLICT guard anyway, because crashes can still happen between the save and the commit.

Advanced 4 — Ingest store-then-send atomicity

What this is: atomicity means "all of it happens, or none of it does" — one unbreakable step. Why it matters: the ingest service does three separate things for each order file, and there is no single transaction across them. Read the lab's own ingest.py and you will see the order:

  1. client.fput_object(BUCKET, name, path) — store the file in the object store.
  2. producer.send(TOPIC, value=order) then producer.flush() — send the order to Kafka.
  3. shutil.move(path, ...) — move the file from incoming/ to processed/.

Now walk through a crash at each gap:

  • Crash after step 1, before step 2: the file is stored, but the order was never sent. The file is still in incoming/ (it is moved only in step 3), so the next loop reads it again, stores it again, and sends it. It heals itself.
  • Crash after step 2, before step 3: the order was sent, but the file is still in incoming/, so the next loop sends it AGAIN. A duplicate in Kafka — which the worker's ON CONFLICT DO NOTHING swallows. Harmless, by design.
  • Crash during step 1: the upload may be partial or missing. The file is still in incoming/, so it retries. Harmless.

The order of the three steps decides which failure you get. This lab's order — store, then send, then move last — means the failure mode is "duplicate", never "lost". And duplicates are harmless because the worker's write is idempotent (Advanced 3). The dangerous order would be move-first-then-send: crash between the move and the send, and the file is in processed/ but the order never reached Kafka — lost, with no trace. So the rule: move last, never first, and make the consumer safe to repeat. There is no way to make the store, Kafka, and the filesystem all happen-or-none — no transaction spans all three — so you pick the safe failure (duplicate) and handle it, instead of pretending the problem does not exist.

What you can now say, truthfully — advanced

  • "I check replication lag with pg_stat_replication before promoting a standby, and I wait when replay_lag is large." (Only if you did Advanced 1.)
  • "I can explain split-brain, fencing, and why the old primary must be rebuilt, not just restarted, after a failover." (Only if you did Advanced 2.)
  • "I read the lab's worker code and can explain auto-commit, duplicate delivery, and why ON CONFLICT DO NOTHING plus a rowcount-checked counter is the correct pair." (Only if you did Advanced 3.)
  • "I traced the ingest order — store, send, move last — and can explain why its failure mode is a harmless duplicate, never a loss." (Only if you did Advanced 4.)

Quick check — try it yourself

Question: What happens to a fake order file as it moves through the pipeline (step-by-step path)?

Open the practice terminal to test this →

Show answer

It lands in a folder, gets stored, is sent as a message, and is saved as a database row and counted.