SlideShare a Scribd company logo
1 of 28
Building Scalable Servers
With EventMachine and Rails


                               Dave Troy
                               Chief Executive Officer



      davetroy@shortmail.com

      @davetroy

      facebook.com/davetroy
EventMachine
EventMachine

    DRY
EventMachine

    DRY
   DRAG
EventMachine

          DRY
          DRAG
(Don’t Repeat Aman Gupta)
require ‘aman_gupta’
EventMachine
scalable non-blocking i/o in ruby
About Me
Aman Gupta
San Francisco, CA
Been maintaining EventMachine for 18
months (last 4 releases)
Ruby Hero 2009
amqp, REE patches, perftools.rb, gdb.rb,
memprof
github.com/tmm1
@tmm1
What is EventMachine?
Implementation of the Reactor pattern
  similar to Python’s Twisted   also node.js, libev
Ruby VM Support
  Ruby 1.8 (MRI)
  Ruby 1.9 (YARV)                         c++ reactor
  Rubinius
  JRuby                                   java reactor
  + simple Pure Ruby version
What is I/O?
 Generally Network I/O
   mysql query responses
   http responses
   memcache results

 Most web applications are I/O bound, not CPU bound
 Basic idea behind EM: Instead of waiting on a response
 from the network, use that time to process other
 requests
What can I use EM for?
Scaling I/O heavy applications
  handle 5-10k concurrent connections with a single
  ruby process
Any type of network I/O
  http requests
  sending emails
  custom tcp proxies
  data access
    redis
    couchdb
    mysql
    postgres
    casandra
    memcached
Simple TCP Server
TCPServer#accept     require 'socket'
                     server = TCPServer.new(2202)
to accept
                     while client = server.accept
connections from       msg = client.readline
new clients            client.write "You said: #{msg}"
                       client.close
TCPSocket#read*      end

blocks, so you can
                     require 'socket'
only handle one      server = TCPServer.new(2202)
client at a time     while true
                       Thread.new(server.accept){ |client|
Common Solution:         msg = client.readline
                         client.write "You said: #{msg}"
use a thread per         client.close
client                 }
                     end
require 'socket'
 inbound                         server = TCPServer.new(2202)
               list of clients   clients = []
buffer per                       buffers = {}


     client IO.select returns    while true
                                   sockets = [server] + clients
            readable/writable      readable, writable = IO.select(sockets)


                       sockets    readable.each do |sock|
                                    begin
                                      if sock == server
                                        clients << server.accept_nonblock
                                      else
                                        client, buf = sock, buffers[sock] ||= ''
    read in available data,
                                         buf << client.read_nonblock(1024)
process if full line received            if buf =~ /^.+?r?n/
                                           client.write "You said: #{buf}"



  Non-Blocking I/O
                                           client.close

                                           buffers.delete(client)
                                           clients.delete(client)
                                         end
    Alternative to                     end
                                     rescue Errno::EAGAIN, Errno::EWOULDBLOCK
    threads: simply don’t              # socket would block, try again later
                                     end
    block                          end
                                 end
EM does Non-Blocking I/O
handles low         module EchoServer
level sockets         def post_init
for you                 @buf = ''
                      end
inbound/              def receive_data(data)
                        @buf << data
outbound                if @buf =~ /^.+?r?n/
buffers for               send_data "You said: #{@buf}"
                          close_connection_after_writing
maximal                 end
throughput            end
                    end
efficient i/o with
writev/readv        require 'eventmachine'
                    EM.run do
                      EM.start_server '0.0.0.0', 2202, EchoServer
epoll & kqueue      end
support
So, what’s a Reactor?
       while reactor_running?
         expired_timers.each{ |timer| timer.process }
         new_network_io.each{ |io| io.process }
       end

reactor is simply a single threaded while loop, called
the “reactor loop”
your code “reacts” to incoming events
if your event handler takes too long, other events
cannot fire
lesson: never block the reactor        while reactor_running?
                                         while true
   no sleep(1)                           end
   no long loops (100_000.times)         # reactor is blocked!
   no blocking I/O (mysql queries)     end
   no polling (while !condition)
Writing Asynchronous Code
synchronous ruby code uses return values
            ret = operation()
            do_something_with(ret)

evented async code uses blocks instead
operation{ |ret| do_something_with(ret) }

different from how you usually use ruby blocks. the block
is stored and invoked later (it’s asynchronous)
puts(1)                      puts(1)
1.times{ puts(2) }           operation{ puts(3) }
puts(3)                      puts(2)
Receiving Email Using ActionMailer

  port 25        postfix
  (smtp)         (spool)

                        fork
                      process


                 Action                   pgsql
                 Mailer    ActiveRecord    (db)
Receiving Email Using LMTP

  port 25       postfix
  (smtp)        (spool)

                     port 8081
                      (lmtp)


                 EM                       pgsql
               (w/Rails)   ActiveRecord    (db)
Receiving Email — Scalably via LMTP


    postfix       postfix       message
    (spool)       (spool)       systems




     EM          EM           EM          EM
   (w/Rails)   (w/Rails)    (w/Rails)   (w/Rails)
LMTP Daemon



http://tools.ietf.org/html/rfc2033
POP3 Daemon



http://tools.ietf.org/html/rfc1939
IMAP Daemon



http://tools.ietf.org/html/rfc3501
EventMachine
Geo Firehose                       LISTEN
                                    8192
(one connection - Port 80)


                                      250, 500, 1000 Connections

 twittervision.com/
                                Apache
       stream

RewriteRule ^/stream(.*)$ http://127.0.0.1:8192%{REQUEST_URI} [P,QSA,L]
replyz.com
Does Anybody Know...?

mailstrom.co
mailstrom.410labs.com
Power Tools for Your Inbox

shortmail.com
Email, simplified.
Some Other Handy Stuff...

  • start_tls: secure any TCP connection
  • Timers: Periodic, Once, Scheduled
  • epoll, kqueue, threadpool_size
  • set_effective_user             (listen on protected ports)



  • teh docs: http://eventmachine.rubyforge.org/EventMachine.html
So, Some Stuff To Remember...

  • EventMachine: awesome for I/O, events
  • Code is Data, Data is Code
  • Often Working with State Machines
  • Don’t peg the CPU. No really, don’t.
  • TEBWTDI
  • Testing can be interesting
Dave Troy
                             Chief Executive Officer



    davetroy@shortmail.com

    @davetroy

    facebook.com/davetroy




 Tomorrow @ BohConf!
http://emrubyconf.com/

More Related Content

What's hot

Solving some of the scalability problems at booking.com
Solving some of the scalability problems at booking.comSolving some of the scalability problems at booking.com
Solving some of the scalability problems at booking.comIvan Kruglov
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxyIsmael Celis
 
Nginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولNginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولefazati
 
Ruby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay ShanghaiRuby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay ShanghaiJackson Tian
 
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
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
vert.x 3.1 - be reactive on the JVM but not only in Java
vert.x 3.1 - be reactive on the JVM but not only in Javavert.x 3.1 - be reactive on the JVM but not only in Java
vert.x 3.1 - be reactive on the JVM but not only in JavaClément Escoffier
 
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)Ontico
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Ruby Concurrency and EventMachine
Ruby Concurrency and EventMachineRuby Concurrency and EventMachine
Ruby Concurrency and EventMachineChristopher Spring
 

What's hot (20)

Solving some of the scalability problems at booking.com
Solving some of the scalability problems at booking.comSolving some of the scalability problems at booking.com
Solving some of the scalability problems at booking.com
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
Concurrency in ruby
Concurrency in rubyConcurrency in ruby
Concurrency in ruby
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
 
Nginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولNginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصول
 
Ruby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay ShanghaiRuby vs Node ShiningRay Shanghai
Ruby vs Node ShiningRay Shanghai
 
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
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
vert.x 3.1 - be reactive on the JVM but not only in Java
vert.x 3.1 - be reactive on the JVM but not only in Javavert.x 3.1 - be reactive on the JVM but not only in Java
vert.x 3.1 - be reactive on the JVM but not only in Java
 
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
Testing applications with traffic control in containers / Alban Crequy (Kinvolk)
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Ruby Concurrency and EventMachine
Ruby Concurrency and EventMachineRuby Concurrency and EventMachine
Ruby Concurrency and EventMachine
 

Similar to Servers with Event Machine - David Troy - RailsConf 2011

Python twisted
Python twistedPython twisted
Python twistedMahendra M
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIEleanor McHugh
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsEleanor McHugh
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Masahiro Nagano
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9Ilya Grigorik
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdfsecunderbadtirumalgi
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...Tom Croucher
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011Lance Ball
 
Scalable Socket Server by Aryo
Scalable Socket Server by AryoScalable Socket Server by Aryo
Scalable Socket Server by AryoAgate Studio
 
JUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBoxJUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBoxmarekgoldmann
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsDigitalOcean
 

Similar to Servers with Event Machine - David Troy - RailsConf 2011 (20)

Python twisted
Python twistedPython twisted
Python twisted
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and RailsAnchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
Anchoring Trust: Rewriting DNS for the Semantic Network with Ruby and Rails
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
Pfm technical-inside
Pfm technical-insidePfm technical-inside
Pfm technical-inside
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...A language for the Internet: Why JavaScript and Node.js is right for Internet...
A language for the Internet: Why JavaScript and Node.js is right for Internet...
 
Npc08
Npc08Npc08
Npc08
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
Scalable Socket Server by Aryo
Scalable Socket Server by AryoScalable Socket Server by Aryo
Scalable Socket Server by Aryo
 
03 sockets
03 sockets03 sockets
03 sockets
 
JUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBoxJUDCon 2010 Boston : TorqueBox
JUDCon 2010 Boston : TorqueBox
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
 
Rack
RackRack
Rack
 

Recently uploaded

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
 
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
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
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
 
[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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Recently uploaded (20)

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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
[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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Servers with Event Machine - David Troy - RailsConf 2011

  • 1. Building Scalable Servers With EventMachine and Rails Dave Troy Chief Executive Officer davetroy@shortmail.com @davetroy facebook.com/davetroy
  • 2.
  • 5. EventMachine DRY DRAG
  • 6. EventMachine DRY DRAG (Don’t Repeat Aman Gupta)
  • 9. About Me Aman Gupta San Francisco, CA Been maintaining EventMachine for 18 months (last 4 releases) Ruby Hero 2009 amqp, REE patches, perftools.rb, gdb.rb, memprof github.com/tmm1 @tmm1
  • 10. What is EventMachine? Implementation of the Reactor pattern similar to Python’s Twisted also node.js, libev Ruby VM Support Ruby 1.8 (MRI) Ruby 1.9 (YARV) c++ reactor Rubinius JRuby java reactor + simple Pure Ruby version
  • 11. What is I/O? Generally Network I/O mysql query responses http responses memcache results Most web applications are I/O bound, not CPU bound Basic idea behind EM: Instead of waiting on a response from the network, use that time to process other requests
  • 12. What can I use EM for? Scaling I/O heavy applications handle 5-10k concurrent connections with a single ruby process Any type of network I/O http requests sending emails custom tcp proxies data access redis couchdb mysql postgres casandra memcached
  • 13. Simple TCP Server TCPServer#accept require 'socket' server = TCPServer.new(2202) to accept while client = server.accept connections from msg = client.readline new clients client.write "You said: #{msg}" client.close TCPSocket#read* end blocks, so you can require 'socket' only handle one server = TCPServer.new(2202) client at a time while true Thread.new(server.accept){ |client| Common Solution: msg = client.readline client.write "You said: #{msg}" use a thread per client.close client } end
  • 14. require 'socket' inbound server = TCPServer.new(2202) list of clients clients = [] buffer per buffers = {} client IO.select returns while true sockets = [server] + clients readable/writable readable, writable = IO.select(sockets) sockets readable.each do |sock| begin if sock == server clients << server.accept_nonblock else client, buf = sock, buffers[sock] ||= '' read in available data, buf << client.read_nonblock(1024) process if full line received if buf =~ /^.+?r?n/ client.write "You said: #{buf}" Non-Blocking I/O client.close buffers.delete(client) clients.delete(client) end Alternative to end rescue Errno::EAGAIN, Errno::EWOULDBLOCK threads: simply don’t # socket would block, try again later end block end end
  • 15. EM does Non-Blocking I/O handles low module EchoServer level sockets def post_init for you @buf = '' end inbound/ def receive_data(data) @buf << data outbound if @buf =~ /^.+?r?n/ buffers for send_data "You said: #{@buf}" close_connection_after_writing maximal end throughput end end efficient i/o with writev/readv require 'eventmachine' EM.run do EM.start_server '0.0.0.0', 2202, EchoServer epoll & kqueue end support
  • 16. So, what’s a Reactor? while reactor_running? expired_timers.each{ |timer| timer.process } new_network_io.each{ |io| io.process } end reactor is simply a single threaded while loop, called the “reactor loop” your code “reacts” to incoming events if your event handler takes too long, other events cannot fire lesson: never block the reactor while reactor_running? while true no sleep(1) end no long loops (100_000.times) # reactor is blocked! no blocking I/O (mysql queries) end no polling (while !condition)
  • 17. Writing Asynchronous Code synchronous ruby code uses return values ret = operation() do_something_with(ret) evented async code uses blocks instead operation{ |ret| do_something_with(ret) } different from how you usually use ruby blocks. the block is stored and invoked later (it’s asynchronous) puts(1) puts(1) 1.times{ puts(2) } operation{ puts(3) } puts(3) puts(2)
  • 18. Receiving Email Using ActionMailer port 25 postfix (smtp) (spool) fork process Action pgsql Mailer ActiveRecord (db)
  • 19. Receiving Email Using LMTP port 25 postfix (smtp) (spool) port 8081 (lmtp) EM pgsql (w/Rails) ActiveRecord (db)
  • 20. Receiving Email — Scalably via LMTP postfix postfix message (spool) (spool) systems EM EM EM EM (w/Rails) (w/Rails) (w/Rails) (w/Rails)
  • 24. EventMachine Geo Firehose LISTEN 8192 (one connection - Port 80) 250, 500, 1000 Connections twittervision.com/ Apache stream RewriteRule ^/stream(.*)$ http://127.0.0.1:8192%{REQUEST_URI} [P,QSA,L]
  • 25. replyz.com Does Anybody Know...? mailstrom.co mailstrom.410labs.com Power Tools for Your Inbox shortmail.com Email, simplified.
  • 26. Some Other Handy Stuff... • start_tls: secure any TCP connection • Timers: Periodic, Once, Scheduled • epoll, kqueue, threadpool_size • set_effective_user (listen on protected ports) • teh docs: http://eventmachine.rubyforge.org/EventMachine.html
  • 27. So, Some Stuff To Remember... • EventMachine: awesome for I/O, events • Code is Data, Data is Code • Often Working with State Machines • Don’t peg the CPU. No really, don’t. • TEBWTDI • Testing can be interesting
  • 28. Dave Troy Chief Executive Officer davetroy@shortmail.com @davetroy facebook.com/davetroy Tomorrow @ BohConf! http://emrubyconf.com/

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n