SlideShare a Scribd company logo
1 of 39
Download to read offline
19 Dec 2013
@lukmdo

Python Asynchronous I/O
asynchronous landscape refresher

Photo by Jake Brown used under CC BY 2.0/“Mono+Balance”
Agenda ⏰10 minutes
!

•

Background (can skip)

•

Problem statement

•

“Current state”

•

Python 3 async horizon (by examples)
Warmup
!

•

CPU IO (CPU bound)

•

Pure IO (IO bound)

•

C10k

•

Concurrency vs. parallelism
Warmup
!

•

Lazy schedule a task for later

•

Avoid waiting for IO (i.e. 2x DB queries)

•

Solve embarrassingly parallel problems

•

Control and manage status of task
PEP index brief
PEP

Name

Status

Doc

PEP 255

Simple Generators

2.2 ✔

»»

PEP 342

Coroutines via Enhanced Generators

2.5 ✔

»

PEP 380

Syntax for Delegating to a Subgenerator

3.3 ✔

»

PEP 3148

Futures - execute computations asynchronously

3.2 ✔

»

PEP 3153

Asynchronous IO support

3.3 ✔

»

PEP 3156

Asynchronous IO Support Rebooted: the
"asyncio" Module

3.4 ✔

»
PEP index brief
PEP

Name

PEP 219

Stackless Python

❙❙

PEP 220

Coroutines, Generators, Continuations

✗

PEP 319

Python Synchronize/Asynchronize Block

✗

PEP 3145
PEP 3152

Asynchronous I/O For subprocess.Popen
Cofunctions

Status

❙❙
❙❙
stackless

In the Class
concurrent.futures
threading
tornado
greenlet
subpocess
eventlet
celery
twisted
pyuv
gevent
shed asyncio
asyncore
In the Class

asyncio
stackless

In the Class
concurrent.futures
threading
tornado
greenlet
subpocess
eventlet
celery
twisted
pyuv
gevent
shed asyncio
asyncore
In the Class
concurrent.futures
threading
tornado
subpocess
celery
twisted
asyncio
Slang*
•

future ~ result wrapper

•

coro != generator function (but close)

•

task = coro wrapped in Future

•

result = yield from future/coro
(to wait for result)
new* old style concurrency
def update_foo(data):
data1 = run_query1(data)
data2 = run_query2(data)
!

data3 = process(data1, data2)
run_update_query(data3)
run_update_cache(data3)
!

return ["OK"]
new* old style concurrency
def update_foo(data):
data1 = run_query1(data)
data2 = run_query2(data)
!

data3 = process(data1, data2)
run_update_query(data3)
run_update_cache(data3)
!

return ["OK"]
new* old style concurrency
new* old style concurrency
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
data1 = yield from run_query1(data)
data2 = yield from run_query2(data)
!

data3 = yield from process(data1, data2)
yield from run_update_query(data3)
loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
data1 = yield from run_query1(data)
data2 = yield from run_query2(data)
!

data3 = yield from process(data1, data2)
yield from run_update_query(data3)
loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
data1 = yield from run_query1(data)
data2 = yield from run_query2(data)
!

data3 = yield from process(data1, data2)
yield from run_update_query(data3)
loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
new* old style concurrency
new* old style concurrency
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
future1 = asyncio.async(run_query1(data))
future2 = asyncio.async(run_query2(data))
!

results = yield from asyncio.gather(
future1, future2)
data3 = yield from process(*results)
yield from run_update_query(data3)
!

loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
future1 = asyncio.async(run_query1(data))
future2 = asyncio.async(run_query2(data))
!

results = yield from asyncio.gather(
future1, future2)
data3 = yield from process(*results)
yield from run_update_query(data3)
!

loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
@asyncio.coroutine
def update_foo(data, loop):
future1 = asyncio.async(run_query1(data))
future2 = asyncio.async(run_query2(data))
!

results = yield from asyncio.gather(
future1, future2)
data3 = yield from process(*results)
yield from run_update_query(data3)
!

loop.call_soon(update_cache, data3)
!

return ["OK"]
new* old style concurrency
new* old style concurrency
new* old style concurrency
new* old style concurrency
def api_calls():
data1 = call_api1()
data2 = call_api2()
data3 = call_api3()
!

return [data1, data2, data3]
new* old style concurrency
def api_calls():
data1 = call_api1()
data3 = call_api2()
data3 = call_api3()
!

return [data1, data2, data3]
new* old style concurrency
new* old style concurrency
new* old style concurrency
@asyncio.coroutine
def api_calls():
future1 = asyncio.Task(call_api1())
future2 = asyncio.Task(call_api2())
future3 = asyncio.Task(call_api3())
!

return ( yield from asyncio.gather(
future1, future2, future3) )
new* old style concurrency
@asyncio.coroutine
def api_calls():
future1 = asyncio.Task(call_api1())
future2 = asyncio.Task(call_api2())
future3 = asyncio.Task(call_api3())
!

return ( yield from asyncio.gather(
future1, future2, future3) )
new* old style concurrency
new* old style concurrency
new* old style concurrency
new* old style concurrency
from aiohttp import request
!

@asyncio.coroutine
def call_api():
url = "URL"
response = yield from request('GET', url)
return (yield from response.read())
Takeaways
•

concurrency patterns

•

asyncio bootstrap

•

early adopters
Links
•

Video by BDFL Tulip: Async I/O for Python 3

•

Video by BDFL PyCon US 2013 Keynote

•

Code by Nikolay Kim aiohttp

•

Code by google appengine-pipeline

•

Code by google ndb tasklets

Photo by Jake Brown used under CC BY 2.0/“Mono+Tile”

More Related Content

What's hot

Something about Golang
Something about GolangSomething about Golang
Something about GolangAnton Arhipov
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Futureemptysquare
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладкаDEVTYPE
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopSaša Tatar
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Chih-Hsuan Kuo
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoChih-Hsuan Kuo
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistAnton Arhipov
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системеDEVTYPE
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistAnton Arhipov
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
 

What's hot (20)

Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка4. Обработка ошибок, исключения, отладка
4. Обработка ошибок, исключения, отладка
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
Explaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to Come
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with JavassistRiga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Rust
RustRust
Rust
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with JavassistJavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
 

Viewers also liked

Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Python Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Geventemptysquare
 
asyncio community, one year later
asyncio community, one year laterasyncio community, one year later
asyncio community, one year laterVictor Stinner
 
LvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioLvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioRoman Rader
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with geventMahendra M
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Feihong Hsu
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
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
 
Practical continuous quality gates for development process
Practical continuous quality gates for development processPractical continuous quality gates for development process
Practical continuous quality gates for development processAndrii Soldatenko
 
Async Tasks with Django Channels
Async Tasks with Django ChannelsAsync Tasks with Django Channels
Async Tasks with Django ChannelsAlbert O'Connor
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4Binay Kumar Ray
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?Andrii Soldatenko
 
Python as number crunching code glue
Python as number crunching code gluePython as number crunching code glue
Python as number crunching code glueJiahao Chen
 
Building social network with Neo4j and Python
Building social network with Neo4j and PythonBuilding social network with Neo4j and Python
Building social network with Neo4j and PythonAndrii Soldatenko
 

Viewers also liked (20)

Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Python Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and GeventPython Performance: Single-threaded, multi-threaded, and Gevent
Python Performance: Single-threaded, multi-threaded, and Gevent
 
asyncio community, one year later
asyncio community, one year laterasyncio community, one year later
asyncio community, one year later
 
LvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncioLvivPy4 - Threading vs asyncio
LvivPy4 - Threading vs asyncio
 
Scaling Django with gevent
Scaling Django with geventScaling Django with gevent
Scaling Django with gevent
 
Asynchronous I/O in Python 3
Asynchronous I/O in Python 3Asynchronous I/O in Python 3
Asynchronous I/O in Python 3
 
Tulip
TulipTulip
Tulip
 
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
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Python class
Python classPython class
Python class
 
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
 
Python master class 3
Python master class 3Python master class 3
Python master class 3
 
Practical continuous quality gates for development process
Practical continuous quality gates for development processPractical continuous quality gates for development process
Practical continuous quality gates for development process
 
Async Tasks with Django Channels
Async Tasks with Django ChannelsAsync Tasks with Django Channels
Async Tasks with Django Channels
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Regexp
RegexpRegexp
Regexp
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?
 
Python as number crunching code glue
Python as number crunching code gluePython as number crunching code glue
Python as number crunching code glue
 
Building social network with Neo4j and Python
Building social network with Neo4j and PythonBuilding social network with Neo4j and Python
Building social network with Neo4j and Python
 

Similar to Python Async IO Horizon

Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyAerospike
 
Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!Cisco DevNet
 
Insomniac Physics
Insomniac PhysicsInsomniac Physics
Insomniac PhysicsSlide_N
 
Reproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and NextflowReproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and Nextflowinside-BigData.com
 
What you need to know for postgresql operation
What you need to know for postgresql operationWhat you need to know for postgresql operation
What you need to know for postgresql operationAnton Bushmelev
 
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data ArtisansApache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data ArtisansEvention
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
Diving into Delta Lake: Unpacking the Transaction Log
Diving into Delta Lake: Unpacking the Transaction LogDiving into Delta Lake: Unpacking the Transaction Log
Diving into Delta Lake: Unpacking the Transaction LogDatabricks
 
Data Structures: Stack Operations
Data Structures:    Stack OperationsData Structures:    Stack Operations
Data Structures: Stack OperationsGopikaS12
 
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...Paris Carbone
 
What’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributorWhat’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributorMasahiko Sawada
 
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...Amazon Web Services
 
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...Flink Forward
 
AWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.pptAWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.pptbugzbinny
 
2021 10-13 i ox query processing
2021 10-13 i ox query processing2021 10-13 i ox query processing
2021 10-13 i ox query processingAndrew Lamb
 
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOxInfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOxInfluxData
 
CS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved ExamplesCS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved Examplesramyaranjith
 

Similar to Python Async IO Horizon (20)

Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
 
Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!Automating with NX-OS: Let's Get Started!
Automating with NX-OS: Let's Get Started!
 
Insomniac Physics
Insomniac PhysicsInsomniac Physics
Insomniac Physics
 
Reproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and NextflowReproducible Computational Pipelines with Docker and Nextflow
Reproducible Computational Pipelines with Docker and Nextflow
 
What you need to know for postgresql operation
What you need to know for postgresql operationWhat you need to know for postgresql operation
What you need to know for postgresql operation
 
Using AWR for IO Subsystem Analysis
Using AWR for IO Subsystem AnalysisUsing AWR for IO Subsystem Analysis
Using AWR for IO Subsystem Analysis
 
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data ArtisansApache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
Apache Flink: Better, Faster & Uncut - Piotr Nowojski, data Artisans
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Diving into Delta Lake: Unpacking the Transaction Log
Diving into Delta Lake: Unpacking the Transaction LogDiving into Delta Lake: Unpacking the Transaction Log
Diving into Delta Lake: Unpacking the Transaction Log
 
Data Structures: Stack Operations
Data Structures:    Stack OperationsData Structures:    Stack Operations
Data Structures: Stack Operations
 
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
State Management in Apache Flink : Consistent Stateful Distributed Stream Pro...
 
What’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributorWhat’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributor
 
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
(PFC303) Milliseconds Matter: Design, Deploy, and Operate Your Application fo...
 
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
Flink Forward San Francisco 2018: Stefan Richter - "How to build a modern str...
 
AWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.pptAWR, ADDM, ASH, Metrics and Advisors.ppt
AWR, ADDM, ASH, Metrics and Advisors.ppt
 
Python 3
Python 3Python 3
Python 3
 
2021 10-13 i ox query processing
2021 10-13 i ox query processing2021 10-13 i ox query processing
2021 10-13 i ox query processing
 
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOxInfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
InfluxDB IOx Tech Talks: Query Processing in InfluxDB IOx
 
2015 bioinformatics bio_python
2015 bioinformatics bio_python2015 bioinformatics bio_python
2015 bioinformatics bio_python
 
CS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved ExamplesCS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved Examples
 

Recently uploaded

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, Adobeapidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
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 challengesrafiqahmad00786416
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 

Recently uploaded (20)

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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Python Async IO Horizon

  • 1. 19 Dec 2013 @lukmdo Python Asynchronous I/O asynchronous landscape refresher Photo by Jake Brown used under CC BY 2.0/“Mono+Balance”
  • 2. Agenda ⏰10 minutes ! • Background (can skip) • Problem statement • “Current state” • Python 3 async horizon (by examples)
  • 3. Warmup ! • CPU IO (CPU bound) • Pure IO (IO bound) • C10k • Concurrency vs. parallelism
  • 4. Warmup ! • Lazy schedule a task for later • Avoid waiting for IO (i.e. 2x DB queries) • Solve embarrassingly parallel problems • Control and manage status of task
  • 5. PEP index brief PEP Name Status Doc PEP 255 Simple Generators 2.2 ✔ »» PEP 342 Coroutines via Enhanced Generators 2.5 ✔ » PEP 380 Syntax for Delegating to a Subgenerator 3.3 ✔ » PEP 3148 Futures - execute computations asynchronously 3.2 ✔ » PEP 3153 Asynchronous IO support 3.3 ✔ » PEP 3156 Asynchronous IO Support Rebooted: the "asyncio" Module 3.4 ✔ »
  • 6. PEP index brief PEP Name PEP 219 Stackless Python ❙❙ PEP 220 Coroutines, Generators, Continuations ✗ PEP 319 Python Synchronize/Asynchronize Block ✗ PEP 3145 PEP 3152 Asynchronous I/O For subprocess.Popen Cofunctions Status ❙❙ ❙❙
  • 11. Slang* • future ~ result wrapper • coro != generator function (but close) • task = coro wrapped in Future • result = yield from future/coro (to wait for result)
  • 12. new* old style concurrency def update_foo(data): data1 = run_query1(data) data2 = run_query2(data) ! data3 = process(data1, data2) run_update_query(data3) run_update_cache(data3) ! return ["OK"]
  • 13. new* old style concurrency def update_foo(data): data1 = run_query1(data) data2 = run_query2(data) ! data3 = process(data1, data2) run_update_query(data3) run_update_cache(data3) ! return ["OK"]
  • 14. new* old style concurrency
  • 15. new* old style concurrency
  • 16. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): data1 = yield from run_query1(data) data2 = yield from run_query2(data) ! data3 = yield from process(data1, data2) yield from run_update_query(data3) loop.call_soon(update_cache, data3) ! return ["OK"]
  • 17. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): data1 = yield from run_query1(data) data2 = yield from run_query2(data) ! data3 = yield from process(data1, data2) yield from run_update_query(data3) loop.call_soon(update_cache, data3) ! return ["OK"]
  • 18. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): data1 = yield from run_query1(data) data2 = yield from run_query2(data) ! data3 = yield from process(data1, data2) yield from run_update_query(data3) loop.call_soon(update_cache, data3) ! return ["OK"]
  • 19. new* old style concurrency
  • 20. new* old style concurrency
  • 21. new* old style concurrency
  • 22. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): future1 = asyncio.async(run_query1(data)) future2 = asyncio.async(run_query2(data)) ! results = yield from asyncio.gather( future1, future2) data3 = yield from process(*results) yield from run_update_query(data3) ! loop.call_soon(update_cache, data3) ! return ["OK"]
  • 23. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): future1 = asyncio.async(run_query1(data)) future2 = asyncio.async(run_query2(data)) ! results = yield from asyncio.gather( future1, future2) data3 = yield from process(*results) yield from run_update_query(data3) ! loop.call_soon(update_cache, data3) ! return ["OK"]
  • 24. new* old style concurrency @asyncio.coroutine def update_foo(data, loop): future1 = asyncio.async(run_query1(data)) future2 = asyncio.async(run_query2(data)) ! results = yield from asyncio.gather( future1, future2) data3 = yield from process(*results) yield from run_update_query(data3) ! loop.call_soon(update_cache, data3) ! return ["OK"]
  • 25. new* old style concurrency
  • 26. new* old style concurrency
  • 27. new* old style concurrency
  • 28. new* old style concurrency def api_calls(): data1 = call_api1() data2 = call_api2() data3 = call_api3() ! return [data1, data2, data3]
  • 29. new* old style concurrency def api_calls(): data1 = call_api1() data3 = call_api2() data3 = call_api3() ! return [data1, data2, data3]
  • 30. new* old style concurrency
  • 31. new* old style concurrency
  • 32. new* old style concurrency @asyncio.coroutine def api_calls(): future1 = asyncio.Task(call_api1()) future2 = asyncio.Task(call_api2()) future3 = asyncio.Task(call_api3()) ! return ( yield from asyncio.gather( future1, future2, future3) )
  • 33. new* old style concurrency @asyncio.coroutine def api_calls(): future1 = asyncio.Task(call_api1()) future2 = asyncio.Task(call_api2()) future3 = asyncio.Task(call_api3()) ! return ( yield from asyncio.gather( future1, future2, future3) )
  • 34. new* old style concurrency
  • 35. new* old style concurrency
  • 36. new* old style concurrency
  • 37. new* old style concurrency from aiohttp import request ! @asyncio.coroutine def call_api(): url = "URL" response = yield from request('GET', url) return (yield from response.read())
  • 39. Links • Video by BDFL Tulip: Async I/O for Python 3 • Video by BDFL PyCon US 2013 Keynote • Code by Nikolay Kim aiohttp • Code by google appengine-pipeline • Code by google ndb tasklets Photo by Jake Brown used under CC BY 2.0/“Mono+Tile”