Full Stack Engineer at Storied
Process Clustering
using Node.js Cluster Module
Â
Container and Server Clustering
using Kubernetes
Server
> Node
Server
đ´
đ´
đ´
> Node
> Node
> Node
> Node
Node uses only a single process (one CPU) and a mamximum of 1.5GB of RAM
Take advantage of multi-core systems.
1 master process forks n workers.
Node.js cluster module will load-balance instances of your app to available CPUs.
Can communicate with the parent using IPC.
There is no shared state between workers.
var cluster = require('cluster')
var app = require('./server')
if (cluster.isMaster) {
var numCPUs = require('os').cpus().length
for (var i = 0; i < numCPUs; i++) {
cluster.fork(process.env)
}
} else {
app.listen(process.env.PORT)
}
var app = require('express')()
app.get('/ping', function(req, res) {
res.send('pong!')
})
module.exports = app
var cluster = require('cluster')
var app = require('./server')
if (cluster.isMaster) {
var numCPUs = require('os').cpus().length
for (var i = 0; i < numCPUs; i++) {
cluster.fork(process.env)
}
} else {
app.listen(process.env.PORT)
}
The Cluster module â
Fork children â
Handle requests â
var app = require('express')()
app.get('/ping', function(req, res) {
res.send('pong!')
})
module.exports = app
Your average Express server
Export for better maintainability â
var cluster = require('cluster')
var app = require('./server')
if (cluster.isMaster) {
var numCPUs = require('os').cpus().length
for (var i = 0; i < numCPUs; i++) {
cluster.fork(process.env)
}
} else {
app.listen(process.env.PORT)
}
cluster.on('exit',
function (worker, code, signal) {
cluster.fork(process.env)
}
)
> Node
Server
> Node
> Node
> Node
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
Distribute load over multiple (virtual or physical) machines
Move away from the monolithic app design.
Services talk to each other using APIs and industry standard protocols.
>
>
>
>
REST API
>
>
>
>
Our services are stateless, authentication should also be stateless.
Session
Store
Service
Service
Service
Using centralized session store.
Application state = hard to scale
Our services are decentralized, authorization should also be decentralized.
Â
Forget about session-based authentication and let's talk about token based authentication.
>
>
>
>
/user/me
>
>
>
>
/photos
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkZS5tZXkubWljaGllbEBnbWFpbC5jb20iLCJpc3MiOiJhdXRoLmRlbWV5LmlvIiwicGVybWlzc2lvbnMiOlsicGluZyIsInBvbmciXX0.yj84-dz1D1HoJQjehsjHQPm7m60FtCM8pi87MaI5eUE
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkZS5tZXkubWljaGllbEBnbWFpbC5jb20iLCJpc3MiOiJhdXRoLmRlbWV5LmlvIiwicGVybWlzc2lvbnMiOlsicGluZyIsInBvbmciXX0.yj84-dz1D1HoJQjehsjHQPm7m60FtCM8pi87MaI5eUE
Similar to oAuth specification