SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Dernier

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 

Dernier (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 

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

Notes de l'éditeur

  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