SlideShare una empresa de Scribd logo
1 de 51
Concurrency in Ruby
Marco Borromeo - @borros


Italian Ruby Day - Milan - 15 June 2012
Concurrency - Why?

Fill up all those cores!
Concurrency - Why?

Fill up all those cores!


Ruby is slow - Just add some more mongrels there
Concurrency - Why?

Fill up all those cores!


Ruby is slow - Just add some more mongrels there
How to achieve concurrency


Multiple processes / forking
Threads
Fibers
Multiple processes / forking
 Most commonly used solution to gain concurrency in Ruby
Multiple processes / forking
 Most commonly used solution to gain concurrency in Ruby

 No shared states between running processes. You need to use DRb, a
 message bus like RabbitMQ
Multiple processes / forking
 Most commonly used solution to gain concurrency in Ruby

 No shared states between running processes. You need to use DRb, a
 message bus like RabbitMQ
                    ... or some shared data store like MySQL
Multiple processes / forking
 Most commonly used solution to gain concurrency in Ruby

 No shared states between running processes. You need to use DRb, a
 message bus like RabbitMQ
                    ... or some shared data store like MySQL
Multiple processes / forking
 Most commonly used solution to gain concurrency in Ruby

 No shared states between running processes. You need to use DRb, a
 message bus like RabbitMQ
                     ... or some shared data store like MySQL

 Forked processses can read the state of the program before the fork, but
 updates wont be shared
Multiple processes / forking
 LOT of memory used!
 5 Rails apps is something like 45MB * 5 = 255MB!


 Unix copy-on-write (CoW) comes to help: no need to copy the whole
 memory into the forked process, and only the data changed after the fork
 will be copied and modified. but...
Multiple processes / forking

Ruby Garbage Collector (GC) will write to every object every time
it will run, so the whole process memory will be then copied.
Basically, Ruby loses all the benefits of CoW.
Multiple processes / forking

 Passenger fixed the copy-on-write issues creating a CoW-
 friendly GC, and it will be integrated into Ruby 2.0
Multiple processes / forking

 Passenger fixed the copy-on-write issues creating a CoW-
 friendly GC, and it will be integrated into Ruby 2.0


 Rubinius is CoW friendly
How to achieve concurrency


Multiple processes / forking
Threads
Fibers
Threads

Ruby 1.8 has "green threads". They are scheduled by the VM,
and emulate multithreaded environments even if they are not.

Ruby 1.9 has OS threads.


Preemptive scheduling
Threads

Both 1.8 and 1.9 have the Global Interpreter Lock (GIL).
Having GIL means that any time one thread is running Ruby
code, no other thread can be running Ruby code.
Even if you have multiple threads, you can only use at most 1
core of your CPU at a time.
Threads

Race conditions, dead locks, synchronizing...
Threads

Race conditions, dead locks, synchronizing...
Threads

Race conditions, dead locks, synchronizing...


... JRuby manages threads very well, has no GIL and let you
use all your cores.
Threads

Race conditions, dead locks, synchronizing...


... JRuby manages threads very well, has no GIL and let you
use all your cores.

Rubinius is working on removing GIL
How to achieve concurrency


Multiple processes / forking
Threads
Fibers
Fibers
 Natively available only in Ruby 1.9


 They are like simplified threads, but they aren't
 scheduled by the VM but by the programmer


 Faster than threads, and use less memory
Fibers
Fibers


They still suffer the GIL presence.
Recap
Recap
Forking
Recap
Forking
 GC prevents us to have a proper memory management
Recap
Forking
 GC prevents us to have a proper memory management
Threads
Recap
Forking
 GC prevents us to have a proper memory management
Threads
 Difficult to manage
 Difficult to debug in production
 GIL prevents us to have concurrency
Recap
Forking
 GC prevents us to have a proper memory management
Threads
 Difficult to manage
 Difficult to debug in production
 GIL prevents us to have concurrency
Fibers
Recap
Forking
 GC prevents us to have a proper memory management
Threads
 Difficult to manage
 Difficult to debug in production
 GIL prevents us to have concurrency
Fibers
 Difficult to debug in production
 GIL prevents us to have concurrency
No Concurrency, sorry.
No Concurrency, sorry.
Blocking I/O

               90% I/O

          10% Code Execution
Reactor Pattern

Application server (AS) receives a request from a browser
AS queues the request in the Reactor
Reactor process the request, passing the control to our App
In order to process the request, our app needs to perform some API
queries over third-party services
Reactor Pattern

Application server (AS) receives a request from a browser
AS queues the request in the Reactor
Reactor process the request, passing the control to our App
In order to process the request, our app needs to perform some API
queries over third-party services

                                  ...zZzZzzZzZzZ...
Reactor Pattern

Application server (AS) receives a request from a browser
AS queues the request in the Reactor
Reactor process the request, passing the control to our App
In order to process the request, our app needs to perform some API
queries over third-party services

                                  ...zZzZzzZzZzZ...
Reactor Pattern

Our app makes the http request to the third-party service, using an async
library (em-http) and provides a callback to be executed when a reply is
received
Control returns to the Reactor
Reactor pulls the next event from the queue and executes it
Reactor Pattern

Earlier HTTP API call returns (or fails!) and the callback is enqueued into the
Reactor
Control returns to the Reactor
Reactor starts executing the callback which processes the results of the API
request, builds a response and sends it to the browser.
Done
Blocking I/O
  Everything has the advantage of being concurrent
          without having to be thread-safe.

           It is a "cooperative multitasking"
    (while Threads have a “Preemptive scheduling“ approach)
EventMachine
Is the Ruby implementation of the Reactor Pattern


 ::DeferrableChildProcess - Wait for a process to exit
 ::FileStreamer - Streams a file over a connection
 ::FileWatch - Monitors a file, get notified when it gets deleted, modified or
 moved
 ::PeriodicTimer - Executes something every interval seconds
EventMachine
Is the Ruby implementation of the Reactor Pattern


 ::Protocols::HttpClient      ::Protocols::SmtpServer
 ::Protocols::Memcache        ::Protocols::Socks4
 ::Protocols::Postgres3       ::Protocols::Stomp
 ::Protocols::SmtpClient
EventMachine
Issues:

   Not so very well documented
   Difficult to adopt for "syncronous programmers"
   Doesn't play well with actual web frameworks
EventMachine
EventMachine
EventMachine.run {
  page = EventMachine::HttpRequest.new('http://github.com/').get
  page.errback { p "GitHub is Down. Everybody run for your life!" }
  page.callback {
    about = EventMachine::HttpRequest.new('http://github.com/api/v2/json/
repos/show/schacon).get
    about.callback { }
    about.errback { }
  }
}
EM-Syncrony
"Collection of convenience classes and primitives to help untangle evented
  code, plus a number of patched EM clients to make them Fiber aware."

    EventMachine.synchrony do
      homepage = EventMachine::HttpRequest.new("http://github.com/").get
      apiResponse = EventMachine::HttpRequest.new("'http://github.com/api/v2/
    json/repos/show/schacon").get

     p "No callbacks! Fetched API: #{apiResponse}"
     EventMachine.stop
    end
EM-Syncrony
 mysql2
 activerecord      Other clients:
 em-http-request      em-redis
 em-memcached         hiredis
 em-mongo
 mongoid
 AMQP
Sinatra::Synchrony
 EventMachine + EM-Syncrony
 Rack::FiberPool
 em-http-request
 em-resolv-replace
 Patches TCPSocket (via EM-Syncrony) (!)
 Patches Rack::Test
Sinatra::Synchrony
         gem install sinatra-synchrony

          require 'sinatra/synchrony'

          register Sinatra::Synchrony
Thanks!
Marco Borromeo
@borros
marco@continuityapp.com

Más contenido relacionado

La actualidad más candente

Javascript internals
Javascript internalsJavascript internals
Javascript internalsAyush Sharma
 
Apache Camel in the belly of the Docker whale
Apache Camel in the belly of the Docker whaleApache Camel in the belly of the Docker whale
Apache Camel in the belly of the Docker whaleHenryk Konsek
 
How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?Hiroshi SHIBATA
 
Background processes and tasks in an async world
Background processes and tasks in an async worldBackground processes and tasks in an async world
Background processes and tasks in an async worldparticlebanana
 
Building real time applications with Symfony2
Building real time applications with Symfony2Building real time applications with Symfony2
Building real time applications with Symfony2Antonio Peric-Mazar
 
JS Fest 2018. Алексей Волков. Полезные инструменты для JS разработки
JS Fest 2018. Алексей Волков. Полезные инструменты для JS разработкиJS Fest 2018. Алексей Волков. Полезные инструменты для JS разработки
JS Fest 2018. Алексей Волков. Полезные инструменты для JS разработкиJSFestUA
 
Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...Love Nyberg
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NETPierre-Luc Maheu
 
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appBASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appHanaStevanovic
 
tDiary annual report 2009 - Sapporo Ruby Kaigi02
tDiary annual report 2009 - Sapporo Ruby Kaigi02tDiary annual report 2009 - Sapporo Ruby Kaigi02
tDiary annual report 2009 - Sapporo Ruby Kaigi02Hiroshi SHIBATA
 
From .Net to Rails, A developers story
From .Net to Rails, A developers storyFrom .Net to Rails, A developers story
From .Net to Rails, A developers storypythonandchips
 
Securing & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave NetSecuring & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave NetLuke Marsden
 
Developing high-performance network servers in Lisp
Developing high-performance network servers in LispDeveloping high-performance network servers in Lisp
Developing high-performance network servers in LispVladimir Sedach
 
Javascript under the hood
Javascript under the hoodJavascript under the hood
Javascript under the hoodRidhwana Khan
 
jLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTjLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTIván López Martín
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingAlex Derkach
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices ArchitectureIdan Fridman
 

La actualidad más candente (20)

Javascript internals
Javascript internalsJavascript internals
Javascript internals
 
Apache Camel in the belly of the Docker whale
Apache Camel in the belly of the Docker whaleApache Camel in the belly of the Docker whale
Apache Camel in the belly of the Docker whale
 
How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?How to develop the Standard Libraries of Ruby?
How to develop the Standard Libraries of Ruby?
 
20140918 ruby kaigi2014
20140918 ruby kaigi201420140918 ruby kaigi2014
20140918 ruby kaigi2014
 
Background processes and tasks in an async world
Background processes and tasks in an async worldBackground processes and tasks in an async world
Background processes and tasks in an async world
 
Building real time applications with Symfony2
Building real time applications with Symfony2Building real time applications with Symfony2
Building real time applications with Symfony2
 
JS Fest 2018. Алексей Волков. Полезные инструменты для JS разработки
JS Fest 2018. Алексей Волков. Полезные инструменты для JS разработкиJS Fest 2018. Алексей Волков. Полезные инструменты для JS разработки
JS Fest 2018. Алексей Волков. Полезные инструменты для JS разработки
 
Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...Using SaltStack to orchestrate microservices in application containers at Sal...
Using SaltStack to orchestrate microservices in application containers at Sal...
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
 
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive appBASICS OF VERT.X - A toolkit for building asynchronous and reactive app
BASICS OF VERT.X - A toolkit for building asynchronous and reactive app
 
tDiary annual report 2009 - Sapporo Ruby Kaigi02
tDiary annual report 2009 - Sapporo Ruby Kaigi02tDiary annual report 2009 - Sapporo Ruby Kaigi02
tDiary annual report 2009 - Sapporo Ruby Kaigi02
 
From 'Legacy' to 'Edge'
From 'Legacy' to 'Edge'From 'Legacy' to 'Edge'
From 'Legacy' to 'Edge'
 
From .Net to Rails, A developers story
From .Net to Rails, A developers storyFrom .Net to Rails, A developers story
From .Net to Rails, A developers story
 
Securing & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave NetSecuring & Enforcing Network Policy and Encryption with Weave Net
Securing & Enforcing Network Policy and Encryption with Weave Net
 
Developing high-performance network servers in Lisp
Developing high-performance network servers in LispDeveloping high-performance network servers in Lisp
Developing high-performance network servers in Lisp
 
Javascript under the hood
Javascript under the hoodJavascript under the hood
Javascript under the hood
 
jLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoTjLove 2020 - Micronaut and graalvm: The power of AoT
jLove 2020 - Micronaut and graalvm: The power of AoT
 
Vert.x – The problem of real-time data binding
Vert.x – The problem of real-time data bindingVert.x – The problem of real-time data binding
Vert.x – The problem of real-time data binding
 
Vert.x for Microservices Architecture
Vert.x for Microservices ArchitectureVert.x for Microservices Architecture
Vert.x for Microservices Architecture
 
Ruby On Rails Ecosystem
Ruby On Rails EcosystemRuby On Rails Ecosystem
Ruby On Rails Ecosystem
 

Destacado

Presentació 1r batx i 4t eso
Presentació 1r batx i 4t esoPresentació 1r batx i 4t eso
Presentació 1r batx i 4t esoiessineu
 
Pipeline - Continuous Delivery
Pipeline - Continuous DeliveryPipeline - Continuous Delivery
Pipeline - Continuous Deliveryalmeidaricardo
 
Celluloid, Celluloid::IO and Friends
Celluloid, Celluloid::IO and FriendsCelluloid, Celluloid::IO and Friends
Celluloid, Celluloid::IO and FriendsMarcelo Pinheiro
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)tarcieri
 
Hybrid concurrency patterns
Hybrid concurrency patternsHybrid concurrency patterns
Hybrid concurrency patternsKyle Drake
 

Destacado (6)

Coding workshop p1
Coding workshop p1Coding workshop p1
Coding workshop p1
 
Presentació 1r batx i 4t eso
Presentació 1r batx i 4t esoPresentació 1r batx i 4t eso
Presentació 1r batx i 4t eso
 
Pipeline - Continuous Delivery
Pipeline - Continuous DeliveryPipeline - Continuous Delivery
Pipeline - Continuous Delivery
 
Celluloid, Celluloid::IO and Friends
Celluloid, Celluloid::IO and FriendsCelluloid, Celluloid::IO and Friends
Celluloid, Celluloid::IO and Friends
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
 
Hybrid concurrency patterns
Hybrid concurrency patternsHybrid concurrency patterns
Hybrid concurrency patterns
 

Similar a Concurrency in ruby

Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyKyle Drake
 
Achieving mass scale with Quasar Fibers
Achieving mass scale with Quasar FibersAchieving mass scale with Quasar Fibers
Achieving mass scale with Quasar FibersIdan Sheinberg
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011Lance Ball
 
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
 
Where is my scalable api?
Where is my scalable api?Where is my scalable api?
Where is my scalable api?Altoros
 
Isomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornIsomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornMaxime Najim
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spacesluccastera
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.jsNitin Gupta
 
Phoenix for Rubyists
Phoenix for RubyistsPhoenix for Rubyists
Phoenix for RubyistsDoug Goldie
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityGleicon Moraes
 
TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011bobmcwhirter
 
Message Queues in Ruby - An Overview
Message Queues in Ruby - An OverviewMessage Queues in Ruby - An Overview
Message Queues in Ruby - An OverviewPradeep Elankumaran
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystemGeison Goes
 
A Fabric/Puppet Build/Deploy System
A Fabric/Puppet Build/Deploy SystemA Fabric/Puppet Build/Deploy System
A Fabric/Puppet Build/Deploy Systemadrian_nye
 
IronRuby for the Rubyist
IronRuby for the RubyistIronRuby for the Rubyist
IronRuby for the RubyistWill Green
 
Road to sbt 1.0 paved with server
Road to sbt 1.0   paved with serverRoad to sbt 1.0   paved with server
Road to sbt 1.0 paved with serverEugene Yokota
 
In Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript AppsIn Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript AppsSpike Brehm
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Enginecatherinewall
 

Similar a Concurrency in ruby (20)

Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::SynchronyFast, concurrent ruby web applications with EventMachine and EM::Synchrony
Fast, concurrent ruby web applications with EventMachine and EM::Synchrony
 
Achieving mass scale with Quasar Fibers
Achieving mass scale with Quasar FibersAchieving mass scale with Quasar Fibers
Achieving mass scale with Quasar Fibers
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
TorqueBox
TorqueBoxTorqueBox
TorqueBox
 
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
 
Where is my scalable api?
Where is my scalable api?Where is my scalable api?
Where is my scalable api?
 
Where is my scalable API?
Where is my scalable API?Where is my scalable API?
Where is my scalable API?
 
Isomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornIsomorphic JavaScript with Nashorn
Isomorphic JavaScript with Nashorn
 
Concurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple SpacesConcurrent Programming with Ruby and Tuple Spaces
Concurrent Programming with Ruby and Tuple Spaces
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.js
 
Phoenix for Rubyists
Phoenix for RubyistsPhoenix for Rubyists
Phoenix for Rubyists
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs Scalability
 
TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011TorqueBox at DC:JBUG - November 2011
TorqueBox at DC:JBUG - November 2011
 
Message Queues in Ruby - An Overview
Message Queues in Ruby - An OverviewMessage Queues in Ruby - An Overview
Message Queues in Ruby - An Overview
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystem
 
A Fabric/Puppet Build/Deploy System
A Fabric/Puppet Build/Deploy SystemA Fabric/Puppet Build/Deploy System
A Fabric/Puppet Build/Deploy System
 
IronRuby for the Rubyist
IronRuby for the RubyistIronRuby for the Rubyist
IronRuby for the Rubyist
 
Road to sbt 1.0 paved with server
Road to sbt 1.0   paved with serverRoad to sbt 1.0   paved with server
Road to sbt 1.0 paved with server
 
In Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript AppsIn Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
In Pursuit of the Holy Grail: Building Isomorphic JavaScript Apps
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 

Último

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 

Último (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
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
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 

Concurrency in ruby

  • 1. Concurrency in Ruby Marco Borromeo - @borros Italian Ruby Day - Milan - 15 June 2012
  • 2. Concurrency - Why? Fill up all those cores!
  • 3. Concurrency - Why? Fill up all those cores! Ruby is slow - Just add some more mongrels there
  • 4. Concurrency - Why? Fill up all those cores! Ruby is slow - Just add some more mongrels there
  • 5. How to achieve concurrency Multiple processes / forking Threads Fibers
  • 6. Multiple processes / forking Most commonly used solution to gain concurrency in Ruby
  • 7. Multiple processes / forking Most commonly used solution to gain concurrency in Ruby No shared states between running processes. You need to use DRb, a message bus like RabbitMQ
  • 8. Multiple processes / forking Most commonly used solution to gain concurrency in Ruby No shared states between running processes. You need to use DRb, a message bus like RabbitMQ ... or some shared data store like MySQL
  • 9. Multiple processes / forking Most commonly used solution to gain concurrency in Ruby No shared states between running processes. You need to use DRb, a message bus like RabbitMQ ... or some shared data store like MySQL
  • 10. Multiple processes / forking Most commonly used solution to gain concurrency in Ruby No shared states between running processes. You need to use DRb, a message bus like RabbitMQ ... or some shared data store like MySQL Forked processses can read the state of the program before the fork, but updates wont be shared
  • 11. Multiple processes / forking LOT of memory used! 5 Rails apps is something like 45MB * 5 = 255MB! Unix copy-on-write (CoW) comes to help: no need to copy the whole memory into the forked process, and only the data changed after the fork will be copied and modified. but...
  • 12. Multiple processes / forking Ruby Garbage Collector (GC) will write to every object every time it will run, so the whole process memory will be then copied. Basically, Ruby loses all the benefits of CoW.
  • 13. Multiple processes / forking Passenger fixed the copy-on-write issues creating a CoW- friendly GC, and it will be integrated into Ruby 2.0
  • 14. Multiple processes / forking Passenger fixed the copy-on-write issues creating a CoW- friendly GC, and it will be integrated into Ruby 2.0 Rubinius is CoW friendly
  • 15. How to achieve concurrency Multiple processes / forking Threads Fibers
  • 16. Threads Ruby 1.8 has "green threads". They are scheduled by the VM, and emulate multithreaded environments even if they are not. Ruby 1.9 has OS threads. Preemptive scheduling
  • 17. Threads Both 1.8 and 1.9 have the Global Interpreter Lock (GIL). Having GIL means that any time one thread is running Ruby code, no other thread can be running Ruby code. Even if you have multiple threads, you can only use at most 1 core of your CPU at a time.
  • 18. Threads Race conditions, dead locks, synchronizing...
  • 19. Threads Race conditions, dead locks, synchronizing...
  • 20. Threads Race conditions, dead locks, synchronizing... ... JRuby manages threads very well, has no GIL and let you use all your cores.
  • 21. Threads Race conditions, dead locks, synchronizing... ... JRuby manages threads very well, has no GIL and let you use all your cores. Rubinius is working on removing GIL
  • 22. How to achieve concurrency Multiple processes / forking Threads Fibers
  • 23. Fibers Natively available only in Ruby 1.9 They are like simplified threads, but they aren't scheduled by the VM but by the programmer Faster than threads, and use less memory
  • 25. Fibers They still suffer the GIL presence.
  • 26. Recap
  • 28. Recap Forking GC prevents us to have a proper memory management
  • 29. Recap Forking GC prevents us to have a proper memory management Threads
  • 30. Recap Forking GC prevents us to have a proper memory management Threads Difficult to manage Difficult to debug in production GIL prevents us to have concurrency
  • 31. Recap Forking GC prevents us to have a proper memory management Threads Difficult to manage Difficult to debug in production GIL prevents us to have concurrency Fibers
  • 32. Recap Forking GC prevents us to have a proper memory management Threads Difficult to manage Difficult to debug in production GIL prevents us to have concurrency Fibers Difficult to debug in production GIL prevents us to have concurrency
  • 35. Blocking I/O 90% I/O 10% Code Execution
  • 36. Reactor Pattern Application server (AS) receives a request from a browser AS queues the request in the Reactor Reactor process the request, passing the control to our App In order to process the request, our app needs to perform some API queries over third-party services
  • 37. Reactor Pattern Application server (AS) receives a request from a browser AS queues the request in the Reactor Reactor process the request, passing the control to our App In order to process the request, our app needs to perform some API queries over third-party services ...zZzZzzZzZzZ...
  • 38. Reactor Pattern Application server (AS) receives a request from a browser AS queues the request in the Reactor Reactor process the request, passing the control to our App In order to process the request, our app needs to perform some API queries over third-party services ...zZzZzzZzZzZ...
  • 39. Reactor Pattern Our app makes the http request to the third-party service, using an async library (em-http) and provides a callback to be executed when a reply is received Control returns to the Reactor Reactor pulls the next event from the queue and executes it
  • 40. Reactor Pattern Earlier HTTP API call returns (or fails!) and the callback is enqueued into the Reactor Control returns to the Reactor Reactor starts executing the callback which processes the results of the API request, builds a response and sends it to the browser. Done
  • 41. Blocking I/O Everything has the advantage of being concurrent without having to be thread-safe. It is a "cooperative multitasking" (while Threads have a “Preemptive scheduling“ approach)
  • 42. EventMachine Is the Ruby implementation of the Reactor Pattern ::DeferrableChildProcess - Wait for a process to exit ::FileStreamer - Streams a file over a connection ::FileWatch - Monitors a file, get notified when it gets deleted, modified or moved ::PeriodicTimer - Executes something every interval seconds
  • 43. EventMachine Is the Ruby implementation of the Reactor Pattern ::Protocols::HttpClient ::Protocols::SmtpServer ::Protocols::Memcache ::Protocols::Socks4 ::Protocols::Postgres3 ::Protocols::Stomp ::Protocols::SmtpClient
  • 44. EventMachine Issues: Not so very well documented Difficult to adopt for "syncronous programmers" Doesn't play well with actual web frameworks
  • 46. EventMachine EventMachine.run { page = EventMachine::HttpRequest.new('http://github.com/').get page.errback { p "GitHub is Down. Everybody run for your life!" } page.callback { about = EventMachine::HttpRequest.new('http://github.com/api/v2/json/ repos/show/schacon).get about.callback { } about.errback { } } }
  • 47. EM-Syncrony "Collection of convenience classes and primitives to help untangle evented code, plus a number of patched EM clients to make them Fiber aware." EventMachine.synchrony do homepage = EventMachine::HttpRequest.new("http://github.com/").get apiResponse = EventMachine::HttpRequest.new("'http://github.com/api/v2/ json/repos/show/schacon").get p "No callbacks! Fetched API: #{apiResponse}" EventMachine.stop end
  • 48. EM-Syncrony mysql2 activerecord Other clients: em-http-request em-redis em-memcached hiredis em-mongo mongoid AMQP
  • 49. Sinatra::Synchrony EventMachine + EM-Syncrony Rack::FiberPool em-http-request em-resolv-replace Patches TCPSocket (via EM-Syncrony) (!) Patches Rack::Test
  • 50. Sinatra::Synchrony gem install sinatra-synchrony require 'sinatra/synchrony' register Sinatra::Synchrony

Notas del editor

  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
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n