SlideShare a Scribd company logo
1 of 23
Python, MongoDB, and
asynchronous web frameworks
        A. Jesse Jiryu Davis
        jesse@10gen.com
         emptysquare.net
Agenda
• Talk about web services in a really dumb
  (“abstract”?) way
• Explain when we need async web servers
• Why is async hard?
• What is Tornado and how does it work?
• Why am I writing a new PyMongo wrapper to
  work with Tornado?
• How does my wrapper work?
CPU-bound web service


   Client                 Server
               socket




• No need for async
• Just spawn one process per core
Normal web service


                                             Backend
   Client                Server            (DB, web service,
              socket              socket        SAN, …)




• Assume backend is unbounded
• Service is bound by:
  • Context-switching overhead
  • Memory!
What’s async for?
• Minimize resources per connection
• I.e., wait for backend as cheaply as possible
CPU- vs. Memory-bound



Crypto         Most web services?           Chat
                      •
CPU-bound                           Memory-bound
HTTP long-polling (“COMET”)
• E.g., chat server
• Async’s killer app
• Short-polling is CPU-bound: tradeoff between
  latency and load
• Long-polling is memory bound
• “C10K problem”: kegel.com/c10k.html
• Tornado was invented for this
Why is async hard to code?
Client                   Server                 Backend
           request

                                      request
time




                       store state

                                     response



            response
Ways to store state
                                    this slide is in beta



                        Multithreading
Memory per connection




                        Greenlets / Gevent
                                                       Tornado, Node.js



                                  Coding difficulty
What’s a greenlet?
• A.K.A. “green threads”
• A feature of Stackless Python, packaged as a
  module for standard Python
• Greenlet stacks are stored on heap, copied to
  / from OS stack on resume / pause
• Cooperative
• Memory-efficient
Threads:
       State stored on OS stacks
# pseudo-Python

sock = listen()

request = parse_http(sock.recv())

mongo_data = db.collection.find()

response = format_response(mongo_data)

sock.sendall(response)
Gevent:
      State stored on greenlet stacks
# pseudo-Python
import gevent.monkey; monkey.patch_all()

sock = listen()

request = parse_http(sock.recv())

mongo_data = db.collection.find()

response = format_response(mongo_data)

sock.sendall(response)
Tornado:
 State stored in RequestHandler
class MainHandler(tornado.web.RequestHandler):
  @tornado.web.asynchronous
  def get(self):
    AsyncHTTPClient().fetch(
            "http://example.com",
       callback=self.on_response)

  def on_response(self, response):
    formatted = format_response(response)
    self.write(formatted)
    self.finish()
Tornado IOStream
class IOStream(object):
  def read_bytes(self, num_bytes, callback):
    self.read_bytes = num_bytes
    self.read_callback = callback

    io_loop.add_handler(
      self.socket.fileno(),
              self.handle_events,
              events=READ)

  def handle_events(self, fd, events):
    data = self.socket.recv(self.read_bytes)
    self.read_callback(data)
Tornado IOLoop
class IOLoop(object):
  def add_handler(self, fd, handler, events):
    self._handlers[fd] = handler
    # _impl is epoll or kqueue or ...
    self._impl.register(fd, events)

  def start(self):
    while True:
       event_pairs = self._impl.poll()
       for fd, events in event_pairs:
          self._handlers[fd](fd, events)
Python, MongoDB, & concurrency
• Threads work great with pymongo
• Gevent works great with pymongo
  – monkey.patch_socket(); monkey.patch_thread()
• Tornado works so-so
  – asyncmongo
     • No replica sets, only first batch, no SON manipulators, no
       document classes, …
  – pymongo
     • OK if all your queries are fast
     • Use extra Tornado processes
Introducing: “Motor”
•   Mongo + Tornado
•   Experimental
•   Might be official in a few months
•   Uses Tornado IOLoop and IOStream
•   Presents standard Tornado callback API
•   Stores state internally with greenlets
•   github.com/ajdavis/mongo-python-driver/tree/tornado_async
Motor
class MainHandler(tornado.web.RequestHandler):
  def __init__(self):
    self.c = MotorConnection()

  @tornado.web.asynchronous
  def post(self):
    # No-op if already open
    self.c.open(callback=self.connected)

  def connected(self, c, error):
    self.c.collection.insert(
       {‘x’:1},
       callback=self.inserted)

  def inserted(self, result, error):
    self.write(’OK’)
    self.finish()
Motor internals
                   stack depth
   Client       IOLoop              RequestHandler        greenlet        pymongo
         request
                                             start


                                                      switch()   IOStream.sendall(callback)

                             return
time




                       callback()          switch()


                                                      parse Mongo response
                             schedule
                             callback


                            callback()

       HTTP response
Motor internals: wrapper
class MotorCollection(object):
  def insert(self, *args, **kwargs):
    callback = kwargs['callback']
     1
    del kwargs['callback']
    kwargs['safe'] = True

     def call_insert():
       # Runs on child greenlet
       result, error = None, None
       try:
          sync_insert = self.sync_collection.insert
            3
          result = sync_insert(*args, **kwargs)
       except Exception, e:
          error = e

       # Schedule the callback to be run on the main greenlet
       tornado.ioloop.IOLoop.instance().add_callback(
          lambda: callback(result, error)
                                                                8
       )

     # Start child greenlet
       2
     greenlet.greenlet(call_insert).switch()


       6
     return
Motor internals: fake socket
class MotorSocket(object):
  def __init__(self, socket):
    # Makes socket non-blocking
    self.stream = tornado.iostream.IOStream(socket)

  def sendall(self, data):
    child_gr = greenlet.getcurrent()

    # This is run by IOLoop on the main greenlet
    # when data has been sent;
    # switch back to child to continue processing
    def sendall_callback():
       child_gr.switch()                   7

    self.stream.write(data, callback=sendall_callback)
     4
    # Resume main greenlet
    child_gr.parent.switch()
     5
Motor
• Shows a general method for asynchronizing
  synchronous network APIs in Python
• Who wants to try it with MySQL? Thrift?
• (Bonus round: resynchronizing Motor for
  testing)
Questions?
   A. Jesse Jiryu Davis
   jesse@10gen.com
    emptysquare.net

(10gen is hiring, of course:
   10gen.com/careers)

More Related Content

What's hot

Real time server
Real time serverReal time server
Real time serverthepian
 
Even faster django
Even faster djangoEven faster django
Even faster djangoGage Tseng
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseChristian Melchior
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2Graham Dumpleton
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJSSylvain Zimmer
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.Graham Dumpleton
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8amix3k
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHPKing Foo
 
Vert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCDVert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCDTim Nolet
 
Node js presentation
Node js presentationNode js presentation
Node js presentationmartincabrera
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryTatsuhiko Miyagawa
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Baruch Sadogursky
 
Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Baruch Sadogursky
 

What's hot (20)

Real time server
Real time serverReal time server
Real time server
 
Even faster django
Even faster djangoEven faster django
Even faster django
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
Web Crawling with NodeJS
Web Crawling with NodeJSWeb Crawling with NodeJS
Web Crawling with NodeJS
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
PyCon AU 2010 - Getting Started With Apache/mod_wsgi.
 
Comet with node.js and V8
Comet with node.js and V8Comet with node.js and V8
Comet with node.js and V8
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
Vert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCDVert.x clustering on Docker, CoreOS and ETCD
Vert.x clustering on Docker, CoreOS and ETCD
 
Node.js in production
Node.js in productionNode.js in production
Node.js in production
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
OneRing @ OSCamp 2010
OneRing @ OSCamp 2010OneRing @ OSCamp 2010
OneRing @ OSCamp 2010
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
 
Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...Presentation: Everything you wanted to know about writing async, high-concurr...
Presentation: Everything you wanted to know about writing async, high-concurr...
 

Viewers also liked

Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with PythonAnton Caceres
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using PythonAyun Park
 
Federmanager Bologna - Personal Branding 8 marzo - Presidente Andrea Molza
Federmanager Bologna - Personal Branding 8 marzo - Presidente Andrea MolzaFedermanager Bologna - Personal Branding 8 marzo - Presidente Andrea Molza
Federmanager Bologna - Personal Branding 8 marzo - Presidente Andrea MolzaMarco Frullanti
 
La televisió blai
La televisió blaiLa televisió blai
La televisió blaimgonellgomez
 
Countering Cyber Threats By Monitoring “Normal” Website Behavior
Countering Cyber Threats By Monitoring “Normal” Website BehaviorCountering Cyber Threats By Monitoring “Normal” Website Behavior
Countering Cyber Threats By Monitoring “Normal” Website BehaviorEMC
 
Friday atlas lesson
Friday atlas lessonFriday atlas lesson
Friday atlas lessonTravis Klein
 
Срок жизни печатающей головки
Срок жизни печатающей головкиСрок жизни печатающей головки
Срок жизни печатающей головкиPROFIBLOG
 
Выпускники 2011
Выпускники 2011Выпускники 2011
Выпускники 2011lexa0784
 
Weapons for peace
Weapons for peaceWeapons for peace
Weapons for peacevicolombia
 
Friday business cycle AP Macro
Friday business cycle AP MacroFriday business cycle AP Macro
Friday business cycle AP MacroTravis Klein
 
It’s a Jungle Out There - Improving Communications with Your Volunteers
It’s a Jungle Out There - Improving Communications with Your VolunteersIt’s a Jungle Out There - Improving Communications with Your Volunteers
It’s a Jungle Out There - Improving Communications with Your VolunteersLaurel Gerdine
 
Get hydrated
Get hydratedGet hydrated
Get hydratedsloeb
 
Biynees khemjee awah
Biynees khemjee awahBiynees khemjee awah
Biynees khemjee awahpvsa_8990
 
A Long Day Second Draft Script by Sophie McAvoy
A Long Day Second Draft Script by Sophie McAvoyA Long Day Second Draft Script by Sophie McAvoy
A Long Day Second Draft Script by Sophie McAvoysophiemcavoy1
 
A Day of Social Media Insights
A Day of Social Media InsightsA Day of Social Media Insights
A Day of Social Media InsightsResearch Now
 

Viewers also liked (20)

Tornado
TornadoTornado
Tornado
 
Asynchronous web-development with Python
Asynchronous web-development with PythonAsynchronous web-development with Python
Asynchronous web-development with Python
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
Federmanager Bologna - Personal Branding 8 marzo - Presidente Andrea Molza
Federmanager Bologna - Personal Branding 8 marzo - Presidente Andrea MolzaFedermanager Bologna - Personal Branding 8 marzo - Presidente Andrea Molza
Federmanager Bologna - Personal Branding 8 marzo - Presidente Andrea Molza
 
La televisió blai
La televisió blaiLa televisió blai
La televisió blai
 
Countering Cyber Threats By Monitoring “Normal” Website Behavior
Countering Cyber Threats By Monitoring “Normal” Website BehaviorCountering Cyber Threats By Monitoring “Normal” Website Behavior
Countering Cyber Threats By Monitoring “Normal” Website Behavior
 
Friday atlas lesson
Friday atlas lessonFriday atlas lesson
Friday atlas lesson
 
Hotel1
Hotel1Hotel1
Hotel1
 
Срок жизни печатающей головки
Срок жизни печатающей головкиСрок жизни печатающей головки
Срок жизни печатающей головки
 
Cvpw
CvpwCvpw
Cvpw
 
Выпускники 2011
Выпускники 2011Выпускники 2011
Выпускники 2011
 
Weapons for peace
Weapons for peaceWeapons for peace
Weapons for peace
 
Friday business cycle AP Macro
Friday business cycle AP MacroFriday business cycle AP Macro
Friday business cycle AP Macro
 
It’s a Jungle Out There - Improving Communications with Your Volunteers
It’s a Jungle Out There - Improving Communications with Your VolunteersIt’s a Jungle Out There - Improving Communications with Your Volunteers
It’s a Jungle Out There - Improving Communications with Your Volunteers
 
Get hydrated
Get hydratedGet hydrated
Get hydrated
 
Biynees khemjee awah
Biynees khemjee awahBiynees khemjee awah
Biynees khemjee awah
 
Palestra Barrett Brown - sustentabilidade
Palestra Barrett Brown - sustentabilidadePalestra Barrett Brown - sustentabilidade
Palestra Barrett Brown - sustentabilidade
 
A Long Day Second Draft Script by Sophie McAvoy
A Long Day Second Draft Script by Sophie McAvoyA Long Day Second Draft Script by Sophie McAvoy
A Long Day Second Draft Script by Sophie McAvoy
 
A Day of Social Media Insights
A Day of Social Media InsightsA Day of Social Media Insights
A Day of Social Media Insights
 

Similar to Python, async web frameworks, and MongoDB

Async programming and python
Async programming and pythonAsync programming and python
Async programming and pythonChetan Giridhar
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
Python twisted
Python twistedPython twisted
Python twistedMahendra M
 
Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011hangxin1940
 
Clug 2011 March web server optimisation
Clug 2011 March  web server optimisationClug 2011 March  web server optimisation
Clug 2011 March web server optimisationgrooverdan
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and ContainersRodolfo Carvalho
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonLuciano Mammino
 
Techniques to Improve Cache Speed
Techniques to Improve Cache SpeedTechniques to Improve Cache Speed
Techniques to Improve Cache SpeedZohaib Hassan
 
Node js
Node jsNode js
Node jshazzaz
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Muduo network library
Muduo network libraryMuduo network library
Muduo network libraryShuo Chen
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisationgrooverdan
 
Xebia Knowledge Exchange (feb 2011) - Large Scale Web Development
Xebia Knowledge Exchange (feb 2011) - Large Scale Web DevelopmentXebia Knowledge Exchange (feb 2011) - Large Scale Web Development
Xebia Knowledge Exchange (feb 2011) - Large Scale Web DevelopmentMichaël Figuière
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestPavan Chitumalla
 
The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)Dylan Jay
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.jsNitin Gupta
 

Similar to Python, async web frameworks, and MongoDB (20)

Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Building Web APIs that Scale
Building Web APIs that ScaleBuilding Web APIs that Scale
Building Web APIs that Scale
 
Python twisted
Python twistedPython twisted
Python twisted
 
Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011
 
Clug 2011 March web server optimisation
Clug 2011 March  web server optimisationClug 2011 March  web server optimisation
Clug 2011 March web server optimisation
 
Automation with Ansible and Containers
Automation with Ansible and ContainersAutomation with Ansible and Containers
Automation with Ansible and Containers
 
An opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathonAn opinionated intro to Node.js - devrupt hospitality hackathon
An opinionated intro to Node.js - devrupt hospitality hackathon
 
Techniques to Improve Cache Speed
Techniques to Improve Cache SpeedTechniques to Improve Cache Speed
Techniques to Improve Cache Speed
 
Scaling django
Scaling djangoScaling django
Scaling django
 
Node js
Node jsNode js
Node js
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Muduo network library
Muduo network libraryMuduo network library
Muduo network library
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Clug 2012 March web server optimisation
Clug 2012 March   web server optimisationClug 2012 March   web server optimisation
Clug 2012 March web server optimisation
 
Xebia Knowledge Exchange (feb 2011) - Large Scale Web Development
Xebia Knowledge Exchange (feb 2011) - Large Scale Web DevelopmentXebia Knowledge Exchange (feb 2011) - Large Scale Web Development
Xebia Knowledge Exchange (feb 2011) - Large Scale Web Development
 
Finagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at PinterestFinagle and Java Service Framework at Pinterest
Finagle and Java Service Framework at Pinterest
 
The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)The goodies of zope, pyramid, and plone (2)
The goodies of zope, pyramid, and plone (2)
 
Evented Ruby VS Node.js
Evented Ruby VS Node.jsEvented Ruby VS Node.js
Evented Ruby VS Node.js
 

More from emptysquare

Cat-Herd's Crook
Cat-Herd's CrookCat-Herd's Crook
Cat-Herd's Crookemptysquare
 
MongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep DiveMongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep Diveemptysquare
 
What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?emptysquare
 
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
 
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
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Futureemptysquare
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornadoemptysquare
 

More from emptysquare (7)

Cat-Herd's Crook
Cat-Herd's CrookCat-Herd's Crook
Cat-Herd's Crook
 
MongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep DiveMongoDB Drivers And High Availability: Deep Dive
MongoDB Drivers And High Availability: Deep Dive
 
What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?What Is Async, How Does It Work, And When Should I Use It?
What Is Async, How Does It Work, And When Should I Use It?
 
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
 
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
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornado
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Python, async web frameworks, and MongoDB

  • 1. Python, MongoDB, and asynchronous web frameworks A. Jesse Jiryu Davis jesse@10gen.com emptysquare.net
  • 2. Agenda • Talk about web services in a really dumb (“abstract”?) way • Explain when we need async web servers • Why is async hard? • What is Tornado and how does it work? • Why am I writing a new PyMongo wrapper to work with Tornado? • How does my wrapper work?
  • 3. CPU-bound web service Client Server socket • No need for async • Just spawn one process per core
  • 4. Normal web service Backend Client Server (DB, web service, socket socket SAN, …) • Assume backend is unbounded • Service is bound by: • Context-switching overhead • Memory!
  • 5. What’s async for? • Minimize resources per connection • I.e., wait for backend as cheaply as possible
  • 6. CPU- vs. Memory-bound Crypto Most web services? Chat • CPU-bound Memory-bound
  • 7. HTTP long-polling (“COMET”) • E.g., chat server • Async’s killer app • Short-polling is CPU-bound: tradeoff between latency and load • Long-polling is memory bound • “C10K problem”: kegel.com/c10k.html • Tornado was invented for this
  • 8. Why is async hard to code? Client Server Backend request request time store state response response
  • 9. Ways to store state this slide is in beta Multithreading Memory per connection Greenlets / Gevent Tornado, Node.js Coding difficulty
  • 10. What’s a greenlet? • A.K.A. “green threads” • A feature of Stackless Python, packaged as a module for standard Python • Greenlet stacks are stored on heap, copied to / from OS stack on resume / pause • Cooperative • Memory-efficient
  • 11. Threads: State stored on OS stacks # pseudo-Python sock = listen() request = parse_http(sock.recv()) mongo_data = db.collection.find() response = format_response(mongo_data) sock.sendall(response)
  • 12. Gevent: State stored on greenlet stacks # pseudo-Python import gevent.monkey; monkey.patch_all() sock = listen() request = parse_http(sock.recv()) mongo_data = db.collection.find() response = format_response(mongo_data) sock.sendall(response)
  • 13. Tornado: State stored in RequestHandler class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): AsyncHTTPClient().fetch( "http://example.com", callback=self.on_response) def on_response(self, response): formatted = format_response(response) self.write(formatted) self.finish()
  • 14. Tornado IOStream class IOStream(object): def read_bytes(self, num_bytes, callback): self.read_bytes = num_bytes self.read_callback = callback io_loop.add_handler( self.socket.fileno(), self.handle_events, events=READ) def handle_events(self, fd, events): data = self.socket.recv(self.read_bytes) self.read_callback(data)
  • 15. Tornado IOLoop class IOLoop(object): def add_handler(self, fd, handler, events): self._handlers[fd] = handler # _impl is epoll or kqueue or ... self._impl.register(fd, events) def start(self): while True: event_pairs = self._impl.poll() for fd, events in event_pairs: self._handlers[fd](fd, events)
  • 16. Python, MongoDB, & concurrency • Threads work great with pymongo • Gevent works great with pymongo – monkey.patch_socket(); monkey.patch_thread() • Tornado works so-so – asyncmongo • No replica sets, only first batch, no SON manipulators, no document classes, … – pymongo • OK if all your queries are fast • Use extra Tornado processes
  • 17. Introducing: “Motor” • Mongo + Tornado • Experimental • Might be official in a few months • Uses Tornado IOLoop and IOStream • Presents standard Tornado callback API • Stores state internally with greenlets • github.com/ajdavis/mongo-python-driver/tree/tornado_async
  • 18. Motor class MainHandler(tornado.web.RequestHandler): def __init__(self): self.c = MotorConnection() @tornado.web.asynchronous def post(self): # No-op if already open self.c.open(callback=self.connected) def connected(self, c, error): self.c.collection.insert( {‘x’:1}, callback=self.inserted) def inserted(self, result, error): self.write(’OK’) self.finish()
  • 19. Motor internals stack depth Client IOLoop RequestHandler greenlet pymongo request start switch() IOStream.sendall(callback) return time callback() switch() parse Mongo response schedule callback callback() HTTP response
  • 20. Motor internals: wrapper class MotorCollection(object): def insert(self, *args, **kwargs): callback = kwargs['callback'] 1 del kwargs['callback'] kwargs['safe'] = True def call_insert(): # Runs on child greenlet result, error = None, None try: sync_insert = self.sync_collection.insert 3 result = sync_insert(*args, **kwargs) except Exception, e: error = e # Schedule the callback to be run on the main greenlet tornado.ioloop.IOLoop.instance().add_callback( lambda: callback(result, error) 8 ) # Start child greenlet 2 greenlet.greenlet(call_insert).switch() 6 return
  • 21. Motor internals: fake socket class MotorSocket(object): def __init__(self, socket): # Makes socket non-blocking self.stream = tornado.iostream.IOStream(socket) def sendall(self, data): child_gr = greenlet.getcurrent() # This is run by IOLoop on the main greenlet # when data has been sent; # switch back to child to continue processing def sendall_callback(): child_gr.switch() 7 self.stream.write(data, callback=sendall_callback) 4 # Resume main greenlet child_gr.parent.switch() 5
  • 22. Motor • Shows a general method for asynchronizing synchronous network APIs in Python • Who wants to try it with MySQL? Thrift? • (Bonus round: resynchronizing Motor for testing)
  • 23. Questions? A. Jesse Jiryu Davis jesse@10gen.com emptysquare.net (10gen is hiring, of course: 10gen.com/careers)