SlideShare a Scribd company logo
Bayu Aldi Yansyah
Data at Kumparan
github.com/pyk
PyCon Indonesia
November 3-4, 2018
Kalbis Institute, Jakarta
Asynchronous Python at Kumparan
x
The basics:
1. Coroutine is a function that has many entry points for
suspending and resuming the execution.
2. Task is used to schedule Coroutines to run concurrently.
3. Event Loop is Coroutine(s) and Task(s) runner.
Asynchronous Programming in Python
# Python 3.5+
import asyncio
Event Loop
Task
Coroutine
Event Loop
import asyncio
# Create new event loop
loop = asyncio.new_event_loop()
# Get the current event loop
loop = asyncio.get_event_loop()
async def process(input: str) -> str:
# time.sleep(5)
await asyncio.sleep(5)
return “Processed: {}”.format(input)
Coroutine
Example of entrypoint where Event Loop
can suspend or resume the execution.
# process(“test”)
loop.run_until_complete(process("test"))
loop.close()
Define Coroutine using async def
keyword
You should not call function that block
the main thread inside a Coroutine.
Coroutine cannot run on itself, it
depends on Event Loop.
You can call other Coroutine using
await keyword.
Task
from typing import None
def callback(future: asyncio.Future) -> None:
processed = future.result()
print(“{} is here”.format(processed))
async def main() -> None:
task1 = asyncio.create_task(process(“input 1”))
task2 = asyncio.create_task(process(“input 2”))
task1.add_done_callback(callback)
task2.add_done_callback(callback)
await asyncio.sleep(5)
loop.run_until_complete(main())
Wrap Coroutines using Task
to run them concurrently.
You can attach a callback
function
asyncio at Kumparan
asyncio is a perfect fit for high-performance web-servers, database connection libraries,
distributed task queues, etc.
List of services that we build on top of Python asyncio:
1. Tracker API
2. Tracker Transporter
3. A/B Test Splitter API
4. Trending Stories API
5. Personalized Feed API
6. And more ...
Use case: Tracking events receiver
Our goal is to be able to receive tracking events as many as possible. We implement
Fire-and-Forget approach on top of asyncio in order to reduce the response time.
# NOTE: Simplified version
async def track(request: Request) -> Response:
# ...
try:
# Fire
task = tracker.collect(event)
# ...
task.add_done_callback(callback)
# and Forget (Return the response immediately)
return api.success()
except ValueError as e:
return api.error(status_code=400, error=str(e))
except Exception as e:
error = "/v1/track failed"
return api.error(error=error, exception=e)
Coroutine.
Schedule another Coroutine with
event data as an input and wrap it
with asyncio.Task
Attach a callback
Use case: Tracking events receiver
With this implementation, we are able to achieve response time in less than 50ms.
.
Use case: Tracking events receiver
With this implementation, we are able to collect more than 10,000,000 tracking events on
daily basis.
Lion Air JT-610 Crash
Lessons Learned
1. The async library from the community is not mature yet, sometimes you
need to implement it by yourself.
2. It's easy to make mistake by calling a blocking function. There is no tool
that helps developers to spot this mistake.
Thanks!
Sounds Exciting?
Send your CV to joindev@kumparan.com

More Related Content

What's hot

Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
P3 InfoTech Solutions Pvt. Ltd.
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
Giordano Scalzo
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
Giordano Scalzo
 
Need to make a horizontal change across 100+ microservices? No worries, Sheph...
Need to make a horizontal change across 100+ microservices? No worries, Sheph...Need to make a horizontal change across 100+ microservices? No worries, Sheph...
Need to make a horizontal change across 100+ microservices? No worries, Sheph...
Aori Nevo, PhD
 
Calico docker+ipam
Calico docker+ipamCalico docker+ipam
Calico docker+ipam
D.Rajesh Kumar
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
P3 InfoTech Solutions Pvt. Ltd.
 
Calico and container
Calico and containerCalico and container
Calico and container
D.Rajesh Kumar
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
Dmitri Nesteruk
 
Reactive programming in PHP
Reactive programming in PHPReactive programming in PHP
Reactive programming in PHP
Johney Park
 
parallel programming in the PVM- task creation-Advanced system architecture
parallel programming in the PVM- task creation-Advanced system architectureparallel programming in the PVM- task creation-Advanced system architecture
parallel programming in the PVM- task creation-Advanced system architecture
RoslinJoseph
 
Async in .NET
Async in .NETAsync in .NET
Async in .NETRTigger
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) MicrosoftJimmy Schementi
 
Python event based network sniffer
Python event based network snifferPython event based network sniffer
Python event based network sniffer
Jirka Vejrazka
 
Rcpp11
Rcpp11Rcpp11
OctoLab Cookbook: how to use composer.yml and stop creating issues about
OctoLab Cookbook: how to use composer.yml and stop creating issues aboutOctoLab Cookbook: how to use composer.yml and stop creating issues about
OctoLab Cookbook: how to use composer.yml and stop creating issues about
Kamil Samigullin
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
SmartLogic
 
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and NimbleTDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
Jianbin LIN
 
Using zone.js
Using zone.jsUsing zone.js
Using zone.js
Standa Opichal
 

What's hot (19)

Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
Need to make a horizontal change across 100+ microservices? No worries, Sheph...
Need to make a horizontal change across 100+ microservices? No worries, Sheph...Need to make a horizontal change across 100+ microservices? No worries, Sheph...
Need to make a horizontal change across 100+ microservices? No worries, Sheph...
 
Calico docker+ipam
Calico docker+ipamCalico docker+ipam
Calico docker+ipam
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Calico and container
Calico and containerCalico and container
Calico and container
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
 
Reactive programming in PHP
Reactive programming in PHPReactive programming in PHP
Reactive programming in PHP
 
parallel programming in the PVM- task creation-Advanced system architecture
parallel programming in the PVM- task creation-Advanced system architectureparallel programming in the PVM- task creation-Advanced system architecture
parallel programming in the PVM- task creation-Advanced system architecture
 
Async in .NET
Async in .NETAsync in .NET
Async in .NET
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
 
Python event based network sniffer
Python event based network snifferPython event based network sniffer
Python event based network sniffer
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
OctoLab Cookbook: how to use composer.yml and stop creating issues about
OctoLab Cookbook: how to use composer.yml and stop creating issues aboutOctoLab Cookbook: how to use composer.yml and stop creating issues about
OctoLab Cookbook: how to use composer.yml and stop creating issues about
 
An Introduction to Reactive Cocoa
An Introduction to Reactive CocoaAn Introduction to Reactive Cocoa
An Introduction to Reactive Cocoa
 
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and NimbleTDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
 
Using zone.js
Using zone.jsUsing zone.js
Using zone.js
 

Similar to Asynchronous Python at Kumparan

AsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your CrawlerAsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your Crawler
Linggar Primahastoko
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Webscraping with asyncio
Webscraping with asyncioWebscraping with asyncio
Webscraping with asyncio
Jose Manuel Ortega Candel
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
RapidValue
 
asyncio internals
asyncio internalsasyncio internals
asyncio internals
Saúl Ibarra Corretgé
 
BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIO
Mykola Novik
 
Secure your Web Application With The New Python Audit Hooks
Secure your Web Application With The New Python Audit HooksSecure your Web Application With The New Python Audit Hooks
Secure your Web Application With The New Python Audit Hooks
Nicolas Vivet
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with PythonLarry Cai
 
"Load Testing Distributed Systems with NBomber 4.0", Anton Moldovan
"Load Testing Distributed Systems with NBomber 4.0",  Anton Moldovan"Load Testing Distributed Systems with NBomber 4.0",  Anton Moldovan
"Load Testing Distributed Systems with NBomber 4.0", Anton Moldovan
Fwdays
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
Jeff Smith
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
Jeff Smith
 
Dev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die SeeleDev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die Seele
DevDay Dresden
 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
Mykola Novik
 
The journey of asyncio adoption in instagram
The journey of asyncio adoption in instagramThe journey of asyncio adoption in instagram
The journey of asyncio adoption in instagram
Jimmy Lai
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingOliver Scheer
 
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
 
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
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
Oon Arfiandwi
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
Knoldus Inc.
 

Similar to Asynchronous Python at Kumparan (20)

AsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your CrawlerAsyncIO To Speed Up Your Crawler
AsyncIO To Speed Up Your Crawler
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
 
Webscraping with asyncio
Webscraping with asyncioWebscraping with asyncio
Webscraping with asyncio
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
 
asyncio internals
asyncio internalsasyncio internals
asyncio internals
 
BUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIOBUILDING APPS WITH ASYNCIO
BUILDING APPS WITH ASYNCIO
 
Secure your Web Application With The New Python Audit Hooks
Secure your Web Application With The New Python Audit HooksSecure your Web Application With The New Python Audit Hooks
Secure your Web Application With The New Python Audit Hooks
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with Python
 
"Load Testing Distributed Systems with NBomber 4.0", Anton Moldovan
"Load Testing Distributed Systems with NBomber 4.0",  Anton Moldovan"Load Testing Distributed Systems with NBomber 4.0",  Anton Moldovan
"Load Testing Distributed Systems with NBomber 4.0", Anton Moldovan
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
Dev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die SeeleDev Day 2019: Mike Sperber – Software Design für die Seele
Dev Day 2019: Mike Sperber – Software Design für die Seele
 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
 
The journey of asyncio adoption in instagram
The journey of asyncio adoption in instagramThe journey of asyncio adoption in instagram
The journey of asyncio adoption in instagram
 
Windows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async ProgrammingWindows Phone 8 - 3.5 Async Programming
Windows Phone 8 - 3.5 Async Programming
 
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...
 
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
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Scala Future & Promises
Scala Future & PromisesScala Future & Promises
Scala Future & Promises
 

More from Bayu Aldi Yansyah

Panduan Memulai Karir di Data Science (Binus University)
Panduan Memulai Karir di Data Science (Binus University)Panduan Memulai Karir di Data Science (Binus University)
Panduan Memulai Karir di Data Science (Binus University)
Bayu Aldi Yansyah
 
Penerapan Machine Learning di Industri
Penerapan Machine Learning di IndustriPenerapan Machine Learning di Industri
Penerapan Machine Learning di Industri
Bayu Aldi Yansyah
 
PyTorch for Deep Learning Practitioners
PyTorch for Deep Learning PractitionersPyTorch for Deep Learning Practitioners
PyTorch for Deep Learning Practitioners
Bayu Aldi Yansyah
 
Panduan untuk Memulai Karir di Data Science
Panduan untuk Memulai Karir di Data SciencePanduan untuk Memulai Karir di Data Science
Panduan untuk Memulai Karir di Data Science
Bayu Aldi Yansyah
 
Intent Classifier with Facebook fastText
Intent Classifier with Facebook fastTextIntent Classifier with Facebook fastText
Intent Classifier with Facebook fastText
Bayu Aldi Yansyah
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Clustering Semantically Similar Words
Clustering Semantically Similar WordsClustering Semantically Similar Words
Clustering Semantically Similar Words
Bayu Aldi Yansyah
 
Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1
Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1
Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1
Bayu Aldi Yansyah
 
Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1
Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1
Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1
Bayu Aldi Yansyah
 

More from Bayu Aldi Yansyah (9)

Panduan Memulai Karir di Data Science (Binus University)
Panduan Memulai Karir di Data Science (Binus University)Panduan Memulai Karir di Data Science (Binus University)
Panduan Memulai Karir di Data Science (Binus University)
 
Penerapan Machine Learning di Industri
Penerapan Machine Learning di IndustriPenerapan Machine Learning di Industri
Penerapan Machine Learning di Industri
 
PyTorch for Deep Learning Practitioners
PyTorch for Deep Learning PractitionersPyTorch for Deep Learning Practitioners
PyTorch for Deep Learning Practitioners
 
Panduan untuk Memulai Karir di Data Science
Panduan untuk Memulai Karir di Data SciencePanduan untuk Memulai Karir di Data Science
Panduan untuk Memulai Karir di Data Science
 
Intent Classifier with Facebook fastText
Intent Classifier with Facebook fastTextIntent Classifier with Facebook fastText
Intent Classifier with Facebook fastText
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Clustering Semantically Similar Words
Clustering Semantically Similar WordsClustering Semantically Similar Words
Clustering Semantically Similar Words
 
Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1
Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1
Pertemuan 2 & 3: A.I. Indonesia Academy Surabaya Batch #1
 
Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1
Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1
Pertemuan 1 - AI Indonesia Academy Surabaya Batch #1
 

Recently uploaded

SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 

Recently uploaded (20)

SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 

Asynchronous Python at Kumparan

  • 1. Bayu Aldi Yansyah Data at Kumparan github.com/pyk PyCon Indonesia November 3-4, 2018 Kalbis Institute, Jakarta Asynchronous Python at Kumparan x
  • 2. The basics: 1. Coroutine is a function that has many entry points for suspending and resuming the execution. 2. Task is used to schedule Coroutines to run concurrently. 3. Event Loop is Coroutine(s) and Task(s) runner. Asynchronous Programming in Python # Python 3.5+ import asyncio Event Loop Task Coroutine
  • 3. Event Loop import asyncio # Create new event loop loop = asyncio.new_event_loop() # Get the current event loop loop = asyncio.get_event_loop()
  • 4. async def process(input: str) -> str: # time.sleep(5) await asyncio.sleep(5) return “Processed: {}”.format(input) Coroutine Example of entrypoint where Event Loop can suspend or resume the execution. # process(“test”) loop.run_until_complete(process("test")) loop.close() Define Coroutine using async def keyword You should not call function that block the main thread inside a Coroutine. Coroutine cannot run on itself, it depends on Event Loop. You can call other Coroutine using await keyword.
  • 5. Task from typing import None def callback(future: asyncio.Future) -> None: processed = future.result() print(“{} is here”.format(processed)) async def main() -> None: task1 = asyncio.create_task(process(“input 1”)) task2 = asyncio.create_task(process(“input 2”)) task1.add_done_callback(callback) task2.add_done_callback(callback) await asyncio.sleep(5) loop.run_until_complete(main()) Wrap Coroutines using Task to run them concurrently. You can attach a callback function
  • 6. asyncio at Kumparan asyncio is a perfect fit for high-performance web-servers, database connection libraries, distributed task queues, etc. List of services that we build on top of Python asyncio: 1. Tracker API 2. Tracker Transporter 3. A/B Test Splitter API 4. Trending Stories API 5. Personalized Feed API 6. And more ...
  • 7. Use case: Tracking events receiver Our goal is to be able to receive tracking events as many as possible. We implement Fire-and-Forget approach on top of asyncio in order to reduce the response time. # NOTE: Simplified version async def track(request: Request) -> Response: # ... try: # Fire task = tracker.collect(event) # ... task.add_done_callback(callback) # and Forget (Return the response immediately) return api.success() except ValueError as e: return api.error(status_code=400, error=str(e)) except Exception as e: error = "/v1/track failed" return api.error(error=error, exception=e) Coroutine. Schedule another Coroutine with event data as an input and wrap it with asyncio.Task Attach a callback
  • 8. Use case: Tracking events receiver With this implementation, we are able to achieve response time in less than 50ms. .
  • 9. Use case: Tracking events receiver With this implementation, we are able to collect more than 10,000,000 tracking events on daily basis. Lion Air JT-610 Crash
  • 10. Lessons Learned 1. The async library from the community is not mature yet, sometimes you need to implement it by yourself. 2. It's easy to make mistake by calling a blocking function. There is no tool that helps developers to spot this mistake.
  • 11. Thanks! Sounds Exciting? Send your CV to joindev@kumparan.com