SlideShare a Scribd company logo
Tornado Web Server Internals
              Praveen Gollakota
                 @pgollakota
          http://shutupandship.com


   A stroll into (and out of) the eye of the tornado
Agenda
●   Tornado at a glance
●   Sockets background
●   I/O monitoring - select, poll, epoll
●   Tornado server setup loop
●   Tornado request - response loop
●   Tornado vs. Apache
Tornado
Tornado
● Tornado - a scalable, non-blocking web server.
● Also a minimal Web Application Framework.
Written in Python. Open source - Apache V2.0 license.
● Originally built by FriendFeed (acquired by Facebook).

   "The framework is distinct from most mainstream web server
   frameworks (and certainly most Python frameworks) because it is non-
   blocking and reasonably fast. Because it is non-blocking and uses epoll
   or kqueue, it can handle thousands of simultaneous standing
   connections, which means it is ideal for real-time web services." -
   Tornado Web Server Home page blurb.

Recommended for you

Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison

This document summarizes and compares Ruby HTTP client libraries. It discusses the sync and async APIs of 16 libraries including Net::HTTP, HTTPClient, and Faraday. It covers their compatibility, supported features like keep-alive connections, and performance based on benchmarks. The document recommends libraries based on priorities like speed, HTML handling, API clients, and SSL support. It encourages readers to check the detailed feature matrix and report any errors found.

rubyhttp
Pycon - Python for ethical hackers
Pycon - Python for ethical hackers Pycon - Python for ethical hackers
Pycon - Python for ethical hackers

The document discusses using Python for ethical hacking and penetration testing. It provides reasons for using Python such as its ease of use, readable syntax, rich libraries, and existing tools. It then covers various Python libraries and frameworks used for tasks like reconnaissance, scanning, exploitation, and packet manipulation. Specific topics covered include file I/O, requests, sockets, scapy, and more.

pythonhackersethical hacker
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples

The document discusses Node.js and asynchronous I/O. It explains that Node.js is an asynchronous event-driven JavaScript runtime that uses a single-threaded model with non-blocking I/O to handle high volumes of simultaneous connections efficiently. It also discusses how Node.js handles asynchronous operations using an event loop and callback functions instead of blocking operations.

cleancodechromejavascript
Tornado modules at a glance
Core web framework                   Integration with other services
 ● tornado.web                        ● tornado.auth
 ● tornado.httpserver                 ● tornado.database
 ● tornado.template                   ● tornado.platform.twisted
 ● tornado.escape                     ● tornado.websocket
 ● tornado.locale                     ●  tornado.wsgi
Asynchronous networking              Utilities
 ● tornado.ioloop — Main event        ● tornado.autoreload
   loop                               ● tornado.gen
 ● tornado.iostream — Convenient      ● tornado.httputil
   wrappers for non-blocking          ● tornado.options
   sockets                            ● tornado.process
 ● tornado.httpclient — Non-          ● tornado.stack_context
   blocking HTTP client               ●  tornado.testing
 ● tornado.netutil — Miscellaneous
   network utilities
Hello World!
from tornado import ioloop
from tornado import web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

app = web.Application([(r"/", MainHandler),])

if __name__ == "__main__":
    srv = httpserver.HTTPServer(app)
    app.listen(8080)
    ioloop.IOLoop.instance().start()
Our Mission
● Analyze "Hello World" application and figure
  out what happens at every step of the way.
  All the way from how the server is setup to
  how the entire request-response cycle works
  under the hood.
● But first a little bit of background about
  sockets and poll.
Sockets
Some background

Recommended for you

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

The document discusses the future of asynchronous I/O in Python. It introduces PEP 3156 and the new asyncio module in Python 3.4 as a standard library for asynchronous I/O. It describes how asyncio (called Tulip in the presentation) provides primitives like event loops, transports, protocols and coroutines to build asynchronous applications and frameworks in a pluggable, coroutine-friendly way. It provides examples of using Tulip to run asynchronous tasks and build an echo server.

pythonasyncasync i/o
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP

This talk was given at the Dutch PHP Conference 2011 and details the use of Comet (aka reverse ajax or ajax push) technologies and the importance of websockets and server-sent events. More information is available at http://joind.in/3237.

king foodpc11php
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...

Facing tens of millions of clients continuously downloading binaries from our repositories, we decided to offer an OSS client that natively supports these downloads. In this talk we will share the main challenges in developing a highly-concurrent, resumable, async download library on top of Apache HTTP client. We will cover other libraries we tested and why we decided to reinvent the wheel. We will see important pitfalls we came across when working with HTTP and how using the right combination of techniques can improve performance by a magnitude. We will also see why your initial assumptions may completely change when faced with other players on the network. Consider yourself forewarned: lots of HTTP internals, NIO and concurrency ahead! As presented at JFokus 2015 (http://www.jfokus.se/jfokus/talks.jsp#Everythingyouwantedt)

jfokushttpjava
Sockets
● Network protocols are handled through a
  programming abstraction known as sockets.
  Socket is an object similar to a file that
  allows a program to accept incoming
  connection, make outgoing connections, and
  send and receive data. Before two machines
  can communicate, both must create a socket
  object. The Python implementation just calls
  the system sockets API.
● For more info $ man socket
Sockets - Address, Family
and Type
● Address - Combination of IP address and
  port
● Address family - controls the OSI network
  layer protocol, for example AF_INET for
  IPv4 Internet sockets using IPv4.
● Socket type - controls the transport layer
  protocol, SOCK_STREAM for TCP.
TCP Connection sequence
         Server                                   Client

         socket()                                socket()


          bind()


          listen()


         accept()


    wait for connection   establish connection
                                                 connect()

                               request
          read()                                  write()

    process
                              response
          write()                                 read()
Client Socket Example
#Examples from Socket Programming HOWTO
#create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#now connect to the web server on port 8080
s.connect(("www.mcmillan-inc.com", 8080))

Recommended for you

Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js

Node.js is a server-side JavaScript runtime built on Google's V8 engine. It uses non-blocking I/O and an event loop to handle concurrent connections efficiently without threads. This asynchronous model improves performance compared to traditional blocking I/O and threads. The event loop iterates through callbacks and executes them in order, allowing Node.js to handle many concurrent connections with a single thread.

nodejsjavascriptevent loop
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

As presented at CodeMotion Tel Aviv: Facing tens of millions of clients continuously downloading binaries from its repositories, JFrog decided to offer an OSS client that natively supports these downloads. This session shares the main challenges of developing a highly concurrent, resumable, async download library on top of an Apache HTTP client. It also covers other libraries JFrog tested and why it decided to reinvent the wheel. Consider yourself forewarned: lots of HTTP internals, NIO, and concurrency ahead!

concurrencyhttpreactor pattern
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio

Slides from my "Introduction to asyncio" talk given at PyLadies Amsterdam, the 20th of March of 2014.

asynciopythonpyladies
Server Socket Example
#Examples from Socket Programming HOWTO
#create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET,
                             socket.SOCK_STREAM)
#bind the socket to a public host,and a well-known port
serversocket.bind('localhost', 8080))
#become a server socket
serversocket.listen(5)
while True:
    #accept connections from outside
    (clientsocket, address) = serversocket.accept()
    #do something. In this case assume in a different
thread
    ct = client_thread(clientsocket)
    ct.run()
Server Socket explained
“server socket ... doesn’t send any data. It doesn’t receive
any data. It just produces client sockets. Each client socket
is created in response to some other client socket doing a
connect() to the host and port we’re bound to. As soon as
we’ve created that client socket, we go back to listening for
more connections. The two clients are free to chat it up -
they are using some dynamically allocated port which will
be recycled when the conversation ends.”
       - Gordon McMillan in Socket Programming HOWTO
Server Socket Loop
Three options -
● dispatch a thread to handle client socket
● create a new process to handle client socket
● Use non-blocking sockets, and mulitplex
  between our server socket and any active
  client sockets using select.
Sockets - Blocking vs. Non-
blocking
● Blocking sockets - socket API calls will block
  indefinitely until the requested action (send,
  recv, connect or accept) has been
  performed.
● Non-blocking sockets - send, recv,
  connect and accept can return
  immediately without having done anything.
● In Python, you can use socket.
  setblocking(0) to make a socket non-
  blocking.

Recommended for you

introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js

This document provides an introduction to Node.js, a framework for building scalable server-side applications with asynchronous JavaScript. It discusses what Node.js is, how it uses non-blocking I/O and events to avoid wasting CPU cycles, and how external Node modules help create a full JavaScript stack. Examples are given of using Node modules like Express for building RESTful APIs and Socket.IO for implementing real-time features like chat. Best practices, limitations, debugging techniques and references are also covered.

node.jsnodejsexpress.socket.io
About Node.js
About Node.jsAbout Node.js
About Node.js

Node.js is a JavaScript runtime built on Chrome's V8 engine that allows building scalable network applications using JavaScript on the server-side. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, suitable for data-intensive real-time applications that run across distributed devices. Common uses of Node.js include building web servers, file upload clients, ad servers, chat servers, and any real-time data applications. The document provides an introduction to Node.js concepts like callbacks, blocking vs non-blocking code, the event loop, streams, events, and modules.

node.jsnode js
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework

A WebSockets HOW-TO using Scala and Play!Framework. Links to example repositories and other resources. Created for the AmsterdamScala meetup.

play frameworkactorsakka
Handling non-blocking
sockets
“You have (of course) a number of
choices. You can check return
code and error codes and
generally drive yourself crazy. If
you don’t believe me, try it
sometime. Your app will grow
large, buggy and suck CPU. So let’
s skip the brain-dead solutions
and do it right. …


   Use select.”                      Gordon McMillan - Author of
                                     Socket Programming HOWTO &
                                     creator of PyInstaller
References
● Socket Programming HOWTO by Gordon
  McMillan
● Python Module of the Week (PyMOTW) -
  Socket by Doug Hellmann
● Python Essential Reference by David Beazley
select, poll, epoll
 Waiting for I/O efficiently
select
● A system call - allows a program to monitor
  multiple file descriptors, waiting until one or
  more of the file descriptors become "ready"
  for some class of I/O operation
● More info $ man select
● Python’s select() function is a direct
  interface to the underlying operating system
  implementation.

Recommended for you

A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js

This document provides a complete guide to Node.js, covering installation methods, checking installation, modules, NPM, events, streams, and persisting data. It discusses installing Node.js from nodejs.org, using a version manager like NVM, or compiling from source. It also covers creating a basic web server, reading and writing files, uploading files, and using Socket.IO for real-time applications.

node.jslearn-nodecomplete-node.js
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale

This document discusses benchmarks and performance testing of Node.js. It notes that while Node.js can handle over 1 million connections, benchmarks are not that important as other factors like productivity. It explores how to meaningfully measure Node.js performance, compares Node.js to other frameworks like Erlang and Tornado, and argues that benchmarks should reflect real-world use cases rather than simplistic "hello world" tests. The document questions overreliance on benchmarks and emphasizes picking the right tool based on the task.

Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Code

This document discusses how Groovy enables clean code through features like native JSON support, builders for JSON and markup, checked exceptions, default imports, AST transformations, extension modules, and scripts. Groovy avoids verbosity through features like built-in reader classes and meta-programming capabilities like registered meta-methods that allow overriding core behaviors.

javaclean-codegroovy
poll
● poll() scales better than select().
● poll() - only requires listing the file
  descriptors of interest, while select()
  builds a bitmap, turns on bits for the fds of
  interest, and then afterward the whole
  bitmap has to be linearly scanned again.
● select() is O(highest file
  descriptor), while poll() is O(number
  of file descriptors).
poll API
● Create a poll object
  p = select.poll()
● Register a fd and the events of interest to be
  notified about
  p.register(fd, events)
● Start monitoring. You will be notified if there
  is an event of interest on any of the
  registered fd's.
  p.poll([timeout])
epoll
● epoll() system call has event notification
  facility.
● So epoll is O(active fd's), poll is O
  (registered fd's)
● So epoll faster than poll (there is debate
  about exactly how much faster, but let's not
  get into that ... because I have no idea).
● Provides exactly same API as poll.
● Tornado tries to use epoll or kqueue and
  falls back to select if it cannot find them.
References
● Python Module of the Week (PyMOTW) -
  select by Doug Hellmann
● The C10K problem by Dan Kegel
● poll, epoll, science, superpoll by Zed Shaw

Recommended for you

Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...

On Saturday, 12 of April, regular quarterly meeting of Tech Hangout Community took place in Creative Space 12, the cultural and educational center based in Kiev! The event was held under the motto «One day of inspiring talks on Web Back-End». This time Python, Ruby and PHP developers gathered to make peace and learn the Force. *TECH HANGOUT COMMUNITY was found in 2012 by the developers for the developers for knowledge and experience sharing. Such meetings are the part of Innovecs Educational Project that actively develops sphere of internal trainings and knowledge exchange program among professionals. This Initiative was born within the walls of Innovecs and has proved to be extremely popular and high-demand. In a short period of time it gained its own Facebook group with more than 90 members, blog with more than 40 posts and constant quarterly external meeting of Tech hangout community with more than 80 participants. The concept of the event proposes a 30-minute report on the topic previously defined, and the discussion in a roundtable session format. Join to discuss - https://www.facebook.com/groups/techhangout/

#techhangout#restapi#api
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning

The document discusses web server performance bottlenecks and tuning. It notes that the majority of end-user response time is spent on the frontend. It then examines factors that affect web server performance like memory usage, processes vs threads, client impacts, and application requirements. Specific techniques are suggested for improving performance like using processes over threads, isolating slow clients with Nginx, preloading applications, and monitoring servers.

wsgipythonnew relic
用Tornado开发RESTful API���用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用

The document discusses using the Tornado web framework to develop RESTful APIs. It provides examples of implementing RESTful APIs in Tornado, including handling HTTP verbs, returning JSON/JSONP responses, handling exceptions, scraping web pages to monitor server status, and notifying subscribers via push notifications when status changes. Other topics mentioned include internationalization, cron jobs, and related resources for Tornado and RESTful APIs.

restfulpythontornado
Tornado
The server loop
Hello World!
from tornado import ioloop
from tornado import web

class MainHandler(web.RequestHandler):
    def get(self):
        self.write("Hello, world")

app = web.Application([(r"/", MainHandler),])

if __name__ == "__main__":
    srv = httpserver.HTTPServer(app)
    app.listen(8080)
    ioloop.IOLoop.instance().start()
app = web.Application(...)
Nothing special here. Just creates an
Application object and adds the handlers to
the handlers attribute.
srv = httpserver.HTTPServer(app)

The constructor of HTTPServer does some
basic setup.




Then calls the constructor of its parent class:
TCPServer

Recommended for you

Real time server
Real time serverReal time server
Real time server

Tornado is a Python web framework that focuses on speed and handling large amounts of simultaneous traffic. It allows starting multiple sub-domains on different ports with auto-reloading capabilities. Tornado handles requests by routing them to different handlers that can render templates and return responses. It also supports asynchronous delayed responses using asynchronous HTTP clients.

tornadoweb real-time ajax europython europython201
Sinatra Ruby Framework
Sinatra Ruby FrameworkSinatra Ruby Framework
Sinatra Ruby Framework

This document discusses several Ruby web frameworks including Sinatra, Rails, Merb, Camping, and others. It then focuses on Sinatra, describing it as a DSL for quickly creating web applications in Ruby with minimal code. Sinatra applications can be single file, run on Rack, and allow the developer to choose their own template engine and JavaScript library. The document proceeds to provide examples of Sinatra features like routes, views, helpers, filters, configuration, and testing.

frameworksinatraruby
Crystal is a Rubyists friend (quick anecdote)
Crystal is a Rubyists friend (quick anecdote)Crystal is a Rubyists friend (quick anecdote)
Crystal is a Rubyists friend (quick anecdote)

The document discusses using Crystal and the Kemal framework for a Rubyist's project that requires streaming log entries in real-time to a browser. While Roda was initially considered for its small size and streaming support, it lacked built-in websocket support needed for the project. Crystal and Kemal were discovered to be faster and smaller than Ruby and frameworks like Sinatra, with Kemal providing an easy way to add websocket support. The author was able to get their project working with Kemal in just 15 minutes due to its simplicity and an active community.

joyperformanceruby
TCPServer.__init__
Basic setup … nothing interesting.
srv.listen(8080)
● First it calls bind_sockets() method
  which creates non-blocking, listening
  server socket (or sockets) bound to the
  given address and port (in this case
  localhost:8080).
● Then creates an instance of the IOLoop
  object
  self.io_loop = IOLoop.instance()
IOLoop.__init__
● New select.epoll object is created.
  self._impl = select.epoll()
● We will register the file descriptors of the
  server sockets with this epoll object to
  monitor for events on the sockets. (will be
  explained shortly).
After IOLoop is instantiated

Recommended for you

Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011

This document introduces Tornado Web and AsyncMongo for asynchronous access to MongoDB from Tornado applications. It discusses evented I/O web servers and the C10k problem. It provides an overview of Tornado Web and demonstrates basic usage. It introduces AsyncMongo for asynchronous MongoDB access from Tornado. It demonstrates how to fetch, insert, update and delete data from MongoDB using AsyncMongo with examples.

Introduction to Tornado - TienNA
Introduction to Tornado - TienNAIntroduction to Tornado - TienNA
Introduction to Tornado - TienNA

Tornado is a Python web framework and asynchronous networking library. It is optimized for non-blocking I/O and can handle a large number of open connections efficiently. Tornado supports features like templates, authentication, and static files. It is well-suited for real-time applications like chat servers that require long-polling connections. Examples of Tornado applications include chat servers and services that count recent Twitter posts.

Asynchronous programming in Python
Asynchronous programming in PythonAsynchronous programming in Python
Asynchronous programming in Python

This document discusses asynchronous programming using Python. It begins with introductions and discusses some of the buzzwords around asynchronous programming like Node.js, Tornado, and event loops. It then provides a brief history of threading, multiprocessing, and asynchronous programming. It defines what an event loop is and discusses concepts like callbacks and deferreds. It notes that asynchronous code is generally harder to write and can be slower than synchronous code. However, asynchronous programming allows for greater scalability by avoiding threads and shared state.

networkprogrammingpython
TCPServer listen() continued
● TCPServer keeps track of the sockets in the _sockets
    dict - {fd: socket}
●   An accept_handler function is created for each socket
    and passed to the IOLoop.add_handlers() method.
●   accept_handler is a thin wrapper around a callback
    function which just accepts the socket (socket.
    accept()) and then runs the callback function.
●   In this case the callback function is the
    _handle_connection method of the TCPServer.
    More on this later.
Adding handlers to IOLoop
● Updates ioloop._handlers, with {fd:
  accept_handler} to keeps track of which
  handler function needs to be called when a
  client tries to establish a connection.
● Registers the fd (file descriptor) and data
  input and error events for the corresponding
  socket with IOLoop._impl (the epoll
  object).
Current status
                 Read and error events on
                 fd's registered with _impl
IOLoop.instance()
● IOLoop.instance()always returns the
  same object, no matter how many times it is
  called.

Recommended for you

What is a tornado?
What is a tornado?What is a tornado?
What is a tornado?

A tornado is a rotating column of air that extends from a thunderstorm to the ground. Most tornadoes have wind speeds between 40-110 mph but the strongest can exceed 300 mph. Tornadoes form from thunderstorms called supercells that contain rotating updrafts. As rain drags down rotating air, a funnel cloud may form and touch down as a tornado. Tornadoes grow strongest as they receive warm air but then weaken as surrounding winds cut off the supply, causing the tornado to dissipate.

tornado weather skywarn education storm spotting w
Tornado
TornadoTornado
Tornado

Tornados are violently destructive columns of air that form over land in the shape of a funnel. They typically have wind speeds between 64-177 km/h and stretch over 75m across. Different types of tornados include supercell tornados, landspouts, firewhirls, gustnados, and waterspouts. Tornadoes form when warm moist air collides with cold dry air, creating a whirling wind that draws air into its center to form a funnel. Weather services issue tornado watches when conditions are right for tornadoes and tornado warnings when a tornado has been sighted on radar or visually. Tornados can cause significant damage and loss of life.

tornadoestornado
Contoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta GuruContoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta Guru

Contoh Lembar Catatan Fakta Hasil Pengamatan dan Pemantauan Proses Pembelajaran

penilaiangurucatatan fakta
IOLoop.instance().start()
● start() method starts the IOLoop. The IOLoop is
  the heartbeat and the nerve center of
  everything.
● Continually runs any callback functions, callbacks
  related to any timeouts, and then runs poll() method
  on self._impl the epoll object for any new data
  input events on the socket.
● Note: A connect() request from a client is considered
  as an input event on a server socket.
● There is logic in here to send signals to wake up the I/O
  loop from idle state, ways to run periodic tasks using
  timeouts etc. which we won't get into.
Tornado
The request-response loop
What happens when a client
connects?
● The client socket connect() is captured by the
  poll() method in the IOLoop's start() method.
● The server runs the accept_handler which
  accept()'s the connection, then immediately runs the
  associated callback function.
● Remember that accept_handler is a closure that
  wraps the callback with logic to accept() the
  connection, so accept_handler knows which callback
  function to run.
● The callback function in this case is
  _handle_connection method of TCPServer
TCPServer._handle_connection()

● Creates an IOStream object.
● IOStream is a wrapper around non-
  blocking sockets which provides utilities to
  read from and write to those sockets.
● Then calls HTTPServer.handle_stream
  (...)and passes it the IOStream object
  and the client socket address.

Recommended for you

Introduction to Apache Cassandra
Introduction to Apache CassandraIntroduction to Apache Cassandra
Introduction to Apache Cassandra

Introduction to Apache Cassandra (September 2014). Design principles, replication, consistency, clusters, CQL.

cassandra cql replication consistency
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier

This document discusses a presentation on advanced uses of generators in Python. It covers context managers, which allow entry and exit actions for code blocks using the 'with' statement. Generators can be used to implement context managers via the yield keyword and decorator contextmanager. This transforms generator functions into objects that support the required __enter__ and __exit__ methods to monitor code block execution. The presentation aims to expand understanding of generators beyond iteration by exploring this technique for simplifying resource management tasks like file handling through context managers.

python3generators
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python

This document summarizes and compares several popular Python web frameworks - Django, Flask, Tornado, and aiohttp. Django is the most popular full-stack framework that provides an ORM, template engine, tests, and other features out of the box. Flask is a microframework that requires extensions for features like SQLAlchemy for ORM and Jinja2 for templating. Tornado is both an asynchronous network library and web framework that has been supporting asynchronous features since Python 2. Aiohttp is an HTTP client/server library for asyncio that can be used to build asynchronous web applications and servers in Python 3. The document discusses when each framework would be suitable depending on requirements like asynchronous features or database usage.

HTTPServer.handle_stream(...)

● handle_stream() method creates a
  HTTPConnection object with our app as a
  request_callback.
● HTTPConnection handles a connection to
  an HTTP client and executes HTTP requests.
  Has methods to parse HTTP headers, bodies,
  execute callback tasks etc.
HTTPConnection.__init__()

● Reads the headers until "rnrn" ...
  delegated to the IOStream object.
  self.stream.read_until(b("rnrn"),
              self._header_callback)
● _header_callback is _on_headers
  method of HTTPConnection. (We'll get to
  that in a moment).
IOStream read
● A bunch of redirections to various _read_* methods.
  Finally once the headers are read and parsed, invokes
  _run_callback method. Invokes the socket.
  recv() methods.
● Call back is not executed right away, but added to the
  IOLoop instance to be called in the next cycle of the IO
  loop.
  self.io_loop.add_callback(wrapper)
● wrapper is just a wrapper around the callback with
  some exception handling. Remember, our callback is
  _on_headers method of HTTPConnection object
HTTPConnection._on_headers

● Creates the appropriate HTTPRequest
  object (now that we have parsed the
  headers).
● Then calls the request_callback and
  passes the HTTPRequest. Remember this?
  May be you don't after all this ...
  request_callback is the original app we
  created.
● Whew! Light at the end of the tunnel. Only a
  couple more steps.

Recommended for you

An Overview of Apache Cassandra
An Overview of Apache CassandraAn Overview of Apache Cassandra
An Overview of Apache Cassandra

Apache Cassandra is a free, distributed, open source, and highly scalable NoSQL database that is designed to handle large amounts of data across many commodity servers. It provides high availability with no single point of failure, linear scalability, and tunable consistency. Cassandra's architecture allows it to spread data across a cluster of servers and replicate across multiple data centers for fault tolerance. It is used by many large companies for applications that require high performance, scalability, and availability.

apache cassandranosqldatastax
Network Traffic Analysis at a financial institution with 788 branches for 350...
Network Traffic Analysis at a financial institution with 788 branches for 350...Network Traffic Analysis at a financial institution with 788 branches for 350...
Network Traffic Analysis at a financial institution with 788 branches for 350...

A leading bank with over 780 branches across the United States had problems with monitoring network traffic across the Enterprise and in finding out the most resource-intensive applications. This Slideshare explains how they solved the challenge with ManageEngine NetFlow Analyzer by monitoring real-time network traffic based on flow data and found out application-wise bandwidth usage.

bank network traffic analysisnetwork traffic at a financial institutionnetflow analyzer
What's new in NetFlow Analyzer 12.2
What's new in NetFlow Analyzer 12.2What's new in NetFlow Analyzer 12.2
What's new in NetFlow Analyzer 12.2

This document describes new features in NetFlow Analyzer v12.2, an integrated network traffic management and configuration management software. The new version includes enhancements to the user interface, integration with wireless LAN controllers, and tighter integration with network management solutions. It also includes new features like one-click flow export, network configuration management, and auto-refresh for traffic graphs.

netflownetflow analyzerlatest release
app.__call__
● Application is a callable object (has the
  __call__ method. So you can just call an
  application.
● The __call__ method looks at the url in
  the HTTPRequest and invokes the
  _execute method of appropriate
  RequestHandler - the MainHandler in
  our example.
RequestHandler._execute
● Executes the appropriate HTTP method
  getattr(self,self.request.method.lower()
          )(*args, **kwargs)
● In our case get method calls write() and
  writes the "Hello World" string.
● Then calls finish() method which
  prepares response headers and calls
  flush() to write the output to the socket
  and close it.
Writing the output and closing
● RequestHandler.flush() delegates the write() to
  the request, which in turn delegates it to the
  HTTPConnection which in turn delegates it to the
  IOStream.
● IOStream adds this write method to the IOLoop.
  _callbacks list and the write is executed in turn
  during the next iteration of IOLoop.
● Once everything is done, the socket is closed (unless of
  course you specify that it stay open).
Points to note ...
● Note that we did fork a process.
● We did not spawn a thread.
● Everything happens in just one thread and is
  multiplexed using epoll.poll()
● Callback handlers are run one at a time, in
  turn, on a single thread.
● If a callback task (in the RequestHandler)
  is long running, for example a database
  query that takes too long, the other requests
  which are queued behind will suffer.

Recommended for you

Cassandra Introduction & Features
Cassandra Introduction & FeaturesCassandra Introduction & Features
Cassandra Introduction & Features

This presentation shortly describes key features of Apache Cassandra. It was held at the Apache Cassandra Meetup in Vienna in January 2014. You can access the meetup here: http://www.meetup.com/Vienna-Cassandra-Users/

mongodbintroductioncassandra
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future

A talk on Python coroutines for asynchronous programming, both *now* in Tornado and Toro, and in the future in Tulip and Python 3.4.

pythoncoroutinestulip
Monkey Server
Monkey ServerMonkey Server
Monkey Server

Eduardo Silva is an open source engineer at Treasure Data working on projects like Fluentd and Fluent Bit. He created the Monkey HTTP server, which is optimized for embedded Linux and has a modular plugin architecture. He also created Duda I/O, a scalable web services stack built on top of Monkey using a friendly C API. Both projects aim to provide lightweight, high performance solutions for collecting and processing data from IoT and embedded devices.

performanceembeddedhttp
Other things to consider
● You can make your request handler
  asynchronous, and keep the connection open
  so that other requests do not suffer.
● But you have to close the connection
  yourself.
● See the chat example in the source code.
Apache vs. Tornado
Apache - multiple requests
● How multiple requests are handled depends
  on Multiprocessing mode (MPM).
● Two modes
  ○ prefork
  ○ worker
prefork MPM
● Most commonly used. Is the default mode in
  2.x and only option in 1.3.
● The main Apache process will at startup
  create multiple child processes. When a
  request is received by the parent process, it
  will be processed by whichever of the child
  processes is ready.

Recommended for you

Python networking
Python networkingPython networking
Python networking

This document provides an overview of network programming in Python. It discusses how Python allows both low-level socket access for building clients and servers as well as higher-level access to application protocols like FTP and HTTP. It then describes socket programming concepts like domains, types, protocols and functions for binding, listening, accepting, connecting, sending and receiving data. Simple client and server code examples are provided to demonstrate creating a basic socket connection between two programs. Finally, commonly used Python network modules for protocols like HTTP, FTP, SMTP and more are listed.

python networkingumakant mumbai university
A.java
A.javaA.java
A.java

INTRODUCTION OF NETWORK BASICS AND SOCKET OVERVIEW.ALSO EXPLAIN URL AND BRIEF ABOUT TCP/IP SERVER AND CLIENT SIDE SOCKETS WITH EXAMPLES.

#networkbasics#socketoverview#sockets
04 android
04 android04 android
04 android

This document provides an overview of Android and how to get started developing Android applications. It discusses Java network programming concepts, the components of an Android application including activities, services and broadcast receivers. It also covers using the Android emulator, configuring projects in Eclipse, and an overview of the APIs provided for the file sharing project including sockets and broadcasting messages.

worker MPM
● Within each child process there will exist a
  number of worker threads.
● The request may be processed by a worker
  thread within a child process which already
  has other worker threads handling other
  requests at the same time.
Apache vs. Tornado
● Apache has additional memory overhead of
  maintaining the other processes which are
  essentially idle when the request load is low.
  Tornado does not have this overhead.
● Tornado natively allows you to use
  websockets. Experimental support in
  apache with apache-websocket module.
● Scalability - There are arguments for both
  sides. Personally I haven't built anything that
  cannot be scaled by Apache. So no idea if one
  is better than the other.
References
● Processes and Threading in mod_wsgi wiki
Thank you!

Recommended for you

Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk

These are the original slides from the nodejs talk. I was surprised not find them on slideshare so adding them. The video link is here https://www.youtube.com/watch?v=ztspvPYybIY

javascriptnodejsconcurrency
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)

An unconventional tutorial to basic socket.io features. Socket.io basic features are explained first of all taking a look directly at the browser (hacker approach) and then taking a look at the documentation (and some code examples).

programmingsocketiojavascript
Sockets
SocketsSockets
Sockets

The document discusses network programming and Java sockets. It introduces elements of client-server computing including networking basics like TCP, UDP and ports. It then covers Java sockets, explaining how to implement both a server and client using Java sockets. Code examples are provided of a simple server and client. The conclusion emphasizes that Java makes socket programming easier than other languages like C.

More Related Content

What's hot

Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
Saúl Ibarra Corretgé
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 
Pycon - Python for ethical hackers
Pycon - Python for ethical hackers Pycon - Python for ethical hackers
Pycon - Python for ethical hackers
Mohammad Reza Kamalifard
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
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
Saúl Ibarra Corretgé
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
King Foo
 
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
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
jacekbecela
 
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
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
Saúl Ibarra Corretgé
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
orkaplan
 
About Node.js
About Node.jsAbout Node.js
About Node.js
Artemisa Yescas Engler
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
Fabio Tiriticco
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
Prabin Silwal
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
Tom Croucher
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Code
noamt
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Innovecs
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
Graham Dumpleton
 

What's hot (20)

Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Pycon - Python for ethical hackers
Pycon - Python for ethical hackers Pycon - Python for ethical hackers
Pycon - Python for ethical hackers
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
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
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
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...
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
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
 
Introduction to asyncio
Introduction to asyncioIntroduction to asyncio
Introduction to asyncio
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
 
A million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scaleA million connections and beyond - Node.js at scale
A million connections and beyond - Node.js at scale
 
Groovy Powered Clean Code
Groovy Powered Clean CodeGroovy Powered Clean Code
Groovy Powered Clean Code
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
 

Viewers also liked

用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
Felinx Lee
 
Real time server
Real time serverReal time server
Real time server
thepian
 
Sinatra Ruby Framework
Sinatra Ruby FrameworkSinatra Ruby Framework
Sinatra Ruby Framework
Craig Jolicoeur
 
Crystal is a Rubyists friend (quick anecdote)
Crystal is a Rubyists friend (quick anecdote)Crystal is a Rubyists friend (quick anecdote)
Crystal is a Rubyists friend (quick anecdote)
Forrest Chang
 
Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011
hangxin1940
 
Introduction to Tornado - TienNA
Introduction to Tornado - TienNAIntroduction to Tornado - TienNA
Introduction to Tornado - TienNA
Framgia Vietnam
 
Asynchronous programming in Python
Asynchronous programming in PythonAsynchronous programming in Python
Asynchronous programming in Python
Aurynn Shaw
 
What is a tornado?
What is a tornado?What is a tornado?
What is a tornado?
Austin
 
Tornado
TornadoTornado
Tornado
Hammam Samara
 
Contoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta GuruContoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta Guru
enesha sie
 
Introduction to Apache Cassandra
Introduction to Apache CassandraIntroduction to Apache Cassandra
Introduction to Apache Cassandra
Robert Stupp
 
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier
David Beazley (Dabeaz LLC)
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
Ayun Park
 
An Overview of Apache Cassandra
An Overview of Apache CassandraAn Overview of Apache Cassandra
An Overview of Apache Cassandra
DataStax
 
Network Traffic Analysis at a financial institution with 788 branches for 350...
Network Traffic Analysis at a financial institution with 788 branches for 350...Network Traffic Analysis at a financial institution with 788 branches for 350...
Network Traffic Analysis at a financial institution with 788 branches for 350...
ManageEngine, Zoho Corporation
 
What's new in NetFlow Analyzer 12.2
What's new in NetFlow Analyzer 12.2What's new in NetFlow Analyzer 12.2
What's new in NetFlow Analyzer 12.2
ManageEngine, Zoho Corporation
 
Cassandra Introduction & Features
Cassandra Introduction & FeaturesCassandra Introduction & Features
Cassandra Introduction & Features
DataStax Academy
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
emptysquare
 

Viewers also liked (18)

用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
 
Real time server
Real time serverReal time server
Real time server
 
Sinatra Ruby Framework
Sinatra Ruby FrameworkSinatra Ruby Framework
Sinatra Ruby Framework
 
Crystal is a Rubyists friend (quick anecdote)
Crystal is a Rubyists friend (quick anecdote)Crystal is a Rubyists friend (quick anecdote)
Crystal is a Rubyists friend (quick anecdote)
 
Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011Phl mongo-philly-tornado-2011
Phl mongo-philly-tornado-2011
 
Introduction to Tornado - TienNA
Introduction to Tornado - TienNAIntroduction to Tornado - TienNA
Introduction to Tornado - TienNA
 
Asynchronous programming in Python
Asynchronous programming in PythonAsynchronous programming in Python
Asynchronous programming in Python
 
What is a tornado?
What is a tornado?What is a tornado?
What is a tornado?
 
Tornado
TornadoTornado
Tornado
 
Contoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta GuruContoh Lembar Catatan Fakta Guru
Contoh Lembar Catatan Fakta Guru
 
Introduction to Apache Cassandra
Introduction to Apache CassandraIntroduction to Apache Cassandra
Introduction to Apache Cassandra
 
Generators: The Final Frontier
Generators: The Final FrontierGenerators: The Final Frontier
Generators: The Final Frontier
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
An Overview of Apache Cassandra
An Overview of Apache CassandraAn Overview of Apache Cassandra
An Overview of Apache Cassandra
 
Network Traffic Analysis at a financial institution with 788 branches for 350...
Network Traffic Analysis at a financial institution with 788 branches for 350...Network Traffic Analysis at a financial institution with 788 branches for 350...
Network Traffic Analysis at a financial institution with 788 branches for 350...
 
What's new in NetFlow Analyzer 12.2
What's new in NetFlow Analyzer 12.2What's new in NetFlow Analyzer 12.2
What's new in NetFlow Analyzer 12.2
 
Cassandra Introduction & Features
Cassandra Introduction & FeaturesCassandra Introduction & Features
Cassandra Introduction & Features
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 

Similar to Tornado Web Server Internals

Monkey Server
Monkey ServerMonkey Server
Monkey Server
Eduardo Silva Pereira
 
Python networking
Python networkingPython networking
A.java
A.javaA.java
04 android
04 android04 android
04 android
guru472
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
Aarti Parikh
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
Andrea Tarquini
 
Sockets
SocketsSockets
Sockets
sivindia
 
Twisted
TwistedTwisted
Twisted
Michal Sedlak
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
Adil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
Adil Jafri
 
Build reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQBuild reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQ
Robin Xiao
 
Scaling application with RabbitMQ
Scaling application with RabbitMQScaling application with RabbitMQ
Scaling application with RabbitMQ
Nahidul Kibria
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Hands on with CoAP and Californium
Hands on with CoAP and CaliforniumHands on with CoAP and Californium
Hands on with CoAP and Californium
Julien Vermillard
 
XML-RPC and SOAP (April 2003)
XML-RPC and SOAP (April 2003)XML-RPC and SOAP (April 2003)
XML-RPC and SOAP (April 2003)
Kiran Jonnalagadda
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
Samy Fodil
 
Network-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQNetwork-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQ
ICS
 
Asynchronous programming intro
Asynchronous programming introAsynchronous programming intro
Asynchronous programming intro
cc liu
 
Nodejs
NodejsNodejs

Similar to Tornado Web Server Internals (20)

Monkey Server
Monkey ServerMonkey Server
Monkey Server
 
Python networking
Python networkingPython networking
Python networking
 
A.java
A.javaA.java
A.java
 
04 android
04 android04 android
04 android
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
 
Sockets
SocketsSockets
Sockets
 
Twisted
TwistedTwisted
Twisted
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Build reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQBuild reliable, traceable, distributed systems with ZeroMQ
Build reliable, traceable, distributed systems with ZeroMQ
 
Scaling application with RabbitMQ
Scaling application with RabbitMQScaling application with RabbitMQ
Scaling application with RabbitMQ
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Hands on with CoAP and Californium
Hands on with CoAP and CaliforniumHands on with CoAP and Californium
Hands on with CoAP and Californium
 
XML-RPC and SOAP (April 2003)
XML-RPC and SOAP (April 2003)XML-RPC and SOAP (April 2003)
XML-RPC and SOAP (April 2003)
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Network-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQNetwork-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQ
 
Asynchronous programming intro
Asynchronous programming introAsynchronous programming intro
Asynchronous programming intro
 
Nodejs
NodejsNodejs
Nodejs
 

Recently uploaded

7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
ishalveerrandhawa1
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Erasmo Purificato
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
Awais Yaseen
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
Matthew Sinclair
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
BookNet Canada
 

Recently uploaded (20)

7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
Calgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptxCalgary MuleSoft Meetup APM and IDP .pptx
Calgary MuleSoft Meetup APM and IDP .pptx
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
Paradigm Shifts in User Modeling: A Journey from Historical Foundations to Em...
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
Best Programming Language for Civil Engineers
Best Programming Language for Civil EngineersBest Programming Language for Civil Engineers
Best Programming Language for Civil Engineers
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
20240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 202420240702 QFM021 Machine Intelligence Reading List June 2024
20240702 QFM021 Machine Intelligence Reading List June 2024
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
 

Tornado Web Server Internals

  • 1. Tornado Web Server Internals Praveen Gollakota @pgollakota http://shutupandship.com A stroll into (and out of) the eye of the tornado
  • 2. Agenda ● Tornado at a glance ● Sockets background ● I/O monitoring - select, poll, epoll ● Tornado server setup loop ● Tornado request - response loop ● Tornado vs. Apache
  • 4. Tornado ● Tornado - a scalable, non-blocking web server. ● Also a minimal Web Application Framework. Written in Python. Open source - Apache V2.0 license. ● Originally built by FriendFeed (acquired by Facebook). "The framework is distinct from most mainstream web server frameworks (and certainly most Python frameworks) because it is non- blocking and reasonably fast. Because it is non-blocking and uses epoll or kqueue, it can handle thousands of simultaneous standing connections, which means it is ideal for real-time web services." - Tornado Web Server Home page blurb.
  • 5. Tornado modules at a glance Core web framework Integration with other services ● tornado.web ● tornado.auth ● tornado.httpserver ● tornado.database ● tornado.template ● tornado.platform.twisted ● tornado.escape ● tornado.websocket ● tornado.locale ● tornado.wsgi Asynchronous networking Utilities ● tornado.ioloop — Main event ● tornado.autoreload loop ● tornado.gen ● tornado.iostream — Convenient ● tornado.httputil wrappers for non-blocking ● tornado.options sockets ● tornado.process ● tornado.httpclient — Non- ● tornado.stack_context blocking HTTP client ● tornado.testing ● tornado.netutil — Miscellaneous network utilities
  • 6. Hello World! from tornado import ioloop from tornado import web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") app = web.Application([(r"/", MainHandler),]) if __name__ == "__main__": srv = httpserver.HTTPServer(app) app.listen(8080) ioloop.IOLoop.instance().start()
  • 7. Our Mission ● Analyze "Hello World" application and figure out what happens at every step of the way. All the way from how the server is setup to how the entire request-response cycle works under the hood. ● But first a little bit of background about sockets and poll.
  • 9. Sockets ● Network protocols are handled through a programming abstraction known as sockets. Socket is an object similar to a file that allows a program to accept incoming connection, make outgoing connections, and send and receive data. Before two machines can communicate, both must create a socket object. The Python implementation just calls the system sockets API. ● For more info $ man socket
  • 10. Sockets - Address, Family and Type ● Address - Combination of IP address and port ● Address family - controls the OSI network layer protocol, for example AF_INET for IPv4 Internet sockets using IPv4. ● Socket type - controls the transport layer protocol, SOCK_STREAM for TCP.
  • 11. TCP Connection sequence Server Client socket() socket() bind() listen() accept() wait for connection establish connection connect() request read() write() process response write() read()
  • 12. Client Socket Example #Examples from Socket Programming HOWTO #create an INET, STREAMing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #now connect to the web server on port 8080 s.connect(("www.mcmillan-inc.com", 8080))
  • 13. Server Socket Example #Examples from Socket Programming HOWTO #create an INET, STREAMing socket serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #bind the socket to a public host,and a well-known port serversocket.bind('localhost', 8080)) #become a server socket serversocket.listen(5) while True: #accept connections from outside (clientsocket, address) = serversocket.accept() #do something. In this case assume in a different thread ct = client_thread(clientsocket) ct.run()
  • 14. Server Socket explained “server socket ... doesn’t send any data. It doesn’t receive any data. It just produces client sockets. Each client socket is created in response to some other client socket doing a connect() to the host and port we’re bound to. As soon as we’ve created that client socket, we go back to listening for more connections. The two clients are free to chat it up - they are using some dynamically allocated port which will be recycled when the conversation ends.” - Gordon McMillan in Socket Programming HOWTO
  • 15. Server Socket Loop Three options - ● dispatch a thread to handle client socket ● create a new process to handle client socket ● Use non-blocking sockets, and mulitplex between our server socket and any active client sockets using select.
  • 16. Sockets - Blocking vs. Non- blocking ● Blocking sockets - socket API calls will block indefinitely until the requested action (send, recv, connect or accept) has been performed. ● Non-blocking sockets - send, recv, connect and accept can return immediately without having done anything. ● In Python, you can use socket. setblocking(0) to make a socket non- blocking.
  • 17. Handling non-blocking sockets “You have (of course) a number of choices. You can check return code and error codes and generally drive yourself crazy. If you don’t believe me, try it sometime. Your app will grow large, buggy and suck CPU. So let’ s skip the brain-dead solutions and do it right. … Use select.” Gordon McMillan - Author of Socket Programming HOWTO & creator of PyInstaller
  • 18. References ● Socket Programming HOWTO by Gordon McMillan ● Python Module of the Week (PyMOTW) - Socket by Doug Hellmann ● Python Essential Reference by David Beazley
  • 19. select, poll, epoll Waiting for I/O efficiently
  • 20. select ● A system call - allows a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation ● More info $ man select ● Python’s select() function is a direct interface to the underlying operating system implementation.
  • 21. poll ● poll() scales better than select(). ● poll() - only requires listing the file descriptors of interest, while select() builds a bitmap, turns on bits for the fds of interest, and then afterward the whole bitmap has to be linearly scanned again. ● select() is O(highest file descriptor), while poll() is O(number of file descriptors).
  • 22. poll API ● Create a poll object p = select.poll() ● Register a fd and the events of interest to be notified about p.register(fd, events) ● Start monitoring. You will be notified if there is an event of interest on any of the registered fd's. p.poll([timeout])
  • 23. epoll ● epoll() system call has event notification facility. ● So epoll is O(active fd's), poll is O (registered fd's) ● So epoll faster than poll (there is debate about exactly how much faster, but let's not get into that ... because I have no idea). ● Provides exactly same API as poll. ● Tornado tries to use epoll or kqueue and falls back to select if it cannot find them.
  • 24. References ● Python Module of the Week (PyMOTW) - select by Doug Hellmann ● The C10K problem by Dan Kegel ● poll, epoll, science, superpoll by Zed Shaw
  • 26. Hello World! from tornado import ioloop from tornado import web class MainHandler(web.RequestHandler): def get(self): self.write("Hello, world") app = web.Application([(r"/", MainHandler),]) if __name__ == "__main__": srv = httpserver.HTTPServer(app) app.listen(8080) ioloop.IOLoop.instance().start()
  • 27. app = web.Application(...) Nothing special here. Just creates an Application object and adds the handlers to the handlers attribute.
  • 28. srv = httpserver.HTTPServer(app) The constructor of HTTPServer does some basic setup. Then calls the constructor of its parent class: TCPServer
  • 29. TCPServer.__init__ Basic setup … nothing interesting.
  • 30. srv.listen(8080) ● First it calls bind_sockets() method which creates non-blocking, listening server socket (or sockets) bound to the given address and port (in this case localhost:8080). ● Then creates an instance of the IOLoop object self.io_loop = IOLoop.instance()
  • 31. IOLoop.__init__ ● New select.epoll object is created. self._impl = select.epoll() ● We will register the file descriptors of the server sockets with this epoll object to monitor for events on the sockets. (will be explained shortly).
  • 32. After IOLoop is instantiated
  • 33. TCPServer listen() continued ● TCPServer keeps track of the sockets in the _sockets dict - {fd: socket} ● An accept_handler function is created for each socket and passed to the IOLoop.add_handlers() method. ● accept_handler is a thin wrapper around a callback function which just accepts the socket (socket. accept()) and then runs the callback function. ● In this case the callback function is the _handle_connection method of the TCPServer. More on this later.
  • 34. Adding handlers to IOLoop ● Updates ioloop._handlers, with {fd: accept_handler} to keeps track of which handler function needs to be called when a client tries to establish a connection. ● Registers the fd (file descriptor) and data input and error events for the corresponding socket with IOLoop._impl (the epoll object).
  • 35. Current status Read and error events on fd's registered with _impl
  • 36. IOLoop.instance() ● IOLoop.instance()always returns the same object, no matter how many times it is called.
  • 37. IOLoop.instance().start() ● start() method starts the IOLoop. The IOLoop is the heartbeat and the nerve center of everything. ● Continually runs any callback functions, callbacks related to any timeouts, and then runs poll() method on self._impl the epoll object for any new data input events on the socket. ● Note: A connect() request from a client is considered as an input event on a server socket. ● There is logic in here to send signals to wake up the I/O loop from idle state, ways to run periodic tasks using timeouts etc. which we won't get into.
  • 39. What happens when a client connects? ● The client socket connect() is captured by the poll() method in the IOLoop's start() method. ● The server runs the accept_handler which accept()'s the connection, then immediately runs the associated callback function. ● Remember that accept_handler is a closure that wraps the callback with logic to accept() the connection, so accept_handler knows which callback function to run. ● The callback function in this case is _handle_connection method of TCPServer
  • 40. TCPServer._handle_connection() ● Creates an IOStream object. ● IOStream is a wrapper around non- blocking sockets which provides utilities to read from and write to those sockets. ● Then calls HTTPServer.handle_stream (...)and passes it the IOStream object and the client socket address.
  • 41. HTTPServer.handle_stream(...) ● handle_stream() method creates a HTTPConnection object with our app as a request_callback. ● HTTPConnection handles a connection to an HTTP client and executes HTTP requests. Has methods to parse HTTP headers, bodies, execute callback tasks etc.
  • 42. HTTPConnection.__init__() ● Reads the headers until "rnrn" ... delegated to the IOStream object. self.stream.read_until(b("rnrn"), self._header_callback) ● _header_callback is _on_headers method of HTTPConnection. (We'll get to that in a moment).
  • 43. IOStream read ● A bunch of redirections to various _read_* methods. Finally once the headers are read and parsed, invokes _run_callback method. Invokes the socket. recv() methods. ● Call back is not executed right away, but added to the IOLoop instance to be called in the next cycle of the IO loop. self.io_loop.add_callback(wrapper) ● wrapper is just a wrapper around the callback with some exception handling. Remember, our callback is _on_headers method of HTTPConnection object
  • 44. HTTPConnection._on_headers ● Creates the appropriate HTTPRequest object (now that we have parsed the headers). ● Then calls the request_callback and passes the HTTPRequest. Remember this? May be you don't after all this ... request_callback is the original app we created. ● Whew! Light at the end of the tunnel. Only a couple more steps.
  • 45. app.__call__ ● Application is a callable object (has the __call__ method. So you can just call an application. ● The __call__ method looks at the url in the HTTPRequest and invokes the _execute method of appropriate RequestHandler - the MainHandler in our example.
  • 46. RequestHandler._execute ● Executes the appropriate HTTP method getattr(self,self.request.method.lower() )(*args, **kwargs) ● In our case get method calls write() and writes the "Hello World" string. ● Then calls finish() method which prepares response headers and calls flush() to write the output to the socket and close it.
  • 47. Writing the output and closing ● RequestHandler.flush() delegates the write() to the request, which in turn delegates it to the HTTPConnection which in turn delegates it to the IOStream. ● IOStream adds this write method to the IOLoop. _callbacks list and the write is executed in turn during the next iteration of IOLoop. ● Once everything is done, the socket is closed (unless of course you specify that it stay open).
  • 48. Points to note ... ● Note that we did fork a process. ● We did not spawn a thread. ● Everything happens in just one thread and is multiplexed using epoll.poll() ● Callback handlers are run one at a time, in turn, on a single thread. ● If a callback task (in the RequestHandler) is long running, for example a database query that takes too long, the other requests which are queued behind will suffer.
  • 49. Other things to consider ● You can make your request handler asynchronous, and keep the connection open so that other requests do not suffer. ● But you have to close the connection yourself. ● See the chat example in the source code.
  • 51. Apache - multiple requests ● How multiple requests are handled depends on Multiprocessing mode (MPM). ● Two modes ○ prefork ○ worker
  • 52. prefork MPM ● Most commonly used. Is the default mode in 2.x and only option in 1.3. ● The main Apache process will at startup create multiple child processes. When a request is received by the parent process, it will be processed by whichever of the child processes is ready.
  • 53. worker MPM ● Within each child process there will exist a number of worker threads. ● The request may be processed by a worker thread within a child process which already has other worker threads handling other requests at the same time.
  • 54. Apache vs. Tornado ● Apache has additional memory overhead of maintaining the other processes which are essentially idle when the request load is low. Tornado does not have this overhead. ● Tornado natively allows you to use websockets. Experimental support in apache with apache-websocket module. ● Scalability - There are arguments for both sides. Personally I haven't built anything that cannot be scaled by Apache. So no idea if one is better than the other.
  • 55. References ● Processes and Threading in mod_wsgi wiki