SlideShare a Scribd company logo
Python Twisted




Mahendra M
@mahendra




         http://creativecommons.org/licenses/by-sa/3.0/

                        
Methods of concurrency
   Workers
              Threads and processes
   Event driven


    Let us examine this with the case of a web server




                             
Worker model

request   dispatch()   worker_1()


                                    read(fp)

                                     db_rd()

                                     db_wr()

                                    sock_wr()




                       worker_n()

                  
Worker model

request   dispatch()     worker_1()


                                      read(fp)

                       BLOCKING!!db_rd()
                                       db_wr()

                                      sock_wr()




                         worker_n()

                  
How does it scale ?
   A worker gets CPU when it is not blocking
   When it makes a blocking call, it sleeps till the sys­
     call is requested
   At this time another worker gets CPU
   Worker might block before it completes it's 
     allocated timeslice.
   This model has worked great and still works great
   Eg: Apache, Squid

                        
Overheads
   Worker management
              Thread creation
              Process creation and management
              Synchronization
              Scheduling (though this is left to OS)
   More system calls for blocking operations




                               
Event Driven Code
   Non blocking code blocks
   Code execution on events
              Data on sockets, timer, new connection
   Execution triggered from an event loop
   Full use of CPU timeslice




                              
Visually ...
                                        Non blocking functions



event_1                                     hdler_1()



event_2         block_on_events( .. )       hdler_2()



          Events are posted



event_n                                     hdler_n()




                          
Visually ...
                                 Non blocking functions



event_1                              hdler_1()            ev()



event_2      block_on_events()       hdler_2()



          Events are posted



event_n                              hdler_n()




                          
Web Server
                             Non blocking functions


 request                         open(fp)             reg()


 opened                           parse()


              event_loop()      read_sql()            reg()


sql_read                         wri_sql()            reg()


sql_writ                         sock_wr()            reg()

responded                         close()

                     
Event Driven Designs
   Nginx, Tornado
   Varnish
   Memcached
   OS support
              epoll – Linux
              kqueue – BSDs




                                
Event Driven Libraries
   Libevent
   Python­twisted
   Java NIO
                Apache MINA, Tomcat (not default)
                Jetty
   QT




                               
Drawbacks
   Tougher to code, design and maintain
   Workers required to make use of multiple CPUs
   All callbacks must be non­blocking
              Tough to get non­blocking libraries for all modules
   No isolation
              A block in any event loop can freeze everything




                              
Python Twisted
   Event driven programming framework
   MIT licensed
   8 years old and stable
   Support for large number of protocols
              Client and server support
              HTTP – SOAP, REST, CouchDB, XMLRPC, ....
              Sockets, TCP/IP, Multicast, TLS, SSH, IMAP …
              SMTP, NNTP, FTP, Memcached, AMQP, XMPP, ...

                              
Deferred
   The central concept of twisted
   A callback returns a deferred to indicate that the job 
     is not done yet.
   The caller can add callbacks to a deferred.
   The callbacks are invoked then the job is done


    Eh ?


                        
Deferred example
from twisted.internet import reactor

# Define a success callback
def cb( arg1, arg2 ):
    print ”Timeout after %d %s” % ( arg1, arg2 )

# Define an error callback
def eb( error ):
    Print ”error %s” % error

# Invoke a non blocking task
deferred = someTimeout( 4 )

# Register the callbacks on the returned deferred
deferred.addCallback( cb, 4, 'twisted is great' )
deferred.addErrback( eb )

# Run the event loop
reactor.run()
                   
Twisted Server

from twisted.internet.protocol import Protocol, Factory
from twisted.internet import reactor

class QOTD(Protocol):
    def connectionMade(self):
        self.transport.write("Welcomern")
        self.transport.loseConnection()

# Next lines are magic:
factory = Factory()
factory.protocol = QOTD

# 8007 is the port you want to run under.
reactor.listenTCP(8007, factory)
reactor.run()



                       
Deferred chaining
   A callback can register and return another deferred
   This callback can return another deferred
   In short we have a deferred chain …
   Web server example:




                       
Deferred Chaining




         
Advanced twisted
   Twisted application support
              Mixing and matching twisted applications
   Command line 'twistd' runner
              Pre­defined twisted apps
              Web, telnet, xmpp, dns, conch (ssh), mail, …
   Plugin architecture
   Live debugging
   ADBAPI – for RDBMS

                              
Advanced twisted
   Perspective Broker
              RPC and object sharing
              Spreading out servers
   Cred – Authentication framework
   Deferring to threads
   External loops (GTK, QT)
   Streaming support
   MVC framework (Complex. Very complex)

                              
Drawbacks
   Single threaded by design
   Makes use of only one core/CPU
   Need external modules for using multiple CPU
              Run multiple instances of twisted on a box
              num_instances = num_cpus
              Use nginx (HTTP), HAProxy for load balancing




                              
Demos




     
Links
   http://twistedmatrix.com/trac/




                       

More Related Content

PDF
An Introduction to Python Concurrency
PPTX
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
PDF
Redis + Apache Spark = Swiss Army Knife Meets Kitchen Sink
PPTX
[211] HBase 기반 검색 데이터 저장소 (공개용)
PDF
InfluxDB IOx Tech Talks: Query Engine Design and the Rust-Based DataFusion in...
PDF
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
PDF
The Rise of ZStandard: Apache Spark/Parquet/ORC/Avro
PPTX
Apache Arrow - An Overview
An Introduction to Python Concurrency
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
Redis + Apache Spark = Swiss Army Knife Meets Kitchen Sink
[211] HBase 기반 검색 데이터 저장소 (공개용)
InfluxDB IOx Tech Talks: Query Engine Design and the Rust-Based DataFusion in...
HTTP by Hand: Exploring HTTP/1.0, 1.1 and 2.0
The Rise of ZStandard: Apache Spark/Parquet/ORC/Avro
Apache Arrow - An Overview

What's hot (20)

PPTX
Apache Ignite vs Alluxio: Memory Speed Big Data Analytics
PPTX
DITA Quick Start for Authors Part II
PDF
The world's next top data model
PDF
A Thorough Comparison of Delta Lake, Iceberg and Hudi
PDF
Hacking Adobe Experience Manager sites
PDF
Optimizing Apache Spark UDFs
PPT
PHP - Introduction to Object Oriented Programming with PHP
PPTX
Deep Dive into Apache Kafka
PDF
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...
PDF
How to Extend Apache Spark with Customized Optimizations
PDF
Cassandra By Example: Data Modelling with CQL3
PDF
[CB16] House of Einherjar :GLIBC上の新たなヒープ活用テクニック by 松隈大樹
PPTX
Attacking thru HTTP Host header
PPTX
A Forgotten HTTP Invisibility Cloak
PPTX
zeromq
PDF
Deep Dive into the New Features of Apache Spark 3.0
PDF
Deep Dive into GPU Support in Apache Spark 3.x
PDF
Advanced Natural Language Processing with Apache Spark NLP
PDF
Offzone | Another waf bypass
PDF
Apache Spark Overview
Apache Ignite vs Alluxio: Memory Speed Big Data Analytics
DITA Quick Start for Authors Part II
The world's next top data model
A Thorough Comparison of Delta Lake, Iceberg and Hudi
Hacking Adobe Experience Manager sites
Optimizing Apache Spark UDFs
PHP - Introduction to Object Oriented Programming with PHP
Deep Dive into Apache Kafka
Designing and Implementing a Real-time Data Lake with Dynamically Changing Sc...
How to Extend Apache Spark with Customized Optimizations
Cassandra By Example: Data Modelling with CQL3
[CB16] House of Einherjar :GLIBC上の新たなヒープ活用テクニック by 松隈大樹
Attacking thru HTTP Host header
A Forgotten HTTP Invisibility Cloak
zeromq
Deep Dive into the New Features of Apache Spark 3.0
Deep Dive into GPU Support in Apache Spark 3.x
Advanced Natural Language Processing with Apache Spark NLP
Offzone | Another waf bypass
Apache Spark Overview
Ad

Viewers also liked (17)

PPTX
Asynchronous Python with Twisted
ODP
Kyua and Jenkins: Testing Framework for BSD
PDF
Обзор фреймворка Twisted
PDF
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
PDF
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
PDF
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
PDF
An Introduction to Twisted
PDF
WTF is Twisted?
PPTX
Twisted pair cable
PPTX
The Onward Journey: Porting Twisted to Python 3
PDF
Implementing microservices tracing with spring cloud and zipkin (spring one)
PDF
Consumer Driven Contracts and Your Microservice Architecture
PDF
Visual Design with Data
PDF
Build Features, Not Apps
PDF
2015 Upload Campaigns Calendar - SlideShare
PPTX
What to Upload to SlideShare
PDF
Getting Started With SlideShare
Asynchronous Python with Twisted
Kyua and Jenkins: Testing Framework for BSD
Обзор фреймворка Twisted
WebCamp 2016.PHP.Боднарчук Михаил.BDD на практике с Codeception
WebCamp 2016: Python. Михаил Бегерский: Использование asyncio-стека для разра...
WebCamp 2016: Python. Вячеслав Каковский: Real-time мессенджер на Python. Осо...
An Introduction to Twisted
WTF is Twisted?
Twisted pair cable
The Onward Journey: Porting Twisted to Python 3
Implementing microservices tracing with spring cloud and zipkin (spring one)
Consumer Driven Contracts and Your Microservice Architecture
Visual Design with Data
Build Features, Not Apps
2015 Upload Campaigns Calendar - SlideShare
What to Upload to SlideShare
Getting Started With SlideShare
Ad

Similar to Python twisted (20)

PPTX
Copper: A high performance workflow engine
PDF
Nginx Internals
PPT
Server side JavaScript: going all the way
KEY
Servers with Event Machine - David Troy - RailsConf 2011
PDF
Virtualizing Java in Java (jug.ru)
ODP
Node js lecture
ODP
Introduce about Nodejs - duyetdev.com
PDF
Silicon Valley JUG: JVM Mechanics
PPTX
Scaling django
PDF
PDF
20140513_jeffyang_demo_openstack
PDF
An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...
PDF
A Scalable I/O Manager for GHC
PDF
Scaling Django with gevent
PPT
Nodejs Intro Part One
PDF
Automated Application Management with SaltStack
PDF
Container orchestration from theory to practice
PDF
Implementações paralelas
PDF
LibOS as a regression test framework for Linux networking #netdev1.1
PPT
A Practical Event Driven Model
Copper: A high performance workflow engine
Nginx Internals
Server side JavaScript: going all the way
Servers with Event Machine - David Troy - RailsConf 2011
Virtualizing Java in Java (jug.ru)
Node js lecture
Introduce about Nodejs - duyetdev.com
Silicon Valley JUG: JVM Mechanics
Scaling django
20140513_jeffyang_demo_openstack
An High Available Database for OpenStack Cloud Production by Pacemaker, Coros...
A Scalable I/O Manager for GHC
Scaling Django with gevent
Nodejs Intro Part One
Automated Application Management with SaltStack
Container orchestration from theory to practice
Implementações paralelas
LibOS as a regression test framework for Linux networking #netdev1.1
A Practical Event Driven Model

Recently uploaded (20)

PPTX
1. Introduction to Computer Programming.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
cloud_computing_Infrastucture_as_cloud_p
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Encapsulation theory and applications.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
1. Introduction to Computer Programming.pptx
Programs and apps: productivity, graphics, security and other tools
Digital-Transformation-Roadmap-for-Companies.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
cloud_computing_Infrastucture_as_cloud_p
SOPHOS-XG Firewall Administrator PPT.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Unlocking AI with Model Context Protocol (MCP)
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Assigned Numbers - 2025 - Bluetooth® Document
Machine learning based COVID-19 study performance prediction
Group 1 Presentation -Planning and Decision Making .pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Per capita expenditure prediction using model stacking based on satellite ima...
Encapsulation theory and applications.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

Python twisted

  • 1. Python Twisted Mahendra M @mahendra http://creativecommons.org/licenses/by-sa/3.0/    
  • 2. Methods of concurrency  Workers  Threads and processes  Event driven Let us examine this with the case of a web server    
  • 3. Worker model request dispatch() worker_1() read(fp) db_rd() db_wr() sock_wr() worker_n()    
  • 4. Worker model request dispatch() worker_1() read(fp) BLOCKING!!db_rd() db_wr() sock_wr() worker_n()    
  • 5. How does it scale ?  A worker gets CPU when it is not blocking  When it makes a blocking call, it sleeps till the sys­ call is requested  At this time another worker gets CPU  Worker might block before it completes it's  allocated timeslice.  This model has worked great and still works great  Eg: Apache, Squid    
  • 6. Overheads  Worker management  Thread creation  Process creation and management  Synchronization  Scheduling (though this is left to OS)  More system calls for blocking operations    
  • 7. Event Driven Code  Non blocking code blocks  Code execution on events  Data on sockets, timer, new connection  Execution triggered from an event loop  Full use of CPU timeslice    
  • 8. Visually ... Non blocking functions event_1 hdler_1() event_2 block_on_events( .. ) hdler_2() Events are posted event_n hdler_n()    
  • 9. Visually ... Non blocking functions event_1 hdler_1() ev() event_2 block_on_events() hdler_2() Events are posted event_n hdler_n()    
  • 10. Web Server Non blocking functions request open(fp) reg() opened parse() event_loop() read_sql() reg() sql_read wri_sql() reg() sql_writ sock_wr() reg() responded close()    
  • 11. Event Driven Designs  Nginx, Tornado  Varnish  Memcached  OS support  epoll – Linux  kqueue – BSDs    
  • 12. Event Driven Libraries  Libevent  Python­twisted  Java NIO  Apache MINA, Tomcat (not default)  Jetty  QT    
  • 13. Drawbacks  Tougher to code, design and maintain  Workers required to make use of multiple CPUs  All callbacks must be non­blocking  Tough to get non­blocking libraries for all modules  No isolation  A block in any event loop can freeze everything    
  • 14. Python Twisted  Event driven programming framework  MIT licensed  8 years old and stable  Support for large number of protocols  Client and server support  HTTP – SOAP, REST, CouchDB, XMLRPC, ....  Sockets, TCP/IP, Multicast, TLS, SSH, IMAP …  SMTP, NNTP, FTP, Memcached, AMQP, XMPP, ...    
  • 15. Deferred  The central concept of twisted  A callback returns a deferred to indicate that the job  is not done yet.  The caller can add callbacks to a deferred.  The callbacks are invoked then the job is done Eh ?    
  • 16. Deferred example from twisted.internet import reactor # Define a success callback def cb( arg1, arg2 ): print ”Timeout after %d %s” % ( arg1, arg2 ) # Define an error callback def eb( error ): Print ”error %s” % error # Invoke a non blocking task deferred = someTimeout( 4 ) # Register the callbacks on the returned deferred deferred.addCallback( cb, 4, 'twisted is great' ) deferred.addErrback( eb ) # Run the event loop reactor.run()    
  • 17. Twisted Server from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor class QOTD(Protocol): def connectionMade(self): self.transport.write("Welcomern") self.transport.loseConnection() # Next lines are magic: factory = Factory() factory.protocol = QOTD # 8007 is the port you want to run under. reactor.listenTCP(8007, factory) reactor.run()    
  • 18. Deferred chaining  A callback can register and return another deferred  This callback can return another deferred  In short we have a deferred chain …  Web server example:    
  • 20. Advanced twisted  Twisted application support  Mixing and matching twisted applications  Command line 'twistd' runner  Pre­defined twisted apps  Web, telnet, xmpp, dns, conch (ssh), mail, …  Plugin architecture  Live debugging  ADBAPI – for RDBMS    
  • 21. Advanced twisted  Perspective Broker  RPC and object sharing  Spreading out servers  Cred – Authentication framework  Deferring to threads  External loops (GTK, QT)  Streaming support  MVC framework (Complex. Very complex)    
  • 22. Drawbacks  Single threaded by design  Makes use of only one core/CPU  Need external modules for using multiple CPU  Run multiple instances of twisted on a box  num_instances = num_cpus  Use nginx (HTTP), HAProxy for load balancing    
  • 23. Demos    
  • 24. Links  http://twistedmatrix.com/trac/