16 min read
Horizontal vs vertical scaling, explained
In one sentence: Scaling vertically means giving your program a bigger machine; scaling horizontally means running several copies with a load balancer that shares the requests out. For any copy to serve any request, nothing can live only in the memory of one: in the shop, the order notices now travel through Redis.
What you will learn
- Tell vertical scaling from horizontal scaling, and what each one costs.
- Find what your API keeps in the memory of a single process and move it to a shared place.
- Carry the order notices from one copy to the others with Redis pub/sub.
- Choose how a load balancer shares requests out, and read a one-copy and a two-copy measurement without fooling yourself.
Before you start, read: 02-cache.md
The problem
Section titled “The problem”Imagine the shop with two copies of the API behind nginx, like the ones you tried in Phase 8. Ana follows order 22 live in one tab and, in another, cancels it. nginx sends the cancellation to the other copy.
The order is cancelled in PostgreSQL, but the first tab still says “pending”: the notice stayed in the memory of the other copy.
And another surprise: two copies on the same computer don’t serve twice as much, and sometimes less. This lesson fixes the first problem and explains the second.
The analogy
Section titled “The analogy”The analogy
Go back to the supermarket from the introduction. If a cashier kept your bag behind the counter, you have to go back to their register, even if another one is free.
And when everyone has to be told something, like “the price of milk has changed,” nobody goes from register to register: the store uses the loudspeaker, and they all hear it at once.
Where the analogy breaks down
- Registers don’t take space from each other. Two copies on the same computer do: they share its cores.
- The loudspeaker keeps nothing: whoever wasn’t listening misses it. Redis pub/sub is the same, and it isn’t meant for a job that has to get done.
How it really works
Section titled “How it really works”A bigger machine or more copies
Section titled “A bigger machine or more copies”There are two ways to make a program handle more:
- Vertical scalingHandling more users by giving the same machine more resources: more processor, more memory. It is the simplest because the program does not change, but it has a ceiling and, if that machine goes down, everything goes down.Go to definition: the same machine, with more processor and more memory. It’s moving your VPS to a bigger plan.
- Horizontal scalingHandling more users by adding more copies of the program, each on its own machine or process, with a load balancer sharing out the work. Its ceiling is much higher than that of a bigger machine, but it requires each copy to remember nothing between one request and the next.Go to definition: more copies of the program, on the same server or on several, with a Load balancerWhat spreads requests across several copies of the same program, so that none of them carries everything and, if one goes down, the others keep serving. It can be a program, like nginx with its upstream block, or a service from a cloud provider.Go to definition in front.
| Vertical | Horizontal | |
|---|---|---|
| The code | Doesn’t change | What lives in the memory of one copy has to move out of it |
| The ceiling | The biggest machine you can rent | The shared pieces, like the database |
| If a copy goes down | Everything goes down | The others keep going; but if they are all on the same machine and the machine goes down, everything goes down |
| What it costs | Expensive machines; resizing usually needs a reboot | A load balancer, and more pieces to watch |
You almost always start with vertical, which doesn’t ask you to change the code. With Node, though, the extra cores are only used with more processes, as you’re about to see.
Node uses one core for your code, and sometimes more
Section titled “Node uses one core for your code, and sometimes more”In Phase 3 you saw that your JavaScript runs on one ThreadA line of work inside a process, which the processor runs instruction by instruction. A process can have several threads working at once, but the JavaScript code of a Node.js server runs on just one.Go to definition, and a thread uses one core. With four cores, your code leaves three unused. A second ProcessA running program. When you start a server, the operating system creates a process that stays alive waiting for requests.Go to definition uses another one: that’s how the work gets shared among several Node processes, as we promised.
Node ships a module for that, node:cluster: a main process starts several children that share the port. The shop uses containers (--scale api=2): the same idea, which also works when the copies run on different machines, where node:cluster doesn’t reach.
But your code isn’t the only thing that computes. What libuv does in its four helper threads, like the argon2id of the login, already uses other cores.
Two copies are not double: what we measured
Section titled “Two copies are not double: what we measured”We measured with autocannon, as in the introduction, on October 22, 2026: an Apple M1 Pro with Docker in Colima, a virtual machine with 4 CPUs and 2 GiB where autocannon also ran, with 10 connections for 10 seconds. Requests per second, on average:
| Test | One copy | Two copies, each with its own autocannon | Two copies, behind nginx |
|---|---|---|---|
Login (POST /v2/session, argon2id) |
179.7 | 83.9 + 82.7 ≈ 166.6 | 161.2 |
Product list (GET /v2/products, from the cache) |
13,003 | 8,977 + 9,015 ≈ 17,992 | 7,355, and 19 errors |
The login doesn’t get better. With a single copy, docker stats saw it at 381% (100% is one core): argon2 computes in the helper threads, and one copy already used almost all four. With two behind nginx, each stayed at about 180%: they share the same cores.
The list does get better, by 38%. There the limit was your JavaScript thread (the copy, at 110%), and the second copy uses another core. It doesn’t reach double because autocannon computes on the same cores.
Behind nginx, the list falls below a single copy. With the Phase 8 configuration, nginx opens a new connection to a copy for every request, and it also computes on those four cores.
We also tried a pool of open connections to the copies (keepalive 16). In an earlier run of the same code, the list reached about 11,200 requests per second: still less than a single copy. The shop doesn’t use it: a new connection per request is what lets nginx move to the other copy when one stops, in lesson 4.
The 19 errors aren’t the shop’s. When we repeated the test in an earlier run, we got 17 errors, but nginx counted 84,297 responses, all 200, and logged no error. The likely cause is that nginx closes each client connection after 1,000 requests (keepalive_requests), and autocannon counts the request that catches the close as an error. With keepalive_requests 100000, there were none.
On a single computer, the copies compete for the same cores. What they do give you already is that, if one goes down, the other answers. Horizontal scaling really pays off when each copy brings its own machine.
Stateless: what cannot live in one copy
Section titled “Stateless: what cannot live in one copy”In Phase 4 we told you that, if the API is StatelessSaid of a server that remembers nothing from one request to the next. Each request carries everything needed to understand it, such as who you are or which page you want, and that’s why any copy of the server can handle it. What it does keep is the data, such as the orders.Go to definition, any copy can answer. Time to check. What the shop remembers between one request and the next:
| What | Where it lives | Can another copy see it? |
|---|---|---|
| Session (on a website)What a server remembers about a visitor from one request to the next, such as who they are or what’s in their cart. The server keeps that data under a long, random identifier, and the browser only keeps that identifier, almost always in a cookie.Go to definition | In PostgreSQL, since Phase 6 | Yes |
| The rate limit’s attempts | In Redis, since Phase 7 | Yes |
| The job queue | In Redis, since lesson 1 | Yes |
| The catalog cache | In the other Redis, since lesson 2 | Yes |
| Uploaded files | It has none; they would go to a store like S3, not to the disk of one copy | — |
| The order notices | In an EventEmitter, in the memory of each process |
No |
Everything is outside except the notice board from Phase 4, the one for the route that follows an order with SSESSE stands for Server-Sent Events.A way for the server to notify the client as soon as something happens. The client makes a normal HTTP request and the server leaves the response open, writing an event into it, a few lines of text, every time there’s news. It only goes one way, from the server to the client.Go to definition.
The notice that stays in one copy
Section titled “The notice that stays in one copy”Each copy has its own EventEmitter. When copy 2 cancels the order, it announces it in its own, and nobody is listening there:
- Copy 1 → Ana's browserstatus: pending
- Copy 2 → Ana's browser200: cancelled
- Copy 2announces it in its EventEmitter:
nobody here follows the order - Ana's browserthe first tab still says "pending"
We warned you in Phase 4: each connection lives on one server, and the notice has to reach the one that holds the client’s connection.
Redis pub/sub: one channel for all the copies
Section titled “Redis pub/sub: one channel for all the copies”The fix is the loudspeaker: Pub/sub (publish and subscribe)Publish and subscribe: a system in which some programs publish messages on a channel and every program subscribed at that moment receives them instantly, not just one as in a queue. If nobody is listening, the message is lost. Whoever publishes does not know who is listening.Go to definition (publish and subscribe). Each copy subscribes to a Redis channel, shop:orders. Whatever anyone publishes on it reaches all of those listening:
- Copy 1 · Copy 2each copy, the first time it needs it
- Redis → Copy 1order 22, cancelled
- Redis → Copy 2order 22, cancelled
- Copy 1 → Ana's browserstatus: cancelled
It all lives in a new file, src/order-events.ts. Without REDIS_URL, with npm start, it’s still an EventEmitter: with one process, that’s enough. With Redis, it uses two connections:
// Two connections to Redis. A connection subscribed to a channel is only good for receiving: while// it listens, no other commands can be sent to it. So one publishes and the other, its own// (duplicate(): another connection, with the same options), listens.// disableOfflineQueue: without a connection, publishing fails at once, without keeping the// notice in a queue for when it comes back. An old notice that arrives late can arrive after a// newer one from another copy (paid after cancelled), and would show as current a status that// no longer is. What is lost this way doesn't recover by itself: when Redis comes back, the// route closes the open streams (lost, further down), and whoever follows the order connects// again and reads its status.// The one that listens does keep its command, SUBSCRIBE, until there is a connection: it is the// only one it sends. After that, each time the client reconnects, it subscribes again on its own.// Creating a client opens no connection: connect() does (open, further down).const publisher = createClient({ url, disableOfflineQueue: true, socket: { connectTimeout: 1000 },});const subscriber = publisher.duplicate({ disableOfflineQueue: false });- Two, because a connection subscribed to a channel can only listen.
duplicate()creates another one with the same options except one: the connection that listens does keep itsSUBSCRIBEqueued until a connection is available. disableOfflineQueue: true: with no connection, publishing fails at once. A notice kept for later could arrive after a newer one, and show “paid” after “cancelled”.- And it subscribes again on its own after every disconnection.
Publishing is what emit does, which changeStatus and cancelOrder call just as before:
// The copy that makes the change doesn't notify its own listeners directly: it publishes it to// Redis and hears about it through Redis, like all the others. That way there is a single path,// and nobody receives it twice (if it notified its own and also received it from Redis, whoever// follows the order on this copy would get it repeated). It costs a trip to Redis, under a// millisecond.// Without waiting: the response to the request that changed the order needn't wait for Redis,// and a hung Redis (it receives the command and doesn't answer) would leave it waiting forever:// node-redis's time limit doesn't count after the command is sent (cache.ts). If it fails, to the// log, without throwing: the change is already saved in PostgreSQL.// Only the first time, while the connection is being opened, does the notice wait for it to be// ready, one second at most, the same connectTimeout; otherwise, it is lost. After that, it never// waits: with the connection cut, publishing fails at once (two-connections), and the notice is// lost now instead of going out late, when it comes back, maybe after a newer one from another// copy.emit(order) { void open(); const publish = () => publisher .publish(channel, JSON.stringify(order)) .catch((error: Error) => log.debug({ order: order.id, reason: error.message }, 'order notice lost'), ); if (everConnected) { void publish(); return; } // A race between the first connection and a one-second clock: whichever comes first. const late = sleep(1000).then(() => Promise.reject(new Error('Redis does not answer in 1 s')), ); Promise.race([firstConnection, late]).then(publish, (error: Error) => log.debug({ order: order.id, reason: error.message }, 'order notice lost'), );},- The copy that makes the change doesn’t notify its own listeners: it publishes the change and receives it back, like all the others. If it notified its own and also received it from Redis, whoever follows the order on that copy would get it twice.
- It doesn’t wait for Redis. The cancellation answers without waiting for the notice: in lesson 2 you saw that a hung Redis may never answer.
- Only the first time, the notice (not the response) waits, one second at most, for the connection to open. After that, if the connection is down, the notice is lost now instead of going out late and out of order.
And what arrives from the channel:
// Each message on the channel should be an order in JSON. All its fields are text, numbers or// null (the date goes as text, createdAt), so JSON.parse leaves it exactly as it was. But the// channel isn't only the shop's: anyone with access to that Redis can publish on it. What isn't an// order (text, null, an object with other fields) is ignored: whoever listens only gets orders,// and the route can read order.id without fear. To the log, without making noise (debug).function receive(message: string) { let parsed: unknown; try { parsed = JSON.parse(message); } catch { parsed = undefined; } const order = orderSchema.safeParse(parsed); if (!order.success) { log.debug( { channel, message: message.slice(0, 100) }, 'a notice on the channel that is not an order', ); return; } local.emit('change', order.data);}Anyone with access to that Redis can publish on the channel. That’s why every message goes through a zod schema: whatever isn’t an order is ignored.
And if Redis goes away and comes back, whatever was published in the meantime is lost. So, when it comes back, the API closes the open SSE streams, and EventSource reconnects on its own and receives the current status.
Pub/sub is not a queue
Section titled “Pub/sub is not a queue”Both go through Redis, with opposite jobs:
| The queue (lesson 1) | Pub/sub | |
|---|---|---|
| Who receives each message | One worker | Everyone listening |
| If nobody is listening | The job waits | The message is lost |
| What it’s for | Something that has to get done, like an email | A notice that only matters to whoever is there |
Redis calls this “at most once” delivery (at-most-once), as opposed to the queue’s at-least-once delivery. For a notice on a screen, it’s enough.
How the load balancer shares requests out
Section titled “How the load balancer shares requests out”The shop’s load balancer is nginx, with its upstream from Phase 8. The two ways of sharing you’ll see most:
- Round robin: one request to each copy, in order. It’s what nginx does by default.
- Least connections (
least_conninside theupstream): to the copy with the fewest open connections. It helps when some requests last much longer than others, like an SSE stream that lasts minutes.
Layer 4 or layer 7
Section titled “Layer 4 or layer 7”In the TCP/IP model we told you about “layer 4” and “layer 7” load balancers:
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| What it sees | IPs and ports | The whole HTTP request: URL, headers, cookies |
| What it shares out | TCPTCP stands for Transmission Control Protocol.The transport layer protocol that makes data arrive complete and in order, and at the right program thanks to ports.Go to definition connections, without looking at what’s inside | Requests, one by one |
| What else it can do | Little more: it shares out very fast | Choose a copy by the URL, add X-Forwarded-For, retry on another copy, HTTPS |
| Examples | nginx’s stream module; AWS’s Network Load Balancer |
nginx with proxy_pass, like the shop; AWS’s Application Load Balancer |
The shop’s is layer 7: that’s why in Phase 8 it answered with a 502, an HTTP response, when it couldn’t talk to any copy.
Sticky sessions, and why the shop doesn’t need them
Section titled “Sticky sessions, and why the shop doesn’t need them”Another way to share out: each visitor always to the same copy, by their IP (ip_hash in nginx) or with a cookie. These are sticky sessions, for APIs that keep state in memory, like the cashier who kept your bag.
The price: the split ends up uneven and, if a copy goes down, its visitors lose what it was keeping. The shop doesn’t need them: the sessions are in PostgreSQL and the notices go through Redis.
Several servers: the load balancer, on its own machine
Section titled “Several servers: the load balancer, on its own machine”With several machines, the idea is the same: each copy on its own server, and the load balancer on another, or as a service from your provider, which is the only one facing the internet.
PostgreSQL and Redis move to their own machine and become the next limit: that’s where the replicas of lesson 6 begin.
Try it
Section titled “Try it”The goal: see how a notice gets lost with two copies, fix it with step 39, and measure how much the second copy gains you.
The outputs are from the Mac of the measurements, with Node 26 in the containers; your times, IDs and numbers will be different. The tables are from autocannon 8.0.0; 9.0.0 prints the same ones. You work in your project, ~/backend-course/phase-3/shop-api, at step 38 from lesson 2.
With step 38: the notice is lost
Section titled “With step 38: the notice is lost”1. Two copies of the API
docker compose up --build --scale api=2 --waitdocker compose port --index 1 api 3000docker compose port --index 2 api 3000What you will see:
…Container shop-api-2 HealthyContainer shop-api-1 Healthy127.0.0.1:3000127.0.0.1:3001--wait waits for both copies to be healthy, and docker compose port --index N api 3000 tells you which port each one got. Always ask: each copy takes whichever one is free in the range, and in another run copy 1 got 3001. If that happens to you, change the ports in the next steps.
2. Ana logs in through copy 1
curl -s -c ana.txt -H 'Content-Type: application/json' -d '{"email":"ana@shop.example","password":"ana-practice-2026"}' http://localhost:3000/v2/sessionWhat you will see:
{"id":1,"email":"ana@shop.example","role":"admin"}-c ana.txt saves the session cookie. The session lives in PostgreSQL, so it’s valid on both copies.
Now you need two terminals. In the first, Ana follows order 22 through copy 1 for 6 seconds (-m 6). Open the second, go into your project too (cd ~/backend-course/phase-3/shop-api, where ana.txt is) and cancel the order through copy 2 before the 6 seconds are up.
3. Follow through one copy, cancel through the other
# terminal 1curl -sN -m 6 -b ana.txt http://localhost:3000/v2/orders/22/events# terminal 2curl -s -b ana.txt -H 'Origin: http://localhost:3000' -X POST http://localhost:3001/v2/orders/22/cancellationWhat you will see:
# terminal 2{"id":22,"productId":2,"quantity":3,"status":"cancelled","createdAt":"2026-10-07T12:00:00.000Z","customerId":4}# terminal 1, what arrived in those 6 secondsevent: statusdata: {"id":22,"productId":2,"quantity":3,"status":"pending","createdAt":"2026-10-07T12:00:00.000Z","customerId":4}The cancellation answers "status":"cancelled". Origin is the header the shop requires on a POST with a cookie, from the CSRF lesson.
Look at terminal 1: a single event, pending. The cancellation never arrived.
If the cancellation gives a 401, that terminal can’t find ana.txt; if it gives a 403, the Origin is missing. If the 6 seconds run out, order 22 is already cancelled and won’t notify again: repeat with another pending order, 23 or 24, and -m 30: the output will show that order’s id.
4. Is it cancelled?
curl -s -b ana.txt http://localhost:3000/v2/orders/22curl -s -b ana.txt http://localhost:3001/v2/orders/22What you will see:
{"id":22,"productId":2,"quantity":3,"status":"cancelled","createdAt":"2026-10-07T12:00:00.000Z","customerId":4}{"id":22,"productId":2,"quantity":3,"status":"cancelled","createdAt":"2026-10-07T12:00:00.000Z","customerId":4}Both copies read cancelled from PostgreSQL. The data is fine; what got lost was the notice.
Update your project
Section titled “Update your project”First, docker compose down -v: order 22 is already cancelled, and -v deletes the volumes so the shop loads its practice data again (and takes your session with it). Then put your project at step 39, as in the introduction:
docker compose down -vcd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/39-scaling.tar.gztar -xzf 39-scaling.tar.gzcp -R 39-scaling/. shop-api/cd shop-apiorder-events.ts is new; data.ts and v2.ts use it, and config.ts reads the channel’s name, ORDERS_CHANNEL (by default, shop:orders). There are no new packages.
With step 39: the notice arrives
Section titled “With step 39: the notice arrives”Repeat steps 1 to 3: up with --build, to build the new image, the ports, Ana’s session, and follow and cancel, with both terminals in your project.
5. Follow through one copy, cancel through the other, again
# terminal 1curl -sN -m 6 -b ana.txt http://localhost:3000/v2/orders/22/events# terminal 2curl -s -b ana.txt -H 'Origin: http://localhost:3000' -X POST http://localhost:3001/v2/orders/22/cancellationWhat you will see:
# terminal 2{"id":22,"productId":2,"quantity":3,"status":"cancelled","createdAt":"2026-10-07T12:00:00.000Z","customerId":4}# terminal 1, what arrived in those 6 secondsevent: statusdata: {"id":22,"productId":2,"quantity":3,"status":"pending","createdAt":"2026-10-07T12:00:00.000Z","customerId":4}
event: statusdata: {"id":22,"productId":2,"quantity":3,"status":"cancelled","createdAt":"2026-10-07T12:00:00.000Z","customerId":4}Now there are two events: pending and, as soon as you cancel, cancelled. The notice went from copy 2 to Redis, and from Redis to copy 1. If you only see one, look at step 6: both copies must listen to the channel.
6. What the copies say
docker compose logs api 2>&1 | grep -v '"path":"/health"' | cut -c1-300What you will see:
api-1 | {"level":30,"time":1792657585690,"pid":1,"hostname":"9f33f1ede048","msg":"The shop is listening on http://localhost:3000"}…api-1 | {"level":30,"time":1792657594739,"pid":1,"hostname":"9f33f1ede048","requestId":"3fc92289-93e7-4d47-b495-313be7415c86","method":"GET","path":"/v2/orders/22/events","status":200,"ms":5,"msg":"request"}api-1 | {"level":30,"time":1792657594741,"pid":1,"hostname":"9f33f1ede048","channel":"shop:orders","msg":"the API listens to the channel of the order notices"}…api-2 | {"level":30,"time":1792657585503,"pid":1,"hostname":"ded95f1becff","msg":"The shop is listening on http://localhost:3000"}api-2 | {"level":30,"time":1792657596261,"pid":1,"hostname":"ded95f1becff","requestId":"af4c4c46-f362-4cf1-8e84-c58ce4333ac6","method":"POST","path":"/v2/orders/22/cancellation","status":200,"ms":11,"msg":"request"}api-2 | {"level":30,"time":1792657596265,"pid":1,"hostname":"ded95f1becff","channel":"shop:orders","msg":"the API listens to the channel of the order notices"}…grep -v removes the health check lines; we removed others with “…”. Each copy subscribes to the channel the first time it needs it: copy 1, with the request that follows the order; copy 2, with the cancellation.
If a copy doesn’t say the API listens to the channel, check that compose.yaml passes it REDIS_URL.
One copy against two, measured
Section titled “One copy against two, measured”With both copies running, launch one autocannon against each at the same time, with 5 connections each. It runs in a node:26 container inside the shop’s network, shop_default, to reach each copy by name. First, as we did, a 3-second pass to warm up: the first read fills the cache, which both copies share.
docker run --rm --network shop_default node:26 npx -y autocannon@9.0.0 -d 3 http://api:3000/v2/products7. Two copies, each with its own autocannon
docker run --rm --network shop_default node:26 npx -y autocannon@9.0.0 -c 5 -d 10 http://shop-api-1:3000/v2/products &docker run --rm --network shop_default node:26 npx -y autocannon@9.0.0 -c 5 -d 10 http://shop-api-2:3000/v2/products &waitWhat you will see:
Running 10s test @ http://shop-api-1:3000/v2/products5 connections…│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │├───────────┼─────────┼─────────┼─────────┼─────────┼──────────┼──────────┼─────────┤│ Req/Sec │ 6,051 │ 6,051 │ 9,247 │ 10,287 │ 8,977.21 │ 1,393.81 │ 6,049 │…90k requests in 9.92s, 83.8 MB readRunning 10s test @ http://shop-api-2:3000/v2/products5 connections…│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │├───────────┼─────────┼─────────┼─────────┼─────────┼──────────┼──────────┼─────────┤│ Req/Sec │ 6,283 │ 6,283 │ 9,191 │ 10,551 │ 9,014.73 │ 1,314.34 │ 6,282 │…99k requests in 10.9s, 92.6 MB readThe & at the end launches each command without waiting for it to finish, and wait waits for both. Each container downloads autocannon with npx before starting, so the two 10 seconds overlap, but they aren’t exact. The tables come out mixed in with the headers; here, they’re sorted and show only the requests-per-second row. Add the two averages, Avg: 8,977 + 9,015, about 17,992 per second.
Go back to a single copy with docker compose up -d --scale api=1 --wait and measure with 10 connections, the same total. autocannon finds it by the service’s name, api:
8. One copy
docker run --rm --network shop_default node:26 npx -y autocannon@9.0.0 -d 10 http://api:3000/v2/productsWhat you will see:
Running 10s test @ http://api:3000/v2/products10 connections
┌─────────┬──────┬──────┬───────┬──────┬─────────┬─────────┬───────┐│ Stat │ 2.5% │ 50% │ 97.5% │ 99% │ Avg │ Stdev │ Max │├─────────┼──────┼──────┼───────┼──────┼─────────┼─────────┼───────┤│ Latency │ 0 ms │ 0 ms │ 1 ms │ 2 ms │ 0.13 ms │ 0.72 ms │ 54 ms │└─────────┴──────┴──────┴───────┴──────┴─────────┴─────────┴───────┘┌───────────┬─────────┬─────────┬─────────┬─────────┬───────────┬────────┬─────────┐│ Stat │ 1% │ 2.5% │ 50% │ 97.5% │ Avg │ Stdev │ Min │├───────────┼─────────┼─────────┼─────────┼─────────┼───────────┼────────┼─────────┤│ Req/Sec │ 10,919 │ 10,919 │ 13,463 │ 14,071 │ 13,002.55 │ 970.65 │ 10,915 │├───────────┼─────────┼─────────┼─────────┼─────────┼───────────┼────────┼─────────┤│ Bytes/Sec │ 10.2 MB │ 10.2 MB │ 12.6 MB │ 13.1 MB │ 12.1 MB │ 906 kB │ 10.2 MB │└───────────┴─────────┴─────────┴─────────┴─────────┴───────────┴────────┴─────────┘
Req/Bytes counts sampled once per second.# of samples: 11
143k requests in 11.01s, 134 MB readAbout 13,003 per second: two copies give 38% more, not double. The p99 of the latency is 2 ms: the list comes out of the cache.
When you’re done: docker compose down and rm ana.txt.
On your server
Section titled “On your server”This time there’s nothing to copy to the server: neither compose.production.yaml nor deployment/ changes. Commit and git push from shop-api, and the timer deploys step 39. There’s nothing to add to .env: the notices use the same REDIS_URL as the queue. Production stays with a single copy, which publishes and hears itself, until lesson 4: there it gets two, api-a and api-b.
You have already seen it
Section titled “You have already seen it”- Your provider’s plans. Moving your VPS from 2 to 4 GB of memory is scaling vertically; renting a second server, horizontally.
- The shop from Phase 7. With
--scale api=2you already had two copies, and the limit worked because it was in Redis.
Common mistakes
Section titled “Common mistakes”- Expecting double with two copies on the same machine. Measure first.
- Keeping something in the process’s memory and scaling later. A
Mapof sessions, a counter: each copy would have its own. - Notifying your own listeners and also publishing. Whoever follows the order on that copy receives it twice.
- Using pub/sub for a job that has to get done. If nobody is listening, it’s lost: that’s what the queue is for.
Summary
Section titled “Summary”- Vertically, a bigger machine; horizontally, more copies with a load balancer in front.
- On a single machine, the copies share the cores: we measured +38% on the list and nothing on the login.
- To scale horizontally, nothing can live in just one copy: in the shop, what was left was the notices’
EventEmitter. - With Redis pub/sub, each copy publishes the changes and all of them, itself included, receive them. With nobody listening, they’re lost.
- A load balancer shares out in turns or to the copy with the fewest connections; a layer 7 one reads the HTTP request.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Using nginx as HTTP load balancer, from the nginx documentation: round robin,
least_connandip_hash. - Redis Pub/sub, from the Redis documentation: channels and why delivery is “at most once.”
- Cluster, from the Node documentation: several Node processes on the same port.
- Processes, from The Twelve-Factor App: why an application shouldn’t keep anything in a process’s memory, and what it says about sticky sessions.