SlideShare a Scribd company logo
1 of 31
Download to read offline
Scaling Django with Gevent

          Mahendra M
          @mahendra
   https://github.com/mahendra
@mahendra
●   Python developer for 6 years
●   FOSS enthusiast/volunteer for 14 years
    ●   Bangalore LUG and Infosys LUG
    ●   FOSS.in and LinuxBangalore/200x
●   Gevent user for 1 year
●   Twisted user for 5 years (before migrating)
    ●   Added twisted support libraries like mustaine
Concurrency models
●   Multi-Process
●   Threads
●   Event driven
●   Coroutines
Process/Thread

request   dispatch()   worker_1()


                                    read(fp)

                                     db_rd()

                                     db_wr()

                                    sock_wr()




                       worker_n()
Process/Thread
●   There are blocking sections in the code
●   Python GIL is an issue in thread based
    concurrency
Event driven

event_1                           hdler_1()   ev()



event_2      block_on_events()    hdler_2()



          Events are posted



event_n                           hdler_n()
Event driven web server

 request                        open(fp)    reg()


 opened                         parse()


                event_loop()   read_sql()   reg()


sql_read                       wri_sql()    reg()


sql_writ                       sock_wr()    reg()

responded                       close()
Two years back
●   Using python twisted for half of our products
●   Using django for the other half
●   Quite a nightmare
Python twisted
●   An event driven library (very scalable)
●   Using epoll or kqueue                 Server 1



                                          Server 2
                             Nginx
             Client
                           (SSL & LB)
                                               .
                                               .
                                               .
                                          Server N

                                              Proc 1 (:8080)

                                              Proc 2 (:8080)

                                              Proc N (:8080)
Gevent
A coroutine-based Python networking library that
uses greenlet to provide a high-level synchronous
API on top of the libevent event loop.
Gevent
A coroutine-based Python networking library that
uses greenlet to provide a high-level synchronous
API on top of the libevent event loop.
Coroutines
●   Python coroutines are almost similar to
    generators.

def abc( seq ):
     lst = list( seq )
     for i in lst:
         value = yield i
         if cmd is not None:
              lst.append( value )
r = abc( [1,2,3] )
r.send( 4 )
Gevent features
●   Fast event-loop based on libevent (epoll,
    kqueue etc.)
●   Lightweight execution units based on greenlets
    (coroutines)
●   Monkey patching support
●   Simple API
●   Fast WSGI server
Greenlets
●   Primitive notion of micro-threads with no implicit
    scheduling
●   Just co-routines or independent pseudo-
    threads
●   Other systems like gevent build micro-threads
    on top of greenlets.
●   Execution happens by switching execution
    among greenlet stacks
●   Greenlet switching is not implicit (switch())
Greenlet execution

Main greenlet                     pause()


                                   abc()


                 Child greenlet   func_1()


                                  pause()


                                  some()     reg()

                                  func_2()
Greenlet code
from greenlet import greenlet


def test1():
   gr2.switch()


def test2():
   gr1.switch()


gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
How does gevent work
●   Creates an implicit event loop inside a
    dedicated greenlet
●   When a function in gevent wants to block, it
    switches to the greenlet of the event loop. This
    will schedule another child greenlet to run
●   The eventloop automatically picks up the
    fastest polling mechanism available in the
    system
●   One event loop runs inside a single OS thread
    (process)
Gevent code
import gevent
from gevent import socket
urls = ['www.google.com', 'www.example.com',
'www.python.org']
jobs = [gevent.spawn(socket.gethostbyname, url) for
url in urls]
gevent.joinall(jobs, timeout=2)
[job.value for job in jobs]


['74.125.79.106', '208.77.188.166', '82.94.164.162']
Gevent apis
●   Greenlet management (spawn, timeout, schedule)
●   Greenlet local data
●   Networking (socket, ssl, dns, select)
●   Synchronization
    ●   Event – notify multiple listeners
    ●   Queue – synchronized producer/consumer queues
    ● Locking – Semaphores
●   Greenlet pools
●   TCP/IP and WSGI servers
Gevent advantages
●   Almost synchronous code. No callbacks and
    deferreds
●   Lightweight greenlets
●   Good concurrency
●   No issues of python GIL
●   No need for in-process locking, since a greenlet
    cannot be pre-empted
Gevent issues
●   A greenlet will run till it blocks or switches
    ●   Be vary of large/infinite loops
●   Monkey patching is required for un-supported
    blocking libraries. Might not work well with
    some libraries
Our django dream
●   We love django
●   I like twisted, but love django more
    ●   Coding complexity
    ●   Lack of developers for hire
    ●   Deployment complexity
●   Gevent saved the day
The Django Problem
●   In a HTTP request cycle, we wanted the
    following operations
    ●   Fetch some metadata for an item being sold
    ●   Purchase the item for the user in the billing system
    ●   Fetch ads to be shown along with the item
    ●   Fetch recommendations based on this item
●   In parallel … !!
    ●   Twisted was the only option
Twisted code
def handle_purchase( rqst ):
   defs = []
   defs.append( biller() )
   defs.append( ads() )
   defs.append( recos() )
   defs.append( meta() )
   def = DeferredList( defs, … )
   def.addCallback( send_response() )
   return NOT_DONE_YET
Twisted issues
●   The issues were with everything else
    ●   Header management
    ●   Templates for response
    ●   ORM support
    ●   SOAP, REST, Hessian/Burlap support
        –   We liked to use suds, requests, mustaine etc.
    ●   Session management and auth
    ●   Caching support
●   The above are django's strength
    ●   Django's vibrant eco-system (celery, south,
        tastypie)
gunicorn
●   A python WSGI HTTP server
●   Supports running code under worker, eventlet,
    gevent etc.
    ●   Uses monkey patching
●   Excellent django support
    ●   gunicorn_django app.settings
●   Enabled gevent support for our app by default
    without any code changes
●   Spawns and manages worker processes and
    distributes load amongst them
Migrating our products
def handle_purchase( request ):
    jobs = []
    jobs.append( gevent.spawn( biller, … ) )
    jobs.append( gevent.spawn( ads, … ) )
    jobs.append( gevent.spawn( meta, … ) )
    jobs.append( gevent.spawn( reco, … ) )
    gevent.joinall()
Migrating our products
●   Migrating our entire code base (2 products)
    took around 1 week to finish
●   Was easier because we were already using
    inlineCallbacks() decorator of twisted
●   Only small parts of our code had to be migrated
Deployment

                        Gunicorn 1



                        Gunicorn 2
             Nginx
Client
           (SSL & LB)
                             .
                             .
                             .
                        Gunicorn N

                                 Proc 1

                                 Proc 2

                                 Proc N
Life today
●   Single framework for all 4 products
●   Use django's awesome features and
    ecosystem
●   Increased scalability. More so with celery.
●   Use blocking python libraries without worrying
    too much
●   No more usage of python-twisted
●   Coding, testing and maintenance is much
    easier
●   We are hiring!!
Links
●   http://greenlet.readthedocs.org/en/latest/index.html
●   http://www.gevent.org/
●   http://in.pycon.org/2010/talks/48-twisted-programming

More Related Content

What's hot

Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스
Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스
Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스Minkyu Cho
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python CeleryMahendra M
 
검색엔진이 데이터를 다루는 법 김종민
검색엔진이 데이터를 다루는 법 김종민검색엔진이 데이터를 다루는 법 김종민
검색엔진이 데이터를 다루는 법 김종민종민 김
 
Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...
Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...
Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...Lightbend
 
Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자Kyoung Up Jung
 
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론Terry Cho
 
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)Seongyun Byeon
 
PFsense 방화벽 소개
PFsense 방화벽 소개PFsense 방화벽 소개
PFsense 방화벽 소개ajj007
 
Optimizing Cypher Queries in Neo4j
Optimizing Cypher Queries in Neo4jOptimizing Cypher Queries in Neo4j
Optimizing Cypher Queries in Neo4jNeo4j
 
20141223 머하웃(mahout) 협업필터링_추천시스템구현
20141223 머하웃(mahout) 협업필터링_추천시스템구현20141223 머하웃(mahout) 협업필터링_추천시스템구현
20141223 머하웃(mahout) 협업필터링_추천시스템구현Tae Young Lee
 
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for UnrealKyu-sung Choi
 
개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 introSeongyun Byeon
 
개인화 추천은 어디로 가고 있는가?
개인화 추천은 어디로 가고 있는가?개인화 추천은 어디로 가고 있는가?
개인화 추천은 어디로 가고 있는가?choi kyumin
 
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...Altinity Ltd
 
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축Youngil Cho
 
Retail referencearchitecture productcatalog
Retail referencearchitecture productcatalogRetail referencearchitecture productcatalog
Retail referencearchitecture productcatalogMongoDB
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBMike Dirolf
 
Java EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldJava EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldRoberto Cortez
 
ClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovAltinity Ltd
 

What's hot (20)

Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스
Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스
Apache Mahout 맛보기 - 30분만에 추천시스템 만들기 for 네이버 TV 서비스
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python Celery
 
검색엔진이 데이터를 다루는 법 김종민
검색엔진이 데이터를 다루는 법 김종민검색엔진이 데이터를 다루는 법 김종민
검색엔진이 데이터를 다루는 법 김종민
 
Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...
Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...
Using the Actor Model with Domain-Driven Design (DDD) in Reactive Systems - w...
 
Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자Django로 쇼핑몰 만들자
Django로 쇼핑몰 만들자
 
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
대용량 분산 아키텍쳐 설계 #1 아키텍쳐 설계 방법론
 
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
[MLOps KR 행사] MLOps 춘추 전국 시대 정리(210605)
 
PFsense 방화벽 소개
PFsense 방화벽 소개PFsense 방화벽 소개
PFsense 방화벽 소개
 
Optimizing Cypher Queries in Neo4j
Optimizing Cypher Queries in Neo4jOptimizing Cypher Queries in Neo4j
Optimizing Cypher Queries in Neo4j
 
20141223 머하웃(mahout) 협업필터링_추천시스템구현
20141223 머하웃(mahout) 협업필터링_추천시스템구현20141223 머하웃(mahout) 협업필터링_추천시스템구현
20141223 머하웃(mahout) 협업필터링_추천시스템구현
 
Log design
Log designLog design
Log design
 
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
게임엔진과 공간정보 3D 콘텐츠 융합 : Cesium for Unreal
 
개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro
 
개인화 추천은 어디로 가고 있는가?
개인화 추천은 어디로 가고 있는가?개인화 추천은 어디로 가고 있는가?
개인화 추천은 어디로 가고 있는가?
 
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
ClickHouse and the Magic of Materialized Views, By Robert Hodges and Altinity...
 
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
2017 Pycon KR - Django/AWS 를 이용한 쇼핑몰 서비스 구축
 
Retail referencearchitecture productcatalog
Retail referencearchitecture productcatalogRetail referencearchitecture productcatalog
Retail referencearchitecture productcatalog
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Java EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real WorldJava EE 7 Batch processing in the Real World
Java EE 7 Batch processing in the Real World
 
ClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei MilovidovClickHouse Features for Advanced Users, by Aleksei Milovidov
ClickHouse Features for Advanced Users, by Aleksei Milovidov
 

Viewers also liked

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
 
Разработка сетевых приложений с gevent
Разработка сетевых приложений с geventРазработка сетевых приложений с gevent
Разработка сетевых приложений с geventAndrey Popp
 
Djangoのエントリポイントとアプリケーションの仕組み
Djangoのエントリポイントとアプリケーションの仕組みDjangoのエントリポイントとアプリケーションの仕組み
Djangoのエントリポイントとアプリケーションの仕組みShinya Okano
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using PythonAyun Park
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBrendan Gregg
 
Python Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The GloryPython Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The Gloryemptysquare
 

Viewers also liked (13)

Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 
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
 
Разработка сетевых приложений с gevent
Разработка сетевых приложений с geventРазработка сетевых приложений с gevent
Разработка сетевых приложений с gevent
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
Djangoのエントリポイントとアプリケーションの仕組み
Djangoのエントリポイントとアプリケーションの仕組みDjangoのエントリポイントとアプリケーションの仕組み
Djangoのエントリポイントとアプリケーションの仕組み
 
Scaling Django
Scaling DjangoScaling Django
Scaling Django
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Blazing Performance with Flame Graphs
Blazing Performance with Flame GraphsBlazing Performance with Flame Graphs
Blazing Performance with Flame Graphs
 
WSGI, Django, Gunicorn
WSGI, Django, GunicornWSGI, Django, Gunicorn
WSGI, Django, Gunicorn
 
Python Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The GloryPython Performance Profiling: The Guts And The Glory
Python Performance Profiling: The Guts And The Glory
 

Similar to Scaling Django with gevent

Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...
Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...
Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...Nicolas Brousse
 
Helidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxHelidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxDmitry Kornilov
 
Improving Operations Efficiency with Puppet
Improving Operations Efficiency with PuppetImproving Operations Efficiency with Puppet
Improving Operations Efficiency with PuppetNicolas Brousse
 
My "Perfect" Toolchain Setup for Grails Projects
My "Perfect" Toolchain Setup for Grails ProjectsMy "Perfect" Toolchain Setup for Grails Projects
My "Perfect" Toolchain Setup for Grails ProjectsGR8Conf
 
[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep DiveAkihiro Suda
 
Python twisted
Python twistedPython twisted
Python twistedMahendra M
 
Meiga Guadec 2009 English
Meiga Guadec 2009 EnglishMeiga Guadec 2009 English
Meiga Guadec 2009 Englisheocanha
 
Testing Django APIs
Testing Django APIsTesting Django APIs
Testing Django APIstyomo4ka
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101Itiel Shwartz
 
Node.js Presentation
Node.js PresentationNode.js Presentation
Node.js PresentationExist
 
A Python Petting Zoo
A Python Petting ZooA Python Petting Zoo
A Python Petting Zoodevondjones
 
Customize and Secure the Runtime and Dependencies of Your Procedural Language...
Customize and Secure the Runtime and Dependencies of Your Procedural Language...Customize and Secure the Runtime and Dependencies of Your Procedural Language...
Customize and Secure the Runtime and Dependencies of Your Procedural Language...VMware Tanzu
 
GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011Manuel Carrasco Moñino
 
Continuous delivery of Windows micro services in the cloud
Continuous delivery of Windows micro services in the cloud Continuous delivery of Windows micro services in the cloud
Continuous delivery of Windows micro services in the cloud Owain Perry
 

Similar to Scaling Django with gevent (20)

Scaling django
Scaling djangoScaling django
Scaling django
 
Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...
Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...
Puppet Camp Silicon Valley 2015: How TubeMogul reached 10,000 Puppet Deployme...
 
Helidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptxHelidon Nima - Loom based microserfice framework.pptx
Helidon Nima - Loom based microserfice framework.pptx
 
Improving Operations Efficiency with Puppet
Improving Operations Efficiency with PuppetImproving Operations Efficiency with Puppet
Improving Operations Efficiency with Puppet
 
My "Perfect" Toolchain Setup for Grails Projects
My "Perfect" Toolchain Setup for Grails ProjectsMy "Perfect" Toolchain Setup for Grails Projects
My "Perfect" Toolchain Setup for Grails Projects
 
[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive
 
Python twisted
Python twistedPython twisted
Python twisted
 
Meiga Guadec 2009 English
Meiga Guadec 2009 EnglishMeiga Guadec 2009 English
Meiga Guadec 2009 English
 
Testing Django APIs
Testing Django APIsTesting Django APIs
Testing Django APIs
 
Distributed Tracing
Distributed TracingDistributed Tracing
Distributed Tracing
 
Distributed tracing 101
Distributed tracing 101Distributed tracing 101
Distributed tracing 101
 
Node.js Presentation
Node.js PresentationNode.js Presentation
Node.js Presentation
 
Netty training
Netty trainingNetty training
Netty training
 
Netty training
Netty trainingNetty training
Netty training
 
A Python Petting Zoo
A Python Petting ZooA Python Petting Zoo
A Python Petting Zoo
 
SWT Tech Sharing: Node.js + Redis
SWT Tech Sharing: Node.js + RedisSWT Tech Sharing: Node.js + Redis
SWT Tech Sharing: Node.js + Redis
 
Customize and Secure the Runtime and Dependencies of Your Procedural Language...
Customize and Secure the Runtime and Dependencies of Your Procedural Language...Customize and Secure the Runtime and Dependencies of Your Procedural Language...
Customize and Secure the Runtime and Dependencies of Your Procedural Language...
 
GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011GQuery a jQuery clone for Gwt, RivieraDev 2011
GQuery a jQuery clone for Gwt, RivieraDev 2011
 
Monkey Server
Monkey ServerMonkey Server
Monkey Server
 
Continuous delivery of Windows micro services in the cloud
Continuous delivery of Windows micro services in the cloud Continuous delivery of Windows micro services in the cloud
Continuous delivery of Windows micro services in the cloud
 

Recently uploaded

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 

Recently uploaded (20)

Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 

Scaling Django with gevent

  • 1. Scaling Django with Gevent Mahendra M @mahendra https://github.com/mahendra
  • 2. @mahendra ● Python developer for 6 years ● FOSS enthusiast/volunteer for 14 years ● Bangalore LUG and Infosys LUG ● FOSS.in and LinuxBangalore/200x ● Gevent user for 1 year ● Twisted user for 5 years (before migrating) ● Added twisted support libraries like mustaine
  • 3. Concurrency models ● Multi-Process ● Threads ● Event driven ● Coroutines
  • 4. Process/Thread request dispatch() worker_1() read(fp) db_rd() db_wr() sock_wr() worker_n()
  • 5. Process/Thread ● There are blocking sections in the code ● Python GIL is an issue in thread based concurrency
  • 6. Event driven event_1 hdler_1() ev() event_2 block_on_events() hdler_2() Events are posted event_n hdler_n()
  • 7. Event driven web server request open(fp) reg() opened parse() event_loop() read_sql() reg() sql_read wri_sql() reg() sql_writ sock_wr() reg() responded close()
  • 8. Two years back ● Using python twisted for half of our products ● Using django for the other half ● Quite a nightmare
  • 9. Python twisted ● An event driven library (very scalable) ● Using epoll or kqueue Server 1 Server 2 Nginx Client (SSL & LB) . . . Server N Proc 1 (:8080) Proc 2 (:8080) Proc N (:8080)
  • 10. Gevent A coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libevent event loop.
  • 11. Gevent A coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libevent event loop.
  • 12. Coroutines ● Python coroutines are almost similar to generators. def abc( seq ): lst = list( seq ) for i in lst: value = yield i if cmd is not None: lst.append( value ) r = abc( [1,2,3] ) r.send( 4 )
  • 13. Gevent features ● Fast event-loop based on libevent (epoll, kqueue etc.) ● Lightweight execution units based on greenlets (coroutines) ● Monkey patching support ● Simple API ● Fast WSGI server
  • 14. Greenlets ● Primitive notion of micro-threads with no implicit scheduling ● Just co-routines or independent pseudo- threads ● Other systems like gevent build micro-threads on top of greenlets. ● Execution happens by switching execution among greenlet stacks ● Greenlet switching is not implicit (switch())
  • 15. Greenlet execution Main greenlet pause() abc() Child greenlet func_1() pause() some() reg() func_2()
  • 16. Greenlet code from greenlet import greenlet def test1(): gr2.switch() def test2(): gr1.switch() gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch()
  • 17. How does gevent work ● Creates an implicit event loop inside a dedicated greenlet ● When a function in gevent wants to block, it switches to the greenlet of the event loop. This will schedule another child greenlet to run ● The eventloop automatically picks up the fastest polling mechanism available in the system ● One event loop runs inside a single OS thread (process)
  • 18. Gevent code import gevent from gevent import socket urls = ['www.google.com', 'www.example.com', 'www.python.org'] jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls] gevent.joinall(jobs, timeout=2) [job.value for job in jobs] ['74.125.79.106', '208.77.188.166', '82.94.164.162']
  • 19. Gevent apis ● Greenlet management (spawn, timeout, schedule) ● Greenlet local data ● Networking (socket, ssl, dns, select) ● Synchronization ● Event – notify multiple listeners ● Queue – synchronized producer/consumer queues ● Locking – Semaphores ● Greenlet pools ● TCP/IP and WSGI servers
  • 20. Gevent advantages ● Almost synchronous code. No callbacks and deferreds ● Lightweight greenlets ● Good concurrency ● No issues of python GIL ● No need for in-process locking, since a greenlet cannot be pre-empted
  • 21. Gevent issues ● A greenlet will run till it blocks or switches ● Be vary of large/infinite loops ● Monkey patching is required for un-supported blocking libraries. Might not work well with some libraries
  • 22. Our django dream ● We love django ● I like twisted, but love django more ● Coding complexity ● Lack of developers for hire ● Deployment complexity ● Gevent saved the day
  • 23. The Django Problem ● In a HTTP request cycle, we wanted the following operations ● Fetch some metadata for an item being sold ● Purchase the item for the user in the billing system ● Fetch ads to be shown along with the item ● Fetch recommendations based on this item ● In parallel … !! ● Twisted was the only option
  • 24. Twisted code def handle_purchase( rqst ): defs = [] defs.append( biller() ) defs.append( ads() ) defs.append( recos() ) defs.append( meta() ) def = DeferredList( defs, … ) def.addCallback( send_response() ) return NOT_DONE_YET
  • 25. Twisted issues ● The issues were with everything else ● Header management ● Templates for response ● ORM support ● SOAP, REST, Hessian/Burlap support – We liked to use suds, requests, mustaine etc. ● Session management and auth ● Caching support ● The above are django's strength ● Django's vibrant eco-system (celery, south, tastypie)
  • 26. gunicorn ● A python WSGI HTTP server ● Supports running code under worker, eventlet, gevent etc. ● Uses monkey patching ● Excellent django support ● gunicorn_django app.settings ● Enabled gevent support for our app by default without any code changes ● Spawns and manages worker processes and distributes load amongst them
  • 27. Migrating our products def handle_purchase( request ): jobs = [] jobs.append( gevent.spawn( biller, … ) ) jobs.append( gevent.spawn( ads, … ) ) jobs.append( gevent.spawn( meta, … ) ) jobs.append( gevent.spawn( reco, … ) ) gevent.joinall()
  • 28. Migrating our products ● Migrating our entire code base (2 products) took around 1 week to finish ● Was easier because we were already using inlineCallbacks() decorator of twisted ● Only small parts of our code had to be migrated
  • 29. Deployment Gunicorn 1 Gunicorn 2 Nginx Client (SSL & LB) . . . Gunicorn N Proc 1 Proc 2 Proc N
  • 30. Life today ● Single framework for all 4 products ● Use django's awesome features and ecosystem ● Increased scalability. More so with celery. ● Use blocking python libraries without worrying too much ● No more usage of python-twisted ● Coding, testing and maintenance is much easier ● We are hiring!!
  • 31. Links ● http://greenlet.readthedocs.org/en/latest/index.html ● http://www.gevent.org/ ● http://in.pycon.org/2010/talks/48-twisted-programming