SlideShare una empresa de Scribd logo
1 de 52
Descargar para leer sin conexión
PLANNING FOR THE
                                  HORIZONTAL
                                     SCALING NODE.JS APPLICATIONS




                        TheReddest           Brandon Cannaday       brandon@modulus.io

Thursday, April 4, 13
ME




                        HOSTING, DATA, STATS FOR NODE.JS

                                   modulus.io



Thursday, April 4, 13
WHEN TO SCALE?


                        1. RESPONSE TIMES
                        2. CPU USAGE
                        3. CONCURRENT CONNECTIONS




Thursday, April 4, 13
NODEFLY.COM




Thursday, April 4, 13
STARTING POINT
                           mydomain.com




                               > NODE


                              SERVER




Thursday, April 4, 13
NODE TWEAKS

                                     CONCURRENT OUTGOING
                                       CONNECTION LIMIT

                        http.globalAgent.maxSockets = Number.MAX_VALUE;




Thursday, April 4, 13
HURTLE: THE SERVER

                        LINUX CONFIGURATION
                          1. FILE-MAX
                          2. SOMAXCONN
                          3. ULIMIT



Thursday, April 4, 13
FILE-MAX

                        SYSTEM FILE DESCRIPTOR LIMIT

                        1. Run sysctl -w fs.file-max=65535
                        2. Run sysctl -p




Thursday, April 4, 13
SOMAXCONN

                             SOCKET LISTEN QUEUE LENGTH

                        1. Run sysctl -w net.core.somaxconn=65535
                        2. Run sysctl -p




Thursday, April 4, 13
ULIMIT
                        PER PROCESS FILE DESCRIPTOR LIMIT
                          1. Edit /etc/security/limits.conf
                          2. Add the following:
                          *      soft   nofile    65535
                          *      hard   nofile    65535
                          root   soft   nofile    65535
                          root   hard   nofile    65535
Thursday, April 4, 13
RUNNING SMOOTH

                            mydomain.com




                                > NODE


                               SERVER




Thursday, April 4, 13
HURTLE: THE CPU

                           BUY A BIGGER BOX



                         > NODE         > NODE


                        SERVER
                                        SERVER
                         1 CORE
                                        4 CORES

Thursday, April 4, 13
MULTICORE NODE

                           100%




                        USAGE




                                  1   2      3   4
                                      CORE


Thursday, April 4, 13
CLUSTER MODULE
                           mydomain.com




                            > NODE    > NODE



                            > NODE    > NODE



                                 SERVER




Thursday, April 4, 13
CLUSTER EXAMPLE

             var cluster = require('cluster');            The Cluster Module
             var http = require('http');
             var numCPUs = require('os').cpus().length;

             if(cluster.isMaster) {
               for(var i = 0; i < numCPUs; i++) {
                 cluster.fork();
               }
             }
             else {
               http.createServer(function(req, res) {
                 res.writeHead(200);
                 res.end('Hello World.');
               }).listen(80);
             }


Thursday, April 4, 13
CLUSTER EXAMPLE

             var cluster = require('cluster');
             var http = require('http');
             var numCPUs = require('os').cpus().length;

             if(cluster.isMaster) {
               for(var i = 0; i < numCPUs; i++) {
                 cluster.fork();                          Fork Children
               }
             }
             else {
               http.createServer(function(req, res) {
                 res.writeHead(200);
                 res.end('Hello World.');
               }).listen(80);
             }


Thursday, April 4, 13
CLUSTER EXAMPLE

             var cluster = require('cluster');
             var http = require('http');
             var numCPUs = require('os').cpus().length;

             if(cluster.isMaster) {
               for(var i = 0; i < numCPUs; i++) {
                 cluster.fork();
               }
             }
             else {
               http.createServer(function(req, res) {     Handle Requests
                 res.writeHead(200);
                 res.end('Hello World.');
               }).listen(80);
             }


Thursday, April 4, 13
CLUSTER LISTEN


                                 listen(...)

                        WORKER                 MASTER

                                 Handle




Thursday, April 4, 13
ROLLING UPDATES

                        1. UPDATE SCRIPT
                        2. WORKER -> STOP LISTENING
                        3. KILL WORKER
                        4. CALL FORK() AGAIN


Thursday, April 4, 13
CLUSTER MODULE
                           mydomain.com




                            > NODE    > NODE



                            > NODE    > NODE



                                 SERVER




Thursday, April 4, 13
HURTLE: SHARED STATE


                                          > NODE    > NODE

                        NO SHARED STATE
                                          > NODE    > NODE



                                               SERVER




Thursday, April 4, 13
INSTALL REDIS


                           > NODE    > NODE



                           > NODE    > NODE


                                REDIS


                                SERVER




Thursday, April 4, 13
EXAMPLE 1: SESSION
                                     MEMORY STORE

                          var express = require('express'),
                              app = express();


                          app.use(express.cookieParser());
                          app.use(express.session({
                            secret: 'My Cookie Signing Secret'
                          }));

                          app.get('/', function(req, res) {
                            req.session.somekey = 'some value';
                          });




Thursday, April 4, 13
EXAMPLE 1: SESSION
                                               REDIS STORE

                        var express = require('express'),
                            RedisStore = require('connect-redis')(express),
                            app = express();


                        app.use(express.cookieParser());
                        app.use(express.session({
                          store: new RedisStore({ host: 'localhost', port: 6379 }),
                          secret: 'My Cookie Signing Secret'
                        }));

                        app.get('/', function(req, res) {
                          req.session.somekey = 'some value';
                        });



Thursday, April 4, 13
EXAMPLE 2: SOCKET.IO

                        var   RedisStore = require('socket.io/lib/stores/redis')
                          ,   redis = require('socket.io/node_modules/redis')
                          ,   pub    = redis.createClient()
                          ,   sub    = redis.createClient()
                          ,   client = redis.createClient();

                        io.set('store', new RedisStore({
                          redisPub : pub
                        , redisSub : sub
                        , redisClient : client
                        }));


                        https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO


Thursday, April 4, 13
RUNNING SMOOTH
                            mydomain.com




                            > NODE    > NODE



                            > NODE    > NODE


                                 REDIS


                                 SERVER


Thursday, April 4, 13
LAST HURTLE: HORIZONTAL


                           > NODE    > NODE   > NODE    > NODE



                           > NODE    > NODE   > NODE    > NODE


                                REDIS              REDIS


                             APP SERVER A       APP SERVER B




Thursday, April 4, 13
SEPARATE REDIS

                        > NODE    > NODE            > NODE    > NODE



                        > NODE    > NODE            > NODE    > NODE


                          APP SERVER A                APP SERVER B




                                           REDIS

                                           SERVER

Thursday, April 4, 13
LOAD BALANCING

                   mydomain.com              LOAD BALANCER

                                                     SERVER



                                  > NODE    > NODE             > NODE    > NODE



                                  > NODE    > NODE             > NODE    > NODE


                                    APP SERVER A                 APP SERVER B




                                                      REDIS

                                                      SERVER



Thursday, April 4, 13
LOAD BALANCING


                         1. MANAGED
                         2. INSTALL ONE
                         3. WRITE YOUR OWN




Thursday, April 4, 13
NGINX

                        http {
                          upstream mydomain_com {
                            server host1.mydomain.com:80;
                            server host2.mydomain.com:80;
                          }                                       LOAD BALANCER

                            server {
                                                                     SERVER
                              listen 80;
                              server_name www.mydomain.com;
                              location / {
                                proxy_pass http://mydomain_com;
                              }
                            }
                        }



Thursday, April 4, 13
WRITE ONE




                        https://github.com/substack/bouncy


Thursday, April 4, 13
BOUNCY
              var bouncy = require('bouncy');                    bouncy module
              var hosts = [
                 'host1.mydomain.com',
                 'host2.mydomain.com'
              ];

              var count = 0;

              var server = bouncy(function(req, res, bounce) {

                   count++;
                   var host = hosts[count % hosts.length];

                   bounce(host, 80);

              });

              server.listen(80);


Thursday, April 4, 13
BOUNCY
              var bouncy = require('bouncy');

              var hosts = [                                      Server collection
                 'host1.mydomain.com',
                 'host2.mydomain.com'
              ];

              var count = 0;

              var server = bouncy(function(req, res, bounce) {

                   count++;
                   var host = hosts[count % hosts.length];

                   bounce(host, 80);

              });

              server.listen(80);


Thursday, April 4, 13
BOUNCY
              var bouncy = require('bouncy');

              var hosts = [
                 'host1.mydomain.com',
                 'host2.mydomain.com'
              ];

              var count = 0;

              var server = bouncy(function(req, res, bounce) {   Create server
                   count++;
                   var host = hosts[count % hosts.length];

                   bounce(host, 80);

              });

              server.listen(80);


Thursday, April 4, 13
BOUNCY
              var bouncy = require('bouncy');

              var hosts = [
                 'host1.mydomain.com',
                 'host2.mydomain.com'
              ];

              var count = 0;

              var server = bouncy(function(req, res, bounce) {

                   count++;
                   var host = hosts[count % hosts.length];

                   bounce(host, 80);                             Bounce request
              });

              server.listen(80);


Thursday, April 4, 13
AFFINITY


                        SESSION AFFINITY
                        STICKY SESSIONS
                          SEND THE SAME PERSON
                         BACK TO THE SAME SERVER



Thursday, April 4, 13
NGINX AFFINITY

                        http {
                          upstream mydomain_com {
                            sticky;
                            server host1.mydomain.com:80;
                            server host2.mydomain.com:80;
                          }

                            server {
                              listen 80;
                              server_name www.mydomain.com;
                              location / {
                                proxy_pass http://mydomain_com;
                              }
                            }
                        }



Thursday, April 4, 13
CUSTOM AFFINITY


                        req.headers['x-forwarded-for']
                        req.connection.remoteAddress




Thursday, April 4, 13
RUNNING SMOOTH

                   mydomain.com              LOAD BALANCER

                                                     SERVER



                                  > NODE    > NODE             > NODE    > NODE



                                  > NODE    > NODE             > NODE    > NODE


                                    APP SERVER A                 APP SERVER B




                                                      REDIS

                                                      SERVER



Thursday, April 4, 13
ROLLING UPDATES


                    1. REMOVE APP SERVER FROM LOAD BALANCER
                    2. UPGRADE APP SERVER
                    3. ADD BACK
                    4. REPEAT


Thursday, April 4, 13
SSL


                        TERMINATE EARLY




Thursday, April 4, 13
SSL

                                    LB               SSL                SSL TERMINATOR

                                           SERVER



                        > NODE    > NODE             > NODE    > NODE



                        > NODE    > NODE             > NODE    > NODE


                          APP SERVER A                 APP SERVER B




                                            REDIS

                                            SERVER



Thursday, April 4, 13
SSL

                        mydomain.com
                              80   443




                         LB             SSL



                               SERVER




Thursday, April 4, 13
STUD
                           EXAMPLE CONFIG FILE


                        frontend = [*]:443
                        backend = [127.0.0.1]:80
                        ssl = on
                        pem-file = "myCert.pem"



                            https://github.com/bumptech/stud

Thursday, April 4, 13
RUNNING SMOOTH W/SSL

                   mydomain.com               LB               SSL

                                                     SERVER



                                  > NODE    > NODE             > NODE    > NODE



                                  > NODE    > NODE             > NODE    > NODE


                                    APP SERVER A                 APP SERVER B




                                                      REDIS

                                                      SERVER



Thursday, April 4, 13
HUGE

                        LB            SSL            LB            SSL

                             SERVER                       SERVER




                                            REDIS

                                            SERVER




Thursday, April 4, 13
DNS


                        ROUND-ROBIN DNS
                         MULTIPLE RECORDS,
                           ONE DOMAIN




Thursday, April 4, 13
ROUND-ROBIN DNS


                        CLIENT 1   1. xxx.xxx.xxx.x
                                   2. xxx.xxx.xxx.y


                        CLIENT 2   1. xxx.xxx.xxx.y
                                   2. xxx.xxx.xxx.x


Thursday, April 4, 13
RUNNING SMOOTH

                          LB            SSL            LB            SSL

                               SERVER                       SERVER




                                              REDIS

                                              SERVER




Thursday, April 4, 13
BIG ENOUGH



                        > NODE


                        SERVER




Thursday, April 4, 13
BIG ENOUGH



                        > NODE


                        SERVER




Thursday, April 4, 13

Más contenido relacionado

La actualidad más candente

FUSE Developing Fillesystems in userspace
FUSE Developing Fillesystems in userspaceFUSE Developing Fillesystems in userspace
FUSE Developing Fillesystems in userspaceelliando dias
 
[Python] Quick book for dell switch_os10
[Python] Quick book for dell switch_os10[Python] Quick book for dell switch_os10
[Python] Quick book for dell switch_os10Jo Hoon
 
Installing and Configuring Domino 10 on CentOS 7
Installing and Configuring Domino 10 on CentOS 7Installing and Configuring Domino 10 on CentOS 7
Installing and Configuring Domino 10 on CentOS 7Devin Olson
 
Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu
Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu
Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu 康志強 大人
 
Andresen 8 21 02
Andresen 8 21 02Andresen 8 21 02
Andresen 8 21 02FNian
 
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템Sam Kim
 
The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212Mahmoud Samir Fayed
 
Guide to clone_sles_instances
Guide to clone_sles_instancesGuide to clone_sles_instances
Guide to clone_sles_instancesSatheesh Thomas
 
Most frequently used unix commands for database administrator
Most frequently used unix commands for database administratorMost frequently used unix commands for database administrator
Most frequently used unix commands for database administratorDinesh jaisankar
 
SSD based storage tuning for databases
SSD based storage tuning for databasesSSD based storage tuning for databases
SSD based storage tuning for databasesAngelo Rajadurai
 
Running hadoop on ubuntu linux
Running hadoop on ubuntu linuxRunning hadoop on ubuntu linux
Running hadoop on ubuntu linuxTRCK
 
The State of Puppet
The State of PuppetThe State of Puppet
The State of PuppetPuppet
 
Domino9on centos6
Domino9on centos6Domino9on centos6
Domino9on centos6a8us
 

La actualidad más candente (19)

PythonFuse (PyCon4)
PythonFuse (PyCon4)PythonFuse (PyCon4)
PythonFuse (PyCon4)
 
FUSE Developing Fillesystems in userspace
FUSE Developing Fillesystems in userspaceFUSE Developing Fillesystems in userspace
FUSE Developing Fillesystems in userspace
 
[Python] Quick book for dell switch_os10
[Python] Quick book for dell switch_os10[Python] Quick book for dell switch_os10
[Python] Quick book for dell switch_os10
 
Installing and Configuring Domino 10 on CentOS 7
Installing and Configuring Domino 10 on CentOS 7Installing and Configuring Domino 10 on CentOS 7
Installing and Configuring Domino 10 on CentOS 7
 
Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu
Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu
Hadoop 2.2.0 Multi-node cluster Installation on Ubuntu
 
Andresen 8 21 02
Andresen 8 21 02Andresen 8 21 02
Andresen 8 21 02
 
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
 
D space manual
D space manualD space manual
D space manual
 
Solaris
SolarisSolaris
Solaris
 
Sun raysetup
Sun raysetupSun raysetup
Sun raysetup
 
The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212The Ring programming language version 1.10 book - Part 92 of 212
The Ring programming language version 1.10 book - Part 92 of 212
 
Guide to clone_sles_instances
Guide to clone_sles_instancesGuide to clone_sles_instances
Guide to clone_sles_instances
 
Most frequently used unix commands for database administrator
Most frequently used unix commands for database administratorMost frequently used unix commands for database administrator
Most frequently used unix commands for database administrator
 
SSD based storage tuning for databases
SSD based storage tuning for databasesSSD based storage tuning for databases
SSD based storage tuning for databases
 
Running hadoop on ubuntu linux
Running hadoop on ubuntu linuxRunning hadoop on ubuntu linux
Running hadoop on ubuntu linux
 
The State of Puppet
The State of PuppetThe State of Puppet
The State of Puppet
 
Web Server Free Bsd
Web Server Free BsdWeb Server Free Bsd
Web Server Free Bsd
 
ubunturef
ubunturefubunturef
ubunturef
 
Domino9on centos6
Domino9on centos6Domino9on centos6
Domino9on centos6
 

Destacado

Horizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSocketsHorizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSocketsJames Simpson
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleTom Croucher
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture AppDynamics
 
Progressive Advancement in Web8
Progressive Advancement in Web8Progressive Advancement in Web8
Progressive Advancement in Web8Paul Irish
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
An Overview of HTML5 Storage
An Overview of HTML5 StorageAn Overview of HTML5 Storage
An Overview of HTML5 StoragePaul Irish
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBApaichon Punopas
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.jsratankadam
 
Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)PCampRussia
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applicationsSergi Mansilla
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Clustering with Node.js
Clustering with Node.jsClustering with Node.js
Clustering with Node.jsMichiel De Mey
 
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...CA API Management
 

Destacado (15)

Horizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSocketsHorizontally Scaling Node.js and WebSockets
Horizontally Scaling Node.js and WebSockets
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture Anatomy of a Modern Node.js Application Architecture
Anatomy of a Modern Node.js Application Architecture
 
Progressive Advancement in Web8
Progressive Advancement in Web8Progressive Advancement in Web8
Progressive Advancement in Web8
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Why i hate node js
Why i hate node jsWhy i hate node js
Why i hate node js
 
An Overview of HTML5 Storage
An Overview of HTML5 StorageAn Overview of HTML5 Storage
An Overview of HTML5 Storage
 
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Scalability using Node.js
Scalability using Node.jsScalability using Node.js
Scalability using Node.js
 
Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)Экономика продуктов и метрики (Илья Краинский, Magic Ink)
Экономика продуктов и метрики (Илья Краинский, Magic Ink)
 
Architecting large Node.js applications
Architecting large Node.js applicationsArchitecting large Node.js applications
Architecting large Node.js applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Clustering with Node.js
Clustering with Node.jsClustering with Node.js
Clustering with Node.js
 
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
Best Practices You Must Apply to Secure Your APIs - Scott Morrison, SVP & Dis...
 

Similar a Scaling Node.js Apps Horizontally with Cluster, Redis

Put on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and NodePut on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and NodeMarc Fasel
 
Arp security by_abdimuna_sep_28
Arp security by_abdimuna_sep_28Arp security by_abdimuna_sep_28
Arp security by_abdimuna_sep_28Abdimuna Muna
 
Building Reusable Puppet Modules
Building Reusable Puppet ModulesBuilding Reusable Puppet Modules
Building Reusable Puppet ModulesPuppet
 
Intravert atx meetup_condensed
Intravert atx meetup_condensedIntravert atx meetup_condensed
Intravert atx meetup_condensedzznate
 

Similar a Scaling Node.js Apps Horizontally with Cluster, Redis (7)

Rails Intro & Tutorial
Rails Intro & TutorialRails Intro & Tutorial
Rails Intro & Tutorial
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
Put on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and NodePut on Your Asynchronous Hat and Node
Put on Your Asynchronous Hat and Node
 
Arp security by_abdimuna_sep_28
Arp security by_abdimuna_sep_28Arp security by_abdimuna_sep_28
Arp security by_abdimuna_sep_28
 
Building Reusable Puppet Modules
Building Reusable Puppet ModulesBuilding Reusable Puppet Modules
Building Reusable Puppet Modules
 
Intravert atx meetup_condensed
Intravert atx meetup_condensedIntravert atx meetup_condensed
Intravert atx meetup_condensed
 
Cors
CorsCors
Cors
 

Último

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Último (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Scaling Node.js Apps Horizontally with Cluster, Redis

  • 1. PLANNING FOR THE HORIZONTAL SCALING NODE.JS APPLICATIONS TheReddest Brandon Cannaday brandon@modulus.io Thursday, April 4, 13
  • 2. ME HOSTING, DATA, STATS FOR NODE.JS modulus.io Thursday, April 4, 13
  • 3. WHEN TO SCALE? 1. RESPONSE TIMES 2. CPU USAGE 3. CONCURRENT CONNECTIONS Thursday, April 4, 13
  • 5. STARTING POINT mydomain.com > NODE SERVER Thursday, April 4, 13
  • 6. NODE TWEAKS CONCURRENT OUTGOING CONNECTION LIMIT http.globalAgent.maxSockets = Number.MAX_VALUE; Thursday, April 4, 13
  • 7. HURTLE: THE SERVER LINUX CONFIGURATION 1. FILE-MAX 2. SOMAXCONN 3. ULIMIT Thursday, April 4, 13
  • 8. FILE-MAX SYSTEM FILE DESCRIPTOR LIMIT 1. Run sysctl -w fs.file-max=65535 2. Run sysctl -p Thursday, April 4, 13
  • 9. SOMAXCONN SOCKET LISTEN QUEUE LENGTH 1. Run sysctl -w net.core.somaxconn=65535 2. Run sysctl -p Thursday, April 4, 13
  • 10. ULIMIT PER PROCESS FILE DESCRIPTOR LIMIT 1. Edit /etc/security/limits.conf 2. Add the following: * soft nofile 65535 * hard nofile 65535 root soft nofile 65535 root hard nofile 65535 Thursday, April 4, 13
  • 11. RUNNING SMOOTH mydomain.com > NODE SERVER Thursday, April 4, 13
  • 12. HURTLE: THE CPU BUY A BIGGER BOX > NODE > NODE SERVER SERVER 1 CORE 4 CORES Thursday, April 4, 13
  • 13. MULTICORE NODE 100% USAGE 1 2 3 4 CORE Thursday, April 4, 13
  • 14. CLUSTER MODULE mydomain.com > NODE > NODE > NODE > NODE SERVER Thursday, April 4, 13
  • 15. CLUSTER EXAMPLE var cluster = require('cluster'); The Cluster Module var http = require('http'); var numCPUs = require('os').cpus().length; if(cluster.isMaster) { for(var i = 0; i < numCPUs; i++) { cluster.fork(); } } else { http.createServer(function(req, res) { res.writeHead(200); res.end('Hello World.'); }).listen(80); } Thursday, April 4, 13
  • 16. CLUSTER EXAMPLE var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if(cluster.isMaster) { for(var i = 0; i < numCPUs; i++) { cluster.fork(); Fork Children } } else { http.createServer(function(req, res) { res.writeHead(200); res.end('Hello World.'); }).listen(80); } Thursday, April 4, 13
  • 17. CLUSTER EXAMPLE var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; if(cluster.isMaster) { for(var i = 0; i < numCPUs; i++) { cluster.fork(); } } else { http.createServer(function(req, res) { Handle Requests res.writeHead(200); res.end('Hello World.'); }).listen(80); } Thursday, April 4, 13
  • 18. CLUSTER LISTEN listen(...) WORKER MASTER Handle Thursday, April 4, 13
  • 19. ROLLING UPDATES 1. UPDATE SCRIPT 2. WORKER -> STOP LISTENING 3. KILL WORKER 4. CALL FORK() AGAIN Thursday, April 4, 13
  • 20. CLUSTER MODULE mydomain.com > NODE > NODE > NODE > NODE SERVER Thursday, April 4, 13
  • 21. HURTLE: SHARED STATE > NODE > NODE NO SHARED STATE > NODE > NODE SERVER Thursday, April 4, 13
  • 22. INSTALL REDIS > NODE > NODE > NODE > NODE REDIS SERVER Thursday, April 4, 13
  • 23. EXAMPLE 1: SESSION MEMORY STORE var express = require('express'), app = express(); app.use(express.cookieParser()); app.use(express.session({ secret: 'My Cookie Signing Secret' })); app.get('/', function(req, res) { req.session.somekey = 'some value'; }); Thursday, April 4, 13
  • 24. EXAMPLE 1: SESSION REDIS STORE var express = require('express'), RedisStore = require('connect-redis')(express), app = express(); app.use(express.cookieParser()); app.use(express.session({ store: new RedisStore({ host: 'localhost', port: 6379 }), secret: 'My Cookie Signing Secret' })); app.get('/', function(req, res) { req.session.somekey = 'some value'; }); Thursday, April 4, 13
  • 25. EXAMPLE 2: SOCKET.IO var RedisStore = require('socket.io/lib/stores/redis') , redis = require('socket.io/node_modules/redis') , pub = redis.createClient() , sub = redis.createClient() , client = redis.createClient(); io.set('store', new RedisStore({ redisPub : pub , redisSub : sub , redisClient : client })); https://github.com/LearnBoost/Socket.IO/wiki/Configuring-Socket.IO Thursday, April 4, 13
  • 26. RUNNING SMOOTH mydomain.com > NODE > NODE > NODE > NODE REDIS SERVER Thursday, April 4, 13
  • 27. LAST HURTLE: HORIZONTAL > NODE > NODE > NODE > NODE > NODE > NODE > NODE > NODE REDIS REDIS APP SERVER A APP SERVER B Thursday, April 4, 13
  • 28. SEPARATE REDIS > NODE > NODE > NODE > NODE > NODE > NODE > NODE > NODE APP SERVER A APP SERVER B REDIS SERVER Thursday, April 4, 13
  • 29. LOAD BALANCING mydomain.com LOAD BALANCER SERVER > NODE > NODE > NODE > NODE > NODE > NODE > NODE > NODE APP SERVER A APP SERVER B REDIS SERVER Thursday, April 4, 13
  • 30. LOAD BALANCING 1. MANAGED 2. INSTALL ONE 3. WRITE YOUR OWN Thursday, April 4, 13
  • 31. NGINX http { upstream mydomain_com { server host1.mydomain.com:80; server host2.mydomain.com:80; } LOAD BALANCER server { SERVER listen 80; server_name www.mydomain.com; location / { proxy_pass http://mydomain_com; } } } Thursday, April 4, 13
  • 32. WRITE ONE https://github.com/substack/bouncy Thursday, April 4, 13
  • 33. BOUNCY var bouncy = require('bouncy'); bouncy module var hosts = [ 'host1.mydomain.com', 'host2.mydomain.com' ]; var count = 0; var server = bouncy(function(req, res, bounce) { count++; var host = hosts[count % hosts.length]; bounce(host, 80); }); server.listen(80); Thursday, April 4, 13
  • 34. BOUNCY var bouncy = require('bouncy'); var hosts = [ Server collection 'host1.mydomain.com', 'host2.mydomain.com' ]; var count = 0; var server = bouncy(function(req, res, bounce) { count++; var host = hosts[count % hosts.length]; bounce(host, 80); }); server.listen(80); Thursday, April 4, 13
  • 35. BOUNCY var bouncy = require('bouncy'); var hosts = [ 'host1.mydomain.com', 'host2.mydomain.com' ]; var count = 0; var server = bouncy(function(req, res, bounce) { Create server count++; var host = hosts[count % hosts.length]; bounce(host, 80); }); server.listen(80); Thursday, April 4, 13
  • 36. BOUNCY var bouncy = require('bouncy'); var hosts = [ 'host1.mydomain.com', 'host2.mydomain.com' ]; var count = 0; var server = bouncy(function(req, res, bounce) { count++; var host = hosts[count % hosts.length]; bounce(host, 80); Bounce request }); server.listen(80); Thursday, April 4, 13
  • 37. AFFINITY SESSION AFFINITY STICKY SESSIONS SEND THE SAME PERSON BACK TO THE SAME SERVER Thursday, April 4, 13
  • 38. NGINX AFFINITY http { upstream mydomain_com { sticky; server host1.mydomain.com:80; server host2.mydomain.com:80; } server { listen 80; server_name www.mydomain.com; location / { proxy_pass http://mydomain_com; } } } Thursday, April 4, 13
  • 39. CUSTOM AFFINITY req.headers['x-forwarded-for'] req.connection.remoteAddress Thursday, April 4, 13
  • 40. RUNNING SMOOTH mydomain.com LOAD BALANCER SERVER > NODE > NODE > NODE > NODE > NODE > NODE > NODE > NODE APP SERVER A APP SERVER B REDIS SERVER Thursday, April 4, 13
  • 41. ROLLING UPDATES 1. REMOVE APP SERVER FROM LOAD BALANCER 2. UPGRADE APP SERVER 3. ADD BACK 4. REPEAT Thursday, April 4, 13
  • 42. SSL TERMINATE EARLY Thursday, April 4, 13
  • 43. SSL LB SSL SSL TERMINATOR SERVER > NODE > NODE > NODE > NODE > NODE > NODE > NODE > NODE APP SERVER A APP SERVER B REDIS SERVER Thursday, April 4, 13
  • 44. SSL mydomain.com 80 443 LB SSL SERVER Thursday, April 4, 13
  • 45. STUD EXAMPLE CONFIG FILE frontend = [*]:443 backend = [127.0.0.1]:80 ssl = on pem-file = "myCert.pem" https://github.com/bumptech/stud Thursday, April 4, 13
  • 46. RUNNING SMOOTH W/SSL mydomain.com LB SSL SERVER > NODE > NODE > NODE > NODE > NODE > NODE > NODE > NODE APP SERVER A APP SERVER B REDIS SERVER Thursday, April 4, 13
  • 47. HUGE LB SSL LB SSL SERVER SERVER REDIS SERVER Thursday, April 4, 13
  • 48. DNS ROUND-ROBIN DNS MULTIPLE RECORDS, ONE DOMAIN Thursday, April 4, 13
  • 49. ROUND-ROBIN DNS CLIENT 1 1. xxx.xxx.xxx.x 2. xxx.xxx.xxx.y CLIENT 2 1. xxx.xxx.xxx.y 2. xxx.xxx.xxx.x Thursday, April 4, 13
  • 50. RUNNING SMOOTH LB SSL LB SSL SERVER SERVER REDIS SERVER Thursday, April 4, 13
  • 51. BIG ENOUGH > NODE SERVER Thursday, April 4, 13
  • 52. BIG ENOUGH > NODE SERVER Thursday, April 4, 13