SlideShare a Scribd company logo
How to scale Django
Ahsanuzzaman Khan
Sr. Software Engineer
Z. S. Solution Ltd.
How does Django
application scale?
Concurrency Models
Models
Found around the web!
Multi-process
Threads
Event driven
Coroutines
Process/Threads
There are blocking sections in the code
1. Python Global Interpreter Locator
(GIL) is an issue in thread based
concurrency
request dispatch
worker_1
worker_n
sock_wr()
db_rd_wr()
read(fp)
Event Driven
Can anyone gives an example?
event_1
event_n
block_on_events(
)
h_n()
h_2()
h_1()
Event Driven Web Servers
1. Nginx
2. Tornado
3. Node.js
event_1
event_n
block_on_events(
)
h_n()
h_2()
h_1()
Python Twisted
1. An event driven library
2. Using epoll or kqueue
client_1
client_n
Nginx
(SSL & LB)
s_n()
s_2()
s_1()
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
A coroutine-based Python networking library that uses greenlet to provide a high-level
synchronous API on top of the libevent event loop.
Details of Gevent
Gevent Features
1. Fast event-loop based on libevent (epoll, kqueue etc.)
2. Lightweight execution units based on greenlets (coroutines)
3. Monkey patching support
4. Simple API
5. TCP/UDP/HTTP and Fast WSGI servers
6. Cooperative socket with SSL support
Greenlets
1. Micro-threads with no implicit scheduling
2. It is nothing just coroutines
3. Other systems like gevent build micro-
threads on top of greenlets
4. Execution happens by switching
execution among greenlet stacks but not
implicit
Main
greenlet
task()
Child greenlet
h_n()
pause()
func()
res()
Greenlet code example
from greenlet import greenlet
def test1():
print 12
gr2.switch()
print 34
def test2():
print 56
gr1.switch()
print 78
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
Output:
12
56
34
How does gevent work
1. Creates an implicit event loop inside a dedicated greenlet
2. 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.
3. The eventloop automatically picks up the fastest polling mechanism available in the
system.
4. One event loop runs inside a single OS thread (process).
Gevent code
import gevent
from gevent import socket
urls = [‘www.google.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]
Output: ['172.217.26.68', '151.101.192.223']
Gevent apis
1. Greenlet management (spawn, timeout, schedule)
2. Greenlet local data
3. Networking (socket, ssl, dns, select)
4. Synchronization
a. Event - notify multiple listeners
b. Queue - synchronized producer/consumer queues
c. Locking - Semaphores
5. Greenlet pools
6. TCP/IP and WSGI servers
and many more...
Gevent advantages
1. Almost synchronous code. No
callbacks and deferred.
2. Lightweight greenlets.
3. Good concurrency.
4. No issues of python GIL.
5. No need for in-process locking, since
a greenlet cannot be preempted.
Gevent issues
1. A greenlet will run till it blocks or switches
a. May vary of large/infinite loops
2. Monkey patching is required for un-supported blocking libraries. Might not work well
with some libraries.
The Django Problem
1. Asynchronous not yet supported
2. In HTTP request cycle we want following operations
a. Fetch some metadata for an item being sold
b. Purchase the item for the user in the billing system
c. Fetch ads to be shown along with the item
d. Fetch recommendations based on this item
3. In parallel … !!
a. Twisted was the only option
Gevent saved the day :)
Twisted Issues
The issues were with everything else
Header management
Templates for response
ORM support
Session management and auth
Caching support
Many more….
The above are django’s strength
Django has vibrant eco-system
Gunicorn
1. Python WSGI HTTP server
2. Supports running code under worker, eventlet, gevent etc.
a. Uses monkey patching
3. Excellent django support
4. Enabled gevent support for our app by default without any
code changes
5. Spawns and manages worker processes and distributes load
among
Migrating our products
Twisted Code:
def handle_purchase( request ):
defs = []
defs.append(billert())
defs.append(ads())
defs.append(recos() )
defs.append(meta() )
def = DeferredList(defs, …)
Return NOT_DONE_YET
Gevent Code:
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
1. Time is concern :(
Deployment
Client Nginx
(SSL & LB)
Gunicorn 1
Gunicorn N
Proc N
Proc 2
Proc 1
Conclusion
1.Single framework for all products
2.Use django’s awesome features and ecosystem
3.Increased scalability. More so with celery.
4.Use blocking python libraries without worrying too much
5.No more usage of python-twisted
6.Coding, testing and maintenance is much easier
Links
http://greenlet.readthedocs.io/en/latest/index.html
http://www.gevent.org/
Mahendra M
https://github.com/mahendra
Special Thanks

More Related Content

PDF
Python in the database
PDF
The Ring programming language version 1.7 book - Part 52 of 196
PDF
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
PDF
Modern Android app library stack
PPTX
Presentation Android Architecture Components
PDF
Android Architecture components
PDF
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
PDF
Deep Dive into Zone.JS
Python in the database
The Ring programming language version 1.7 book - Part 52 of 196
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Modern Android app library stack
Presentation Android Architecture Components
Android Architecture components
JCConf 2015 - 輕鬆學google的雲端開發 - Google App Engine入門(上)
Deep Dive into Zone.JS

What's hot (20)

PPTX
Advanced #3 threading
ODP
XML-RPC vs Psycopg2
PDF
Php user groupmemcached
PPTX
Android architecture components
PPTX
Servlet session 9
PDF
Workflows ss
PPTX
TDD in the wild
PDF
Dagger & rxjava & retrofit
PPTX
Sapphire Gimlets
PPTX
Guice gin
PDF
JJUG CCC 2011 Spring
PPTX
Advanced #2 threading
PDF
Browser testing with nightwatch.js - Drupal Europe
PPTX
Django and working with large database tables
PPTX
Unit/Integration Testing using Spock
PPTX
Beyond Profilers: Tracing Node.js Transactions
PDF
Pycon 2012 Apache Cassandra
PPTX
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
PPTX
Advanced #3 threading
XML-RPC vs Psycopg2
Php user groupmemcached
Android architecture components
Servlet session 9
Workflows ss
TDD in the wild
Dagger & rxjava & retrofit
Sapphire Gimlets
Guice gin
JJUG CCC 2011 Spring
Advanced #2 threading
Browser testing with nightwatch.js - Drupal Europe
Django and working with large database tables
Unit/Integration Testing using Spock
Beyond Profilers: Tracing Node.js Transactions
Pycon 2012 Apache Cassandra
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Ad

Similar to Scaling django (20)

PDF
Scaling Django with gevent
PDF
Gevent be or not to be
PDF
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
PPTX
Using Coroutines to Create Efficient, High-Concurrency Web Applications
PDF
gevent at TellApart
PDF
Gevent at TellApart
PPTX
Gevent rabbit rpc
PDF
Python twisted
PPTX
Realtime web2012
KEY
DjangoCon recap
PPT
Real-Time Python Web: Gevent and Socket.io
PDF
The State of WebSockets in Django
PDF
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
PDF
Twisted
KEY
Gevent what's the point
PDF
Python, do you even async?
PDF
Real time web_apps_pycon2012-v1
ODP
Introduction to Python Celery
PDF
2012 07 making disqus realtime@euro python
PDF
Advanced workflows
Scaling Django with gevent
Gevent be or not to be
«Gevent — быть или не быть?» Александр Мокров, Positive Technologies
Using Coroutines to Create Efficient, High-Concurrency Web Applications
gevent at TellApart
Gevent at TellApart
Gevent rabbit rpc
Python twisted
Realtime web2012
DjangoCon recap
Real-Time Python Web: Gevent and Socket.io
The State of WebSockets in Django
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Twisted
Gevent what's the point
Python, do you even async?
Real time web_apps_pycon2012-v1
Introduction to Python Celery
2012 07 making disqus realtime@euro python
Advanced workflows
Ad

Recently uploaded (20)

PDF
Getting Started with Data Integration: FME Form 101
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation theory and applications.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Machine learning based COVID-19 study performance prediction
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Getting Started with Data Integration: FME Form 101
MIND Revenue Release Quarter 2 2025 Press Release
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation theory and applications.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Programs and apps: productivity, graphics, security and other tools
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
Tartificialntelligence_presentation.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Machine learning based COVID-19 study performance prediction
A comparative analysis of optical character recognition models for extracting...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Advanced methodologies resolving dimensionality complications for autism neur...
SOPHOS-XG Firewall Administrator PPT.pptx
Assigned Numbers - 2025 - Bluetooth® Document
Diabetes mellitus diagnosis method based random forest with bat algorithm

Scaling django

  • 1. How to scale Django Ahsanuzzaman Khan Sr. Software Engineer Z. S. Solution Ltd.
  • 4. Models Found around the web! Multi-process Threads Event driven Coroutines
  • 5. Process/Threads There are blocking sections in the code 1. Python Global Interpreter Locator (GIL) is an issue in thread based concurrency request dispatch worker_1 worker_n sock_wr() db_rd_wr() read(fp)
  • 6. Event Driven Can anyone gives an example? event_1 event_n block_on_events( ) h_n() h_2() h_1()
  • 7. Event Driven Web Servers 1. Nginx 2. Tornado 3. Node.js event_1 event_n block_on_events( ) h_n() h_2() h_1()
  • 8. Python Twisted 1. An event driven library 2. Using epoll or kqueue client_1 client_n Nginx (SSL & LB) s_n() s_2() s_1()
  • 9. 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)
  • 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.
  • 12. Gevent Features 1. Fast event-loop based on libevent (epoll, kqueue etc.) 2. Lightweight execution units based on greenlets (coroutines) 3. Monkey patching support 4. Simple API 5. TCP/UDP/HTTP and Fast WSGI servers 6. Cooperative socket with SSL support
  • 13. Greenlets 1. Micro-threads with no implicit scheduling 2. It is nothing just coroutines 3. Other systems like gevent build micro- threads on top of greenlets 4. Execution happens by switching execution among greenlet stacks but not implicit Main greenlet task() Child greenlet h_n() pause() func() res()
  • 14. Greenlet code example from greenlet import greenlet def test1(): print 12 gr2.switch() print 34 def test2(): print 56 gr1.switch() print 78 gr1 = greenlet(test1) gr2 = greenlet(test2) gr1.switch() Output: 12 56 34
  • 15. How does gevent work 1. Creates an implicit event loop inside a dedicated greenlet 2. 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. 3. The eventloop automatically picks up the fastest polling mechanism available in the system. 4. One event loop runs inside a single OS thread (process).
  • 16. Gevent code import gevent from gevent import socket urls = [‘www.google.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] Output: ['172.217.26.68', '151.101.192.223']
  • 17. Gevent apis 1. Greenlet management (spawn, timeout, schedule) 2. Greenlet local data 3. Networking (socket, ssl, dns, select) 4. Synchronization a. Event - notify multiple listeners b. Queue - synchronized producer/consumer queues c. Locking - Semaphores 5. Greenlet pools 6. TCP/IP and WSGI servers and many more...
  • 18. Gevent advantages 1. Almost synchronous code. No callbacks and deferred. 2. Lightweight greenlets. 3. Good concurrency. 4. No issues of python GIL. 5. No need for in-process locking, since a greenlet cannot be preempted.
  • 19. Gevent issues 1. A greenlet will run till it blocks or switches a. May vary of large/infinite loops 2. Monkey patching is required for un-supported blocking libraries. Might not work well with some libraries.
  • 20. The Django Problem 1. Asynchronous not yet supported 2. In HTTP request cycle we want following operations a. Fetch some metadata for an item being sold b. Purchase the item for the user in the billing system c. Fetch ads to be shown along with the item d. Fetch recommendations based on this item 3. In parallel … !! a. Twisted was the only option Gevent saved the day :)
  • 21. Twisted Issues The issues were with everything else Header management Templates for response ORM support Session management and auth Caching support Many more…. The above are django’s strength Django has vibrant eco-system
  • 22. Gunicorn 1. Python WSGI HTTP server 2. Supports running code under worker, eventlet, gevent etc. a. Uses monkey patching 3. Excellent django support 4. Enabled gevent support for our app by default without any code changes 5. Spawns and manages worker processes and distributes load among
  • 23. Migrating our products Twisted Code: def handle_purchase( request ): defs = [] defs.append(billert()) defs.append(ads()) defs.append(recos() ) defs.append(meta() ) def = DeferredList(defs, …) Return NOT_DONE_YET Gevent Code: 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()
  • 24. Migrating our products 1. Time is concern :(
  • 25. Deployment Client Nginx (SSL & LB) Gunicorn 1 Gunicorn N Proc N Proc 2 Proc 1
  • 26. Conclusion 1.Single framework for all products 2.Use django’s awesome features and ecosystem 3.Increased scalability. More so with celery. 4.Use blocking python libraries without worrying too much 5.No more usage of python-twisted 6.Coding, testing and maintenance is much easier