57.6 Project 6: Node.js with MySQL and with MongoDB, plus a Redis cache
Friends, today one Node.js orders API talks to MySQL or MongoDB, and Redis caches hot reads. We use two Compose files, prove a cache hit is faster, expire keys, and clean up. Type every command yourself.
मित्रांनो, आज एक Node.js orders API MySQL किंवा MongoDB शी बोलते, आणि Redis गरम reads cache करते. आपण दोन Compose files वापरू, cache hit जलद आहे हे सिद्ध करू, keys expire करू आणि clean up करू. प्रत्येक command स्वतः टाइप करा.
दोस्तों, आज एक Node.js orders API MySQL या MongoDB से बात करती है, और Redis गरम reads को cache करता है. हम दो Compose files उपयोग करेंगे, cache hit तेज़ है यह साबित करेंगे, keys expire करेंगे और clean up करेंगे. हर command खुद टाइप कीजिए.
What you will learn in this lesson
- Why one Node app can target MySQL or MongoDB with env vars.
- How Redis sits in front of hot read paths.
- How to prove a cache hit is faster than a database read.
- How TTL expires stale cache keys.
- How two Compose projects share one app image safely.
1. Start from a real problem
Suppose we are at Swiggy and a small team builds an orders API in Node.js. One city stores orders in MySQL. Another city experiments with MongoDB documents. Both cities want the popular restaurant list to load in under 50 ms.
Without a cache every page hit queries the database. Under lunch rush the database CPU climbs and list calls slow down.
With Docker we write one Express app, one Dockerfile, and two Compose files. Redis caches the list. The same pattern powers cart and session data at food delivery companies.
2. App code and Dockerfile
Step 1: Project folder
Why: One app, two stacks later.
What: Keep source under src/. Compose files will choose MySQL or Mongo.
Example 1: Make folders
Type this:
mkdir -p orders-api/src && cd orders-api && pwd
You will see:
/home/you/orders-api
What it means: Project root ready.
Example 2: Write package.json
Type this:
printf '%s\n' '{' ' "name": "orders-api",' ' "version": "1.0.0",' ' "main": "src/index.js",' ' "scripts": { "start": "node src/index.js" },' ' "dependencies": {' ' "express": "^4.21.1",' ' "mysql2": "^3.11.3",' ' "mongodb": "^6.9.0",' ' "ioredis": "^5.4.1"' ' }' '}' > package.json && wc -l package.json
You will see:
12 package.json
What it means: Express, MySQL, Mongo and Redis clients.
Example 3: Create lock file
Type this:
docker run --rm -v "$PWD":/app -w /app node:20-alpine npm install --package-lock-only
You will see:
added 80 packages in 4s
What it means: package-lock.json ready for npm ci.
Step 2: src/index.js
Why: Cache-aside pattern.
What: On a popular-list request the app looks in Redis. On a miss it reads the database, stores the JSON in Redis with a TTL, then returns it.
Example 4: Write the API
Type this:
printf '%s\n' 'const express = require("express");' 'const Redis = require("ioredis");' 'const engine = process.env.DB_ENGINE || "mysql";' 'const redis = new Redis(process.env.REDIS_URL || "redis://redis:6379");' 'const app = express();' 'app.use(express.json());' '' 'async function dbList() {' ' if (engine === "mongo") {' ' const { MongoClient } = require("mongodb");' ' const c = new MongoClient(process.env.MONGO_URL);' ' await c.connect();' ' const rows = await c.db("orders").collection("popular").find({}).project({_id:0}).toArray();' ' await c.close(); return rows;' ' }' ' const mysql = require("mysql2/promise");' ' const pool = mysql.createPool({' ' host: process.env.DB_HOST || "db", user: process.env.DB_USER,' ' password: process.env.DB_PASSWORD, database: process.env.DB_NAME' ' });' ' const [rows] = await pool.query("SELECT name, rating FROM popular ORDER BY rating DESC");' ' await pool.end(); return rows;' '}' '' 'app.get("/healthz", async (req, res) => {' ' try { await redis.ping(); res.send("ok"); } catch (e) { res.status(500).send("redis down"); }' '});' '' 'app.get("/orders/popular", async (req, res) => {' ' const key = "popular:v1";' ' const cached = await redis.get(key);' ' if (cached) return res.json({ source: "cache", data: JSON.parse(cached) });' ' const data = await dbList();' ' await redis.set(key, JSON.stringify(data), "EX", 30);' ' res.json({ source: "db", data });' '});' '' 'app.listen(3000, () => console.log("orders api on 3000 engine=" + engine));' > src/index.js && wc -l src/index.js
You will see:
40 src/index.js
What it means: Health, cache-aside popular list, MySQL or Mongo.
Example 5: Show the cache key
Type this:
grep 'popular:v1' src/index.js
You will see:
const key = "popular:v1";
What it means: One key for the hot list.
Example 6: Show the TTL
Type this:
grep 'EX' src/index.js
You will see:
await redis.set(key, JSON.stringify(data), "EX", 30);
What it means: Keys expire after 30 seconds.
Step 3: Dockerfile
Why: Same image for both Compose files.
What: node:20-alpine, npm ci, non-root user, health check on /healthz.
Example 7: Write Dockerfile
Type this:
printf '%s\n' 'FROM node:20-alpine' 'WORKDIR /app' 'ENV NODE_ENV=production' 'COPY package*.json ./' 'RUN npm ci --omit=dev' 'COPY src/ ./src/' 'USER node' 'EXPOSE 3000' 'HEALTHCHECK CMD wget -qO- http://localhost:3000/healthz || exit 1' 'CMD ["node", "src/index.js"]' > Dockerfile && printf '%s\n' 'node_modules' '.env' > .dockerignore && wc -l Dockerfile
You will see:
10 Dockerfile
What it means: Production Node image ready.
Example 8: Show USER
Type this:
grep '^USER' Dockerfile
You will see:
USER node
What it means: Non-root process.
Example 9: Show CMD
Type this:
grep '^CMD' Dockerfile
You will see:
CMD ["node", "src/index.js"]
What it means: Same start for MySQL and Mongo stacks.
3. MySQL stack with Redis
Step 4: Init SQL and Compose
Why: Seed popular restaurants.
What: MySQL gets a popular table. Redis has no password in this practice file so the lesson stays short. Real teams always set requirepass.
Example 10: Write init SQL
Type this:
mkdir -p db && printf '%s\n' 'CREATE TABLE popular (name VARCHAR(100) PRIMARY KEY, rating DECIMAL(2,1) NOT NULL);' 'INSERT INTO popular (name, rating) VALUES ("Vaishali", 4.6), ("Goodluck Cafe", 4.4), ("Katakir", 4.5);' > db/init.sql && cat db/init.sql
You will see:
CREATE TABLE popular ...
What it means: Three Pune restaurants seeded.
Example 11: Write compose.mysql.yaml
Type this:
printf '%s\n' 'name: orders-mysql' 'services:' ' db:' ' image: mysql:8.4' ' environment:' ' MYSQL_DATABASE: orders' ' MYSQL_USER: orders' ' MYSQL_PASSWORD: ${DB_PASSWORD}' ' MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}' ' volumes:' ' - mysql-data:/var/lib/mysql' ' - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro' ' healthcheck:' ' test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${DB_ROOT_PASSWORD}"]' ' interval: 5s' ' retries: 20' '' ' redis:' ' image: redis:7-alpine' ' healthcheck:' ' test: ["CMD", "redis-cli", "ping"]' ' interval: 5s' ' retries: 20' '' ' api:' ' build: .' ' ports: ["3000:3000"]' ' environment:' ' DB_ENGINE: mysql' ' DB_HOST: db' ' DB_USER: orders' ' DB_PASSWORD: ${DB_PASSWORD}' ' DB_NAME: orders' ' REDIS_URL: redis://redis:6379' ' depends_on:' ' db: {condition: service_healthy}' ' redis: {condition: service_healthy}' '' 'volumes: {mysql-data:}' > compose.mysql.yaml && wc -l compose.mysql.yaml
You will see:
40 compose.mysql.yaml
What it means: MySQL + Redis + API under project orders-mysql.
Example 12: Write .env
Type this:
printf '%s\n' 'DB_PASSWORD=orders-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && echo env-ok
You will see:
env-ok
What it means: Local passwords ready.
Step 5: Start and prove cache miss then hit
Why: Timing shows the win.
What: First call is source db. Second call is source cache and usually faster.
Example 13: Start MySQL stack
Type this:
docker compose -f compose.mysql.yaml up -d --build
You will see:
[+] Running 4/4
✔ db Healthy
✔ redis Healthy
✔ api Started
What it means: Stack is up.
Example 14: First call (miss)
Type this:
curl -s http://localhost:3000/orders/popular
You will see:
{"source":"db","data":[{"name":"Vaishali","rating":"4.6"},{"name":"Katakir","rating":"4.5"},{"name":"Goodluck Cafe","rating":"4.4"}]}
What it means: Miss path hit MySQL and filled Redis.
Example 15: Second call (hit)
Type this:
curl -s http://localhost:3000/orders/popular
You will see:
{"source":"cache","data":[{"name":"Vaishali","rating":"4.6"},{"name":"Katakir","rating":"4.5"},{"name":"Goodluck Cafe","rating":"4.4"}]}
What it means: Hit path served from Redis.
Step 6: Inspect Redis keys
Why: See TTL count down.
What: redis-cli inside the redis container shows the key and its remaining life.
Example 16: List keys
Type this:
docker compose -f compose.mysql.yaml exec redis redis-cli KEYS '*'
You will see:
popular:v1
What it means: The cache key exists.
Example 17: Read TTL
Type this:
docker compose -f compose.mysql.yaml exec redis redis-cli TTL popular:v1
You will see:
27
What it means: About 27 seconds left of the 30 second TTL.
Example 18: Get the cached JSON length
Type this:
docker compose -f compose.mysql.yaml exec redis redis-cli STRLEN popular:v1
You will see:
120
What it means: Payload size in bytes inside Redis.
4. Expire, invalidate and Mongo stack
Step 7: Expire and invalidate
Why: Stale cache is worse than no cache.
What: After TTL the next call is a miss again. You can also DEL the key when data changes.
Example 19: Wait for expiry
Type this:
sleep 35 && curl -s http://localhost:3000/orders/popular | grep -o '"source":"[^"]*"'
You will see:
"source":"db"
What it means: After TTL the app reads MySQL again.
Example 20: Force invalidate
Type this:
curl -s http://localhost:3000/orders/popular >/dev/null
docker compose -f compose.mysql.yaml exec redis redis-cli DEL popular:v1
curl -s http://localhost:3000/orders/popular | grep -o '"source":"[^"]*"'
You will see:
1
"source":"db"
What it means: DEL removed the key. Next call filled it from db.
Example 21: Health still ok
Type this:
curl -s http://localhost:3000/healthz
You will see:
ok
What it means: Redis ping still works.
Step 8: Mongo Compose file
Why: Same API image, different engine.
What: Stop the MySQL stack first or use another host port. Here we use 3001.
Example 22: Write compose.mongo.yaml
Type this:
printf '%s\n' 'name: orders-mongo' 'services:' ' db:' ' image: mongo:7' ' volumes: [mongo-data:/data/db]' ' healthcheck:' ' test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand(\"ping\").ok"]' ' interval: 5s' ' retries: 20' '' ' seed:' ' image: mongo:7' ' depends_on:' ' db: {condition: service_healthy}' ' entrypoint: ["mongosh", "mongodb://db:27017/orders", "--eval", "db.popular.insertMany([{name:\"Vaishali\",rating:4.6},{name:\"Goodluck Cafe\",rating:4.4}])"]' '' ' redis:' ' image: redis:7-alpine' ' healthcheck:' ' test: ["CMD", "redis-cli", "ping"]' ' interval: 5s' ' retries: 20' '' ' api:' ' build: .' ' ports: ["3001:3000"]' ' environment:' ' DB_ENGINE: mongo' ' MONGO_URL: mongodb://db:27017' ' REDIS_URL: redis://redis:6379' ' depends_on:' ' seed: {condition: service_completed_successfully}' ' redis: {condition: service_healthy}' '' 'volumes: {mongo-data:}' > compose.mongo.yaml && wc -l compose.mongo.yaml
You will see:
36 compose.mongo.yaml
What it means: Mongo seed job inserts two restaurants then exits.
Example 23: Start Mongo stack on 3001
Type this:
docker compose -f compose.mongo.yaml up -d --build
You will see:
... Started
What it means: orders-mongo project is up.
Example 24: Miss then hit on 3001
Type this:
curl -s http://localhost:3001/orders/popular | grep -o '"source":"[^"]*"'
curl -s http://localhost:3001/orders/popular | grep -o '"source":"[^"]*"'
You will see:
"source":"db"
"source":"cache"
What it means: Same cache-aside behaviour on Mongo.
5. Compare, mistakes and clean up
Step 9: Compare both stacks
Why: One image, two engines.
What: Both answer with the same JSON shape. Only DB_ENGINE and URLs differ.
Example 25: MySQL popular names
Type this:
curl -s http://localhost:3000/orders/popular | grep -o 'Vaishali' | head -1
You will see:
Vaishali
What it means: MySQL stack still serves Vaishali from cache or db.
Example 26: Mongo popular names
Type this:
curl -s http://localhost:3001/orders/popular | grep -o 'Vaishali' | head -1
You will see:
Vaishali
What it means: Mongo stack serves the same restaurant name.
Example 27: List both projects
Type this:
docker ps --format '{{.Names}}' | grep orders | sort
You will see:
orders-mongo-api-1
orders-mongo-db-1
orders-mongo-redis-1
orders-mysql-api-1
orders-mysql-db-1
orders-mysql-redis-1
What it means: Two isolated projects on one Docker engine.
Step 10: Common mistakes
Why: Cache bugs are sneaky.
What: Caching forever, caching errors, and forgetting to invalidate after writes cause production incidents.
Example 28: TTL must be set
Type this:
docker compose -f compose.mysql.yaml exec redis redis-cli TTL popular:v1 || echo 'key missing means expired'
You will see:
21
What it means: A positive TTL means the key will die. -1 would mean no expiry: bad for this list.
Example 29: Do not cache error bodies
Type this:
echo 'Only redis.set after a successful dbList()'
You will see:
Only redis.set after a successful dbList()
What it means: Never store a 500 response in Redis.
Example 30: Password Redis in real life
Type this:
grep requirepass compose.mysql.yaml || echo 'practice-only: add requirepass before any shared host'
You will see:
practice-only: add requirepass before any shared host
What it means: Swiggy and Zomato Redis clusters always need auth.
Step 11: Clean up
Why: Remove both projects.
What: down -v on each Compose file. Remove the image if you need disk space.
Example 31: Stop MySQL project
Type this:
docker compose -f compose.mysql.yaml down -v
You will see:
... Volumes removed
What it means: orders-mysql gone.
Example 32: Stop Mongo project
Type this:
docker compose -f compose.mongo.yaml down -v
You will see:
... Volumes removed
What it means: orders-mongo gone.
Example 33: Confirm clean
Type this:
docker ps -a --filter name=orders- --format '{{.Names}}' | wc -l
You will see:
0
What it means: No leftover containers.
Step 12: Measure miss versus hit timing
Why: Numbers convince managers.
What: Use curl -w to print total time. The second call should be clearly faster when Redis is warm.
Example 34: Time a miss
Type this:
docker compose -f compose.mysql.yaml exec redis redis-cli DEL popular:v1 >/dev/null
curl -s -o /dev/null -w 'miss %{time_total}\n' http://localhost:3000/orders/popular
You will see:
miss 0.045
What it means: About 45 ms including the MySQL round trip.
Example 35: Time a hit
Type this:
curl -s -o /dev/null -w 'hit %{time_total}\n' http://localhost:3000/orders/popular
You will see:
hit 0.004
What it means: About 4 ms from Redis. Roughly ten times faster here.
Example 36: Show the speedup idea
Type this:
echo 'hit should be several times faster than miss on the same machine'
You will see:
hit should be several times faster than miss on the same machine
What it means: Interview tip: always show before and after timings.
Ravindra Bagale's Tip
Cache the popular read path, not every write. At Swiggy and Uber Eats the menu list is cached with a short TTL, while each new order still writes straight to the database. Short TTL plus delete-on-write keeps data honest.
लोकप्रिय read path cache करा, प्रत्येक write नाही. Swiggy आणि Uber Eats येथे menu list short TTL सह cache होते, तर प्रत्येक नवीन order थेट database मध्ये लिहितो. Short TTL आणि delete-on-write डेटा प्रामाणिक ठेवतात.
लोकप्रिय read path को cache करें, हर write को नहीं. Swiggy और Uber Eats में menu list short TTL के साथ cache होती है, जबकि हर नया order सीधे database में लिखा जाता है. Short TTL और delete-on-write डेटा को ईमानदार रखते हैं.
Check yourself
Q1. What is the cache-aside pattern in this API?
Read Redis first. On a miss, read the database, store the result in Redis with a TTL, then return it.
Q2. Why set EX 30 on the Redis key?
So the popular list expires after 30 seconds and cannot stay stale forever.
Q3. How do you force a fresh database read right now?
Delete the cache key with redis-cli DEL, then call the API again.
Q4. How can one Node image talk to MySQL and MongoDB?
DB_ENGINE and connection env vars choose the driver at runtime.
Q5. Why use two Compose project names?
So MySQL and Mongo stacks do not clash on one Docker engine.
Q6. Should you cache error responses?
No. Only cache successful database results.
Friends, you built a Node orders API with MySQL, MongoDB and a Redis cache, proved miss versus hit, expired keys and ran two projects side by side. Did you understand? Let us try it once more. If not, look at Picture 1 and repeat the miss-then-hit curl steps. Next project: Go with MySQL and MongoDB in a tiny distroless image.
मित्रांनो, आज तुम्ही MySQL, MongoDB आणि Redis cache सह Node orders API बनवली, miss versus hit सिद्ध केले, keys expire केल्या आणि दोन projects एकत्र चालवले. नसेल तर Picture 1 बघा आणि miss-then-hit curl steps पुन्हा करा. पुढचा project: tiny distroless image मध्ये MySQL आणि MongoDB सह Go.
दोस्तों, आज आपने MySQL, MongoDB और Redis cache के साथ Node orders API बनाई, miss versus hit साबित किया, keys expire कीं और दो projects साथ चलाए. नहीं तो Picture 1 देखिए और miss-then-hit curl steps दोहराइए. अगला project: tiny distroless image में MySQL और MongoDB के साथ Go.
Lab: try at home
- Create orders-api with package.json and src/index.js.
- Write the Dockerfile and MySQL init SQL.
- Start compose.mysql.yaml and prove db then cache sources.
- Inspect the Redis key and TTL.
- Wait for expiry and also try DEL invalidation.
- Start compose.mongo.yaml on port 3001 and prove miss then hit.
- Clean up both projects with down -v.
Recap
- One Node image can target MySQL or Mongo by env.
- Redis cache-aside speeds hot reads.
- Always set a TTL on cache keys.
- Delete keys when the source data changes.
- Project names isolate Compose stacks.
- Never cache error responses.
Revision card
Interview card