SlideShare a Scribd company logo
1 of 32
Download to read offline
Life in a Queue
          Tareque Hossain
          Education  Technology
What is Message Queue?
•  Message Queues are:
  o  Communication Buffers
  o  Between independent sender & receiver processes
  o  Asynchronous
     •  Time of sending not necessarily same as receiving
•  In context of Web Applications:
  o  Sender: Web Application Servers
  o  Receiver: Background worker processes
  o  Queue items: Tasks that the web server doesn’t have
     time/resources to do
Inside a Message Queue
Web	
  App	
  
 Server	
  
                          Dequeue	
  
                          Manager	
  
                                                  Worker	
  Server	
  

Web	
  App	
           T1            T3
 Server	
  
                       T2            T4

                                     T6           Worker	
  Server	
  
                       T5

Web	
  App	
                         T7
 Server	
  
                       Q1            Q2


                         Enqueue	
                Worker	
  Server	
  
                         Manager	
  
Web	
  App	
  
 Server	
  
                 Message	
  Queue	
  Broker	
  
How does it work?
•  Say a web application server has a task it
   doesn’t have time to do
•  It puts the task in the message queue
•  Other web servers can access the same queue(s)
   and put tasks there
•  Queues are FIFO (First In First Out)
•  Workers are greedy and they all watch the
   queues for tasks
•  Workers asynchronously pick up the first
   available task on the queue when they are ready
Do I need Message Queues?
•  Message Queues are useful in certain
   situations
•  General guidelines:
  o Does your web applications take more than a
    few seconds to generate a response?
  o Are you using a lot of cron jobs to process data
    in the background?
  o Do you wish you could distribute the processing
    of the data generated by your application among
    many servers?
Wait I’ve heard Asynchronous before!
•  Yes. AJAX is an asynchronous communication
   method between client & server
•  Some of the response time issues can be solved:
   o  With AJAX responses that continually enhance the
      initial response
   o  Only if the AJAX responses also complete within a
      reasonable amount of time
•  You need Message Queues when:
   o  Long processing times can’t be avoided in generating
      responses
   o  You want application data to be continuously processed
      in the background and readily available when requested
MQ Tasks: Processing User Uploads
•  Resize uploaded image to generate different
   resolutions of images, avatars, gallery snapshots
•  Reformat videos to match your player
   requirements
•  YouTube, Facebook, Slideshare are good examples
MQ Tasks: Generate Reports
•  Generating reports from large amount of data
  o  Reports that contains graphical charts
  o  Multiple reports that cross reference each other
MQ Tasks: 3rd Party Integrations
•  Bulk processing of 3rd party service requests
   o  Refund hundreds of transactions using Paypal
   o  Any kind of data synchronization
   o  Aggregation of RSS/other feeds




                              Social	
  Network	
  Feed	
  Aggregator	
  
MQ Tasks: Cron Jobs
•  Any cron job that is not time sensitive
   o  Asynchronous behavior of message queue doesn’t
      guarantee execution of tasks on the dot
   o  Jobs in cron that should be done as soon as resources
      become available are good candidates
Message Queue Solution Stack

                                        Message	
  Queue	
  Broker	
  




Message	
  Queue	
  Protocol	
  Library	
                         Message	
  Queue	
  Protocol	
  Library	
  




 Task	
  Management	
  Subsystem	
                                  Task	
  Management	
  Subsystem	
  




     Web	
  Application	
  Server	
                                          Queue	
  Worker	
  
Protocol/Broker Choices
              AMQP	
                                  JMS	
                             STOMP	
  
       (Advanced	
  Message	
             (Java	
  Message	
  Service)	
     (Streaming	
  Text	
  Orientated	
  
        Queuing	
  Protocol)	
                           	
                      Messaging	
  Protocol)	
  
                  	
                              Brokers	
                                   	
  
            Brokers	
              	
                                                  Brokers	
  
	
                                 •       Apache	
  Qpid	
                  	
  
•      RabbitMQ	
                  •       Apache	
  ActiveMQ	
              •  Apache	
  ActiveMQ	
  
•      Apache	
  Qpid	
            •       OpenJMS	
                         •  STOMPServer	
  
•      Apache	
  ActiveMQ	
        •       Open	
  Message	
                 •  CoilMQ	
  
•      OpenAMQ	
                           Queue	
  
•      StormMQ	
                                                                             	
  
                 	
                                                                          	
  
                 	
  
OMG That’s too much!
•  Yeah. I agree.
•  Read great research details at Second Life dev site
   o  http://wiki.secondlife.com/wiki/Message_Queue_Evaluation_Notes

•  Let’s simplify. How do we choose?
   o  How is the exception handling and recovery?
   o  Is maintenance relatively low?
   o  How easy is deployment?
   o  Are the queues persistent?
   o  How is the community support?
   o  What language is it written in? How compatible is that
      with our current systems?
   o  How detailed are the documentations?
Choice of PBS Education
•  We chose AMQP & RabbitMQ
•  Why?
  o  We don’t expect message volumes as high as 1M or
     more at a time
  o  RabbitMQ is free to use
  o  The documentation is decent
  o  There is decent clustering support, even though we never
     needed clustering
  o  We didn’t want to lose queues or messages upon broker
     crash/ restart
  o  We develop applications using Python/django and
     setting up an AMQP backend using celery/kombu was
     easy
Message Queue Solution Stack

                                   RabbitMQ	
  




  PyAMQPlib/Kombu	
                               PyAMQPlib/Kombu	
  




           Celery	
                                      Celery	
  




Web	
  Application	
  Server	
                      Queue	
  Worker	
  
Celery? Kombu? Yummy.
•  django made web development using Python a
   piece of cake
•  Celery & Kombu make using message queue in
   your django/Python applications a piece of cake
•  Kombu
   o  AMQP based Messaging Framework for Python,
      powered by PyAMQPlib
   o  Provides fundamentals for creating queues, configuring
      broker, sending receiving messages
•  Celery
   o  Distributed task queue management application
Celery Backends
•  Celery is very, very powerful
•  You can use celery to emulate message queue
   brokers using a DB backend for broker
   o  Involves polling & less efficient than AMQP
   o  Use for local development
•  Bundled broker backends
   o  amqplib, pika, redis, beanstalk, sqlalchemy, django,
      mongodb, couchdb
•  Broker backend is different that task & task result
   store backend
   o  Used by celery to store results of a task, errors if failed
A Problem with a View
•  What is wrong with this view?

   	
  
   def	
  create_report(request):	
  
   	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  Code	
  for	
  extracting	
  parameters	
  from	
  request	
  
   	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  Code	
  for	
  generating	
  report	
  from	
  lots	
  of	
  data	
  
   	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  return	
  render_to_response(‘profiles/
   index.html’,	
  {	
  
   	
  	
  	
  	
  	
  	
  	
  	
  ‘report’:	
  report,	
  
   	
  	
  	
  	
  },	
  context_instance=RequestContext(request))	
  
   	
  
A Problem with a View
Lets Write a Celery Task
•  Writing celery tasks was never any more difficult
   than this:

   	
  
   import	
  celery	
  
   	
  
   @celery.task()	
  
   def	
  generate_report(*args,	
  **kwargs):	
  
   	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  Code	
  for	
  generating	
  report	
  
   	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  report.save()	
  
   	
  
Lets Write a Celery Task II
•  If you want to customize your tasks, inherit from
   the base Task object
   	
  
   from	
  celery.task.base	
  import	
  Task	
  
   	
  
   class	
  GenerateReport(Task):	
  
   	
  	
  	
  	
  def	
  __init__(self,	
  *args,	
  **kwargs):	
  
   	
  	
  	
  	
  	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  	
  	
  	
  	
  Custom	
  init	
  code	
  
   	
  	
  	
  	
  	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  	
  	
  	
  	
  return	
  super(GenerateReport,	
  self).__init__(*args,	
  
   **kwargs)	
  
   	
  
   	
  	
  	
  	
  def	
  run(self,	
  *args,	
  **kwargs):	
  
   	
  	
  	
  	
  	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  	
  	
  	
  	
  Code	
  for	
  generating	
  report	
  
   	
  	
  	
  	
  	
  	
  	
  	
  ...	
  
   	
  	
  	
  	
  	
  	
  	
  	
  report.save()	
  
   	
  
Issuing a task
•  After writing a task, we issue the task from within
   a request in the following way:

	
  
def	
  create_report(request):	
  
	
  	
  	
  	
  ...	
  
	
  	
  	
  	
  Code	
  for	
  extracting	
  parameters	
  from	
  request	
  
	
  	
  	
  	
  ...	
  
	
  	
  	
  	
  generate_report.delay(**params)	
  
	
  	
  	
  	
  //	
  or	
  
	
  	
  	
  	
  GenerateReport.delay(**params)	
  
	
  	
  	
  	
  messages.success(request,	
  'You	
  will	
  receive	
  an	
  email	
  
when	
  report	
  generation	
  is	
  complete.')	
  
	
  	
  	
  	
  return	
  HTTPResponseRedirect(reverse
(‘reports_index’))	
  
	
  
What happens when you issue tasks?

                            Broker	
     Queue	
  




           Celery	
  


                                           Celery	
     Celery	
     Celery	
  



Application	
       Request	
  
Server	
            Handler	
  
                                           Worker	
     Worker	
     Worker	
  
Understanding Queue Routing
•  Brokers contains multiple virtual hosts
•  Each virtual host contains multiple exchanges
•  Messages are sent to exchanges
   o  Exchanges are hubs that connect to a set of queues
•  An exchange routes messages to one or more
   queues



                                       Queue	
  

                                                   Exchange	
  
                           VHost	
  
Understanding Queue Routing
•  In Celery configurations:
   o  binding_key binds a task namespace to a queue
   o  exchange defines the name of an exchange
   o  routing_key defines which queue a message should be
      directed to under a certain exchange
   o  exchange_type = ‘direct’ routes for exact routing keys
   o  exchange_type = ‘topic’ routes for namespaced &
      wildcard routing keys
       •  * (matches a single word)
       •  # (matches zero or more words)
Example Celery Config for Routing
CELERY_DEFAULT_QUEUE	
  =	
  "default"	
  
CELERY_QUEUES	
  =	
  {	
  
	
  	
  	
  	
  "feed_tasks":	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  "binding_key":	
  "feed.#",	
  
	
  	
  	
  	
  },	
  
	
  	
  	
  	
  "regular_tasks":	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  "binding_key":	
  "task.#",	
  
	
  	
  	
  	
  },	
  
	
  	
  	
  	
  "image_tasks":	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  "binding_key":	
  "image.compress",	
  
	
  	
  	
  	
  	
  	
  	
  	
  "exchange":	
  "mediatasks",	
  
	
  	
  	
  	
  	
  	
  	
  	
  "exchange_type":	
  "direct",	
  
	
  	
  	
  	
  },	
  
}	
  
CELERY_DEFAULT_EXCHANGE	
  =	
  "tasks"	
  
CELERY_DEFAULT_EXCHANGE_TYPE	
  =	
  "topic"	
  
CELERY_DEFAULT_ROUTING_KEY	
  =	
  "task.default”	
  
Quick Tips
#	
  Route	
  a	
  task	
  
mytask.apply_async(	
  
            	
  args=[filename],	
  	
  
            	
  routing_key=“video.compress”	
  
)	
  
#	
  Or	
  define	
  task	
  mapping	
  in	
  CELERY_ROUTES	
  setting	
  

#	
  Set	
  expiration	
  for	
  a	
  task	
  –	
  in	
  seconds	
  
mytask.apply_async(args=[10,	
  10],	
  expires=60)	
  


#	
  Revoke	
  a	
  task	
  using	
  the	
  task	
  instance	
  
result	
  =	
  mytask.apply_async(args=[2,	
  2],	
  countdown=120)	
  
result.revoke()	
  
#	
  Or	
  save	
  the	
  task	
  ID	
  (result.task_id)	
  somewhere	
  
from	
  celery.task.control	
  import	
  revoke	
  
revoke(task_id)	
  
Quick Tips
•  Execute task as a blocking call using:
generate_report.apply(kwargs=params,	
  **options)	
  

•  Avoid issuing tasks inside an asynchronous task
   that waits on children data (blocking)
   o  Write re-usable pieces of code that can be called as
      functions instead of called as tasks
   o  If necessary, use the callback + subtask feature of celery
•  Ignore results if you don’t need them
   o  If your asynchronous task doesn’t return anything
@celery.task(ignore_results=True)	
  
Good to know
•  Do check whether your task parameters are
   serializable
  o  WSGI request objects are not serializable
  o  Don’t pass request as a parameter for your task
•  Don’t pass unnecessary data in task
   parameters
  o  They have to be stored until task is complete
Good to know
•  Avoid starvation of tasks using multiple
   queues
  o  If really long video re-formatting tasks are processed
     in the same queue as relatively quicker thumbnail
     generation tasks, the latter may starve
  o  Only available when using AMQP broker backend
•  Use celerybeat for time sensitive repeated
   tasks
  o  Can replace time sensitive cron jobs related to your web
     application
Q&A
•  Slides available at:
   o  http://www.slideshare.net/tarequeh
•  Extensive guides & documentation available at:
   o  http://ask.github.com/celery/

More Related Content

What's hot

NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀승명 양
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)Chris Cowan
 
[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)
[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)
[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)Heungsub Lee
 
NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현noerror
 
이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015
이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015
이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015devCAT Studio, NEXON
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python CeleryMahendra M
 
게임서버프로그래밍 #1 - IOCP
게임서버프로그래밍 #1 - IOCP게임서버프로그래밍 #1 - IOCP
게임서버프로그래밍 #1 - IOCPSeungmo Koo
 
Iocp 기본 구조 이해
Iocp 기본 구조 이해Iocp 기본 구조 이해
Iocp 기본 구조 이해Nam Hyeonuk
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것흥배 최
 
라이브 서비스를 위한 게임 서버 구성
라이브 서비스를 위한 게임 서버 구성라이브 서비스를 위한 게임 서버 구성
라이브 서비스를 위한 게임 서버 구성Hyunjik Bae
 
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games ConferenceKGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games ConferenceXionglong Jin
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...Amazon Web Services Korea
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기Sang Heon Lee
 
홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019
홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019
홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019devCAT Studio, NEXON
 
Removing performance bottlenecks with Kafka Monitoring and topic configuration
Removing performance bottlenecks with Kafka Monitoring and topic configurationRemoving performance bottlenecks with Kafka Monitoring and topic configuration
Removing performance bottlenecks with Kafka Monitoring and topic configurationKnoldus Inc.
 
Next-generation MMORPG service architecture
Next-generation MMORPG service architectureNext-generation MMORPG service architecture
Next-generation MMORPG service architectureJongwon Kim
 
MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현YEONG-CHEON YOU
 

What's hot (20)

NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀NDC 11 자이언트 서버의 비밀
NDC 11 자이언트 서버의 비밀
 
Intro to Node.js (v1)
Intro to Node.js (v1)Intro to Node.js (v1)
Intro to Node.js (v1)
 
[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)
[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)
[야생의 땅: 듀랑고] 서버 아키텍처 Vol. 2 (자막)
 
Mongo db 최범균
Mongo db 최범균Mongo db 최범균
Mongo db 최범균
 
NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현NDC12_Lockless게임서버설계와구현
NDC12_Lockless게임서버설계와구현
 
이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015
이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015
이승재, 마비노기 듀얼: 분산 데이터베이스 트랜잭션 설계와 구현, NDC2015
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python Celery
 
게임서버프로그래밍 #1 - IOCP
게임서버프로그래밍 #1 - IOCP게임서버프로그래밍 #1 - IOCP
게임서버프로그래밍 #1 - IOCP
 
Iocp 기본 구조 이해
Iocp 기본 구조 이해Iocp 기본 구조 이해
Iocp 기본 구조 이해
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
multi-thread 어플리케이션에 대해 모든 개발자가 알아 두지 않으면 안 되는 것
 
라이브 서비스를 위한 게임 서버 구성
라이브 서비스를 위한 게임 서버 구성라이브 서비스를 위한 게임 서버 구성
라이브 서비스를 위한 게임 서버 구성
 
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games ConferenceKGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
KGC 2016: HTTPS 로 모바일 게임 서버 구축한다는 것 - Korea Games Conference
 
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
오딘: 발할라 라이징 MMORPG의 성능 최적화 사례 공유 [카카오게임즈 - 레벨 300] - 발표자: 김문권, 팀장, 라이온하트 스튜디오...
 
[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기[NDC2016] TERA 서버의 Modern C++ 활용기
[NDC2016] TERA 서버의 Modern C++ 활용기
 
홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019
홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019
홍성우, 게임 서버의 목차 - 시작부터 출시까지, NDC2019
 
Removing performance bottlenecks with Kafka Monitoring and topic configuration
Removing performance bottlenecks with Kafka Monitoring and topic configurationRemoving performance bottlenecks with Kafka Monitoring and topic configuration
Removing performance bottlenecks with Kafka Monitoring and topic configuration
 
Node js for beginners
Node js for beginnersNode js for beginners
Node js for beginners
 
Next-generation MMORPG service architecture
Next-generation MMORPG service architectureNext-generation MMORPG service architecture
Next-generation MMORPG service architecture
 
MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현MMOG Server-Side 충돌 및 이동처리 설계와 구현
MMOG Server-Side 충돌 및 이동처리 설계와 구현
 

Similar to Life in a Queue - Using Message Queue with django

Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...Jimmy DeadcOde
 
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20....Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...Javier García Magna
 
Real time system_performance_mon
Real time system_performance_monReal time system_performance_mon
Real time system_performance_monTomas Doran
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudyJohn Adams
 
The Art of Message Queues - TEKX
The Art of Message Queues - TEKXThe Art of Message Queues - TEKX
The Art of Message Queues - TEKXMike Willbanks
 
PyCon India 2012: Celery Talk
PyCon India 2012: Celery TalkPyCon India 2012: Celery Talk
PyCon India 2012: Celery TalkPiyush Kumar
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'EnterprisePyCon Italia
 
Ruby Microservices with RabbitMQ
Ruby Microservices with RabbitMQRuby Microservices with RabbitMQ
Ruby Microservices with RabbitMQZoran Majstorovic
 
NoSQL afternoon in Japan Kumofs & MessagePack
NoSQL afternoon in Japan Kumofs & MessagePackNoSQL afternoon in Japan Kumofs & MessagePack
NoSQL afternoon in Japan Kumofs & MessagePackSadayuki Furuhashi
 
NoSQL afternoon in Japan kumofs & MessagePack
NoSQL afternoon in Japan kumofs & MessagePackNoSQL afternoon in Japan kumofs & MessagePack
NoSQL afternoon in Japan kumofs & MessagePackSadayuki Furuhashi
 
Chirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterChirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterJohn Adams
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesAmazon Web Services
 
Building a [micro]services platform on AWS
Building a [micro]services platform on AWSBuilding a [micro]services platform on AWS
Building a [micro]services platform on AWSShaun Pearce
 
Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...
Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...
Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...Startupfest
 
Handling 1 Billion Requests/hr with Minimal Latency Using Docker
Handling 1 Billion Requests/hr with Minimal Latency Using DockerHandling 1 Billion Requests/hr with Minimal Latency Using Docker
Handling 1 Billion Requests/hr with Minimal Latency Using DockerMatomy
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices💡 Tomasz Kogut
 
Jms deep dive [con4864]
Jms deep dive [con4864]Jms deep dive [con4864]
Jms deep dive [con4864]Ryan Cuprak
 

Similar to Life in a Queue - Using Message Queue with django (20)

Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
 
The bigrabbit
The bigrabbitThe bigrabbit
The bigrabbit
 
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20....Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
.Net Microservices with Event Sourcing, CQRS, Docker and... Windows Server 20...
 
Real time system_performance_mon
Real time system_performance_monReal time system_performance_mon
Real time system_performance_mon
 
John adams talk cloudy
John adams   talk cloudyJohn adams   talk cloudy
John adams talk cloudy
 
The Art of Message Queues - TEKX
The Art of Message Queues - TEKXThe Art of Message Queues - TEKX
The Art of Message Queues - TEKX
 
Fastest Servlets in the West
Fastest Servlets in the WestFastest Servlets in the West
Fastest Servlets in the West
 
PyCon India 2012: Celery Talk
PyCon India 2012: Celery TalkPyCon India 2012: Celery Talk
PyCon India 2012: Celery Talk
 
Django è pronto per l'Enterprise
Django è pronto per l'EnterpriseDjango è pronto per l'Enterprise
Django è pronto per l'Enterprise
 
Ruby Microservices with RabbitMQ
Ruby Microservices with RabbitMQRuby Microservices with RabbitMQ
Ruby Microservices with RabbitMQ
 
NoSQL afternoon in Japan Kumofs & MessagePack
NoSQL afternoon in Japan Kumofs & MessagePackNoSQL afternoon in Japan Kumofs & MessagePack
NoSQL afternoon in Japan Kumofs & MessagePack
 
NoSQL afternoon in Japan kumofs & MessagePack
NoSQL afternoon in Japan kumofs & MessagePackNoSQL afternoon in Japan kumofs & MessagePack
NoSQL afternoon in Japan kumofs & MessagePack
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Chirp 2010: Scaling Twitter
Chirp 2010: Scaling TwitterChirp 2010: Scaling Twitter
Chirp 2010: Scaling Twitter
 
Getting Started with Serverless Architectures
Getting Started with Serverless ArchitecturesGetting Started with Serverless Architectures
Getting Started with Serverless Architectures
 
Building a [micro]services platform on AWS
Building a [micro]services platform on AWSBuilding a [micro]services platform on AWS
Building a [micro]services platform on AWS
 
Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...
Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...
Jeremy Edberg (MinOps ) - How to build a solid infrastructure for a startup t...
 
Handling 1 Billion Requests/hr with Minimal Latency Using Docker
Handling 1 Billion Requests/hr with Minimal Latency Using DockerHandling 1 Billion Requests/hr with Minimal Latency Using Docker
Handling 1 Billion Requests/hr with Minimal Latency Using Docker
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
 
Jms deep dive [con4864]
Jms deep dive [con4864]Jms deep dive [con4864]
Jms deep dive [con4864]
 

More from Tareque Hossain

django Forms in a Web API World
django Forms in a Web API Worlddjango Forms in a Web API World
django Forms in a Web API WorldTareque Hossain
 
RESTful APIs: Promises & lies
RESTful APIs: Promises & liesRESTful APIs: Promises & lies
RESTful APIs: Promises & liesTareque Hossain
 
API Design & Security in django
API Design & Security in djangoAPI Design & Security in django
API Design & Security in djangoTareque Hossain
 
Introducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerIntroducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerTareque Hossain
 
SIGTRAN - An Introduction
SIGTRAN - An IntroductionSIGTRAN - An Introduction
SIGTRAN - An IntroductionTareque Hossain
 
Linux Composite Communication
Linux Composite CommunicationLinux Composite Communication
Linux Composite CommunicationTareque Hossain
 
Xen & the Art of Virtualization
Xen & the Art of VirtualizationXen & the Art of Virtualization
Xen & the Art of VirtualizationTareque Hossain
 
Introduction to django-config
Introduction to django-configIntroduction to django-config
Introduction to django-configTareque Hossain
 

More from Tareque Hossain (11)

django Forms in a Web API World
django Forms in a Web API Worlddjango Forms in a Web API World
django Forms in a Web API World
 
The solr power
The solr powerThe solr power
The solr power
 
RESTful APIs: Promises & lies
RESTful APIs: Promises & liesRESTful APIs: Promises & lies
RESTful APIs: Promises & lies
 
API Design & Security in django
API Design & Security in djangoAPI Design & Security in django
API Design & Security in django
 
Introducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel MultiplexerIntroducing KMux - The Kernel Multiplexer
Introducing KMux - The Kernel Multiplexer
 
SIGTRAN - An Introduction
SIGTRAN - An IntroductionSIGTRAN - An Introduction
SIGTRAN - An Introduction
 
Django orm-tips
Django orm-tipsDjango orm-tips
Django orm-tips
 
Linux Composite Communication
Linux Composite CommunicationLinux Composite Communication
Linux Composite Communication
 
Django Deployment
Django DeploymentDjango Deployment
Django Deployment
 
Xen & the Art of Virtualization
Xen & the Art of VirtualizationXen & the Art of Virtualization
Xen & the Art of Virtualization
 
Introduction to django-config
Introduction to django-configIntroduction to django-config
Introduction to django-config
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

Life in a Queue - Using Message Queue with django

  • 1. Life in a Queue Tareque Hossain Education  Technology
  • 2. What is Message Queue? •  Message Queues are: o  Communication Buffers o  Between independent sender & receiver processes o  Asynchronous •  Time of sending not necessarily same as receiving •  In context of Web Applications: o  Sender: Web Application Servers o  Receiver: Background worker processes o  Queue items: Tasks that the web server doesn’t have time/resources to do
  • 3.
  • 4. Inside a Message Queue Web  App   Server   Dequeue   Manager   Worker  Server   Web  App   T1 T3 Server   T2 T4 T6 Worker  Server   T5 Web  App   T7 Server   Q1 Q2 Enqueue   Worker  Server   Manager   Web  App   Server   Message  Queue  Broker  
  • 5. How does it work? •  Say a web application server has a task it doesn’t have time to do •  It puts the task in the message queue •  Other web servers can access the same queue(s) and put tasks there •  Queues are FIFO (First In First Out) •  Workers are greedy and they all watch the queues for tasks •  Workers asynchronously pick up the first available task on the queue when they are ready
  • 6. Do I need Message Queues? •  Message Queues are useful in certain situations •  General guidelines: o Does your web applications take more than a few seconds to generate a response? o Are you using a lot of cron jobs to process data in the background? o Do you wish you could distribute the processing of the data generated by your application among many servers?
  • 7. Wait I’ve heard Asynchronous before! •  Yes. AJAX is an asynchronous communication method between client & server •  Some of the response time issues can be solved: o  With AJAX responses that continually enhance the initial response o  Only if the AJAX responses also complete within a reasonable amount of time •  You need Message Queues when: o  Long processing times can’t be avoided in generating responses o  You want application data to be continuously processed in the background and readily available when requested
  • 8. MQ Tasks: Processing User Uploads •  Resize uploaded image to generate different resolutions of images, avatars, gallery snapshots •  Reformat videos to match your player requirements •  YouTube, Facebook, Slideshare are good examples
  • 9. MQ Tasks: Generate Reports •  Generating reports from large amount of data o  Reports that contains graphical charts o  Multiple reports that cross reference each other
  • 10. MQ Tasks: 3rd Party Integrations •  Bulk processing of 3rd party service requests o  Refund hundreds of transactions using Paypal o  Any kind of data synchronization o  Aggregation of RSS/other feeds Social  Network  Feed  Aggregator  
  • 11. MQ Tasks: Cron Jobs •  Any cron job that is not time sensitive o  Asynchronous behavior of message queue doesn’t guarantee execution of tasks on the dot o  Jobs in cron that should be done as soon as resources become available are good candidates
  • 12. Message Queue Solution Stack Message  Queue  Broker   Message  Queue  Protocol  Library   Message  Queue  Protocol  Library   Task  Management  Subsystem   Task  Management  Subsystem   Web  Application  Server   Queue  Worker  
  • 13. Protocol/Broker Choices AMQP   JMS   STOMP   (Advanced  Message   (Java  Message  Service)   (Streaming  Text  Orientated   Queuing  Protocol)     Messaging  Protocol)     Brokers     Brokers     Brokers     •  Apache  Qpid     •  RabbitMQ   •  Apache  ActiveMQ   •  Apache  ActiveMQ   •  Apache  Qpid   •  OpenJMS   •  STOMPServer   •  Apache  ActiveMQ   •  Open  Message   •  CoilMQ   •  OpenAMQ   Queue   •  StormMQ          
  • 14. OMG That’s too much! •  Yeah. I agree. •  Read great research details at Second Life dev site o  http://wiki.secondlife.com/wiki/Message_Queue_Evaluation_Notes •  Let’s simplify. How do we choose? o  How is the exception handling and recovery? o  Is maintenance relatively low? o  How easy is deployment? o  Are the queues persistent? o  How is the community support? o  What language is it written in? How compatible is that with our current systems? o  How detailed are the documentations?
  • 15. Choice of PBS Education •  We chose AMQP & RabbitMQ •  Why? o  We don’t expect message volumes as high as 1M or more at a time o  RabbitMQ is free to use o  The documentation is decent o  There is decent clustering support, even though we never needed clustering o  We didn’t want to lose queues or messages upon broker crash/ restart o  We develop applications using Python/django and setting up an AMQP backend using celery/kombu was easy
  • 16. Message Queue Solution Stack RabbitMQ   PyAMQPlib/Kombu   PyAMQPlib/Kombu   Celery   Celery   Web  Application  Server   Queue  Worker  
  • 17. Celery? Kombu? Yummy. •  django made web development using Python a piece of cake •  Celery & Kombu make using message queue in your django/Python applications a piece of cake •  Kombu o  AMQP based Messaging Framework for Python, powered by PyAMQPlib o  Provides fundamentals for creating queues, configuring broker, sending receiving messages •  Celery o  Distributed task queue management application
  • 18. Celery Backends •  Celery is very, very powerful •  You can use celery to emulate message queue brokers using a DB backend for broker o  Involves polling & less efficient than AMQP o  Use for local development •  Bundled broker backends o  amqplib, pika, redis, beanstalk, sqlalchemy, django, mongodb, couchdb •  Broker backend is different that task & task result store backend o  Used by celery to store results of a task, errors if failed
  • 19. A Problem with a View •  What is wrong with this view?   def  create_report(request):          ...          Code  for  extracting  parameters  from  request          ...          ...          Code  for  generating  report  from  lots  of  data          ...          return  render_to_response(‘profiles/ index.html’,  {                  ‘report’:  report,          },  context_instance=RequestContext(request))    
  • 20. A Problem with a View
  • 21. Lets Write a Celery Task •  Writing celery tasks was never any more difficult than this:   import  celery     @celery.task()   def  generate_report(*args,  **kwargs):          ...          Code  for  generating  report          ...          report.save()    
  • 22. Lets Write a Celery Task II •  If you want to customize your tasks, inherit from the base Task object   from  celery.task.base  import  Task     class  GenerateReport(Task):          def  __init__(self,  *args,  **kwargs):                  ...                  Custom  init  code                  ...                  return  super(GenerateReport,  self).__init__(*args,   **kwargs)            def  run(self,  *args,  **kwargs):                  ...                  Code  for  generating  report                  ...                  report.save()    
  • 23. Issuing a task •  After writing a task, we issue the task from within a request in the following way:   def  create_report(request):          ...          Code  for  extracting  parameters  from  request          ...          generate_report.delay(**params)          //  or          GenerateReport.delay(**params)          messages.success(request,  'You  will  receive  an  email   when  report  generation  is  complete.')          return  HTTPResponseRedirect(reverse (‘reports_index’))    
  • 24. What happens when you issue tasks? Broker   Queue   Celery   Celery   Celery   Celery   Application   Request   Server   Handler   Worker   Worker   Worker  
  • 25. Understanding Queue Routing •  Brokers contains multiple virtual hosts •  Each virtual host contains multiple exchanges •  Messages are sent to exchanges o  Exchanges are hubs that connect to a set of queues •  An exchange routes messages to one or more queues Queue   Exchange   VHost  
  • 26. Understanding Queue Routing •  In Celery configurations: o  binding_key binds a task namespace to a queue o  exchange defines the name of an exchange o  routing_key defines which queue a message should be directed to under a certain exchange o  exchange_type = ‘direct’ routes for exact routing keys o  exchange_type = ‘topic’ routes for namespaced & wildcard routing keys •  * (matches a single word) •  # (matches zero or more words)
  • 27. Example Celery Config for Routing CELERY_DEFAULT_QUEUE  =  "default"   CELERY_QUEUES  =  {          "feed_tasks":  {                  "binding_key":  "feed.#",          },          "regular_tasks":  {                  "binding_key":  "task.#",          },          "image_tasks":  {                  "binding_key":  "image.compress",                  "exchange":  "mediatasks",                  "exchange_type":  "direct",          },   }   CELERY_DEFAULT_EXCHANGE  =  "tasks"   CELERY_DEFAULT_EXCHANGE_TYPE  =  "topic"   CELERY_DEFAULT_ROUTING_KEY  =  "task.default”  
  • 28. Quick Tips #  Route  a  task   mytask.apply_async(    args=[filename],      routing_key=“video.compress”   )   #  Or  define  task  mapping  in  CELERY_ROUTES  setting   #  Set  expiration  for  a  task  –  in  seconds   mytask.apply_async(args=[10,  10],  expires=60)   #  Revoke  a  task  using  the  task  instance   result  =  mytask.apply_async(args=[2,  2],  countdown=120)   result.revoke()   #  Or  save  the  task  ID  (result.task_id)  somewhere   from  celery.task.control  import  revoke   revoke(task_id)  
  • 29. Quick Tips •  Execute task as a blocking call using: generate_report.apply(kwargs=params,  **options)   •  Avoid issuing tasks inside an asynchronous task that waits on children data (blocking) o  Write re-usable pieces of code that can be called as functions instead of called as tasks o  If necessary, use the callback + subtask feature of celery •  Ignore results if you don’t need them o  If your asynchronous task doesn’t return anything @celery.task(ignore_results=True)  
  • 30. Good to know •  Do check whether your task parameters are serializable o  WSGI request objects are not serializable o  Don’t pass request as a parameter for your task •  Don’t pass unnecessary data in task parameters o  They have to be stored until task is complete
  • 31. Good to know •  Avoid starvation of tasks using multiple queues o  If really long video re-formatting tasks are processed in the same queue as relatively quicker thumbnail generation tasks, the latter may starve o  Only available when using AMQP broker backend •  Use celerybeat for time sensitive repeated tasks o  Can replace time sensitive cron jobs related to your web application
  • 32. Q&A •  Slides available at: o  http://www.slideshare.net/tarequeh •  Extensive guides & documentation available at: o  http://ask.github.com/celery/