SlideShare a Scribd company logo
1 of 39
Download to read offline
Concurrency
 & Gevent
Scaling Real World Applications
Concurrency
handling a number of things at the same time




Examples: (Incoming) WebServers, Database Servers
         (Outgoing) SSH Mux
SSH Mux

●
    Execute a command on a remote
    SSH server
●
    Handle concurrent SSH Clients
●
    Command execution time varies
    from seconds to days
●
    Command execution happens on
    remote servers, SSH mux is I/O
    bound
SSH Client


1. Init session

2. Authenticate

3. Get a channel

4. Issue command

5. Read output
Need Concurrency?
●
    Process blocks on read()
●
    No new connections can be inititated
●
    Need ability to handle multiple clients at the same
    time
Multiprocessing
●
    One process is the master
●
    Master can spawn workers
●
    Each worker handles one request at a time
●
    Pre-forked pool of workers
Concurrent SSH Clients
SSH Mux Memory Usage

                                              ssh mux memory usage

               600


               500


               400
 Memory (MB)




               300                                                                     Processes


               200


               100


                0
                     0   5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
                                            # Concurrent Reqs
SSH Mux Performace

                                     ssh mux performance sheet

          160

          140

          120

          100
Time(s)




          80                                                                           Processes

          60

          40

          20

           0
                20   40   80   150   200     400     800   1200   1500   1800   2100
                                     # Concurrent Reqs
Multiprocessing yay

●
    Easy to get started
●
    OS guaranteed process isolation & fairness
●
    Covers up for misbehaving workers
●
    Add more concurrency by adding more workers
●
    Convenient when numbers are smaller numbers
Multiprocessing nay
●
    Concurrency limited by number of processes
●
    Memory heavy
●
    Implicit scheduling
●
    Synchronization is not trivial
More Concurrency?

●
    Command execution is happening on remote servers, we
    are mostly blocked on I/O




●
    Handle multiple I/O in a single process?
Gevent
gevent is a coroutine-based Python networking library that
 uses greenlet to provide a high-level synchronous API on
             top of the libevent event loop.
Greenlets
●
    Lightweight 'threads' - not OS threads
●
    Explicit scheduling - Cooperative
●
    Minimal stack
●
    Application decides execution flow
●
    Easy to synchronize/ Avoid locks
●
    All run inside one process
Libevent
●
    Use fastest mechanism to poll (portable)
●
    Fast Event loop
●
    In Gevent, event loop runs in a greenlet (event hub)
●
    Instead of blocking, greenlets switch to event hub
●
    It's all done behind the scene
Monkey Patching

Monkey patching
Modifies behaviour of blocking calls such as select, sleep to
non-blocking
Patches the python standard socket library
Gevent
●
    Greenlet 1 is running
●
    Greenlet 2 and 3 are ready
Gevent
●
    Greenlet 1 has to wait for read
●
    Greenlet 1 switches to Event hub
Gevent
●
    Event hub switches to Greenlet 3
Gevent
●
    Greenlet 2 runs
Gevent
●
    Greenlet 2 wants to sleep
●
    Greenlet 2 switches to Event hub
Gevent
●
    Greenlet 1 data has come, moved to ready state
●
    Eventhub switches to Greenlet 3
Gevent
●
    Greenlet 3 runs
Gevent
●
    When Greenlet 1 resumes, its from next instruction
●
    It's as if it were a blocking call
Green SSH Client


1. Init session

2. Authenticate

3. Get a channel

4. Issue command

5. Read output
A closer look
Going Concurrent




 Use pre-forked processes to use all cores
Memory usage
                                               ssh mux memory usage

             45

             40

             35

             30
Memory(MB)




             25
                                                                                    Gevent+Processes
             20

             15

             10

             5

             0
                  0   5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

                                          # Concurrent Reqs
SSH Mux Performace
                                           ssh mux performace chart

           70


           60


           50


           40
 Time(s)




                                                                                     Gevent+Processes
           30


           20


           10


           0
                20   40   80   150   200     400   800   1200   1500   1800   2100
                                     # Concurrent Reqs
SSH Mux memory usage

                                              ssh mux memory usage

                600


                500


                400
   Memory(MB)




                                                                                        Processes
                300
                                                                                        Gevent

                200


                100


                 0
                      0   5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100
                                             # Concurrent Reqs
SSH Mux Performance
                                        ssh mux performance sheet

          160

          140

          120

          100
                                                                                       Processes
Time(s)




          80                                                                           Gevent+Processes

          60

          40

          20

           0
                20   40   80   150   200     400     800   1200   1500   1800   2100

                                     # Concurrent Reqs
Gevent yay!
●
    Untwist – write linear non blocking code
●
    Explicit scheduling, dictate the execution flow
●
    Timeouts
●
    Events, AsyncResults for Synchronization
●
    gevent.wsgi
●
    Pre-spawned pool of greenlets
Gevent beware of

●
    No multicore support
●
    Not great for CPU bound applications
●
    Third party libs must be green (non blocking)
●
    Misbehaving workers can be lethal
●
    No fairness when it comes to scheduling
Take Away
●
    Gevent lets you write asynchronous code in a
    synchronous manner
●
    No multicore support, still need multiprocessing
●
    Not so great for CPU bound applications
●
    Split your application into CPU bound and IO bound
    parts
●
    Be willing to contribute patches
●
    Code available at
    git@github.com:aaloksood/pyexamples.git
Thank you




            That's all folks!
Countdown Timer
●
    Count down from 200000000
●
    Split work among workers
Threads

                                 Multithreading wonder

            25


            20


            15
                                                                      1 Core
  Time(s)




                                                                      4 cores
            10


            5


            0
                 1   2   3   4     5           6   7     8   9   10
                                   # Workers
One core


                                    Execution time One Core

             14.5
              14
             13.5
              13                                                           Processes
                                                                           1 Core
  Time (s)




             12.5
                                                                           Gevent_1
              12                                                           Gevent_4
             11.5
              11
             10.5
                    1   2   3   4       5         6   7       8   9   10
                                      # Workers
Four cores


                                  Execution time 4 cores

             25


             20

                                                                        Process
             15
                                                                        Threads
   Time(s)




                                                                        Gevent_1
             10
                                                                        Gevent_4

             5


             0
                  1   2   3   4     5          6   7       8   9   10
                                   # Workers

More Related Content

What's hot

FPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpegFPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpegChan Shik Lim
 
Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Jimmy Lai
 
Working with multiple git repositories
Working with multiple git repositoriesWorking with multiple git repositories
Working with multiple git repositoriesJulien Pivotto
 
High performance json- postgre sql vs. mongodb
High performance json- postgre sql vs. mongodbHigh performance json- postgre sql vs. mongodb
High performance json- postgre sql vs. mongodbWei Shan Ang
 
Data processing with celery and rabbit mq
Data processing with celery and rabbit mqData processing with celery and rabbit mq
Data processing with celery and rabbit mqJeff Peck
 
Scala, docker and testing, oh my! mario camou
Scala, docker and testing, oh my! mario camouScala, docker and testing, oh my! mario camou
Scala, docker and testing, oh my! mario camouJ On The Beach
 
Vert.x v3 - high performance polyglot application toolkit
Vert.x v3 - high performance  polyglot application toolkitVert.x v3 - high performance  polyglot application toolkit
Vert.x v3 - high performance polyglot application toolkitSages
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Michael Barker
 
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
 
Scaling real world applications using gevent
Scaling real world applications using geventScaling real world applications using gevent
Scaling real world applications using geventaalokthemagnificient
 
pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)
pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)
pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)Wei Shan Ang
 
Docker and Containers for Development and Deployment — SCALE12X
Docker and Containers for Development and Deployment — SCALE12XDocker and Containers for Development and Deployment — SCALE12X
Docker and Containers for Development and Deployment — SCALE12XJérôme Petazzoni
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Find bottleneck and tuning in Java Application
Find bottleneck and tuning in Java ApplicationFind bottleneck and tuning in Java Application
Find bottleneck and tuning in Java Applicationguest1f2740
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 

What's hot (20)

Reactive server with netty
Reactive server with nettyReactive server with netty
Reactive server with netty
 
FPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpegFPV Streaming Server with ffmpeg
FPV Streaming Server with ffmpeg
 
Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...Distributed system coordination by zookeeper and introduction to kazoo python...
Distributed system coordination by zookeeper and introduction to kazoo python...
 
Working with multiple git repositories
Working with multiple git repositoriesWorking with multiple git repositories
Working with multiple git repositories
 
High performance json- postgre sql vs. mongodb
High performance json- postgre sql vs. mongodbHigh performance json- postgre sql vs. mongodb
High performance json- postgre sql vs. mongodb
 
Data processing with celery and rabbit mq
Data processing with celery and rabbit mqData processing with celery and rabbit mq
Data processing with celery and rabbit mq
 
Scala, docker and testing, oh my! mario camou
Scala, docker and testing, oh my! mario camouScala, docker and testing, oh my! mario camou
Scala, docker and testing, oh my! mario camou
 
Vert.x v3 - high performance polyglot application toolkit
Vert.x v3 - high performance  polyglot application toolkitVert.x v3 - high performance  polyglot application toolkit
Vert.x v3 - high performance polyglot application toolkit
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
 
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Apache ZooKeeper | Big Data Hadoop Spark Tutorial | CloudxLab
 
Scaling real world applications using gevent
Scaling real world applications using geventScaling real world applications using gevent
Scaling real world applications using gevent
 
How we use Twisted in Launchpad
How we use Twisted in LaunchpadHow we use Twisted in Launchpad
How we use Twisted in Launchpad
 
pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)
pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)
pgDay Asia 2016 - Swapping Pacemaker-Corosync for repmgr (1)
 
Docker meetup
Docker meetupDocker meetup
Docker meetup
 
Docker and Containers for Development and Deployment — SCALE12X
Docker and Containers for Development and Deployment — SCALE12XDocker and Containers for Development and Deployment — SCALE12X
Docker and Containers for Development and Deployment — SCALE12X
 
Event loop
Event loopEvent loop
Event loop
 
Lock free programming- pro tips
Lock free programming- pro tipsLock free programming- pro tips
Lock free programming- pro tips
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
Find bottleneck and tuning in Java Application
Find bottleneck and tuning in Java ApplicationFind bottleneck and tuning in Java Application
Find bottleneck and tuning in Java Application
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 

Similar to Scaling real world applications using gevent

It's all about the timing
It's all about the timingIt's all about the timing
It's all about the timingSensePost
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Usenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a ProxyUsenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a ProxyLeif Hedstrom
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningGraham Dumpleton
 
Joomla! Day Deutschland 2012 - Active Security
Joomla! Day Deutschland 2012 - Active SecurityJoomla! Day Deutschland 2012 - Active Security
Joomla! Day Deutschland 2012 - Active SecurityNicholas Dionysopoulos
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with MicronautQAware GmbH
 
Puppet Availability and Performance at 100K Nodes - PuppetConf 2014
Puppet Availability and Performance at 100K Nodes - PuppetConf 2014Puppet Availability and Performance at 100K Nodes - PuppetConf 2014
Puppet Availability and Performance at 100K Nodes - PuppetConf 2014Puppet
 
ずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケースずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケースSadayuki Furuhashi
 
Analyze Virtual Machine Overhead Compared to Bare Metal with Tracing
Analyze Virtual Machine Overhead Compared to Bare Metal with TracingAnalyze Virtual Machine Overhead Compared to Bare Metal with Tracing
Analyze Virtual Machine Overhead Compared to Bare Metal with TracingScyllaDB
 
Analyzing OS X Systems Performance with the USE Method
Analyzing OS X Systems Performance with the USE MethodAnalyzing OS X Systems Performance with the USE Method
Analyzing OS X Systems Performance with the USE MethodBrendan Gregg
 
Performance tests with gatling
Performance tests with gatlingPerformance tests with gatling
Performance tests with gatlingSoftwareMill
 
分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計Sadayuki Furuhashi
 
[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기
[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기
[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기Ji-Woong Choi
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.jsPiotr Pelczar
 
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMUSFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMULinaro
 
Scaling sql server 2014 parallel insert
Scaling sql server 2014 parallel insertScaling sql server 2014 parallel insert
Scaling sql server 2014 parallel insertChris Adkin
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialTom Croucher
 

Similar to Scaling real world applications using gevent (20)

It's all about the timing
It's all about the timingIt's all about the timing
It's all about the timing
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Usenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a ProxyUsenix LISA 2012 - Choosing a Proxy
Usenix LISA 2012 - Choosing a Proxy
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
 
Joomla! Day Deutschland 2012 - Active Security
Joomla! Day Deutschland 2012 - Active SecurityJoomla! Day Deutschland 2012 - Active Security
Joomla! Day Deutschland 2012 - Active Security
 
Getput suite
Getput suiteGetput suite
Getput suite
 
Microservices with Micronaut
Microservices with MicronautMicroservices with Micronaut
Microservices with Micronaut
 
Puppet Availability and Performance at 100K Nodes - PuppetConf 2014
Puppet Availability and Performance at 100K Nodes - PuppetConf 2014Puppet Availability and Performance at 100K Nodes - PuppetConf 2014
Puppet Availability and Performance at 100K Nodes - PuppetConf 2014
 
ずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケースずばり動く!kumofs と ずばり動かないケース
ずばり動く!kumofs と ずばり動かないケース
 
Analyze Virtual Machine Overhead Compared to Bare Metal with Tracing
Analyze Virtual Machine Overhead Compared to Bare Metal with TracingAnalyze Virtual Machine Overhead Compared to Bare Metal with Tracing
Analyze Virtual Machine Overhead Compared to Bare Metal with Tracing
 
Analyzing OS X Systems Performance with the USE Method
Analyzing OS X Systems Performance with the USE MethodAnalyzing OS X Systems Performance with the USE Method
Analyzing OS X Systems Performance with the USE Method
 
Rails Performance
Rails PerformanceRails Performance
Rails Performance
 
Performance tests with gatling
Performance tests with gatlingPerformance tests with gatling
Performance tests with gatling
 
分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計分散Key-valueストアkumofsの思想と設計
分散Key-valueストアkumofsの思想と設計
 
[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기
[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기
[오픈소스컨설팅] 프로메테우스 모니터링 살펴보고 구성하기
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMUSFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
SFO15-202: Towards Multi-Threaded Tiny Code Generator (TCG) in QEMU
 
Scaling sql server 2014 parallel insert
Scaling sql server 2014 parallel insertScaling sql server 2014 parallel insert
Scaling sql server 2014 parallel insert
 
OSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js TutorialOSCON 2011 - Node.js Tutorial
OSCON 2011 - Node.js Tutorial
 
RubyKaigi 2014: ServerEngine
RubyKaigi 2014: ServerEngineRubyKaigi 2014: ServerEngine
RubyKaigi 2014: ServerEngine
 

Recently uploaded

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
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 

Recently uploaded (20)

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...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
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
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 

Scaling real world applications using gevent

  • 1. Concurrency & Gevent Scaling Real World Applications
  • 2. Concurrency handling a number of things at the same time Examples: (Incoming) WebServers, Database Servers (Outgoing) SSH Mux
  • 3. SSH Mux ● Execute a command on a remote SSH server ● Handle concurrent SSH Clients ● Command execution time varies from seconds to days ● Command execution happens on remote servers, SSH mux is I/O bound
  • 4. SSH Client 1. Init session 2. Authenticate 3. Get a channel 4. Issue command 5. Read output
  • 5. Need Concurrency? ● Process blocks on read() ● No new connections can be inititated ● Need ability to handle multiple clients at the same time
  • 6. Multiprocessing ● One process is the master ● Master can spawn workers ● Each worker handles one request at a time ● Pre-forked pool of workers
  • 8. SSH Mux Memory Usage ssh mux memory usage 600 500 400 Memory (MB) 300 Processes 200 100 0 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 # Concurrent Reqs
  • 9. SSH Mux Performace ssh mux performance sheet 160 140 120 100 Time(s) 80 Processes 60 40 20 0 20 40 80 150 200 400 800 1200 1500 1800 2100 # Concurrent Reqs
  • 10. Multiprocessing yay ● Easy to get started ● OS guaranteed process isolation & fairness ● Covers up for misbehaving workers ● Add more concurrency by adding more workers ● Convenient when numbers are smaller numbers
  • 11. Multiprocessing nay ● Concurrency limited by number of processes ● Memory heavy ● Implicit scheduling ● Synchronization is not trivial
  • 12. More Concurrency? ● Command execution is happening on remote servers, we are mostly blocked on I/O ● Handle multiple I/O in a single process?
  • 13. Gevent gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libevent event loop.
  • 14. Greenlets ● Lightweight 'threads' - not OS threads ● Explicit scheduling - Cooperative ● Minimal stack ● Application decides execution flow ● Easy to synchronize/ Avoid locks ● All run inside one process
  • 15. Libevent ● Use fastest mechanism to poll (portable) ● Fast Event loop ● In Gevent, event loop runs in a greenlet (event hub) ● Instead of blocking, greenlets switch to event hub ● It's all done behind the scene
  • 16. Monkey Patching Monkey patching Modifies behaviour of blocking calls such as select, sleep to non-blocking Patches the python standard socket library
  • 17. Gevent ● Greenlet 1 is running ● Greenlet 2 and 3 are ready
  • 18. Gevent ● Greenlet 1 has to wait for read ● Greenlet 1 switches to Event hub
  • 19. Gevent ● Event hub switches to Greenlet 3
  • 20. Gevent ● Greenlet 2 runs
  • 21. Gevent ● Greenlet 2 wants to sleep ● Greenlet 2 switches to Event hub
  • 22. Gevent ● Greenlet 1 data has come, moved to ready state ● Eventhub switches to Greenlet 3
  • 23. Gevent ● Greenlet 3 runs
  • 24. Gevent ● When Greenlet 1 resumes, its from next instruction ● It's as if it were a blocking call
  • 25. Green SSH Client 1. Init session 2. Authenticate 3. Get a channel 4. Issue command 5. Read output
  • 27. Going Concurrent Use pre-forked processes to use all cores
  • 28. Memory usage ssh mux memory usage 45 40 35 30 Memory(MB) 25 Gevent+Processes 20 15 10 5 0 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 # Concurrent Reqs
  • 29. SSH Mux Performace ssh mux performace chart 70 60 50 40 Time(s) Gevent+Processes 30 20 10 0 20 40 80 150 200 400 800 1200 1500 1800 2100 # Concurrent Reqs
  • 30. SSH Mux memory usage ssh mux memory usage 600 500 400 Memory(MB) Processes 300 Gevent 200 100 0 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 # Concurrent Reqs
  • 31. SSH Mux Performance ssh mux performance sheet 160 140 120 100 Processes Time(s) 80 Gevent+Processes 60 40 20 0 20 40 80 150 200 400 800 1200 1500 1800 2100 # Concurrent Reqs
  • 32. Gevent yay! ● Untwist – write linear non blocking code ● Explicit scheduling, dictate the execution flow ● Timeouts ● Events, AsyncResults for Synchronization ● gevent.wsgi ● Pre-spawned pool of greenlets
  • 33. Gevent beware of ● No multicore support ● Not great for CPU bound applications ● Third party libs must be green (non blocking) ● Misbehaving workers can be lethal ● No fairness when it comes to scheduling
  • 34. Take Away ● Gevent lets you write asynchronous code in a synchronous manner ● No multicore support, still need multiprocessing ● Not so great for CPU bound applications ● Split your application into CPU bound and IO bound parts ● Be willing to contribute patches ● Code available at git@github.com:aaloksood/pyexamples.git
  • 35. Thank you That's all folks!
  • 36. Countdown Timer ● Count down from 200000000 ● Split work among workers
  • 37. Threads Multithreading wonder 25 20 15 1 Core Time(s) 4 cores 10 5 0 1 2 3 4 5 6 7 8 9 10 # Workers
  • 38. One core Execution time One Core 14.5 14 13.5 13 Processes 1 Core Time (s) 12.5 Gevent_1 12 Gevent_4 11.5 11 10.5 1 2 3 4 5 6 7 8 9 10 # Workers
  • 39. Four cores Execution time 4 cores 25 20 Process 15 Threads Time(s) Gevent_1 10 Gevent_4 5 0 1 2 3 4 5 6 7 8 9 10 # Workers