SlideShare ist ein Scribd-Unternehmen logo
1 von 30
Downloaden Sie, um offline zu lesen
Why Task Queues in
Python, Ruby and More!
      ~ a talk by Bryan Helmig
task queue noun ˈtask ˈkyü
a system for parallel execution of discrete
tasks in a non-blocking fashion.
               celery, resque, or home-grown...
broker noun broh-ker
the middle man holding the tasks
(messages) themselves.
               rabbitmq, gearman, redis, etc...
producer noun pruh-doo-ser
the code that places the tasks to be
executed later in the broker.
                        your application code!
consumer noun kuhn-soo-mer
also called the worker, takes tasks from
the broker and perform them.
           usually a daemon under supervision.
imagine this...
your app: posting a new message triggers
“new message” emails to all your friends.
def new_message(request):
    user = get_user_or_404(request)
    message = request.POST.get('message', None)

    if not message:
        raise Http404

    user.save_new_message(message)

    for friend in user.friends.all():
        friend.send_email(message)

    return redirect(reverse('dashboard'))
def new_message(request):
    user = get_user_or_404(request)
    message = request.POST.get('message', None)

    if not message:
        raise Http404

    user.save_new_message(message)

   for friend in user.friends.all():
       friend.send_email(message)

    return redirect(reverse('dashboard'))
the problem:
that works good for like 0-6 friends... but
what if you have 100,000? or more? will
your user ever get a response?
bad idea #1: ignore
make your users wait through your long
request/response cycle.
            your users are important, right?
bad idea #2: ajax
return the page fast with JS code that calls
another script in the browser’s background.
     duplicate calls & http cycles are not cool.
bad idea #3: cronjob
make a email_friends table with user_id &
message column. cron every 5/10 minutes.
                  backlogs will destroy you.
good idea: queues
the task to potentially email thousands of
users is put into a queue to be dealt with
later, leaving you to return the response.
@task
def alert_friends(user_id, message):
    user = User.objects.get(id=user_id)

    for friend in user.friends.all():
        friend.send_email(message)

def new_message(request):
    user = get_user_or_404(request)
    message = request.POST.get('message', None)
    if not message:
        raise Http404
    user.save_new_message(message)

    alert_friends.delay(user.id, message)

    return redirect(reverse('dashboard'))
RULE #1:
  adding a task to a queue should be
faster than performing the task itself.
RULE #2:
you should consume tasks faster than you
 produce them. if not, add more workers.
queue libraries:
1. celery (python) earlier...
2. resque (ruby) up next...
3. build your own grand finalé!
class MessageSend
  def self.perform(user_id, message)
    user = User.find(user_id)
    user.friends.each do |friend|
      friend.send_email(message)
    end
  end
end

class MessageController < ActionController::Base
  def new_message
    render(file: 'public/404.html',
           status: 404) unless params[:message]
    current_user.save_new_message(params[:message])

    Resque.enqueue(MessageSend,
        current_user.id, params[:message])

    redirect_to dashboard_url
  end
end
let’s build our own!
and let’s do it with redis, in php and
   in less than 50 lines of code!
     (not including the task code)
quick redis aside:
so, redis is a key-value store. values can
be strings, blobs, lists or hashes. we’ll use
lists and RPUSH and LPOP.
step #1: task runner
i’m envisioning this as a Task class with
various methods named after each task.
each method accepts an array $params.
class Tasks {
    public function email_friends($params) {
        $user_id = $params->user_id;
        $message = $params->message;

        # get $friends from a db query...
        $friends = array('paul@example.com',
                         'john@example.com');

        foreach ($friends as $friend) {
            echo "Fake email ".$friend.
                 " with ".$message."n";
        }
    }
}
step #2: worker
i think an infinite loop with a blocking
redis BLPOP will work. then it needs to run
the right method on the Task object.
include_once 'redis.php'; # sets up $redis, $queue
include_once 'tasks.php';

$tasks = new Tasks();

while (true) {
    # BLPOP will block until it gets an item..
    $data = $redis->blpop($queue, 0);
    $obj = json_decode($data[1]); # grab json...

    $method = $obj->task_name;
    $params = $obj->params;

    # calls the task: Task->$task_name($params)...
    call_user_func(array($tasks, $method), $params);
}
step #3: run it!
we will need to run the worker:

   ➜ php worker.php
step #4: producer
let’s make a handy add_task function for
easy placement of tasks into the queue.
include_once 'redis.php'; # sets up $redis & $queue

function add_task($task_name, $params) {
    global $redis, $queue;
    $data = Array('task_name' => $task_name,
                  'params'     => $params);
    $json = json_encode($data)
    $redis->rpush($queue, $json);
}

# an example of our task api...
add_task('email_friends',
   array('user_id' => 1234,
         'message' => 'I just bought a car!')
);
step #5: watch it
a command line that runs a worker is
standard. use something like supervisord
or god to run it & monitor it.
things missing:
our php example does not: store return
results, handle errors, route tasks,
degrade gracefully, log activity, etc...
the end
question time!

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to RedisDvir Volk
 
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
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Codemotion
 
맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 jbugkorea
 
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...Edureka!
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring bootAntoine Rey
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application TechnologiesSam Bowne
 
Advanced nGrinder 2nd Edition
Advanced nGrinder 2nd EditionAdvanced nGrinder 2nd Edition
Advanced nGrinder 2nd EditionJunHo Yoon
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootOmri Spector
 
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우IMQA
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Cv Moez HAMZAOUI JAVA J2EE FULL STACK
Cv Moez HAMZAOUI JAVA J2EE FULL STACKCv Moez HAMZAOUI JAVA J2EE FULL STACK
Cv Moez HAMZAOUI JAVA J2EE FULL STACKMoez Hamzaoui
 
FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기Jongwon Kim
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance TuningPuneet Behl
 

Was ist angesagt? (20)

Introduction to Redis
Introduction to RedisIntroduction to Redis
Introduction to Redis
 
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
 
Django Celery
Django Celery Django Celery
Django Celery
 
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
Why Rust? - Matthias Endler - Codemotion Amsterdam 2016
 
맛만 보자 액터 모델이란
맛만 보자 액터 모델이란 맛만 보자 액터 모델이란
맛만 보자 액터 모델이란
 
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
 
Support distributed computing and caching avec hazelcast
Support distributed computing and caching avec hazelcastSupport distributed computing and caching avec hazelcast
Support distributed computing and caching avec hazelcast
 
Redis
RedisRedis
Redis
 
Celery
CeleryCelery
Celery
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
 
Ch 3: Web Application Technologies
Ch 3: Web Application TechnologiesCh 3: Web Application Technologies
Ch 3: Web Application Technologies
 
Vue.js
Vue.jsVue.js
Vue.js
 
Advanced nGrinder 2nd Edition
Advanced nGrinder 2nd EditionAdvanced nGrinder 2nd Edition
Advanced nGrinder 2nd Edition
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
 
웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우웹서버 부하테스트 실전 노하우
웹서버 부하테스트 실전 노하우
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Cv Moez HAMZAOUI JAVA J2EE FULL STACK
Cv Moez HAMZAOUI JAVA J2EE FULL STACKCv Moez HAMZAOUI JAVA J2EE FULL STACK
Cv Moez HAMZAOUI JAVA J2EE FULL STACK
 
Introduction to Celery
Introduction to CeleryIntroduction to Celery
Introduction to Celery
 
FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기FIFA 온라인 3의 MongoDB 사용기
FIFA 온라인 3의 MongoDB 사용기
 
MongoDB Performance Tuning
MongoDB Performance TuningMongoDB Performance Tuning
MongoDB Performance Tuning
 

Ähnlich wie Why Task Queues - ComoRichWeb

Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To BatchLuca Mearelli
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHPRohan Sharma
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Pedro Cunha
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful CodeGreggPollack
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Andre Foeken
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applicationschartjes
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethodsdreampuf
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptxrani marri
 

Ähnlich wie Why Task Queues - ComoRichWeb (20)

Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Oops in php
Oops in phpOops in php
Oops in php
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Lecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptxLecture9_OOPHP_SPring2023.pptx
Lecture9_OOPHP_SPring2023.pptx
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
12-OO-PHP.pptx
12-OO-PHP.pptx12-OO-PHP.pptx
12-OO-PHP.pptx
 

Kürzlich hochgeladen

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
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
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
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
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
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
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Kürzlich hochgeladen (20)

TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
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
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
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
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
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
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 

Why Task Queues - ComoRichWeb

  • 1. Why Task Queues in Python, Ruby and More! ~ a talk by Bryan Helmig
  • 2. task queue noun ˈtask ˈkyü a system for parallel execution of discrete tasks in a non-blocking fashion. celery, resque, or home-grown...
  • 3. broker noun broh-ker the middle man holding the tasks (messages) themselves. rabbitmq, gearman, redis, etc...
  • 4. producer noun pruh-doo-ser the code that places the tasks to be executed later in the broker. your application code!
  • 5. consumer noun kuhn-soo-mer also called the worker, takes tasks from the broker and perform them. usually a daemon under supervision.
  • 6. imagine this... your app: posting a new message triggers “new message” emails to all your friends.
  • 7. def new_message(request): user = get_user_or_404(request) message = request.POST.get('message', None) if not message: raise Http404 user.save_new_message(message) for friend in user.friends.all(): friend.send_email(message) return redirect(reverse('dashboard'))
  • 8. def new_message(request): user = get_user_or_404(request) message = request.POST.get('message', None) if not message: raise Http404 user.save_new_message(message) for friend in user.friends.all(): friend.send_email(message) return redirect(reverse('dashboard'))
  • 9. the problem: that works good for like 0-6 friends... but what if you have 100,000? or more? will your user ever get a response?
  • 10. bad idea #1: ignore make your users wait through your long request/response cycle. your users are important, right?
  • 11. bad idea #2: ajax return the page fast with JS code that calls another script in the browser’s background. duplicate calls & http cycles are not cool.
  • 12. bad idea #3: cronjob make a email_friends table with user_id & message column. cron every 5/10 minutes. backlogs will destroy you.
  • 13. good idea: queues the task to potentially email thousands of users is put into a queue to be dealt with later, leaving you to return the response.
  • 14. @task def alert_friends(user_id, message): user = User.objects.get(id=user_id) for friend in user.friends.all(): friend.send_email(message) def new_message(request): user = get_user_or_404(request) message = request.POST.get('message', None) if not message: raise Http404 user.save_new_message(message) alert_friends.delay(user.id, message) return redirect(reverse('dashboard'))
  • 15. RULE #1: adding a task to a queue should be faster than performing the task itself.
  • 16. RULE #2: you should consume tasks faster than you produce them. if not, add more workers.
  • 17. queue libraries: 1. celery (python) earlier... 2. resque (ruby) up next... 3. build your own grand finalé!
  • 18. class MessageSend def self.perform(user_id, message) user = User.find(user_id) user.friends.each do |friend| friend.send_email(message) end end end class MessageController < ActionController::Base def new_message render(file: 'public/404.html', status: 404) unless params[:message] current_user.save_new_message(params[:message]) Resque.enqueue(MessageSend, current_user.id, params[:message]) redirect_to dashboard_url end end
  • 19. let’s build our own! and let’s do it with redis, in php and in less than 50 lines of code! (not including the task code)
  • 20. quick redis aside: so, redis is a key-value store. values can be strings, blobs, lists or hashes. we’ll use lists and RPUSH and LPOP.
  • 21. step #1: task runner i’m envisioning this as a Task class with various methods named after each task. each method accepts an array $params.
  • 22. class Tasks { public function email_friends($params) { $user_id = $params->user_id; $message = $params->message; # get $friends from a db query... $friends = array('paul@example.com', 'john@example.com'); foreach ($friends as $friend) { echo "Fake email ".$friend. " with ".$message."n"; } } }
  • 23. step #2: worker i think an infinite loop with a blocking redis BLPOP will work. then it needs to run the right method on the Task object.
  • 24. include_once 'redis.php'; # sets up $redis, $queue include_once 'tasks.php'; $tasks = new Tasks(); while (true) { # BLPOP will block until it gets an item.. $data = $redis->blpop($queue, 0); $obj = json_decode($data[1]); # grab json... $method = $obj->task_name; $params = $obj->params; # calls the task: Task->$task_name($params)... call_user_func(array($tasks, $method), $params); }
  • 25. step #3: run it! we will need to run the worker: ➜ php worker.php
  • 26. step #4: producer let’s make a handy add_task function for easy placement of tasks into the queue.
  • 27. include_once 'redis.php'; # sets up $redis & $queue function add_task($task_name, $params) { global $redis, $queue; $data = Array('task_name' => $task_name, 'params' => $params); $json = json_encode($data) $redis->rpush($queue, $json); } # an example of our task api... add_task('email_friends', array('user_id' => 1234, 'message' => 'I just bought a car!') );
  • 28. step #5: watch it a command line that runs a worker is standard. use something like supervisord or god to run it & monitor it.
  • 29. things missing: our php example does not: store return results, handle errors, route tasks, degrade gracefully, log activity, etc...