SlideShare ist ein Scribd-Unternehmen logo
1 von 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 modiïŹed. 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 beneïŹts of CoW.
Multiple processes / forking

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

 Passenger ïŹxed 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 simpliïŹed 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
 DifïŹcult to manage
 DifïŹcult to debug in production
 GIL prevents us to have concurrency
Recap
Forking
 GC prevents us to have a proper memory management
Threads
 DifïŹcult to manage
 DifïŹcult to debug in production
 GIL prevents us to have concurrency
Fibers
Recap
Forking
 GC prevents us to have a proper memory management
Threads
 DifïŹcult to manage
 DifïŹcult to debug in production
 GIL prevents us to have concurrency
Fibers
 DifïŹcult 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 ïŹle over a connection
 ::FileWatch - Monitors a ïŹle, get notiïŹed when it gets deleted, modiïŹed 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
   DifïŹcult 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

Weitere Àhnliche Inhalte

Was ist angesagt?

20140918 ruby kaigi2014
20140918 ruby kaigi201420140918 ruby kaigi2014
20140918 ruby kaigi2014
Hiroshi SHIBATA
 
JS Fest 2018. АлДĐșсДĐč Đ’ĐŸĐ»ĐșĐŸĐČ. ĐŸĐŸĐ»Đ”Đ·ĐœŃ‹Đ” ĐžĐœŃŃ‚Ń€ŃƒĐŒĐ”ĐœŃ‚Ń‹ ĐŽĐ»Ń JS Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐž
JS Fest 2018. АлДĐșсДĐč Đ’ĐŸĐ»ĐșĐŸĐČ. ĐŸĐŸĐ»Đ”Đ·ĐœŃ‹Đ” ĐžĐœŃŃ‚Ń€ŃƒĐŒĐ”ĐœŃ‚Ń‹ ĐŽĐ»Ń JS Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐžJS Fest 2018. АлДĐșсДĐč Đ’ĐŸĐ»ĐșĐŸĐČ. ĐŸĐŸĐ»Đ”Đ·ĐœŃ‹Đ” ĐžĐœŃŃ‚Ń€ŃƒĐŒĐ”ĐœŃ‚Ń‹ ĐŽĐ»Ń JS Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐž
JS Fest 2018. АлДĐșсДĐč Đ’ĐŸĐ»ĐșĐŸĐČ. ĐŸĐŸĐ»Đ”Đ·ĐœŃ‹Đ” ĐžĐœŃŃ‚Ń€ŃƒĐŒĐ”ĐœŃ‚Ń‹ ĐŽĐ»Ń JS Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐž
JSFestUA
 
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
Hiroshi SHIBATA
 
From 'Legacy' to 'Edge'
From 'Legacy' to 'Edge'From 'Legacy' to 'Edge'
From 'Legacy' to 'Edge'
Hiroshi SHIBATA
 

Was ist angesagt? (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
 

Andere mochten auch

PresentaciĂł 1r batx i 4t eso
PresentaciĂł 1r batx i 4t esoPresentaciĂł 1r batx i 4t eso
PresentaciĂł 1r batx i 4t eso
iessineu
 
Pipeline - Continuous Delivery
Pipeline - Continuous DeliveryPipeline - Continuous Delivery
Pipeline - Continuous Delivery
almeidaricardo
 

Andere mochten auch (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
 

Ähnlich wie 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::Synchrony
Kyle Drake
 
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
Spike Brehm
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
catherinewall
 

Ähnlich wie 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
 

KĂŒrzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
Christopher Logan Kennedy
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

KĂŒrzlich hochgeladen (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

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 modiïŹed. 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 beneïŹts of CoW.
  • 13. Multiple processes / forking Passenger ïŹxed the copy-on-write issues creating a CoW- friendly GC, and it will be integrated into Ruby 2.0
  • 14. Multiple processes / forking Passenger ïŹxed 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 simpliïŹed 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 DifïŹcult to manage DifïŹcult to debug in production GIL prevents us to have concurrency
  • 31. Recap Forking GC prevents us to have a proper memory management Threads DifïŹcult to manage DifïŹcult to debug in production GIL prevents us to have concurrency Fibers
  • 32. Recap Forking GC prevents us to have a proper memory management Threads DifïŹcult to manage DifïŹcult to debug in production GIL prevents us to have concurrency Fibers DifïŹcult 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 ïŹle over a connection ::FileWatch - Monitors a ïŹle, get notiïŹed when it gets deleted, modiïŹed 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 DifïŹcult 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

Hinweis der Redaktion

  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