SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
Advantages and Disadvantages
Of Using
Python’s Asynchronous
Frameworks for Web Services
Ryan C. Johnson
https://www.linkedin.com/in/ryanjohnson5
Key Asynchronous Concepts
● The best introduction to the asynchronous model is by my friend and former
colleague Dave Peticolas (highly recommended):
http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/
● “The fundamental idea behind the asynchronous model is that an
asynchronous program, when faced with a task that would normally block in a
synchronous program, will instead execute some other task that can still make
progress.”
Key Asynchronous Concepts (cont.)
● Event-based
● Locus-of-control is the event loop
● I/O calls are non-blocking (rely on events to signal when data is
ready)
● Conditions for async outperforming sync (Dave Peticolas):
○ “The tasks perform lots of I/O, causing a synchronous program to
waste lots of time blocking when other tasks could be running.”
○ “There are a large number of tasks so there is likely always at least
one task that can make progress.”
○ “The tasks are largely independent from one another so there is little
need for inter-task communication (and thus for one task to wait upon
another).”
Example
Synchronous:
def get(...):
...
results1 = io_call_1(...)
results2 = io_call_2(...)
...
Asynchronous (Twisted):
@inlineCallbacks
def get(...):
...
results1 = yield io_call_1(...)
results2 = yield io_call_2(...)
...
The Typical Web Service Provides Ideal Conditions
● HTTP requests are handled independently from each other
● The handling of HTTP requests typically involves one or more I/O calls to
one or more databases or other web services, and in most real-world
cases, the majority of time is spent waiting on these I/O calls
● The service is constantly accepting requests or should be available for
accepting requests
Key advantages
● Efficiency
○ Handle an equivalent number of requests with fewer/smaller servers
compared to sync
○ Scalability limited by the number of open socket connections within a
single process vs. the number of concurrent threads/processes for
sync web frameworks (thousands to tens-of-thousands for async vs.
tens to hundreds for sync)
○ A small server (in terms of CPU and memory) running an async web
service in a single process will match and often outperform a larger
server running a sync web service using tens to hundreds of
threads/processes
Key advantages (cont.)
● Able to handle large numbers of concurrent, long-lived requests
○ Only burn a socket, not a thread/process
○ This can be the determining factor in choosing async over sync
○ Allows efficient “push” functionality via web sockets, EventSource or
other long-lived connections
○ Gavin Roy at PyCon 2012 (then CTO of MyYearBook.com): “We do
more traffic and volume through this [Tornado] than the rest of our site
infrastructure combined...8 servers as opposed to 400-500.”
(http://pyvideo.org/video/720/more-than-just-a-pretty-web-framework-t
he-tornad)
Key disadvantage
A single async process has a more complex model for thinking about
shared state and how it can change than a single sync process
● Must keep in mind that shared state can change between the moments of
yielding control to the event loop and returning control back to your code
Simple example
shared = []
@inlineCallbacks
def get(self, id):
shared.append(id)
print ‘pre yield for get({id}): shared={shared}’.format(id=id, shared=shared)
obj = yield async_get_from_db(id)
print ‘post yield for get({id}): shared={shared}’.format(id-id, shared=shared)
Possible sequence of events:
1. An incoming GET request is handled, calling get with id=1
2. Print pre yield for get(1): shared=[1]
3. Yield to the event loop after calling async_get_from_db(1)
4. While waiting for the result of async_get_from_db(1), the event loop handles the next request, calling get
with id=2
5. Print pre yield for get(2): shared=[1, 2]
6. Yield to the event loop after calling async_get_from_db(2)
7. While waiting for the result of async_get_from_db(2), the event loop sees that the result from
async_get_from_db(1) is ready, and returns control back to the “paused” execution of get(1)
8. Print post yield get(1): shared = [1, 2] ← within the call to get(1) the shared state has
changed between the yield to the event loop and the return of the result
Asynchronous Frameworks
● Implicit (yields to the event loop occur implicitly when an I/O call is made)
○ gevent
● Explicit (yields to the event loop controlled by the programmer)
○ Twisted
■ Cyclone (Tornado API on Twisted’s event loop)
■ Klein (Flask-like API on Twisted Web)
■ Tornado (in Twisted-compatibility mode)
○ Tornado
○ asyncio (Python 3.4+)
■ aiohttp
■ Tornado (running on the asyncio event loop)
Implicit Style - Advantages
● Coding syntax and style is same as synchronous (when an I/O call is made,
control implicitly returns to the event loop to work on another request or event)
● Compatible with the huge ecosystem of popular synchronous Python
packages that perform I/O (e.g., SQLAlchemy)
○ This is a huge advantage over the explicit style
○ Assumes that the socket module is used for I/O, so when it is
monkey-patched (using gevent), you will no longer block on I/O calls but
instead yield control to the event loop
○ Python packages that perform I/O but don’t use the socket module can
still be used, but they will block on I/O
Implicit Style - Disadvantages
● Lack of explicit yielding syntax fails to indicate the points in the code where
shared state may change:
https://glyph.twistedmatrix.com/2014/02/unyielding.html
● Lack of control over yielding to the event loop prevents the ability to launch
multiple I/O calls before yielding (impossible to launch independent I/O
tasks in parallel)
○ In my opinion, this is the biggest disadvantage, but only if multiple and
independent I/O tasks could be performed
○ For example, the following is impossible to do using the implicit style:
@inlineCalbacks
def get(...):
deferred1 = io_call_1(...)
deferred2 = io_call_2(...)
result1 = yield deferred1
result2 = yield deferred2
Explicit Style - Advantages
● Explicit yielding syntax indicates points at which shared state may change
● Complete control over yielding to the event loop allows the ability to launch
multiple I/O calls before yielding (parallelism of independent I/O tasks)
○ In my opinion, this is the biggest advantage, but only if multiple and
independent I/O tasks could be performed
○ For example:
@inlineCalbacks
def get(...):
deferred1 = io_call_1(...)
deferred2 = io_call_2(...)
result1 = yield deferred1
result2 = yield deferred2
Explicit Style - Disadvantages
● Different syntax and coding style than synchronous code
● Much smaller and sometimes less mature ecosystem of Python packages
can be used
○ This is a huge disadvantage
○ For example, it precludes the use of SQLAlchemy
● If not using Python 3.5 with its async and await keywords, or if there is
no generator-style decorator like Twisted’s @inlineCallbacks or
Tornado’s @coroutine, any significant amount of code becomes an
unreadable mess of callbacks
Generator-Based Decorators are Essential
def func():
deferred = io_call()
def on_result(result):
print result
deferred.addCallback(on_result)
return deferred
becomes readable and very similar to the synchronous style:
@inlineCallbacks
def func():
result = yield io_call()
print result
Conclusions
● Large (10x to 100x) performance/efficiency gains for I/O bound web
services
● Implicit style recommended for most cases (assuming the monkey-patch of
the socket module does the trick), as there is very little required to reap
the benefits (for example, simple configuration of uWSGI or gunicorn to
use gevent)
● Explicit style only recommended if the gains from launching multiple I/O
tasks in parallel outweigh the losses due to a smaller and sometimes
less-mature ecosystem of Python packages and a more complex coding
style

Weitere ähnliche Inhalte

Andere mochten auch

Introduction to Python and Web Programming
Introduction to Python and Web ProgrammingIntroduction to Python and Web Programming
Introduction to Python and Web ProgrammingDavid Neiss
 
Python and the Web
Python and the WebPython and the Web
Python and the Webpycontw
 
Why Python Web Frameworks Are Changing the Web
Why Python Web Frameworks Are Changing the WebWhy Python Web Frameworks Are Changing the Web
Why Python Web Frameworks Are Changing the Webjoelburton
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
Зоопарк python веб-фреймворков
Зоопарк python веб-фреймворковЗоопарк python веб-фреймворков
Зоопарк python веб-фреймворковPyNSK
 
Python talk web frameworks
Python talk web frameworksPython talk web frameworks
Python talk web frameworksKat Chuang
 
Чем Python плох для стартапа?
Чем Python плох для стартапа?Чем Python плох для стартапа?
Чем Python плох для стартапа?PyNSK
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programmingSudheer Kiran
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Asynchronous Python with Twisted
Asynchronous Python with TwistedAsynchronous Python with Twisted
Asynchronous Python with TwistedAdam Englander
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerGeek Advisor Freddy
 

Andere mochten auch (20)

C language tutorial
C language tutorialC language tutorial
C language tutorial
 
Introduction to Python and Web Programming
Introduction to Python and Web ProgrammingIntroduction to Python and Web Programming
Introduction to Python and Web Programming
 
Python and the Web
Python and the WebPython and the Web
Python and the Web
 
Snakes on the Web
Snakes on the WebSnakes on the Web
Snakes on the Web
 
Why Python Web Frameworks Are Changing the Web
Why Python Web Frameworks Are Changing the WebWhy Python Web Frameworks Are Changing the Web
Why Python Web Frameworks Are Changing the Web
 
Спецификация WSGI (PEP-333)
Спецификация WSGI (PEP-333)Спецификация WSGI (PEP-333)
Спецификация WSGI (PEP-333)
 
bin'Abdullah_JACM 2015
bin'Abdullah_JACM 2015bin'Abdullah_JACM 2015
bin'Abdullah_JACM 2015
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
Зоопарк python веб-фреймворков
Зоопарк python веб-фреймворковЗоопарк python веб-фреймворков
Зоопарк python веб-фреймворков
 
Python talk web frameworks
Python talk web frameworksPython talk web frameworks
Python talk web frameworks
 
Чем Python плох для стартапа?
Чем Python плох для стартапа?Чем Python плох для стартапа?
Чем Python плох для стартапа?
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Python on Rails 2014
Python on Rails 2014Python on Rails 2014
Python on Rails 2014
 
Python class
Python classPython class
Python class
 
Asynchronous Python with Twisted
Asynchronous Python with TwistedAsynchronous Python with Twisted
Asynchronous Python with Twisted
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocer
 

Ähnlich wie Async Web Frameworks in Python

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingJuti Noppornpitak
 
Understanding concurrency
Understanding concurrencyUnderstanding concurrency
Understanding concurrencyAnshul Sharma
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Ramith Jayasinghe
 
Meetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaCMeetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaCDamienCarpy
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performanceAndrew Rota
 
Concurrency, Parallelism And IO
Concurrency,  Parallelism And IOConcurrency,  Parallelism And IO
Concurrency, Parallelism And IOPiyush Katariya
 
Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...
Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...
Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...Kaxil Naik
 
Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problemJose Galarza
 
Programming for Performance
Programming for PerformanceProgramming for Performance
Programming for PerformanceCris Holdorph
 
Flow based programming in golang
Flow based programming in golangFlow based programming in golang
Flow based programming in golangAnton Stepanenko
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...
KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...
KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...confluent
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad WoodOrtus Solutions, Corp
 
The working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор ТурскийThe working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор ТурскийSigma Software
 

Ähnlich wie Async Web Frameworks in Python (20)

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Why Concurrency is hard ?
Why Concurrency is hard ?Why Concurrency is hard ?
Why Concurrency is hard ?
 
Understanding concurrency
Understanding concurrencyUnderstanding concurrency
Understanding concurrency
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?
 
Meetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaCMeetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaC
 
Ten practical ways to improve front-end performance
Ten practical ways to improve front-end performanceTen practical ways to improve front-end performance
Ten practical ways to improve front-end performance
 
Concurrency, Parallelism And IO
Concurrency,  Parallelism And IOConcurrency,  Parallelism And IO
Concurrency, Parallelism And IO
 
Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...
Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...
Apache Airflow in the Cloud: Programmatically orchestrating workloads with Py...
 
Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problem
 
Programming for Performance
Programming for PerformanceProgramming for Performance
Programming for Performance
 
Nodejs
NodejsNodejs
Nodejs
 
Flow based programming in golang
Flow based programming in golangFlow based programming in golang
Flow based programming in golang
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...
KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...
KafkaConsumer - Decoupling Consumption and Processing for Better Resource Uti...
 
Netty training
Netty trainingNetty training
Netty training
 
Threads
ThreadsThreads
Threads
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Wood
 
The working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор ТурскийThe working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор Турский
 

Kürzlich hochgeladen

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 

Kürzlich hochgeladen (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

Async Web Frameworks in Python

  • 1. Advantages and Disadvantages Of Using Python’s Asynchronous Frameworks for Web Services Ryan C. Johnson https://www.linkedin.com/in/ryanjohnson5
  • 2. Key Asynchronous Concepts ● The best introduction to the asynchronous model is by my friend and former colleague Dave Peticolas (highly recommended): http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/ ● “The fundamental idea behind the asynchronous model is that an asynchronous program, when faced with a task that would normally block in a synchronous program, will instead execute some other task that can still make progress.”
  • 3. Key Asynchronous Concepts (cont.) ● Event-based ● Locus-of-control is the event loop ● I/O calls are non-blocking (rely on events to signal when data is ready) ● Conditions for async outperforming sync (Dave Peticolas): ○ “The tasks perform lots of I/O, causing a synchronous program to waste lots of time blocking when other tasks could be running.” ○ “There are a large number of tasks so there is likely always at least one task that can make progress.” ○ “The tasks are largely independent from one another so there is little need for inter-task communication (and thus for one task to wait upon another).”
  • 4. Example Synchronous: def get(...): ... results1 = io_call_1(...) results2 = io_call_2(...) ... Asynchronous (Twisted): @inlineCallbacks def get(...): ... results1 = yield io_call_1(...) results2 = yield io_call_2(...) ...
  • 5. The Typical Web Service Provides Ideal Conditions ● HTTP requests are handled independently from each other ● The handling of HTTP requests typically involves one or more I/O calls to one or more databases or other web services, and in most real-world cases, the majority of time is spent waiting on these I/O calls ● The service is constantly accepting requests or should be available for accepting requests
  • 6. Key advantages ● Efficiency ○ Handle an equivalent number of requests with fewer/smaller servers compared to sync ○ Scalability limited by the number of open socket connections within a single process vs. the number of concurrent threads/processes for sync web frameworks (thousands to tens-of-thousands for async vs. tens to hundreds for sync) ○ A small server (in terms of CPU and memory) running an async web service in a single process will match and often outperform a larger server running a sync web service using tens to hundreds of threads/processes
  • 7. Key advantages (cont.) ● Able to handle large numbers of concurrent, long-lived requests ○ Only burn a socket, not a thread/process ○ This can be the determining factor in choosing async over sync ○ Allows efficient “push” functionality via web sockets, EventSource or other long-lived connections ○ Gavin Roy at PyCon 2012 (then CTO of MyYearBook.com): “We do more traffic and volume through this [Tornado] than the rest of our site infrastructure combined...8 servers as opposed to 400-500.” (http://pyvideo.org/video/720/more-than-just-a-pretty-web-framework-t he-tornad)
  • 8. Key disadvantage A single async process has a more complex model for thinking about shared state and how it can change than a single sync process ● Must keep in mind that shared state can change between the moments of yielding control to the event loop and returning control back to your code
  • 9. Simple example shared = [] @inlineCallbacks def get(self, id): shared.append(id) print ‘pre yield for get({id}): shared={shared}’.format(id=id, shared=shared) obj = yield async_get_from_db(id) print ‘post yield for get({id}): shared={shared}’.format(id-id, shared=shared) Possible sequence of events: 1. An incoming GET request is handled, calling get with id=1 2. Print pre yield for get(1): shared=[1] 3. Yield to the event loop after calling async_get_from_db(1) 4. While waiting for the result of async_get_from_db(1), the event loop handles the next request, calling get with id=2 5. Print pre yield for get(2): shared=[1, 2] 6. Yield to the event loop after calling async_get_from_db(2) 7. While waiting for the result of async_get_from_db(2), the event loop sees that the result from async_get_from_db(1) is ready, and returns control back to the “paused” execution of get(1) 8. Print post yield get(1): shared = [1, 2] ← within the call to get(1) the shared state has changed between the yield to the event loop and the return of the result
  • 10. Asynchronous Frameworks ● Implicit (yields to the event loop occur implicitly when an I/O call is made) ○ gevent ● Explicit (yields to the event loop controlled by the programmer) ○ Twisted ■ Cyclone (Tornado API on Twisted’s event loop) ■ Klein (Flask-like API on Twisted Web) ■ Tornado (in Twisted-compatibility mode) ○ Tornado ○ asyncio (Python 3.4+) ■ aiohttp ■ Tornado (running on the asyncio event loop)
  • 11. Implicit Style - Advantages ● Coding syntax and style is same as synchronous (when an I/O call is made, control implicitly returns to the event loop to work on another request or event) ● Compatible with the huge ecosystem of popular synchronous Python packages that perform I/O (e.g., SQLAlchemy) ○ This is a huge advantage over the explicit style ○ Assumes that the socket module is used for I/O, so when it is monkey-patched (using gevent), you will no longer block on I/O calls but instead yield control to the event loop ○ Python packages that perform I/O but don’t use the socket module can still be used, but they will block on I/O
  • 12. Implicit Style - Disadvantages ● Lack of explicit yielding syntax fails to indicate the points in the code where shared state may change: https://glyph.twistedmatrix.com/2014/02/unyielding.html ● Lack of control over yielding to the event loop prevents the ability to launch multiple I/O calls before yielding (impossible to launch independent I/O tasks in parallel) ○ In my opinion, this is the biggest disadvantage, but only if multiple and independent I/O tasks could be performed ○ For example, the following is impossible to do using the implicit style: @inlineCalbacks def get(...): deferred1 = io_call_1(...) deferred2 = io_call_2(...) result1 = yield deferred1 result2 = yield deferred2
  • 13. Explicit Style - Advantages ● Explicit yielding syntax indicates points at which shared state may change ● Complete control over yielding to the event loop allows the ability to launch multiple I/O calls before yielding (parallelism of independent I/O tasks) ○ In my opinion, this is the biggest advantage, but only if multiple and independent I/O tasks could be performed ○ For example: @inlineCalbacks def get(...): deferred1 = io_call_1(...) deferred2 = io_call_2(...) result1 = yield deferred1 result2 = yield deferred2
  • 14. Explicit Style - Disadvantages ● Different syntax and coding style than synchronous code ● Much smaller and sometimes less mature ecosystem of Python packages can be used ○ This is a huge disadvantage ○ For example, it precludes the use of SQLAlchemy ● If not using Python 3.5 with its async and await keywords, or if there is no generator-style decorator like Twisted’s @inlineCallbacks or Tornado’s @coroutine, any significant amount of code becomes an unreadable mess of callbacks
  • 15. Generator-Based Decorators are Essential def func(): deferred = io_call() def on_result(result): print result deferred.addCallback(on_result) return deferred becomes readable and very similar to the synchronous style: @inlineCallbacks def func(): result = yield io_call() print result
  • 16. Conclusions ● Large (10x to 100x) performance/efficiency gains for I/O bound web services ● Implicit style recommended for most cases (assuming the monkey-patch of the socket module does the trick), as there is very little required to reap the benefits (for example, simple configuration of uWSGI or gunicorn to use gevent) ● Explicit style only recommended if the gains from launching multiple I/O tasks in parallel outweigh the losses due to a smaller and sometimes less-mature ecosystem of Python packages and a more complex coding style