SlideShare a Scribd company logo
HOW TO DEAL WITH
BLOCKING CODE WITHIN
ASYNCIO EVENT LOOP
Nikolay Novik
http://github.com/jettify
I AM ...
Software Engineer: at DataRobot Ukraine
Github:
My Projects:
database clients:
aiomysql, aioobc, aiogibson
web and etc:
aiohttp_debugtoolbar, aiobotocore,
aiohttp_mako, aiohttp_sse, aiogearman,
aiomysql_replicatoin
http://github.com/jettify
POLL
YOU AND ASYNCIO:
1. I am using asyncio extensively
2. I am using Twisted, Tornado, gevent etc. extensively
3. I think async programming is kinda cool
ASYNCIO
The asyncio project was officially launched with the release
of Python 3.4 in March 2014.
Bare: almost no library
One year later, asyncio has a strong community writing
libraries on top of it.
But what to do when available libraries work in sync way,
potentially blocking event loop?
RULES OF ASYNC CLUB
RULE #1
You do not block event loop
RULE #2
You never block event loop
BLOCKING CALLS IN THIRD PARTY
LIBRARIES
Network IO
API wrappers
Database clients
Message queues
FileSystem IO
CPU
Set environment variable
DEBUGGING BLOCKING CALLS TIP
PYTHONASYNCIODEBUG=1
import asyncio
import time
loop = asyncio.get_event_loop()
loop.slow_callback_duration = 0.01
async def sleeper():
time.sleep(0.1) # we block here
loop.run_until_complete(sleeper())
Executing <Task finished coro=<sleeper() done, defined at
code/debug_example.py:9> result=None created at
/usr/local/lib/python3.5/asyncio/base_events.py:323>
took 0.102 seconds
APPROACH #1 IS THERE ANY
SUITABLE LIBRARY?
Search asyncio compatible library on:
1. google ~ 98k results
2. pypi ~200 packages
3. asyncio wiki page:
4. aio-libs:
https://github.com/python/asyncio/wiki/ThirdParty
https://github.com/aio-libs
Read the (f*g) source code of your libraries! Example of
python code from OneDrive SDK
Most of the time you want to do HTTP requests using event
loop not thread pool.
THIRD PARTY LIBRARIES PRO TIP
@asyncio.coroutine
def get_async(self):
"""Sends the GET request using an asyncio coroutine
....
"""
future = self._client._loop.run_in_executor(None,
self.get)
collection_response = yield from future
return collection_response
Most hipsters databases use REST API as primary access
method:
Easy to implement required subset of APIs.
APPROACH #2 IS REST API AVAILABLE?
DynamoDB
Neo4j
Elasticsearch
HBase
HDFS
CouchDB
Riak
VoltDB
InfluxDB
ArangoDB
is your friend
Connection pooling helps to save on expensive connection
creation. (PS: checkout new aiohttp 0.18.x release)
REST CLIENT TIP
aiohttp.ClientSession
import asyncio
import aiohttp
# carry the loop Luke!
loop = asyncio.get_event_loop()
async def go():
session = aiohttp.ClientSession(loop=loop)
async with session.get('http://python.org') as resp:
data = await resp.text()
print(data)
session.close()
loop.run_until_complete(go())
APPROACH #3 IS THERE SIMPLE TEXT
OR BINARY PROTOCOL?
Example of databases and message queues with binary
protocol:
redis
memcached
couchebase
grearman
beanstalkd
disque
Do not afraid to get your hands dirty.
Example: Simple binary protocol implementation
Simple but no protocol pipelining.
import asyncio, struct
from aiogibson import encode_command
async def read_from_connection(host, port, *, loop=None):
reader, writer = await asyncio.open_connection(
host, port, loop=loop)
cmd = encode_command(b'GET', 'key')
writer.write(cmd)
header = await reader.readexactly(4 + 2 + 1)
unpacked = struct.unpack(b'<HBI', header)
code, gb_encoding, resp_size = unpacked
payload = await reader.readexactly(resp_size)
print(payload)
Most binary protocols support pipelining
More info: http://tailhook.github.io/request-pipelining-
presentation/ presentation/index.html
PROTOCOL PIPELINING
Example: Simple pipelined binary protocol implementation
See for reference implementation.
def execute(self):
cmd = encode_command(b'GET', 'key')
self.writer.write(cmd)
fut = asyncio.Future(loop=self._loop)
self._queue.append(fut)
return fut
async def reader_task(self):
while True:
header = await self.reader.readexactly(4 + 2 + 1)
unpacked = struct.unpack(b'<HBI', header)
code, gb_encoding, resp_size = unpacked
# wait and read payload
payload = await reader.readexactly(resp_size)
future = self._queue.pop()
future.set_result(payload)
aioredis
In good sync database clients IO decoupled from protocol
parsers why not just rewrite IO part?
APPROACH #4 IS SYNC PYTHON CLIENT
AVAILABLE?
1. Locate socket.recv()
2. Replace with await reader.read()
3. Make function coroutine with async def
4. Call this function with await
5. Call parent functions with await
Yes. Make every blocking call in separate thread
APPROACH #5 IS THERE UNIVERSAL
SOLUTION TO ALL PROBLEMS?
import asyncio
from pyodbc import connect
loop = asyncio.get_event_loop()
executor = ThreadPoolExecutor(max_workers=4)
async def test_example():
dsn = 'Driver=SQLite;Database=sqlite.db'
conn = await loop.run_in_executor(executor, connect, dsn)
cursor = await loop.run_in_executor(executor, conn.cursor)
conn = await loop.run_in_executor(executor, cursor.execute,
'SELECT 42;')
loop.run_until_complete(test_example())
For python code
For Cython
BUT HOW I KNOW WHICH METHOD TO
CALL IN THREAD?
requests.get()
with nogil:
[code to be executed with the GIL released]
For C extension
Py_BEGIN_ALLOW_THREADS
ret = SQLDriverConnect(hdbc, 0, szConnect, SQL_NTS,
0, 0, 0, SQL_DRIVER_NOPROMPT);
Py_END_ALLOW_THREADS
Only good way to use files asynchronously by using thread
pools.
WHAT ABOUT FILESYSTEM IO?
asyncio does not support asynchronous operations on the
filesystem due to OS limitations.
On background uses ThreadPoolExecutor for
blocking calls.
aiofiles library workaround
async def go():
f = await aiofiles.open('filename', mode='r')
try:
data = await f.read()
finally:
await f.close()
print(data)
loop.run_until_complete(go())
aiofiles
WHAT ABOUT CPU INTENSIVE TASK?
loop = asyncio.get_event_loop()
executor = ProcessPoolExecutor(max_workers=3)
def is_prime(n):
if n % 2 == 0: return False
sqrt_n = int(math.floor(math.sqrt(n)))
for i in range(3, sqrt_n + 1, 2):
if n % i == 0: return False
return True
async def go():
n = 112272535095293
result = await loop.run_in_executor(executor, is_prime, n)
loop.run_until_complete(go(loop, executor))
THANKS!
Ad

More Related Content

Similar to HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP (20)

BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIO
Mykola Novik
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
Nathan Van Gheem
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
Tatsuhiko Miyagawa
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Pôle Systematic Paris-Region
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
David Padbury
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
John Congdon
 
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Logging for Production Systems in The Container Era
Logging for Production Systems in The Container EraLogging for Production Systems in The Container Era
Logging for Production Systems in The Container Era
Sadayuki Furuhashi
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
Remy Sharp
 
PHP on Heroku: Deploying and Scaling Apps in the Cloud
PHP on Heroku: Deploying and Scaling Apps in the CloudPHP on Heroku: Deploying and Scaling Apps in the Cloud
PHP on Heroku: Deploying and Scaling Apps in the Cloud
Salesforce Developers
 
Node Session - 1
Node Session - 1Node Session - 1
Node Session - 1
Bhavin Shah
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Fabrice Bernhard
 
Exploring Node.jS
Exploring Node.jSExploring Node.jS
Exploring Node.jS
Deepu S Nath
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
Ruslan Shevchenko
 
Proposal
ProposalProposal
Proposal
Constantine Priemski
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Baruch Sadogursky
 
BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIO
Mykola Novik
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
Nathan Van Gheem
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Plack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and serversPlack perl superglue for web frameworks and servers
Plack perl superglue for web frameworks and servers
Tatsuhiko Miyagawa
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan GumbsSyncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Syncing up with Python’s asyncio for (micro) service development, Joir-dan Gumbs
Pôle Systematic Paris-Region
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
David Padbury
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
John Congdon
 
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Logging for Production Systems in The Container Era
Logging for Production Systems in The Container EraLogging for Production Systems in The Container Era
Logging for Production Systems in The Container Era
Sadayuki Furuhashi
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
Remy Sharp
 
PHP on Heroku: Deploying and Scaling Apps in the Cloud
PHP on Heroku: Deploying and Scaling Apps in the CloudPHP on Heroku: Deploying and Scaling Apps in the Cloud
PHP on Heroku: Deploying and Scaling Apps in the Cloud
Salesforce Developers
 
Node Session - 1
Node Session - 1Node Session - 1
Node Session - 1
Bhavin Shah
 
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Fabrice Bernhard
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
Ruslan Shevchenko
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Baruch Sadogursky
 

Recently uploaded (20)

What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
EASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License CodeEASEUS Partition Master Crack + License Code
EASEUS Partition Master Crack + License Code
aneelaramzan63
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Ad

HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP

  • 1. HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP Nikolay Novik http://github.com/jettify
  • 2. I AM ... Software Engineer: at DataRobot Ukraine Github: My Projects: database clients: aiomysql, aioobc, aiogibson web and etc: aiohttp_debugtoolbar, aiobotocore, aiohttp_mako, aiohttp_sse, aiogearman, aiomysql_replicatoin http://github.com/jettify
  • 3. POLL YOU AND ASYNCIO: 1. I am using asyncio extensively 2. I am using Twisted, Tornado, gevent etc. extensively 3. I think async programming is kinda cool
  • 4. ASYNCIO The asyncio project was officially launched with the release of Python 3.4 in March 2014. Bare: almost no library One year later, asyncio has a strong community writing libraries on top of it. But what to do when available libraries work in sync way, potentially blocking event loop?
  • 5. RULES OF ASYNC CLUB RULE #1 You do not block event loop RULE #2 You never block event loop
  • 6. BLOCKING CALLS IN THIRD PARTY LIBRARIES Network IO API wrappers Database clients Message queues FileSystem IO CPU
  • 7. Set environment variable DEBUGGING BLOCKING CALLS TIP PYTHONASYNCIODEBUG=1 import asyncio import time loop = asyncio.get_event_loop() loop.slow_callback_duration = 0.01 async def sleeper(): time.sleep(0.1) # we block here loop.run_until_complete(sleeper()) Executing <Task finished coro=<sleeper() done, defined at code/debug_example.py:9> result=None created at /usr/local/lib/python3.5/asyncio/base_events.py:323> took 0.102 seconds
  • 8. APPROACH #1 IS THERE ANY SUITABLE LIBRARY? Search asyncio compatible library on: 1. google ~ 98k results 2. pypi ~200 packages 3. asyncio wiki page: 4. aio-libs: https://github.com/python/asyncio/wiki/ThirdParty https://github.com/aio-libs
  • 9. Read the (f*g) source code of your libraries! Example of python code from OneDrive SDK Most of the time you want to do HTTP requests using event loop not thread pool. THIRD PARTY LIBRARIES PRO TIP @asyncio.coroutine def get_async(self): """Sends the GET request using an asyncio coroutine .... """ future = self._client._loop.run_in_executor(None, self.get) collection_response = yield from future return collection_response
  • 10. Most hipsters databases use REST API as primary access method: Easy to implement required subset of APIs. APPROACH #2 IS REST API AVAILABLE? DynamoDB Neo4j Elasticsearch HBase HDFS CouchDB Riak VoltDB InfluxDB ArangoDB
  • 11. is your friend Connection pooling helps to save on expensive connection creation. (PS: checkout new aiohttp 0.18.x release) REST CLIENT TIP aiohttp.ClientSession import asyncio import aiohttp # carry the loop Luke! loop = asyncio.get_event_loop() async def go(): session = aiohttp.ClientSession(loop=loop) async with session.get('http://python.org') as resp: data = await resp.text() print(data) session.close() loop.run_until_complete(go())
  • 12. APPROACH #3 IS THERE SIMPLE TEXT OR BINARY PROTOCOL? Example of databases and message queues with binary protocol: redis memcached couchebase grearman beanstalkd disque Do not afraid to get your hands dirty.
  • 13. Example: Simple binary protocol implementation Simple but no protocol pipelining. import asyncio, struct from aiogibson import encode_command async def read_from_connection(host, port, *, loop=None): reader, writer = await asyncio.open_connection( host, port, loop=loop) cmd = encode_command(b'GET', 'key') writer.write(cmd) header = await reader.readexactly(4 + 2 + 1) unpacked = struct.unpack(b'<HBI', header) code, gb_encoding, resp_size = unpacked payload = await reader.readexactly(resp_size) print(payload)
  • 14. Most binary protocols support pipelining More info: http://tailhook.github.io/request-pipelining- presentation/ presentation/index.html PROTOCOL PIPELINING
  • 15. Example: Simple pipelined binary protocol implementation See for reference implementation. def execute(self): cmd = encode_command(b'GET', 'key') self.writer.write(cmd) fut = asyncio.Future(loop=self._loop) self._queue.append(fut) return fut async def reader_task(self): while True: header = await self.reader.readexactly(4 + 2 + 1) unpacked = struct.unpack(b'<HBI', header) code, gb_encoding, resp_size = unpacked # wait and read payload payload = await reader.readexactly(resp_size) future = self._queue.pop() future.set_result(payload) aioredis
  • 16. In good sync database clients IO decoupled from protocol parsers why not just rewrite IO part? APPROACH #4 IS SYNC PYTHON CLIENT AVAILABLE? 1. Locate socket.recv() 2. Replace with await reader.read() 3. Make function coroutine with async def 4. Call this function with await 5. Call parent functions with await
  • 17. Yes. Make every blocking call in separate thread APPROACH #5 IS THERE UNIVERSAL SOLUTION TO ALL PROBLEMS? import asyncio from pyodbc import connect loop = asyncio.get_event_loop() executor = ThreadPoolExecutor(max_workers=4) async def test_example(): dsn = 'Driver=SQLite;Database=sqlite.db' conn = await loop.run_in_executor(executor, connect, dsn) cursor = await loop.run_in_executor(executor, conn.cursor) conn = await loop.run_in_executor(executor, cursor.execute, 'SELECT 42;') loop.run_until_complete(test_example())
  • 18. For python code For Cython BUT HOW I KNOW WHICH METHOD TO CALL IN THREAD? requests.get() with nogil: [code to be executed with the GIL released] For C extension Py_BEGIN_ALLOW_THREADS ret = SQLDriverConnect(hdbc, 0, szConnect, SQL_NTS, 0, 0, 0, SQL_DRIVER_NOPROMPT); Py_END_ALLOW_THREADS
  • 19. Only good way to use files asynchronously by using thread pools. WHAT ABOUT FILESYSTEM IO? asyncio does not support asynchronous operations on the filesystem due to OS limitations.
  • 20. On background uses ThreadPoolExecutor for blocking calls. aiofiles library workaround async def go(): f = await aiofiles.open('filename', mode='r') try: data = await f.read() finally: await f.close() print(data) loop.run_until_complete(go()) aiofiles
  • 21. WHAT ABOUT CPU INTENSIVE TASK? loop = asyncio.get_event_loop() executor = ProcessPoolExecutor(max_workers=3) def is_prime(n): if n % 2 == 0: return False sqrt_n = int(math.floor(math.sqrt(n))) for i in range(3, sqrt_n + 1, 2): if n % i == 0: return False return True async def go(): n = 112272535095293 result = await loop.run_in_executor(executor, is_prime, n) loop.run_until_complete(go(loop, executor))