File tree Expand file tree Collapse file tree 5 files changed +74
-0
lines changed
12-scalability-and-architectural-patterns/07-peer-to-peer-load-balancing Expand file tree Collapse file tree 5 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 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!
Original file line number Diff line number Diff line change 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 } ` ) )
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments