Skip to content

Commit dd0ca7a

Browse files
committed
chore: continuing with chapter 12
1 parent ccbd1e3 commit dd0ca7a

File tree

5 files changed

+74
-0
lines changed

5 files changed

+74
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# 07-peer-to-peer-load-balancing
2+
3+
This example demonstrates how to implement peer-to-peer load balancing
4+
5+
## Run
6+
7+
Run 2 instances of the app with:
8+
9+
```bash
10+
node app.js 8081
11+
node app.js 8082
12+
```
13+
14+
Now run the client with:
15+
16+
```bash
17+
node client.js
18+
```
19+
20+
We should notice how each request is sent to a different server, confirming that
21+
we are now able to balance the load without a dedicated reverse proxy!
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { createServer } from 'node:http'
2+
3+
const { pid } = process
4+
const server = createServer((req, res) => {
5+
const url = new URL(req.url, `http://${req.headers.host}`)
6+
const searchParams = url.searchParams
7+
8+
console.log(`Handling request ${searchParams.get('request')} from ${pid}`)
9+
res.end(`Hello from ${pid}\n`)
10+
})
11+
12+
const port = Number.parseInt(process.env.PORT || process.argv[2]) || 8080
13+
server.listen(port, () => console.log(`Started at ${pid}`))
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const servers = [
2+
{ host: 'localhost', port: 8081 },
3+
{ host: 'localhost', port: 8082 },
4+
]
5+
let i = 0
6+
7+
export function balancedRequest(url, fetchOptions = {}) {
8+
i = (i + 1) % servers.length
9+
const server = servers[i]
10+
11+
const rewrittenUrl = new URL(url, `http://${server.host}:${server.port}`)
12+
rewrittenUrl.host = `${server.host}:${server.port}`
13+
14+
return fetch(rewrittenUrl.toString(), fetchOptions)
15+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { balancedRequest } from './balancedRequest.js'
2+
3+
for (let i = 0; i < 10; i++) {
4+
const response = await balancedRequest(`/?request=${i}`)
5+
const body = await response.text()
6+
console.log(
7+
`Request ${i} completed\nStatus: ${response.status}\nBody: ${body}`
8+
)
9+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "07-peer-to-peer-load-balancing",
3+
"version": "1.0.0",
4+
"description": "This example demonstrates how to implement peer-to-peer load balancing",
5+
"type": "module",
6+
"scripts": {},
7+
"engines": {
8+
"node": ">=24"
9+
},
10+
"engineStrict": true,
11+
"keywords": [],
12+
"author": "Luciano Mammino and Mario Casciaro",
13+
"license": "MIT",
14+
"devDependencies": {},
15+
"dependencies": {}
16+
}

0 commit comments

Comments
 (0)