SlideShare una empresa de Scribd logo
1 de 20
Building and Scaling
Node.js Applications
    Ohad Kravchick
      7/5/2012



    http://bit.ly/nodeApps
When to use Node and when not to
• Don't use node to server static files - there are
  better and easier [to configure] servers than node
  (NGINX, varnish, HAProxy)
• Don't use node for simple CRUD apps - you will
  have to build it all yourself
• You have to build almost everything yourself -
  great for APIs
   – Great for iterative development
• Use it for real-time
   – Node is responding to requests super fast
What do you need to start
• Node (http://nodejs.org/)
  – brew install node or download via URL
• nvm (https://github.com/creationix/nvm/)
  – nvm install v0.7.1
• npm (http://npmjs.org/)
  – we have our NYT repo
• online docs and tutorials, READMEs
• your favorite text editor
• node whatever.js
  – node compiles your code before every invocation
Simple web servers
• http
         1 var http = require('http');
         2 http.createServer(function (req, res) {
         3 res.writeHead(200, {'Content-Type': 'text/plain'});
         4 res.end('Hello Worldn');
         5 }).listen(1337, "127.0.0.1");
         6 console.log('Server running at http://127.0.0.1:1337/');


• express
         1 var express = require('express');
         2 var app = express.createServer();
         3 app.get('/', function(req, res){
         4 res.send('Hello World');
         5 });
         6 app.listen(3000);
Simple web servers
• Express supports:
  – HTTPS
  – Template-based views and partials + caching
  – Parameterized Routing /users/:user
  – Session
  – JSONP, MethodOverride, BodyParser, ENVs
  – Customizable Middleware
Middleware
 1 function loadUser(req, res, next) {
 2 // You would fetch your user from the db
 3 var user = users[req.params.id];
 4 if (user) {
 5 req.user = user;
 6 next();
 7 } else {
 8 next(new Error('Failed to load user ' + req.params.id));
 9 }
10 }
11
12 app.get('/user/:id', loadUser, function(req, res){
13 res.send('Viewing user ' + req.user.name);
14 });
Middleware plugins
• Uses connect
  1 var express = require('express');
  2 var app = express.createServer();
  3
  4 app.use(express.logger('dev'));
  5 app.use(express.bodyParser());
  6 app.use(express.cookieParser());
  7 app.use(express.favicon());
  8 app.use(express.session({ secret: 'my secret here' }));
  9 app.use(app.router);
 10 app.use(express.static('public'));
 11 app.use(express.directory('public'));
 12 app.use(express.errorHandler({showStack: true, dumpExceptions: true}));
 13
 14 app.get('/', function (req, res) {
 15 res.send('hello world');
 16 });
 17
 18 app.listen(3000);
Middleware plugins
•   logger request logger with custom format support
•   csrf Cross-site request forgery protection
•   compress Gzip compression middleware
•   basicAuth basic http authentication
•   bodyParser extensible request body parser
•   json application/json parser
•   urlencoded application/x-www-form-urlencoded parser
•   multipart multipart/form-data parser
•   cookieParser cookie parser
•   session session management support with bundled MemoryStore
•   cookieSession cookie-based session support
•   methodOverride faux HTTP method support
•   responseTime calculates response-time and exposes via X-Response-Time
•   staticCache memory cache layer for the static() middleware
•   static streaming static file server supporting Range and more
•   directory directory listing middleware
•   vhost virtual host sub-domain mapping middleware
•   favicon efficient favicon server (with default icon)
•   limit limit the bytesize of request bodies
•   query automatic querystring parser, populating req.query
•   errorHandler flexible error handler
Real-time using Node
• Socket.IO
   – WebSockets, Flash, long-polling, iframe forever
   – Supports IE 5.5+
   – Runs cross-domain
• Server      1 var io = require('socket.io').listen(80);
              2
              3 io.sockets.on('connection', function (socket) {
              4 socket.emit('news', { hello: 'world' });
              5 socket.on('my other event', function (data) {
              6 console.log(data);
              7 });
              8 });
              1 <script src="/socket.io/socket.io.js"></script>
• Client      2 <script>
              3 var socket = io.connect('http://localhost');
              4 socket.on('news', function (data) {
              5 console.log(data);
              6 socket.emit('my other event', { my: 'data' });
              7 });
              8 </script>
Simple DBs
• mysql
  1 var mysql = require('mysql');
  2 var connection = mysql.createConnection({host: 'example.org', user: 'bob', password: 'secret'});
  3 var state = 'NY';
  4 connection.query('SELECT * FROM users WHERE state = ?', [state], function(err, results) {
  5 var index;
  6 if (err) throw err;
  7 for (index in results) {
  8      console.log('Found user ' + fields[index].username + ' from ' + state);
  9 }
 10 connection.end(function(err) { });
 11 });




• mongo
  1 var mongodb = require('mongodb');
  2 var server = new mongodb.Server("127.0.0.1", 27017, {});
  3 new mongodb.Db('test', server, {}).open(function (error, client) {
  4 if (error) throw error;
  5 var collection = new mongodb.Collection(client, 'test_collection');
  6 collection.find({}, {limit:10}).toArray(function(err, docs) {
  7 console.dir(docs);
  8 });
  9 });
Debugging
• Node --debug whatever.js
• node-inspector
--------------------------------------------------------------          8080          ----------------
| Node.js server <--> 5858 <--> node-inspector |                 <-----------------> | web client |
--------------------------------------------------------------                        ----------------
                       DebuggerProtocol


      – Demo


• kill -s USR1 <pid>
• node --debug-brk much_faster_whatever.js
General
• Uncaught Exception kills the server
  – Log errors using process.on('uncaugtException')
  – deamontools supervise, monit
• Logging
  – Winston (https://github.com/flatiron/winston/)
• Use ab for testing
  – sudo sysctl -w net.inet.tcp.msl=300
  – Demo (ex3)
Concurrency model
• Non-blocking IO
   – Uses epoll, kqueue, select
• Single-threaded event-loop (uses libev and libeio)
   – As oppose to thread per request
   – less context-switching, less CPU usage, less memory
• The event loop is not intended to make
  computationally intensive tasks responsive, it’s meant
  to cut the resource waste related to waiting for I/O
  by Mikito Takada
• Long synchronous code WILL BLOCK ALL OTHERS
   – Extract heavy code to its own service or process
   – Use WebWorkers to spawn a “process”
Node vs. Apache
Maximizing the server
• Single thread running on a single CPU
• Use cluster to take all CPUs
  1 var cluster = require('cluster');
  2 var http = require('http');
  3 var numCPUs = require('os').cpus().length;
  4
  5 if (cluster.isMaster) {
  6 // Fork workers.
  7 for (var i = 0; i < numCPUs; i++) {
  8 cluster.fork();
  9 }
 10 } else {
 11 // Workers can share any TCP connection
 12 // In this case its a HTTP server
 13 http.createServer(function(req, res) {
 14 res.writeHead(200);
 15 res.end("hello worldn");
 16 }).listen(8000);
 17 }
Sharing between instances
• As you spawn multiple instances, you need to
  share data (=memory)
• You can use IPC
• You can use DB
• Or, you can use in-memory cache
  – memcached
     • Strings, integers, anything else is serialized
     • Set, get, delete, replace, append, prepend
     • Expiry
  – redis
redis
• Key-value storage that atomically supports:
   – Strings: get, set, strlen, append, getrange, setrange
   – Bit strings: setbit, getbit, bitcount, bitop
   – Integers and floats: incr, decr, incrby, decrby,
   – Lists: llen, lpop, lpush, lrem, linsert, lindex, lset, lrange,
   – Sets: sadd, sismember, srem, spop, smembers, scard
         • Inter-sets: sinter, sinterstore, sdiff, sdiffstore, sunion, sunionstore
   – Sorted sets: zscore, zadd, zrem, zrank, zrange, zrangebyscore
   – Hashes: hset, hget, hmset, hmget, hdel, hexists, hkeys, hvals, hgetall,
      hincrby
• Native to developers
• Makes the developer think about the implications of large-scale
• Demo
redis
 1 var redis = require("redis"),
 2       client = redis.createClient();
 3
 4 client.set("string key", "string val", redis.print);
 5 client.hset("hash key", "hashtest 1", "some value", redis.print);
 6 client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
 7 client.hkeys("hash key", function (err, replies) {
 8 console.log(replies.length + " replies:");
 9 replies.forEach(function (reply, i) {
10        console.log(" " + i + ": " + reply);
11 });
12 client.quit();
13 });
redis
• Blazingly fast, in-memory cache
   – Size limited to memory
   – Good for ephemeral data (cache, session), for
     syncing servers
• Can be saved to disk, mostly for faster start up
• Use async/Q for handling multiple requests
• Supports expiry, pub-sub, transactions, server-
  side LUA scripts
• connect-redis for automatic session sync
Fin


Thank You



Questions?

Más contenido relacionado

La actualidad más candente

DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
[212] large scale backend service develpment
[212] large scale backend service develpment[212] large scale backend service develpment
[212] large scale backend service develpmentNAVER D2
 
Understanding DSE Search by Matt Stump
Understanding DSE Search by Matt StumpUnderstanding DSE Search by Matt Stump
Understanding DSE Search by Matt StumpDataStax
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"IT Event
 
Building the Right Platform Architecture for Hadoop
Building the Right Platform Architecture for HadoopBuilding the Right Platform Architecture for Hadoop
Building the Right Platform Architecture for HadoopAll Things Open
 
Deploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and MarathonDeploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and MarathonDiscover Pinterest
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.jsFDConf
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDDSudar Muthu
 
Introduction to .Net Driver
Introduction to .Net DriverIntroduction to .Net Driver
Introduction to .Net DriverDataStax Academy
 
Automation with Packer and TerraForm
Automation with Packer and TerraFormAutomation with Packer and TerraForm
Automation with Packer and TerraFormWesley Charles Blake
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
Devoxx 2016 talk: Going Global with Nomad and Google Cloud Platform
Devoxx 2016 talk: Going Global with Nomad and Google Cloud PlatformDevoxx 2016 talk: Going Global with Nomad and Google Cloud Platform
Devoxx 2016 talk: Going Global with Nomad and Google Cloud PlatformBastiaan Bakker
 
MySQL NDB 8.0 clusters in your laptop with dbdeployer
MySQL NDB 8.0 clusters in your laptop with dbdeployerMySQL NDB 8.0 clusters in your laptop with dbdeployer
MySQL NDB 8.0 clusters in your laptop with dbdeployerGiuseppe Maxia
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cacheMarc Cortinas Val
 

La actualidad más candente (20)

DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
[212] large scale backend service develpment
[212] large scale backend service develpment[212] large scale backend service develpment
[212] large scale backend service develpment
 
Understanding DSE Search by Matt Stump
Understanding DSE Search by Matt StumpUnderstanding DSE Search by Matt Stump
Understanding DSE Search by Matt Stump
 
Exploring Node.jS
Exploring Node.jSExploring Node.jS
Exploring Node.jS
 
Apache Cassandra and Go
Apache Cassandra and GoApache Cassandra and Go
Apache Cassandra and Go
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Introduction Node.js
Introduction Node.jsIntroduction Node.js
Introduction Node.js
 
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Leonid Vasilyev  "Building, deploying and running production code at Dropbox"Leonid Vasilyev  "Building, deploying and running production code at Dropbox"
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
 
Building the Right Platform Architecture for Hadoop
Building the Right Platform Architecture for HadoopBuilding the Right Platform Architecture for Hadoop
Building the Right Platform Architecture for Hadoop
 
Move Over, Rsync
Move Over, RsyncMove Over, Rsync
Move Over, Rsync
 
Deploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and MarathonDeploying Docker Containers at Scale with Mesos and Marathon
Deploying Docker Containers at Scale with Mesos and Marathon
 
Writing RESTful web services using Node.js
Writing RESTful web services using Node.jsWriting RESTful web services using Node.js
Writing RESTful web services using Node.js
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
 
Introduction to .Net Driver
Introduction to .Net DriverIntroduction to .Net Driver
Introduction to .Net Driver
 
Automation with Packer and TerraForm
Automation with Packer and TerraFormAutomation with Packer and TerraForm
Automation with Packer and TerraForm
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Devoxx 2016 talk: Going Global with Nomad and Google Cloud Platform
Devoxx 2016 talk: Going Global with Nomad and Google Cloud PlatformDevoxx 2016 talk: Going Global with Nomad and Google Cloud Platform
Devoxx 2016 talk: Going Global with Nomad and Google Cloud Platform
 
MySQL NDB 8.0 clusters in your laptop with dbdeployer
MySQL NDB 8.0 clusters in your laptop with dbdeployerMySQL NDB 8.0 clusters in your laptop with dbdeployer
MySQL NDB 8.0 clusters in your laptop with dbdeployer
 
cache concepts and varnish-cache
cache concepts and varnish-cachecache concepts and varnish-cache
cache concepts and varnish-cache
 

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
 
Planning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsPlanning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsModulus
 
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
 

Destacado (8)

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
 
Planning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js ApplicationsPlanning for the Horizontal: Scaling Node.js Applications
Planning for the Horizontal: Scaling Node.js Applications
 
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
 

Similar a Building and Scaling Node.js Applications

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationBen Hall
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETGianluca Carucci
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Building an ActionScript Game Server with over 15,000 Concurrent Connections
Building an ActionScript Game Server with over 15,000 Concurrent ConnectionsBuilding an ActionScript Game Server with over 15,000 Concurrent Connections
Building an ActionScript Game Server with over 15,000 Concurrent Connections Renaun Erickson
 
Real World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsReal World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsBen Hall
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++Amazon Web Services
 

Similar a Building and Scaling Node.js Applications (20)

Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
Future Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NETFuture Decoded - Node.js per sviluppatori .NET
Future Decoded - Node.js per sviluppatori .NET
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Building an ActionScript Game Server with over 15,000 Concurrent Connections
Building an ActionScript Game Server with over 15,000 Concurrent ConnectionsBuilding an ActionScript Game Server with over 15,000 Concurrent Connections
Building an ActionScript Game Server with over 15,000 Concurrent Connections
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Real World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js ApplicationsReal World Lessons on the Pain Points of Node.js Applications
Real World Lessons on the Pain Points of Node.js Applications
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
 

Último

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

Building and Scaling Node.js Applications

  • 1. Building and Scaling Node.js Applications Ohad Kravchick 7/5/2012 http://bit.ly/nodeApps
  • 2. When to use Node and when not to • Don't use node to server static files - there are better and easier [to configure] servers than node (NGINX, varnish, HAProxy) • Don't use node for simple CRUD apps - you will have to build it all yourself • You have to build almost everything yourself - great for APIs – Great for iterative development • Use it for real-time – Node is responding to requests super fast
  • 3. What do you need to start • Node (http://nodejs.org/) – brew install node or download via URL • nvm (https://github.com/creationix/nvm/) – nvm install v0.7.1 • npm (http://npmjs.org/) – we have our NYT repo • online docs and tutorials, READMEs • your favorite text editor • node whatever.js – node compiles your code before every invocation
  • 4. Simple web servers • http 1 var http = require('http'); 2 http.createServer(function (req, res) { 3 res.writeHead(200, {'Content-Type': 'text/plain'}); 4 res.end('Hello Worldn'); 5 }).listen(1337, "127.0.0.1"); 6 console.log('Server running at http://127.0.0.1:1337/'); • express 1 var express = require('express'); 2 var app = express.createServer(); 3 app.get('/', function(req, res){ 4 res.send('Hello World'); 5 }); 6 app.listen(3000);
  • 5. Simple web servers • Express supports: – HTTPS – Template-based views and partials + caching – Parameterized Routing /users/:user – Session – JSONP, MethodOverride, BodyParser, ENVs – Customizable Middleware
  • 6. Middleware 1 function loadUser(req, res, next) { 2 // You would fetch your user from the db 3 var user = users[req.params.id]; 4 if (user) { 5 req.user = user; 6 next(); 7 } else { 8 next(new Error('Failed to load user ' + req.params.id)); 9 } 10 } 11 12 app.get('/user/:id', loadUser, function(req, res){ 13 res.send('Viewing user ' + req.user.name); 14 });
  • 7. Middleware plugins • Uses connect 1 var express = require('express'); 2 var app = express.createServer(); 3 4 app.use(express.logger('dev')); 5 app.use(express.bodyParser()); 6 app.use(express.cookieParser()); 7 app.use(express.favicon()); 8 app.use(express.session({ secret: 'my secret here' })); 9 app.use(app.router); 10 app.use(express.static('public')); 11 app.use(express.directory('public')); 12 app.use(express.errorHandler({showStack: true, dumpExceptions: true})); 13 14 app.get('/', function (req, res) { 15 res.send('hello world'); 16 }); 17 18 app.listen(3000);
  • 8. Middleware plugins • logger request logger with custom format support • csrf Cross-site request forgery protection • compress Gzip compression middleware • basicAuth basic http authentication • bodyParser extensible request body parser • json application/json parser • urlencoded application/x-www-form-urlencoded parser • multipart multipart/form-data parser • cookieParser cookie parser • session session management support with bundled MemoryStore • cookieSession cookie-based session support • methodOverride faux HTTP method support • responseTime calculates response-time and exposes via X-Response-Time • staticCache memory cache layer for the static() middleware • static streaming static file server supporting Range and more • directory directory listing middleware • vhost virtual host sub-domain mapping middleware • favicon efficient favicon server (with default icon) • limit limit the bytesize of request bodies • query automatic querystring parser, populating req.query • errorHandler flexible error handler
  • 9. Real-time using Node • Socket.IO – WebSockets, Flash, long-polling, iframe forever – Supports IE 5.5+ – Runs cross-domain • Server 1 var io = require('socket.io').listen(80); 2 3 io.sockets.on('connection', function (socket) { 4 socket.emit('news', { hello: 'world' }); 5 socket.on('my other event', function (data) { 6 console.log(data); 7 }); 8 }); 1 <script src="/socket.io/socket.io.js"></script> • Client 2 <script> 3 var socket = io.connect('http://localhost'); 4 socket.on('news', function (data) { 5 console.log(data); 6 socket.emit('my other event', { my: 'data' }); 7 }); 8 </script>
  • 10. Simple DBs • mysql 1 var mysql = require('mysql'); 2 var connection = mysql.createConnection({host: 'example.org', user: 'bob', password: 'secret'}); 3 var state = 'NY'; 4 connection.query('SELECT * FROM users WHERE state = ?', [state], function(err, results) { 5 var index; 6 if (err) throw err; 7 for (index in results) { 8 console.log('Found user ' + fields[index].username + ' from ' + state); 9 } 10 connection.end(function(err) { }); 11 }); • mongo 1 var mongodb = require('mongodb'); 2 var server = new mongodb.Server("127.0.0.1", 27017, {}); 3 new mongodb.Db('test', server, {}).open(function (error, client) { 4 if (error) throw error; 5 var collection = new mongodb.Collection(client, 'test_collection'); 6 collection.find({}, {limit:10}).toArray(function(err, docs) { 7 console.dir(docs); 8 }); 9 });
  • 11. Debugging • Node --debug whatever.js • node-inspector -------------------------------------------------------------- 8080 ---------------- | Node.js server <--> 5858 <--> node-inspector | <-----------------> | web client | -------------------------------------------------------------- ---------------- DebuggerProtocol – Demo • kill -s USR1 <pid> • node --debug-brk much_faster_whatever.js
  • 12. General • Uncaught Exception kills the server – Log errors using process.on('uncaugtException') – deamontools supervise, monit • Logging – Winston (https://github.com/flatiron/winston/) • Use ab for testing – sudo sysctl -w net.inet.tcp.msl=300 – Demo (ex3)
  • 13. Concurrency model • Non-blocking IO – Uses epoll, kqueue, select • Single-threaded event-loop (uses libev and libeio) – As oppose to thread per request – less context-switching, less CPU usage, less memory • The event loop is not intended to make computationally intensive tasks responsive, it’s meant to cut the resource waste related to waiting for I/O by Mikito Takada • Long synchronous code WILL BLOCK ALL OTHERS – Extract heavy code to its own service or process – Use WebWorkers to spawn a “process”
  • 15. Maximizing the server • Single thread running on a single CPU • Use cluster to take all CPUs 1 var cluster = require('cluster'); 2 var http = require('http'); 3 var numCPUs = require('os').cpus().length; 4 5 if (cluster.isMaster) { 6 // Fork workers. 7 for (var i = 0; i < numCPUs; i++) { 8 cluster.fork(); 9 } 10 } else { 11 // Workers can share any TCP connection 12 // In this case its a HTTP server 13 http.createServer(function(req, res) { 14 res.writeHead(200); 15 res.end("hello worldn"); 16 }).listen(8000); 17 }
  • 16. Sharing between instances • As you spawn multiple instances, you need to share data (=memory) • You can use IPC • You can use DB • Or, you can use in-memory cache – memcached • Strings, integers, anything else is serialized • Set, get, delete, replace, append, prepend • Expiry – redis
  • 17. redis • Key-value storage that atomically supports: – Strings: get, set, strlen, append, getrange, setrange – Bit strings: setbit, getbit, bitcount, bitop – Integers and floats: incr, decr, incrby, decrby, – Lists: llen, lpop, lpush, lrem, linsert, lindex, lset, lrange, – Sets: sadd, sismember, srem, spop, smembers, scard • Inter-sets: sinter, sinterstore, sdiff, sdiffstore, sunion, sunionstore – Sorted sets: zscore, zadd, zrem, zrank, zrange, zrangebyscore – Hashes: hset, hget, hmset, hmget, hdel, hexists, hkeys, hvals, hgetall, hincrby • Native to developers • Makes the developer think about the implications of large-scale • Demo
  • 18. redis 1 var redis = require("redis"), 2 client = redis.createClient(); 3 4 client.set("string key", "string val", redis.print); 5 client.hset("hash key", "hashtest 1", "some value", redis.print); 6 client.hset(["hash key", "hashtest 2", "some other value"], redis.print); 7 client.hkeys("hash key", function (err, replies) { 8 console.log(replies.length + " replies:"); 9 replies.forEach(function (reply, i) { 10 console.log(" " + i + ": " + reply); 11 }); 12 client.quit(); 13 });
  • 19. redis • Blazingly fast, in-memory cache – Size limited to memory – Good for ephemeral data (cache, session), for syncing servers • Can be saved to disk, mostly for faster start up • Use async/Q for handling multiple requests • Supports expiry, pub-sub, transactions, server- side LUA scripts • connect-redis for automatic session sync