Slide 1

Slide 1 text

Hello!

Slide 2

Slide 2 text

I'm Darcy. ! ! @sutto

Slide 3

Slide 3 text

If I talk too fast, yell out

Slide 4

Slide 4 text

Hacking Sidekiq For Fun!

Slide 5

Slide 5 text

(and Profit)

Slide 6

Slide 6 text

Sidekiq.explain!

Slide 7

Slide 7 text

Background Processing

Slide 8

Slide 8 text

Complex logic with many side effects

Slide 9

Slide 9 text

Slow logic

Slide 10

Slide 10 text

Decouple from Request / Response Lifecycle

Slide 11

Slide 11 text

e.g. hit an external API to update expired data on every request

Slide 12

Slide 12 text

Background Jobs in Ruby

Slide 13

Slide 13 text

backgroundrb

Slide 14

Slide 14 text

delayed job

Slide 15

Slide 15 text

resque

Slide 16

Slide 16 text

sidekiq

Slide 17

Slide 17 text

Mike Perham

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

Enter Sidekiq

Slide 20

Slide 20 text

Threaded

Slide 21

Slide 21 text

Actor based concurrency

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

Even in MRI, great for network-heavy logic

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

Redis for job & metadata storage

Slide 26

Slide 26 text

… using same redis layout as Resque.

Slide 27

Slide 27 text

Batteries-included

Slide 28

Slide 28 text

Built in exception reporting support

Slide 29

Slide 29 text

No content

Slide 30

Slide 30 text

Job retries on failures

Slide 31

Slide 31 text

Scheduled Jobs!

Slide 32

Slide 32 text

Built in support for many queues

Slide 33

Slide 33 text

Built to be extensible

Slide 34

Slide 34 text

… we'll talk about this shortly

Slide 35

Slide 35 text

Sidekiq Pro

Slide 36

Slide 36 text

Not Free but adds powerful features such as: batching, notifications, metrics and reliable workers.

Slide 37

Slide 37 text

Scales from a small number of jobs to many

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

But how?

Slide 41

Slide 41 text

class HelloPersonWorker! ! include Sidekiq::Worker! sidekiq_options queue: "onboarding"! ! def perform(name)! Rails.logger.info "Saying hello to #{name}"! end! ! end!

Slide 42

Slide 42 text

Bonus: Testing is simple - instantiate and test worker class.

Slide 43

Slide 43 text

HelloPersonWorker.perform_async "Darcy"! # => "2dbfbc3f28d26be12107db84"

Slide 44

Slide 44 text

Sidekiq::Client.push({! "class" => HelloPersonWorker,! "args" => ["Darcy"]! })!

Slide 45

Slide 45 text

{! "class": "HelloPersonWorker",! "args": ["Darcy"],! "retry": true,! "queue": "onboarding",! "jid": "2dbfbc3f28d26be12107db84",! "enqueued_at": 1392701981.091299! }

Slide 46

Slide 46 text

sadd queues onboarding lpush queue:onboarding [json encoded job]

Slide 47

Slide 47 text

Scheduled job?

Slide 48

Slide 48 text

Sidekiq::Client.push({! "class" => HelloPersonWorker,! "args" => ["Darcy"],! "at" => Time.now.to_f! })!

Slide 49

Slide 49 text

zadd schedule timestamp_1 encoded_json_blob

Slide 50

Slide 50 text

Remembering JSON includes Queue Name

Slide 51

Slide 51 text

How do we run jobs?

Slide 52

Slide 52 text

Sidekiq::Manager

Slide 53

Slide 53 text

Sidekiq::Fetch

Slide 54

Slide 54 text

… or, more accurately, it's strategy.

Slide 55

Slide 55 text

class BasicFetch! def initialize(options)! @strictly_ordered_queues = !!options[:strict]! @queues = options[:queues].map { |q| "queue:#{q}" }! @unique_queues = @queues.uniq! end! ! def retrieve_work! work = Sidekiq.redis { |conn| conn.brpop(*queues_cmd) }! UnitOfWork.new(*work) if work! end! ! # ... more goes here ...! end!

Slide 56

Slide 56 text

brpop semantics control how / what we fetch from

Slide 57

Slide 57 text

Sidekiq::Fetch::UnitOfWork

Slide 58

Slide 58 text

UnitOfWork = Struct.new(:queue, :message) do! def acknowledge! # nothing to do! end! ! def queue_name! queue.gsub(/.*queue:/, '')! end! ! def requeue! Sidekiq.redis do |conn|! conn.rpush("queue:#{queue_name}", message)! end! end! end!

Slide 59

Slide 59 text

Job is fetched, run through middleware and “invoked”.

Slide 60

Slide 60 text

More around that, but that's the core.

Slide 61

Slide 61 text

Making the most of Sidekiq

Slide 62

Slide 62 text

Trick #1: Unique Jobs

Slide 63

Slide 63 text

Middleware!

Slide 64

Slide 64 text

module Sidekiq! module Middleware! module Server! class Logging! ! def call(worker, item, queue)! Sidekiq::Logging.with_context("#{worker.class.to_s} JID-#{item['jid']}") do! begin! start = Time.now! logger.info { "start" }! yield! logger.info { "done: #{elapsed(start)} sec" }! rescue Exception! logger.info { "fail: #{elapsed(start)} sec" }! raise! end! end! end! ! def elapsed(start)! (Time.now - start).to_f.round(3)! end! ! def logger! Sidekiq.logger! end! end! end! end! end!

Slide 65

Slide 65 text

def call(worker, item, queue)! Sidekiq::Logging.with_context("#{worker.class.to_s} JID-#{item['jid']}") do! begin! start = Time.now! logger.info { "start" }! yield! logger.info { "done: #{elapsed(start)} sec" }! rescue Exception! logger.info { "fail: #{elapsed(start)} sec" }! raise! end! end! end!

Slide 66

Slide 66 text

We want to queue a job, but only if it's not currently queued.

Slide 67

Slide 67 text

E.g. Loading external data from an API.

Slide 68

Slide 68 text

$ gem install sidekiq-middleware

Slide 69

Slide 69 text

Store job uniqueness somehow?

Slide 70

Slide 70 text

Client AND Server middleware

Slide 71

Slide 71 text

Pushing AND Pulling Jobs

Slide 72

Slide 72 text

module Sidekiq! module Middleware! module Client! class UniqueJobs! def call(worker_class, item, queue)! worker_class = worker_class.constantize if worker_class.is_a?(String)! enabled = Sidekiq::Middleware::Helpers.unique_enabled?(worker_class, item)! ! if enabled! expiration = Sidekiq::Middleware::Helpers.unique_exiration(worker_class)! job_id = item['jid']! unique = false! ! # Scheduled! if item.has_key?('at')! # Use expiration period as specified in configuration,! # but relative to job schedule time! expiration += (item['at'].to_i - Time.now.to_i)! end! ! unique_key = Sidekiq::Middleware::Helpers.unique_digest(worker_class, item)! ! Sidekiq.redis do |conn|! conn.watch(unique_key)! ! locked_job_id = conn.get(unique_key)! if locked_job_id && locked_job_id != job_id! conn.unwatch! else! unique = conn.multi do! conn.setex(unique_key, expiration, job_id)! end! end! end! ! yield if unique! else! yield! end! end! end! end! end! end!

Slide 73

Slide 73 text

unique_key = Sidekiq::Middleware::Helpers.unique_digest(worker_class, item)! ! Sidekiq.redis do |conn|! conn.watch(unique_key)! ! locked_job_id = conn.get(unique_key)! if locked_job_id && locked_job_id != job_id! conn.unwatch! else! unique = conn.multi do! conn.setex(unique_key, expiration, job_id)! end! end! end! ! yield if unique!

Slide 74

Slide 74 text

1. Generate a key from the job structure 2. Check if locked 3. Set lock (with expiry) if not locked

Slide 75

Slide 75 text

… with some redis magic

Slide 76

Slide 76 text

Hash the JSON of the job, check existence of hash in Redis

Slide 77

Slide 77 text

No content

Slide 78

Slide 78 text

module Sidekiq! module Middleware! module Server! class UniqueJobs! def call(worker_instance, item, queue)! worker_class = worker_instance.class! enabled = Sidekiq::Middleware::Helpers.unique_enabled?(worker_class, item)! ! if enabled! begin! yield! ensure! unless Sidekiq::Middleware::Helpers.unique_manual?(worker_class)! clear(worker_class, item)! end! end! else! yield! end! end! ! def clear(worker_class, item)! Sidekiq.redis do |conn|! conn.del Sidekiq::Middleware::Helpers.unique_digest(worker_class, item)! end! end! end! end! end! end!

Slide 79

Slide 79 text

begin! yield! ensure! unless Sidekiq::Middleware::Helpers.unique_manual?(worker_class)! clear(worker_class, item)! end! end!

Slide 80

Slide 80 text

1. Run the work 2. Unless user has specified they'll clear the lock, clear the lock

Slide 81

Slide 81 text

Trick #2: Adjusting Running Instances

Slide 82

Slide 82 text

Transitions into more powerful territory

Slide 83

Slide 83 text

How can we prioritise and schedule work?

Slide 84

Slide 84 text

Control number of workers dedicated to a task

Slide 85

Slide 85 text

Temporarily pause a queue

Slide 86

Slide 86 text

Make queues block others

Slide 87

Slide 87 text

Dynamically reorganise workers without process changes

Slide 88

Slide 88 text

$ gem install sidekiq-limit_fetch

Slide 89

Slide 89 text

Store queue / system metadata in Redis (seperate to jobs)

Slide 90

Slide 90 text

Act on settings stored in Redis to control the system state.

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

A smart locking algorithm for jobs in Lua

Slide 94

Slide 94 text

… running on your Applications Redis server

Slide 95

Slide 95 text

No content

Slide 96

Slide 96 text

Use the lua script to acquire a job instead of brpop

Slide 97

Slide 97 text

Custom fetch strategy, a unit of work (to update state) & way to manage metadata.

Slide 98

Slide 98 text

Trick #3: Replacing the queue

Slide 99

Slide 99 text

… if we can replace the fetcher, what about how we store data?

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

No content

Slide 102

Slide 102 text

No content

Slide 103

Slide 103 text

$ gem install sidekiq-sqs

Slide 104

Slide 104 text

Monkey patches Sidekiq::Client.push to override adding a job

Slide 105

Slide 105 text

… but reasonably cleanly switches the fetch strategy

Slide 106

Slide 106 text

… but avoid this.

Slide 107

Slide 107 text

Final Trick: Spot Instances and AutoScaling

Slide 108

Slide 108 text

Spot instances average much, much cheaper

Slide 109

Slide 109 text

… but are transient and not guaranteed

Slide 110

Slide 110 text

Normal Price for a c1.medium: $0.145 per Hour

Slide 111

Slide 111 text

Spot Price for a c1.medium: Average $0.018 per Hour, Peak at $5.00 an hour.

Slide 112

Slide 112 text

No content

Slide 113

Slide 113 text

Perfect for processing big amounts of data / backed up queues

Slide 114

Slide 114 text

“I always want at least 5 worker servers, but I can happily jump to 100 if need be”

Slide 115

Slide 115 text

… but do it without human intervention

Slide 116

Slide 116 text

Sidekiq

Slide 117

Slide 117 text

Sidekiq CloudWatch! (Metrics) Publish Sidekiq Queue Sizes

Slide 118

Slide 118 text

Sidekiq CloudWatch! (Metrics) Publish Sidekiq Queue Sizes AutoScaling Scale Up / Down based on # of waiting jobs

Slide 119

Slide 119 text

Sidekiq CloudWatch! (Metrics) Publish Sidekiq Queue Sizes AutoScaling Scale Up / Down based on # of waiting jobs EC2 Instances Launch Instances w/ Queue or Groups specified via User Data

Slide 120

Slide 120 text

Sidekiq CloudWatch! (Metrics) Publish Sidekiq Queue Sizes AutoScaling Scale Up / Down based on # of waiting jobs EC2 Instances Launch Instances w/ Queue or Groups specified via User Data Read Queues / Group from the config, start processing jobs

Slide 121

Slide 121 text

System responds to load and instigates measures to help solve it

Slide 122

Slide 122 text

No content

Slide 123

Slide 123 text

No content

Slide 124

Slide 124 text

I mentioned queue groups, but they're not a sidekiq feature.

Slide 125

Slide 125 text

sidekiq.yml config is run through ERB first.

Slide 126

Slide 126 text

Write logic based on ENV

Slide 127

Slide 127 text

---! queues:! <% if ENV['SIDEKIQ_GROUP'] == 'onboarding' %>! - [hello, 10]! - [world, 5]! <% else %>! - [hello, 2]! - [world, 2]! - [default, 1]! <% end %>!

Slide 128

Slide 128 text

Want to move to controllable queues per instance / group

Slide 129

Slide 129 text

Opportunity for custom extensions?

Slide 130

Slide 130 text

On spot, expect machines to just be turned off at any time

Slide 131

Slide 131 text

Jobs must be idempotent

Slide 132

Slide 132 text

… also, you must design them to fail gracefully

Slide 133

Slide 133 text

It shouldn't matter if it runs 1 time or 1000

Slide 134

Slide 134 text

Harder than it sounds

Slide 135

Slide 135 text

Other tips

Slide 136

Slide 136 text

Tooling is sparse(r)

Slide 137

Slide 137 text

Metrics around performance specifically

Slide 138

Slide 138 text

… but you can tail log files and collate information

Slide 139

Slide 139 text

No content

Slide 140

Slide 140 text

… just from tailing files

Slide 141

Slide 141 text

Data imports start approaching Hadoop-level complexity.

Slide 142

Slide 142 text

Summary

Slide 143

Slide 143 text

Understand how Sidekiq is designed / structured

Slide 144

Slide 144 text

Know redis & store job metadata there

Slide 145

Slide 145 text

You can do things in your redis instance using Lua

Slide 146

Slide 146 text

But don't limit yourself to whats there

Slide 147

Slide 147 text

Bend Queues to your will.

Slide 148

Slide 148 text

Huge amounts of existing sidekiq middleware

Slide 149

Slide 149 text

And libraries for other languages

Slide 150

Slide 150 text

Also, consider when you need to move to a proper MQ.

Slide 151

Slide 151 text

What's coming in Sidekiq?

Slide 152

Slide 152 text

Sidekiq 3.0!

Slide 153

Slide 153 text

Main Feature: Dead Job Queue For when job fails all retries.

Slide 154

Slide 154 text

Sidekiq Pro 2.0!

Slide 155

Slide 155 text

Main Feature: Nested Job Batches For complex workflows

Slide 156

Slide 156 text

e.g. multi stage data imports.

Slide 157

Slide 157 text

Questions?