SlideShare a Scribd company logo
Background Jobs with
      Resque
           Jon Homan
       Apprentice @ Obtiva

       http://jonhoman.com
           @jonhoman
Background Jobs with Resque
Agenda
• Resque
• Examples
• Real world use
• Plugins
• Alternate Implementations
• When to use Resque
Background Jobs

• Remote API calls
• Uploading images
• Number crunching
• Updating RSS feeds
Resque
     https://github.com/defunkt/resque


• Open-source library for creating background
  jobs
• Redis backend
• Support for multiple queues
• Queues are processed by workers
More Resque Features
• Monitor with god or monit
• Distributed processing
• Priorities
• Persistent queues
• Memory leak resistant
• Web interface
resque-web
Redis
              http://redis.io/


• Key-value datastore
• data structure server
• constant time pushes and pops
• atomic operations
All “Foreground”
class FeedsController
 def create
   feed = Feed.create!
   feed.fetch
   redirect_to feed_path(feed)
 end
end

class Feed
 def fetch
   rss = RSS::Parse.parse(url, false)
   feed.title = rss.title
 end
end
Queue up creation
class FeedsController
 def create
  feed = Feed.create!
  Queue.push(feed) # won’t block UI
  redirect_to feed_path(feed)
 end
end

class Queue
 def push(feed)
  queue << feed
 end
end
Now with Resque
class FeedsController
 def create
  feed = Feed.create!
  Resque.enqueue(FeedCreator, feed.id)
  redirect_to feed_path(feed)
 end
end
How to process jobs
class FeedCreator
 @queue = :feed_creation

 def perform(feed_id)
   feed = Feed.find(feed_id)
   rss = RSS::Parser.parse(feed.url,false)
   feed.title = rss.title
   # create all items in the rss
 end
end
Workers?

• Long-running Rake tasks
• Look for jobs every n seconds
How to start workers
$ rake resque:work

$ QUEUE=feed rake resque:work

$ QUEUE=feed, twitter rake resque:work

$ QUEUE=* rake resque:work

$ COUNT=3 QUEUE=* rake resque:work
Testing w/ RSpec

it "stores the name of the feed" do
 FeedCreator.perform(feed.id)
 feed.reload.title.should == "Feed
end
Testing w/ RSpec

it "creates Items for every item in the feed" do
 FeedCreator.perform(feed.id)
 feed.reload.items.count.should == 5
end
Testing w/ RSpec

it “parses the feed” do
 RSS::Parser.should_receive(:parse)

 FeedCreator.perform(feed.id)
end
Real world uses


• GitHub
• Groupon
•   lifeStreams
GitHub
35 different types of jobs:
  • Warming caches
  • Counting disk usage
  • Building tarballs
  • Building Rubygems
  • Building graphs
  • Updating search index
Groupon

• Resque for background jobs
 • Notifications
 • Lockable worker
• Redis for semaphores
lifeStreams
• Process updates to blog feeds
• Publish updates to Facebook, Twitter, Email
Plugins
• resque_spec
• Resque Heroku Autoscaler
• resque multi step
• ResqueMailer
• resque-retry
• and at least 25 others
ResqueSpec
    https://github.com/leshill/resque_spec

• Resque plugin that adds resque-specific
  matchers
• have_queued
• have_scheduled
• have_queue_size_of
Examples
it “adds a feed to the creation queue” do
 post :create, :feed
 FeedCreator.should have_queued(feed.id)
end

it “schedules a feed update” do
 feed.update
 FeedUpdater.should have_scheduled(feed.id)
end
Resque Heroku
         Autoscaler

• Scales Heroku workers
• Start worker if none running
• Stops worker after jobs are processed
RHA
require 'resque/plugins/resque_heroku_autoscaler'

class TestJob
  extend Resque::Plugins::HerokuAutoscaler

  @queue = :test

  def perform
    ...awesome stuff...
  end
end
Resque Mailer


• Asynchronously deliver email in Rails
Resque Mailer

class MyMailer < ActionMailer::Base
  include Resque::Mailer
end


MyMailer.subject_email(params).deliver

QUEUE=mailer rake environment resque:work
resque-retry


• Retry, delay and exponential backoff support
resque-retry
require 'resque-retry'

class ExampleRetryJob
  extend Resque::Plugins::Retry
  @queue = :example_queue

  @retry_limit = 3
  @retry_delay = 60

  def self.perform(*args)
    # your magic/heavy lifting goes here.
  end
end
resque-retry

              no delay, 1m, 10m,   1h,    3h,    6h
@backoff_strategy = [0, 60, 600, 3600, 10800, 21600]
Alternate
           Implementations
•   C
•   Java
•   Scala
•   .NET
•   Python
•   PHP
•   node.js
jesque
// Add a job to the queue
final Job job = new Job("TestAction",
    new Object[]{ 1, 2, true, "test", Arrays.asList("inner",
4ß)});
final Client client = new ClientImpl(config);
client.enqueue("foo", job);
client.end();

// Start a worker to run jobs from the queue
final Worker worker = new WorkerImpl(config,
    Arrays.asList("foo"), Arrays.asList(TestAction.class));
final Thread workerThread = new Thread(worker);
workerThread.start();
Resque?

• Multiple queues
• Potentially HUGE queues
• Admin UI
• Expecting chaos/failures
DelayedJob?

• Numeric priorities
• Queue is small
• Add whole objects to queue
• No need to setup Redis
Do your homework
I didn’t
 (kinda)
Resources
github.com/defunkt/resque

redis.io

redistogo.com
Questions?

More Related Content

KEY
Php resque
KEY
GPerf Using Jesque
PDF
Background processing with Resque
PPTX
Capistrano - automate all the things
PPT
Open Source Saturday - How can I contribute to Ruby on Rails?
PPTX
Getting Started with Capistrano
PPT
Capistrano
PDF
Scaling up task processing with Celery
Php resque
GPerf Using Jesque
Background processing with Resque
Capistrano - automate all the things
Open Source Saturday - How can I contribute to Ruby on Rails?
Getting Started with Capistrano
Capistrano
Scaling up task processing with Celery

What's hot (20)

PDF
Celery for internal API in SOA infrastructure
PDF
Introduction to Celery
PDF
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
PDF
kRouter
PDF
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
PDF
Celery with python
PDF
Infrastructure = code - 1 year later
ODP
Introduction to Python Celery
PDF
Ansible 2 and Ansible Galaxy 2
PDF
Trying Continuous Delivery - pyconjp 2012
PDF
Designing net-aws-glacier
PDF
Celery
PDF
Celery: The Distributed Task Queue
PDF
The Puppet Master on the JVM - PuppetConf 2014
PPTX
Asynchronous Task Queues with Celery
PDF
Data processing with celery and rabbit mq
PDF
Building Distributed System with Celery on Docker Swarm
PPTX
Controlling multiple VMs with the power of Python
PDF
Selenium sandwich-3: Being where you aren't.
PDF
Testing http calls with Webmock and VCR
Celery for internal API in SOA infrastructure
Introduction to Celery
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
kRouter
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
Celery with python
Infrastructure = code - 1 year later
Introduction to Python Celery
Ansible 2 and Ansible Galaxy 2
Trying Continuous Delivery - pyconjp 2012
Designing net-aws-glacier
Celery
Celery: The Distributed Task Queue
The Puppet Master on the JVM - PuppetConf 2014
Asynchronous Task Queues with Celery
Data processing with celery and rabbit mq
Building Distributed System with Celery on Docker Swarm
Controlling multiple VMs with the power of Python
Selenium sandwich-3: Being where you aren't.
Testing http calls with Webmock and VCR
Ad

Viewers also liked (20)

PPT
Loto training
PPS
Lockout Tagout
PPS
Loto.ppt
PPT
Intro to basic fire alarm technology
PPT
Safety On Construction site
PPTX
Construction safety management
PPTX
Fire Evacuation Plan
PPTX
Personal Protective Equipment
PPT
Fire drill procedure
PPTX
Fire Alarm, Smoke Detector and Automatic Sprinkle System
PPT
fire detection and alarm system
PPT
Construction site safety
PPS
DETERMINATION ~ DO OR DIE
PPT
PPT
Tallinna üLikool
PPTX
Pokus214
PPTX
Hydrogen Progress, Priorities and Opportunities
DOCX
Unit 2. reinforcement
Loto training
Lockout Tagout
Loto.ppt
Intro to basic fire alarm technology
Safety On Construction site
Construction safety management
Fire Evacuation Plan
Personal Protective Equipment
Fire drill procedure
Fire Alarm, Smoke Detector and Automatic Sprinkle System
fire detection and alarm system
Construction site safety
DETERMINATION ~ DO OR DIE
Tallinna üLikool
Pokus214
Hydrogen Progress, Priorities and Opportunities
Unit 2. reinforcement
Ad

Similar to Background Jobs with Resque (20)

KEY
Django Celery
PDF
Spring Batch in Code - simple DB to DB batch applicaiton
PDF
Rhebok, High Performance Rack Handler / Rubykaigi 2015
KEY
Ruby/Rails
PDF
Puppet Performance Profiling - CM Camp 2015
PPTX
Sharding and Load Balancing in Scala - Twitter's Finagle
PDF
To Batch Or Not To Batch
PDF
Java APIs- The missing manual (concurrency)
PDF
Let's read code: python-requests library
PDF
Matthew Eernisse, NodeJs, .toster {webdev}
PDF
BPM-3 Advanced Workflow Deep Dive
ZIP
Rails 3 (beta) Roundup
KEY
NodeJS
PDF
Getting to know Laravel 5
PDF
Fast Web Applications Development with Ruby on Rails on Oracle
PDF
Intro To JavaScript Unit Testing - Ran Mizrahi
PDF
CakePHP
PDF
Rails 4.0
PDF
Mongo à la Resque
PDF
Ruby on Rails - Introduction
Django Celery
Spring Batch in Code - simple DB to DB batch applicaiton
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Ruby/Rails
Puppet Performance Profiling - CM Camp 2015
Sharding and Load Balancing in Scala - Twitter's Finagle
To Batch Or Not To Batch
Java APIs- The missing manual (concurrency)
Let's read code: python-requests library
Matthew Eernisse, NodeJs, .toster {webdev}
BPM-3 Advanced Workflow Deep Dive
Rails 3 (beta) Roundup
NodeJS
Getting to know Laravel 5
Fast Web Applications Development with Ruby on Rails on Oracle
Intro To JavaScript Unit Testing - Ran Mizrahi
CakePHP
Rails 4.0
Mongo à la Resque
Ruby on Rails - Introduction

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PPT
Teaching material agriculture food technology
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
A Presentation on Artificial Intelligence
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
Teaching material agriculture food technology
NewMind AI Monthly Chronicles - July 2025
Mobile App Security Testing_ A Comprehensive Guide.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Unlocking AI with Model Context Protocol (MCP)
Review of recent advances in non-invasive hemoglobin estimation
Agricultural_Statistics_at_a_Glance_2022_0.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
The AUB Centre for AI in Media Proposal.docx
A Presentation on Artificial Intelligence
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25 Week I
Digital-Transformation-Roadmap-for-Companies.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows

Background Jobs with Resque

  • 1. Background Jobs with Resque Jon Homan Apprentice @ Obtiva http://jonhoman.com @jonhoman
  • 3. Agenda • Resque • Examples • Real world use • Plugins • Alternate Implementations • When to use Resque
  • 4. Background Jobs • Remote API calls • Uploading images • Number crunching • Updating RSS feeds
  • 5. Resque https://github.com/defunkt/resque • Open-source library for creating background jobs • Redis backend • Support for multiple queues • Queues are processed by workers
  • 6. More Resque Features • Monitor with god or monit • Distributed processing • Priorities • Persistent queues • Memory leak resistant • Web interface
  • 8. Redis http://redis.io/ • Key-value datastore • data structure server • constant time pushes and pops • atomic operations
  • 9. All “Foreground” class FeedsController def create feed = Feed.create! feed.fetch redirect_to feed_path(feed) end end class Feed def fetch rss = RSS::Parse.parse(url, false) feed.title = rss.title end end
  • 10. Queue up creation class FeedsController def create feed = Feed.create! Queue.push(feed) # won’t block UI redirect_to feed_path(feed) end end class Queue def push(feed) queue << feed end end
  • 11. Now with Resque class FeedsController def create feed = Feed.create! Resque.enqueue(FeedCreator, feed.id) redirect_to feed_path(feed) end end
  • 12. How to process jobs class FeedCreator @queue = :feed_creation def perform(feed_id) feed = Feed.find(feed_id) rss = RSS::Parser.parse(feed.url,false) feed.title = rss.title # create all items in the rss end end
  • 13. Workers? • Long-running Rake tasks • Look for jobs every n seconds
  • 14. How to start workers $ rake resque:work $ QUEUE=feed rake resque:work $ QUEUE=feed, twitter rake resque:work $ QUEUE=* rake resque:work $ COUNT=3 QUEUE=* rake resque:work
  • 15. Testing w/ RSpec it "stores the name of the feed" do FeedCreator.perform(feed.id) feed.reload.title.should == "Feed end
  • 16. Testing w/ RSpec it "creates Items for every item in the feed" do FeedCreator.perform(feed.id) feed.reload.items.count.should == 5 end
  • 17. Testing w/ RSpec it “parses the feed” do RSS::Parser.should_receive(:parse) FeedCreator.perform(feed.id) end
  • 18. Real world uses • GitHub • Groupon • lifeStreams
  • 19. GitHub 35 different types of jobs: • Warming caches • Counting disk usage • Building tarballs • Building Rubygems • Building graphs • Updating search index
  • 20. Groupon • Resque for background jobs • Notifications • Lockable worker • Redis for semaphores
  • 21. lifeStreams • Process updates to blog feeds • Publish updates to Facebook, Twitter, Email
  • 22. Plugins • resque_spec • Resque Heroku Autoscaler • resque multi step • ResqueMailer • resque-retry • and at least 25 others
  • 23. ResqueSpec https://github.com/leshill/resque_spec • Resque plugin that adds resque-specific matchers • have_queued • have_scheduled • have_queue_size_of
  • 24. Examples it “adds a feed to the creation queue” do post :create, :feed FeedCreator.should have_queued(feed.id) end it “schedules a feed update” do feed.update FeedUpdater.should have_scheduled(feed.id) end
  • 25. Resque Heroku Autoscaler • Scales Heroku workers • Start worker if none running • Stops worker after jobs are processed
  • 26. RHA require 'resque/plugins/resque_heroku_autoscaler' class TestJob extend Resque::Plugins::HerokuAutoscaler @queue = :test def perform ...awesome stuff... end end
  • 27. Resque Mailer • Asynchronously deliver email in Rails
  • 28. Resque Mailer class MyMailer < ActionMailer::Base include Resque::Mailer end MyMailer.subject_email(params).deliver QUEUE=mailer rake environment resque:work
  • 29. resque-retry • Retry, delay and exponential backoff support
  • 30. resque-retry require 'resque-retry' class ExampleRetryJob extend Resque::Plugins::Retry @queue = :example_queue @retry_limit = 3 @retry_delay = 60 def self.perform(*args) # your magic/heavy lifting goes here. end end
  • 31. resque-retry no delay, 1m, 10m, 1h, 3h, 6h @backoff_strategy = [0, 60, 600, 3600, 10800, 21600]
  • 32. Alternate Implementations • C • Java • Scala • .NET • Python • PHP • node.js
  • 33. jesque // Add a job to the queue final Job job = new Job("TestAction", new Object[]{ 1, 2, true, "test", Arrays.asList("inner", 4ß)}); final Client client = new ClientImpl(config); client.enqueue("foo", job); client.end(); // Start a worker to run jobs from the queue final Worker worker = new WorkerImpl(config, Arrays.asList("foo"), Arrays.asList(TestAction.class)); final Thread workerThread = new Thread(worker); workerThread.start();
  • 34. Resque? • Multiple queues • Potentially HUGE queues • Admin UI • Expecting chaos/failures
  • 35. DelayedJob? • Numeric priorities • Queue is small • Add whole objects to queue • No need to setup Redis

Editor's Notes

  • #2: \n
  • #3: Software consulting company in Chicago, IL.\n\nPrimarily RoR, but have mobile, Java, .NET project from time to time\n\nAlways looking for good developers. Interested? Find me after the talk\n
  • #4: \n
  • #5: Useful for cpu- and network-intensive tasks\n\nProcesses that run on an interval\n
  • #6: queue examples: \n* one for each email type; \n* one for updating feeds, one for posting to twitter\n\n
  • #7: priority is assigned per-worker; specified by queue\n\nMemory leak -&gt; worker forks a child process for every job\n
  • #8: \n
  • #9: Resque uses Redis as its database backend\n\ndata structure: string, hash, list, set\n\nlinked list gives great performance for insert/retrieve at head and tail\n\natomic operations: one action won&amp;#x2019;t stomp on another\n
  • #10: UI will block for each feed creation\nunder load, consume a ton of resources (each call to the controller forks a process???)\n
  • #11: \n
  • #12: enqueue takes a Ruby class and any number of arguments after that\n\nargs passed as JSON; can&amp;#x2019;t pass entire objects, pass an id\n
  • #13: \n
  • #14: 5 seconds is the default\n
  • #15: \n
  • #16: processors are POROs so testing is pretty straightforward\ntest side effects\n
  • #17: \n
  • #18: \n
  • #19: \n
  • #20: copies from Resque&amp;#x2019;s README\n
  • #21: semaphore - ensures a deal is still able to sold\n\natomic value of deal sales remaining across processess\n
  • #22: \n
  • #23: \n
  • #24: \n
  • #25: \n
  • #26: \n
  • #27: \n
  • #28: \n
  • #29: \n
  • #30: \n
  • #31: \n
  • #32: \n
  • #33: \n
  • #34: \n
  • #35: \n
  • #36: \n
  • #37: Ethan&amp;#x2019;s geekfest on nosql db&amp;#x2019;s - choose the right solution for the job\n\n
  • #38: I picked Resque as a learning tool\n\nBreakable Toys\n
  • #39: \n
  • #40: \n