SlideShare a Scribd company logo
Asynchronous Python
and You
A guide by Dayne Jones
dir(Dayne)
I’m Dayne. I try to make martech better.
Itinerary
I. A bit about AddShoppers
II. What is asynchronous
programming?
A. In general
B. In python
III. Why does it matter?
A. Are there benefits?
B. Is it worth using?
IV. How do I use it?
A. Which libraries should I use?
B. What kind of support can I
expect?
V. Demo
How are we using
asynchronous Python at
AddShoppers?
AddShoppers
● ### million requests per day, ####
rps
● Hanes, American Giant, Jockey,
more
● ## app servers (all tornado), ## db,
## cache, ## queue
● ## data pipeline servicing ~ ### rps
(asyncio)
● Hiring? Yes, please.
What is asynchronous
programming anyways?
Sync vs. Async
● Synchronous code waits to
return
● Asynchronous code returns
immediately
# synchronous
response = requests.get(url)
print(response)
# asynchronous
def print_resp(response):
print(response)
async_requests.get(url, callback=print_resp)
How does it work?
Event Loopdef start(self):
[...]
try:
while True:
[...]
while self._events:
fd, events = self._events.popitem()
try:
fd_obj, handler_func = self._handlers[fd]
handler_func(fd_obj, events)
except (OSError, IOError) as e:
[...]
except Exception:
self.handle_callback_exception(self._handlers.get(fd))
fd_obj = handler_func = None
Event Loop
def sync_handler(url):
response = requests.get(url) # takes 1 second
return response.status_code
def async_handler(url):
def print_resp(response):
return response.status_code
async_requests.get(url, callback=print_resp) # takes 1 second
Synchronous Asynchronous
1 Thread Available
1s
2s
3s
4s
5s
6s
1 Request
1s
2s
3s
4s
5s
6s
Synchronous Asynchronous
5 Threads Available
1s
2s
3s
4s
5s
6s
1 Request
1s
2s
3s
4s
5s
6s
Event-loop (continued)
● The CPU very often context switches at non deterministic intervals.
● Allows the programmer to mark context switches
● Single threaded (don’t use synchronous code in your thread)
Common Patterns
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
http = tornado.httpclient.AsyncHTTPClient()
http.fetch("http://my-api.com/v2/users", callback=self.on_response)
def on_response(self, response):
if response.error: raise tornado.web.HTTPError(500)
json = tornado.escape.json_decode(response.body)
self.write("Fetched " + str(len(json["entries"])) + "users from the API")
self.finish()
Callbacks
Futures/Coroutines
class MainHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
http = tornado.httpclient.AsyncHTTPClient()
response = yield http.fetch("http://my-api.com/v2/users")
json = tornado.escape.json_decode(response.body)
self.write("Fetched " + str(len(json["entries"])) + " users from the API")
# Python 3.5
async def fetch_coroutine(url):
response = await some_async_function()
return response.body
# Tornado 4.3, Python 3.5
async def fetch_coroutine(url):
http_client = AsyncHTTPClient()
response = await http_client.fetch(url)
return response.body
Async/Await
Why do I want to use
asynchronous python?
# synchronous
response = requests.get(url) # takes 1 second
print(response)
# asynchronous
def print_resp(response):
print(response)
async_requests.get(url, callback=print_resp) # still takes 1 second
Efficiency
Real-time web
● Long lived connections
● Mostly idle
Common Use Cases
● Real-time web. Anything that requires long lived, mostly idle connections from
users.
● Network I/O. Waiting for HTTP requests to return.
● Database calls. Waiting for a database to return a query.
● Filesystem. Waiting for a disk.
● Anything else non CPU bound.
How do I write asynchronous
programs in Python?
Libraries
● Tornado Web
● asyncio
● Twisted (Event driven networking engine)
● Gevent (Networking library)
● Cyclone (Tornado API on top of Twisted)
Python 2.x, <= 3.3
● Tornado
○ Callbacks
○ Coroutines (generators)
● Gevent
● Twisted
● Cyclone
# Python 2
class MyHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(“http://url.com")
return response
Python >= 3.3, < 3.5
● Tornado
○ Asyncio bridge library
○ Callbacks
○ Coroutines
● Asyncio
○ Coroutines (generators)
# Tornado
class MyHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch(“http://url.com"
return response
# asyncio
import asyncio
import aiohttp
@asyncio.coroutine
def fetch_page(url):
response = yield from aiohttp.request('GET', url)
assert response.status == 200
content = yield from response.read()
print('URL: {0}: Content: {1}'.format(url, content))
Python >= 3.5
● Tornado
○ async/await
● Asyncio
○ async/await
# Tornado
class MyHandler(tornado.web.RequestHandler):
async def get(self):
http_client = AsyncHTTPClient()
url = 'http://myurl.com'
response = await http_client.fetch(url)
return response
# asyncio
import asyncio
import aiohttp
@asyncio.coroutine
def fetch_page(url):
response = yield from aiohttp.request('GET', url)
assert response.status == 200
content = yield from response.read()
print('URL: {0}: Content: {1}'.format(url, content))
Miscellaneous
● Database driver (motor, Momoko)
● Redis
● Reading files
DEMO
Questions?

More Related Content

PPTX
Cryptocurrency && Ruby
ODP
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
PDF
GPU Computing for Data Science
PPT
Python for pentesters
PPTX
Port Scanning with Node.js
PDF
Infrastructure as code might be literally impossible
PPT
scaling compiled applications - highload 2013
PPTX
Rusty Python
Cryptocurrency && Ruby
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
GPU Computing for Data Science
Python for pentesters
Port Scanning with Node.js
Infrastructure as code might be literally impossible
scaling compiled applications - highload 2013
Rusty Python

Similar to Asynchronous Python and You (20)

PPTX
C# 5 deep drive into asynchronous programming
PDF
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
PDF
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
PDF
Highly concurrent yet natural programming
ODP
Asynctasks
PDF
Asynchronous web-development with Python
PDF
Asynchronous web-development with Python
PPT
py4inf-01-intro.ppt
PPTX
Async programming in c#
PDF
Async Await for Mobile Apps
KEY
Motion Django Meetup
PPTX
Async programming and python
PPT
Py4 inf 01-intro
PDF
High-Performance Networking Using eBPF, XDP, and io_uring
PDF
Real time web
PDF
Android concurrency
PDF
Communication in Python and the C10k problem
PDF
Rundown of Async/Await in Rust
PDF
社内勉強会資料_Two Papers Contribute to Faster Python.pdf
PPTX
C++ Coroutines
C# 5 deep drive into asynchronous programming
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
Async programming in Python_ Build non-blocking, scalable apps with coroutine...
Highly concurrent yet natural programming
Asynctasks
Asynchronous web-development with Python
Asynchronous web-development with Python
py4inf-01-intro.ppt
Async programming in c#
Async Await for Mobile Apps
Motion Django Meetup
Async programming and python
Py4 inf 01-intro
High-Performance Networking Using eBPF, XDP, and io_uring
Real time web
Android concurrency
Communication in Python and the C10k problem
Rundown of Async/Await in Rust
社内勉強会資料_Two Papers Contribute to Faster Python.pdf
C++ Coroutines
Ad

Recently uploaded (20)

PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
AI in Product Development-omnex systems
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
L1 - Introduction to python Backend.pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Transform Your Business with a Software ERP System
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
top salesforce developer skills in 2025.pdf
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
medical staffing services at VALiNTRY
PDF
System and Network Administration Chapter 2
PPTX
ai tools demonstartion for schools and inter college
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
How to Choose the Right IT Partner for Your Business in Malaysia
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
AI in Product Development-omnex systems
Upgrade and Innovation Strategies for SAP ERP Customers
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
L1 - Introduction to python Backend.pptx
VVF-Customer-Presentation2025-Ver1.9.pptx
Transform Your Business with a Software ERP System
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
top salesforce developer skills in 2025.pdf
Softaken Excel to vCard Converter Software.pdf
wealthsignaloriginal-com-DS-text-... (1).pdf
medical staffing services at VALiNTRY
System and Network Administration Chapter 2
ai tools demonstartion for schools and inter college
Navsoft: AI-Powered Business Solutions & Custom Software Development
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Ad

Asynchronous Python and You

  • 1. Asynchronous Python and You A guide by Dayne Jones
  • 2. dir(Dayne) I’m Dayne. I try to make martech better.
  • 3. Itinerary I. A bit about AddShoppers II. What is asynchronous programming? A. In general B. In python III. Why does it matter? A. Are there benefits? B. Is it worth using? IV. How do I use it? A. Which libraries should I use? B. What kind of support can I expect? V. Demo
  • 4. How are we using asynchronous Python at AddShoppers?
  • 5. AddShoppers ● ### million requests per day, #### rps ● Hanes, American Giant, Jockey, more ● ## app servers (all tornado), ## db, ## cache, ## queue ● ## data pipeline servicing ~ ### rps (asyncio) ● Hiring? Yes, please.
  • 7. Sync vs. Async ● Synchronous code waits to return ● Asynchronous code returns immediately # synchronous response = requests.get(url) print(response) # asynchronous def print_resp(response): print(response) async_requests.get(url, callback=print_resp)
  • 8. How does it work?
  • 9. Event Loopdef start(self): [...] try: while True: [...] while self._events: fd, events = self._events.popitem() try: fd_obj, handler_func = self._handlers[fd] handler_func(fd_obj, events) except (OSError, IOError) as e: [...] except Exception: self.handle_callback_exception(self._handlers.get(fd)) fd_obj = handler_func = None Event Loop
  • 10. def sync_handler(url): response = requests.get(url) # takes 1 second return response.status_code def async_handler(url): def print_resp(response): return response.status_code async_requests.get(url, callback=print_resp) # takes 1 second
  • 11. Synchronous Asynchronous 1 Thread Available 1s 2s 3s 4s 5s 6s 1 Request 1s 2s 3s 4s 5s 6s
  • 12. Synchronous Asynchronous 5 Threads Available 1s 2s 3s 4s 5s 6s 1 Request 1s 2s 3s 4s 5s 6s
  • 13. Event-loop (continued) ● The CPU very often context switches at non deterministic intervals. ● Allows the programmer to mark context switches ● Single threaded (don’t use synchronous code in your thread)
  • 15. class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch("http://my-api.com/v2/users", callback=self.on_response) def on_response(self, response): if response.error: raise tornado.web.HTTPError(500) json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + "users from the API") self.finish() Callbacks
  • 16. Futures/Coroutines class MainHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch("http://my-api.com/v2/users") json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + " users from the API")
  • 17. # Python 3.5 async def fetch_coroutine(url): response = await some_async_function() return response.body # Tornado 4.3, Python 3.5 async def fetch_coroutine(url): http_client = AsyncHTTPClient() response = await http_client.fetch(url) return response.body Async/Await
  • 18. Why do I want to use asynchronous python?
  • 19. # synchronous response = requests.get(url) # takes 1 second print(response) # asynchronous def print_resp(response): print(response) async_requests.get(url, callback=print_resp) # still takes 1 second Efficiency
  • 20. Real-time web ● Long lived connections ● Mostly idle
  • 21. Common Use Cases ● Real-time web. Anything that requires long lived, mostly idle connections from users. ● Network I/O. Waiting for HTTP requests to return. ● Database calls. Waiting for a database to return a query. ● Filesystem. Waiting for a disk. ● Anything else non CPU bound.
  • 22. How do I write asynchronous programs in Python?
  • 23. Libraries ● Tornado Web ● asyncio ● Twisted (Event driven networking engine) ● Gevent (Networking library) ● Cyclone (Tornado API on top of Twisted)
  • 24. Python 2.x, <= 3.3 ● Tornado ○ Callbacks ○ Coroutines (generators) ● Gevent ● Twisted ● Cyclone # Python 2 class MyHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch(“http://url.com") return response
  • 25. Python >= 3.3, < 3.5 ● Tornado ○ Asyncio bridge library ○ Callbacks ○ Coroutines ● Asyncio ○ Coroutines (generators) # Tornado class MyHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http_client = AsyncHTTPClient() response = yield http_client.fetch(“http://url.com" return response # asyncio import asyncio import aiohttp @asyncio.coroutine def fetch_page(url): response = yield from aiohttp.request('GET', url) assert response.status == 200 content = yield from response.read() print('URL: {0}: Content: {1}'.format(url, content))
  • 26. Python >= 3.5 ● Tornado ○ async/await ● Asyncio ○ async/await # Tornado class MyHandler(tornado.web.RequestHandler): async def get(self): http_client = AsyncHTTPClient() url = 'http://myurl.com' response = await http_client.fetch(url) return response # asyncio import asyncio import aiohttp @asyncio.coroutine def fetch_page(url): response = yield from aiohttp.request('GET', url) assert response.status == 200 content = yield from response.read() print('URL: {0}: Content: {1}'.format(url, content))
  • 27. Miscellaneous ● Database driver (motor, Momoko) ● Redis ● Reading files
  • 28. DEMO