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

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
Graham Dumpleton
 
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
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
martincabrera
 
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
Tatsuhiko Miyagawa
 

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

La televisió blai
La televisió blaiLa televisió blai
La televisió blai
mgonellgomez
 
Friday atlas lesson
Friday atlas lessonFriday atlas lesson
Friday atlas lesson
Travis Klein
 
Выпускники 2011
Выпускники 2011Выпускники 2011
Выпускники 2011
lexa0784
 
Weapons for peace
Weapons for peaceWeapons for peace
Weapons for peace
vicolombia
 
Friday business cycle AP Macro
Friday business cycle AP MacroFriday business cycle AP Macro
Friday business cycle AP Macro
Travis Klein
 
Biynees khemjee awah
Biynees khemjee awahBiynees khemjee awah
Biynees khemjee awah
pvsa_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 McAvoy
sophiemcavoy1
 

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

Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
seanmcq
 
Node js
Node jsNode js
Node js
hazzaz
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
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
Michaël Figuière
 

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

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

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

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)