SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
Celery
An introduction to the distributed task queue.



Rich Leland
ZPUGDC // April 6, 2010

@richleland
richard_leland@discovery.com
http://creative.discovery.com
What is Celery?
A task queue based on distributed message passing.
What is Celery?
An asynchronous, concurrent, distributed,
      super-awesome task queue.
A brief history
• First commit in April 2009 as "crunchy"
• Originally built for use with Django
• Django is still a requirement
• Don't be scurred! No Django app required!
• It's for the ORM, caching, and signaling
• Future is celery using SQLAlchemy and louie
Why should I use Celery?
User perspective

• Minimize request/response cycle
• Smoother user experience
• Difference between pleasant and unpleasant
Developer perspective

• Offload time/cpu intensive processes
• Scalability - add workers as needed
• Flexibility - many points of customization
• About to turn 1 (apr 24)
• Actively developed
• Great documentation
• Lots of tutorials
LATENCY == DELAY == NOT GOOD!
Business perspective

• Latency == $$$
• Every 100ms of latency cost Amazon 1% in sales
• Google found an extra .5 seconds in search page
    generation time dropped traffic by 20%
•   5ms latency in an electronic trading platform could mean
    $4 million in lost revenues per millisecond




http://highscalability.com/latency-everywhere-and-it-costs-you-sales-how-crush-it
Example Uses

• Image processing
• Calculate points and award badges
• Upload files to a CDN
• Re-generate static files
• Generate graphs for enormous data sets periodically
• Send blog comments through a spam filter
• Transcoding of audio and video
What do I need?
Users




requests responses                                           Result Store




   Application          tasks      Message Queue




                     Worker 1   Worker 2    Worker 3   ...    Worker N
Users


                                                                           Database
                                                                           memcached
requests responses                                               MongoDB   Redis
                                                                           Tokyo Tyrant
                                                                           AMQP



   Application          tasks        RabbitMQ
                                                      Stomp
                                                      Redis
                                                      Database




                     celeryd    celeryd     celeryd       ...    celeryd
USE RABBITMQ!
Installation
Installation

1. Install message queue from source or w/package mgr
2. pip install celery
3. pip install -r http://github.com/ask/celery/blob/v1.0.2/
  contrib/requirements/default.txt?raw=true
4. Configure application
5. Launch services (app server, rabbitmq, celeryd, etc.)
Usage
Configure

• celeryconf.py for pure python
• settings.py within a Django project
Define a task

from celery.decorators import task

@task
def add(x, y):
    return x + y
Execute the task

>>> from tasks import add
>>> add.delay(4, 4)
<AsyncResult: 889143a6-39a2-4e52-837b-d80d33efb22d>
Analyze the results

>>> result = add.delay(4, 4)
>>> result.ready() # has task has finished processing?
False
>>> result.result # task is not ready, so no return value yet.
None
>>> result.get()   # wait until the task is done and get retval.
8
>>> result.result # access result
8
>>> result.successful()
True
The Task class
class CanDrinkTask(Task):
    """
    A task that determines if a person is 21 years of age or older.
    """
    def run(self, person_id, **kwargs):
        logger = self.get_logger(**kwargs)
        logger.info("Running determine_can_drink task for person %s" % person_id)

       person = Person.objects.get(pk=person_id)
       now = date.today()
       diff = now - person.date_of_birth
       # i know, i know, this doesn't account for leap year
       age = diff.days / 365
       if age >= 21:
           person.can_drink = True
           person.save()
       else:
           person.can_drink = False
           person.save()
       return True
Task retries
class CanDrinkTask(Task):
    """
    A task that determines if a person is 21 years of age or older.
    """
    default_retry_delay = 5 * 60 # retry in 5 minutes
    max_retries = 5

   def run(self, person_id, **kwargs):
       logger = self.get_logger(**kwargs)
       logger.info("Running determine_can_drink task for person %s" % person_id)

  ...
The PeriodicTask class

class FullNameTask(PeriodicTask):
    """
    A periodic task that concatenates fields to form a person's full name.
    """
    run_every = timedelta(seconds=60)

    def run(self, **kwargs):
        logger = self.get_logger(**kwargs)
        logger.info("Running full name task.")

        for person in Person.objects.all():
            person.full_name = " ".join([person.prefix, person.first_name,
                                         person.middle_name, person.last_name,
                                         person.suffix]).strip()
            person.save()
        return True
Holy chock full of features Batman!

• Messaging            • Remote-control
• Distribution         • Monitoring
• Concurrency          • Serialization
• Scheduling           • Tracebacks
• Performance          • Retries
• Return values        • Task sets
• Result stores        • Web views
• Webhooks             • Error reporting
• Rate limiting        • Supervising
• Routing              • init scripts
Resources
Community

• Friendly core dev: Ask Solem Hoel
• IRC: #celery
• Mailing lists: celery-users
• Twitter: @ask
Docs and articles

Celery
• http://celeryproject.org
• http://ask.github.com/celery/
• http://ask.github.com/celery/tutorials/external.html
Message Queues
• http://amqp.org
• http://bit.ly/amqp_intro
• http://rabbitmq.com/faq.html
Thank you!

Rich Leland
Discovery Creative

@richleland
richard_leland@discovery.com
http://creative.discovery.com

Contenu connexe

Tendances

Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task QueueDuy Do
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryMauro Rocco
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to CeleryIdan Gazit
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaCODE WHITE GmbH
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]MongoDB
 
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018Kenneth Ceyer
 
Building resilient scheduling in distributed systems with Spring
Building resilient scheduling in distributed systems with SpringBuilding resilient scheduling in distributed systems with Spring
Building resilient scheduling in distributed systems with SpringMarek Jeszka
 
스프링 부트와 로깅
스프링 부트와 로깅스프링 부트와 로깅
스프링 부트와 로깅Keesun Baik
 
분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용
분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용
분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용승필 박
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMydbops
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at NetflixBrendan Gregg
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019min woog kim
 
NGINX Installation and Tuning
NGINX Installation and TuningNGINX Installation and Tuning
NGINX Installation and TuningNGINX, Inc.
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use CasesFabrizio Farinacci
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
Spring Data JDBC: Beyond the Obvious
Spring Data JDBC: Beyond the ObviousSpring Data JDBC: Beyond the Obvious
Spring Data JDBC: Beyond the ObviousVMware Tanzu
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교Woo Yeong Choi
 

Tendances (20)

Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task Queue
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Europython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & CeleryEuropython 2011 - Playing tasks with Django & Celery
Europython 2011 - Playing tasks with Django & Celery
 
An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
Naver속도의, 속도에 의한, 속도를 위한 몽고DB (네이버 컨텐츠검색과 몽고DB) [Naver]
 
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
우아하게 준비하는 테스트와 리팩토링 - PyCon Korea 2018
 
Async Programming in C# 5
Async Programming in C# 5Async Programming in C# 5
Async Programming in C# 5
 
Building resilient scheduling in distributed systems with Spring
Building resilient scheduling in distributed systems with SpringBuilding resilient scheduling in distributed systems with Spring
Building resilient scheduling in distributed systems with Spring
 
스프링 부트와 로깅
스프링 부트와 로깅스프링 부트와 로깅
스프링 부트와 로깅
 
분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용
분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용
분산 트랜잭션 환경에서 데이터 일관성 유지 방안 업로드용
 
MongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To TransactionsMongoDB WiredTiger Internals: Journey To Transactions
MongoDB WiredTiger Internals: Journey To Transactions
 
Linux Profiling at Netflix
Linux Profiling at NetflixLinux Profiling at Netflix
Linux Profiling at Netflix
 
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
김민욱, (달빛조각사) 엘릭서를 이용한 mmorpg 서버 개발, NDC2019
 
NGINX Installation and Tuning
NGINX Installation and TuningNGINX Installation and Tuning
NGINX Installation and Tuning
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use Cases
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Spring Data JDBC: Beyond the Obvious
Spring Data JDBC: Beyond the ObviousSpring Data JDBC: Beyond the Obvious
Spring Data JDBC: Beyond the Obvious
 
mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교mongodb와 mysql의 CRUD 연산의 성능 비교
mongodb와 mysql의 CRUD 연산의 성능 비교
 

En vedette

Klassify: Text Classification with Redis
Klassify: Text Classification with RedisKlassify: Text Classification with Redis
Klassify: Text Classification with RedisFatih Erikli
 
Django ORM Optimizasyonu
Django ORM OptimizasyonuDjango ORM Optimizasyonu
Django ORM OptimizasyonuFatih Erikli
 
Distributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZHDistributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZHCesar Cardenas Desales
 
Agent-based Models
Agent-based ModelsAgent-based Models
Agent-based ModelsFatih Erikli
 
Processing - Programcılar için eskiz defteri
Processing - Programcılar için eskiz defteriProcessing - Programcılar için eskiz defteri
Processing - Programcılar için eskiz defteriFatih Erikli
 
The Redis API Akbar Ahmed, DynomiteDB
The Redis API Akbar Ahmed, DynomiteDBThe Redis API Akbar Ahmed, DynomiteDB
The Redis API Akbar Ahmed, DynomiteDBRedis Labs
 
Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queueBrandon Lamb
 
Architecture by Accident
Architecture by AccidentArchitecture by Accident
Architecture by AccidentGleicon Moraes
 
Celery for internal API in SOA infrastructure
Celery for internal API in SOA infrastructureCelery for internal API in SOA infrastructure
Celery for internal API in SOA infrastructureRoman Imankulov
 
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016Wei Lin
 
Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to ThriftDvir Volk
 
New Ceph capabilities and Reference Architectures
New Ceph capabilities and Reference ArchitecturesNew Ceph capabilities and Reference Architectures
New Ceph capabilities and Reference ArchitecturesKamesh Pemmaraju
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redisDvir Volk
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueGleicon Moraes
 
Redis in Practice
Redis in PracticeRedis in Practice
Redis in PracticeNoah Davis
 
Gearman: A Job Server made for Scale
Gearman: A Job Server made for ScaleGearman: A Job Server made for Scale
Gearman: A Job Server made for ScaleMike Willbanks
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowPyData
 
REST vs. Messaging For Microservices
REST vs. Messaging For MicroservicesREST vs. Messaging For Microservices
REST vs. Messaging For MicroservicesEberhard Wolff
 
Everything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askEverything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askCarlos Abalde
 

En vedette (20)

Klassify: Text Classification with Redis
Klassify: Text Classification with RedisKlassify: Text Classification with Redis
Klassify: Text Classification with Redis
 
Django ORM Optimizasyonu
Django ORM OptimizasyonuDjango ORM Optimizasyonu
Django ORM Optimizasyonu
 
Distributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZHDistributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZH
 
Agent-based Models
Agent-based ModelsAgent-based Models
Agent-based Models
 
Processing - Programcılar için eskiz defteri
Processing - Programcılar için eskiz defteriProcessing - Programcılar için eskiz defteri
Processing - Programcılar için eskiz defteri
 
The Redis API Akbar Ahmed, DynomiteDB
The Redis API Akbar Ahmed, DynomiteDBThe Redis API Akbar Ahmed, DynomiteDB
The Redis API Akbar Ahmed, DynomiteDB
 
Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queue
 
Architecture by Accident
Architecture by AccidentArchitecture by Accident
Architecture by Accident
 
Celery for internal API in SOA infrastructure
Celery for internal API in SOA infrastructureCelery for internal API in SOA infrastructure
Celery for internal API in SOA infrastructure
 
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
 
Introduction to Thrift
Introduction to ThriftIntroduction to Thrift
Introduction to Thrift
 
New Ceph capabilities and Reference Architectures
New Ceph capabilities and Reference ArchitecturesNew Ceph capabilities and Reference Architectures
New Ceph capabilities and Reference Architectures
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
 
Redis in Practice
Redis in PracticeRedis in Practice
Redis in Practice
 
Gearman: A Job Server made for Scale
Gearman: A Job Server made for ScaleGearman: A Job Server made for Scale
Gearman: A Job Server made for Scale
 
Facebook thrift
Facebook thriftFacebook thrift
Facebook thrift
 
How I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with AirflowHow I learned to time travel, or, data pipelining and scheduling with Airflow
How I learned to time travel, or, data pipelining and scheduling with Airflow
 
REST vs. Messaging For Microservices
REST vs. Messaging For MicroservicesREST vs. Messaging For Microservices
REST vs. Messaging For Microservices
 
Everything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askEverything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to ask
 

Similaire à Celery: The Distributed Task Queue

Docker interview Questions-3.pdf
Docker interview Questions-3.pdfDocker interview Questions-3.pdf
Docker interview Questions-3.pdfYogeshwaran R
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsMarcelo Pinheiro
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performanceEngine Yard
 
Python Load Testing - Pygotham 2012
Python Load Testing - Pygotham 2012Python Load Testing - Pygotham 2012
Python Load Testing - Pygotham 2012Dan Kuebrich
 
Lessons Learnt in 2009
Lessons Learnt in 2009Lessons Learnt in 2009
Lessons Learnt in 2009pratiknaik
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)DECK36
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Pavel Chunyayev
 
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"Daniel Bryant
 
Azure Cloud Patterns
Azure Cloud PatternsAzure Cloud Patterns
Azure Cloud PatternsTamir Dresher
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Ryan Cuprak
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nlbartzon
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nltieleman
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
MongoDB World 2019: Becoming an Ops Manager Backup Superhero!
MongoDB World 2019: Becoming an Ops Manager Backup Superhero!MongoDB World 2019: Becoming an Ops Manager Backup Superhero!
MongoDB World 2019: Becoming an Ops Manager Backup Superhero!MongoDB
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoTareque Hossain
 
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Nilesh Panchal
 

Similaire à Celery: The Distributed Task Queue (20)

Loom promises: be there!
Loom promises: be there!Loom promises: be there!
Loom promises: be there!
 
Docker interview Questions-3.pdf
Docker interview Questions-3.pdfDocker interview Questions-3.pdf
Docker interview Questions-3.pdf
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 
Python Load Testing - Pygotham 2012
Python Load Testing - Pygotham 2012Python Load Testing - Pygotham 2012
Python Load Testing - Pygotham 2012
 
Lessons Learnt in 2009
Lessons Learnt in 2009Lessons Learnt in 2009
Lessons Learnt in 2009
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)Our Puppet Story (GUUG FFG 2015)
Our Puppet Story (GUUG FFG 2015)
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015
 
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
J1 2015 "Debugging Java Apps in Containers: No Heavy Welding Gear Required"
 
Azure Cloud Patterns
Azure Cloud PatternsAzure Cloud Patterns
Azure Cloud Patterns
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nl
 
Lessons learned while building Omroep.nl
Lessons learned while building Omroep.nlLessons learned while building Omroep.nl
Lessons learned while building Omroep.nl
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
MongoDB World 2019: Becoming an Ops Manager Backup Superhero!
MongoDB World 2019: Becoming an Ops Manager Backup Superhero!MongoDB World 2019: Becoming an Ops Manager Backup Superhero!
MongoDB World 2019: Becoming an Ops Manager Backup Superhero!
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with django
 
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
Ruby on-rails-101-presentation-slides-for-a-five-day-introductory-course-1194...
 
Rails Performance
Rails PerformanceRails Performance
Rails Performance
 

Plus de Richard Leland

Living in harmony - a brief into to ES6
Living in harmony - a brief into to ES6Living in harmony - a brief into to ES6
Living in harmony - a brief into to ES6Richard Leland
 
django-district October
django-district Octoberdjango-district October
django-district OctoberRichard Leland
 

Plus de Richard Leland (8)

Living in harmony - a brief into to ES6
Living in harmony - a brief into to ES6Living in harmony - a brief into to ES6
Living in harmony - a brief into to ES6
 
django-district October
django-district Octoberdjango-district October
django-district October
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
 
Django District April
Django District AprilDjango District April
Django District April
 

Dernier

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
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
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 

Dernier (20)

What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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?
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
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
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 

Celery: The Distributed Task Queue

  • 1. Celery An introduction to the distributed task queue. Rich Leland ZPUGDC // April 6, 2010 @richleland richard_leland@discovery.com http://creative.discovery.com
  • 2. What is Celery? A task queue based on distributed message passing.
  • 3. What is Celery? An asynchronous, concurrent, distributed, super-awesome task queue.
  • 4. A brief history • First commit in April 2009 as "crunchy" • Originally built for use with Django • Django is still a requirement • Don't be scurred! No Django app required! • It's for the ORM, caching, and signaling • Future is celery using SQLAlchemy and louie
  • 5. Why should I use Celery?
  • 6. User perspective • Minimize request/response cycle • Smoother user experience • Difference between pleasant and unpleasant
  • 7. Developer perspective • Offload time/cpu intensive processes • Scalability - add workers as needed • Flexibility - many points of customization • About to turn 1 (apr 24) • Actively developed • Great documentation • Lots of tutorials
  • 8. LATENCY == DELAY == NOT GOOD!
  • 9. Business perspective • Latency == $$$ • Every 100ms of latency cost Amazon 1% in sales • Google found an extra .5 seconds in search page generation time dropped traffic by 20% • 5ms latency in an electronic trading platform could mean $4 million in lost revenues per millisecond http://highscalability.com/latency-everywhere-and-it-costs-you-sales-how-crush-it
  • 10. Example Uses • Image processing • Calculate points and award badges • Upload files to a CDN • Re-generate static files • Generate graphs for enormous data sets periodically • Send blog comments through a spam filter • Transcoding of audio and video
  • 11. What do I need?
  • 12. Users requests responses Result Store Application tasks Message Queue Worker 1 Worker 2 Worker 3 ... Worker N
  • 13. Users Database memcached requests responses MongoDB Redis Tokyo Tyrant AMQP Application tasks RabbitMQ Stomp Redis Database celeryd celeryd celeryd ... celeryd
  • 16. Installation 1. Install message queue from source or w/package mgr 2. pip install celery 3. pip install -r http://github.com/ask/celery/blob/v1.0.2/ contrib/requirements/default.txt?raw=true 4. Configure application 5. Launch services (app server, rabbitmq, celeryd, etc.)
  • 17. Usage
  • 18. Configure • celeryconf.py for pure python • settings.py within a Django project
  • 19. Define a task from celery.decorators import task @task def add(x, y): return x + y
  • 20. Execute the task >>> from tasks import add >>> add.delay(4, 4) <AsyncResult: 889143a6-39a2-4e52-837b-d80d33efb22d>
  • 21. Analyze the results >>> result = add.delay(4, 4) >>> result.ready() # has task has finished processing? False >>> result.result # task is not ready, so no return value yet. None >>> result.get() # wait until the task is done and get retval. 8 >>> result.result # access result 8 >>> result.successful() True
  • 22. The Task class class CanDrinkTask(Task): """ A task that determines if a person is 21 years of age or older. """ def run(self, person_id, **kwargs): logger = self.get_logger(**kwargs) logger.info("Running determine_can_drink task for person %s" % person_id) person = Person.objects.get(pk=person_id) now = date.today() diff = now - person.date_of_birth # i know, i know, this doesn't account for leap year age = diff.days / 365 if age >= 21: person.can_drink = True person.save() else: person.can_drink = False person.save() return True
  • 23. Task retries class CanDrinkTask(Task): """ A task that determines if a person is 21 years of age or older. """ default_retry_delay = 5 * 60 # retry in 5 minutes max_retries = 5 def run(self, person_id, **kwargs): logger = self.get_logger(**kwargs) logger.info("Running determine_can_drink task for person %s" % person_id) ...
  • 24. The PeriodicTask class class FullNameTask(PeriodicTask): """ A periodic task that concatenates fields to form a person's full name. """ run_every = timedelta(seconds=60) def run(self, **kwargs): logger = self.get_logger(**kwargs) logger.info("Running full name task.") for person in Person.objects.all(): person.full_name = " ".join([person.prefix, person.first_name, person.middle_name, person.last_name, person.suffix]).strip() person.save() return True
  • 25. Holy chock full of features Batman! • Messaging • Remote-control • Distribution • Monitoring • Concurrency • Serialization • Scheduling • Tracebacks • Performance • Retries • Return values • Task sets • Result stores • Web views • Webhooks • Error reporting • Rate limiting • Supervising • Routing • init scripts
  • 27. Community • Friendly core dev: Ask Solem Hoel • IRC: #celery • Mailing lists: celery-users • Twitter: @ask
  • 28. Docs and articles Celery • http://celeryproject.org • http://ask.github.com/celery/ • http://ask.github.com/celery/tutorials/external.html Message Queues • http://amqp.org • http://bit.ly/amqp_intro • http://rabbitmq.com/faq.html
  • 29. Thank you! Rich Leland Discovery Creative @richleland richard_leland@discovery.com http://creative.discovery.com