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

PPTX
CPU Scheduling in OS Presentation
usmankiyani1
 
PPSX
Strings in Java
Hitesh-Java
 
PDF
An Introduction to Python Concurrency
David Beazley (Dabeaz LLC)
 
PPTX
Asynchronous programming
Filip Ekberg
 
PPTX
Big o notation
hamza mushtaq
 
PPT
Deadlock
Rajandeep Gill
 
CPU Scheduling in OS Presentation
usmankiyani1
 
Strings in Java
Hitesh-Java
 
An Introduction to Python Concurrency
David Beazley (Dabeaz LLC)
 
Asynchronous programming
Filip Ekberg
 
Big o notation
hamza mushtaq
 
Deadlock
Rajandeep Gill
 

What's hot (20)

PPTX
Producer consumer
Mohd Tousif
 
PPTX
JSON in Solr: from top to bottom
Alexandre Rafalovitch
 
PPTX
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
PPT
Transaction
Amin Omi
 
PDF
Unicode basics in python
Navaneethan Ramasamy
 
PPTX
Lecture 3 general problem solver
Student at University Of Malakand, Pakistan
 
PPTX
Networking in python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
PDF
Error Management: Future vs ZIO
John De Goes
 
PPTX
Correcting Common Async Await Mistakes in .NET
Brandon Minnick, MBA
 
PDF
Lambda Expressions in Java
Erhan Bagdemir
 
PPTX
Java 8 lambda
Manav Prasad
 
PDF
동시성 프로그래밍 하기 좋은 Clojure
Eunmin Kim
 
PPT
Dinive conquer algorithm
Mohd Arif
 
ODP
Garbage collection
Mudit Gupta
 
PPTX
page replacement.pptx
homipeh
 
PPT
Java And Multithreading
Shraddha
 
PPTX
Divide and conquer 1
Kumar
 
PDF
JavaScript Looping Statements
Janssen Harvey Insigne
 
PPTX
Round robin scheduling
Raghav S
 
PPTX
jQuery
Jay Poojara
 
Producer consumer
Mohd Tousif
 
JSON in Solr: from top to bottom
Alexandre Rafalovitch
 
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Transaction
Amin Omi
 
Unicode basics in python
Navaneethan Ramasamy
 
Lecture 3 general problem solver
Student at University Of Malakand, Pakistan
 
Error Management: Future vs ZIO
John De Goes
 
Correcting Common Async Await Mistakes in .NET
Brandon Minnick, MBA
 
Lambda Expressions in Java
Erhan Bagdemir
 
Java 8 lambda
Manav Prasad
 
동시성 프로그래밍 하기 좋은 Clojure
Eunmin Kim
 
Dinive conquer algorithm
Mohd Arif
 
Garbage collection
Mudit Gupta
 
page replacement.pptx
homipeh
 
Java And Multithreading
Shraddha
 
Divide and conquer 1
Kumar
 
JavaScript Looping Statements
Janssen Harvey Insigne
 
Round robin scheduling
Raghav S
 
jQuery
Jay Poojara
 
Ad

Viewers also liked (17)

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

Similar to Python twisted (20)

PDF
Twisted
Michal Sedlak
 
PDF
Scaling Django with gevent
Mahendra M
 
PPTX
Using Coroutines to Create Efficient, High-Concurrency Web Applications
Matt Spitz
 
PDF
How do event loops work in Python?
Saúl Ibarra Corretgé
 
PDF
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Twilio Inc
 
PDF
Twisted Introduction
cyli
 
PDF
Building Web APIs that Scale
Salesforce Developers
 
KEY
Gevent what's the point
seanmcq
 
PPTX
Async programming and python
Chetan Giridhar
 
ODP
Introduction to Python Celery
Mahendra M
 
PDF
Server Tips
liqingfang126
 
KEY
Introduction to node.js
jacekbecela
 
PPTX
vert.x - asynchronous event-driven web applications on the JVM
jbandi
 
PDF
Concurrency patterns in Ruby
ThoughtWorks
 
PDF
Concurrency patterns in Ruby
ThoughtWorks
 
PDF
Embracing Events
Lourens Naudé
 
PPTX
Chapter 3-Processes2.pptx
MeymunaMohammed1
 
PDF
Distributed and concurrent programming with RabbitMQ and EventMachine Rails U...
Paolo Negri
 
PDF
Tornado Web Server Internals
Praveen Gollakota
 
PDF
Asynchronous Io Programming
l xf
 
Twisted
Michal Sedlak
 
Scaling Django with gevent
Mahendra M
 
Using Coroutines to Create Efficient, High-Concurrency Web Applications
Matt Spitz
 
How do event loops work in Python?
Saúl Ibarra Corretgé
 
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Twilio Inc
 
Twisted Introduction
cyli
 
Building Web APIs that Scale
Salesforce Developers
 
Gevent what's the point
seanmcq
 
Async programming and python
Chetan Giridhar
 
Introduction to Python Celery
Mahendra M
 
Server Tips
liqingfang126
 
Introduction to node.js
jacekbecela
 
vert.x - asynchronous event-driven web applications on the JVM
jbandi
 
Concurrency patterns in Ruby
ThoughtWorks
 
Concurrency patterns in Ruby
ThoughtWorks
 
Embracing Events
Lourens Naudé
 
Chapter 3-Processes2.pptx
MeymunaMohammed1
 
Distributed and concurrent programming with RabbitMQ and EventMachine Rails U...
Paolo Negri
 
Tornado Web Server Internals
Praveen Gollakota
 
Asynchronous Io Programming
l xf
 

Recently uploaded (20)

PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Doc9.....................................
SofiaCollazos
 
Software Development Methodologies in 2025
KodekX
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 

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/