# Rails Internals: A Deep Dive Into Active Job Codebase

*Published on December 15, 2023*

Tags: Rails Internals

---


> We&nbsp;_must_&nbsp;read other people's code&nbsp;because we have to understand it to get things done. So don't be afraid to&nbsp;**read the source, Luke**&nbsp;– and follow it wherever it takes you, no matter how scary looking that code is.  
>   
> _- Coding Horror, in_&nbsp;[_Learn to Read the Source, Luke_](https://blog.codinghorror.com/learn-to-read-the-source-luke/)

Reading the source code is one of the best ways to deepen your understanding of a programming language or a framework.

Since Ruby is such a beautiful and aesthetically pleasing programming language, I've found an immense joy in spending hours and hours just reading the Rails codebase and trying to understand how various features that I use everyday are put together by some really smart developers.

In this article, we will follow the journey of a Rails background job, from its creation to execution. We will learn how a job is configured and enqueued, and how an adapter invokes it. We will also see the different ways to configure a job.

![activejob-design.webp](https://writesoftwarewell.com/media/o8o3k7szcrqp5sn8msjf5oz442wa.webp "Active Job Design")

I hope that you will have a much better understanding of the Active Job framework after reading this article.

Sounds fun? Let’s dive in...

* * *

_**Note:**_&nbsp;_To get the most out from this article, I suggest you to clone the_&nbsp;[_Rails codebase_](https://github.com/rails/rails)&nbsp;_on your computer, open it in an IDE, and trace the code execution as you read. Even better,_&nbsp;[_debug and step-through the Rails codebase_](/how-to-debug-and-step-through-rails-source-code)_, examining the state of various variables during the execution._

Here’s a simple job class that inherits from&nbsp;`ApplicationJob`, which itself inherits from&nbsp;`ActiveJob::Base`&nbsp;class.

```ruby
# app/jobs/create_invoice_job.rb
class CreateInvoiceJob < ApplicationJob
  def perform(job_id)
    # logic to generate invoice
  end
end

# app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base
end
```

The&nbsp;`ActiveJob::Base`&nbsp;class includes 12 modules, most of which are&nbsp;[Rails concerns](/how-rails-concerns-work-and-how-to-use-them), adding instance and class methods on the including class, i.e.&nbsp;`ActiveJob::Base`&nbsp;class. Due to inheritance, the&nbsp;`CreateInvoiceJob`&nbsp;class gets all these methods. To learn more about concerns, check out this article: [Concerns in Rails: Everything You Need to Know](/how-rails-concerns-work-and-how-to-use-them)

We will inspect each module in detail as we study the Active Job API.

```ruby
# activejob/lib/active_job/base.rb

module ActiveJob
  class Base
    include Core
    include QueueAdapter
    include QueueName
    include QueuePriority
    include Enqueuing
    include Execution
    include Callbacks
    include Exceptions
    include Instrumentation
    include Logging
    include Timezones
    include Translation

    ActiveSupport.run_load_hooks(:active_job, self)
  end
end
```

Let’s start with the&nbsp;`perform`&nbsp;method, because that’s all we have at this point in our job.

The&nbsp;`perform`&nbsp;method in&nbsp;`CreateInvoiceJob`&nbsp;class overrides the&nbsp;`perform`&nbsp;method provided by the&nbsp;`ActiveJob::Execution`&nbsp;concern. It fails immediately, as it expects your concrete job class to provide the implementation.

```ruby
# activejob/lib/active_job/execution.rb

module ActiveJob
  module Execution
    def perform(*)
      fail NotImplementedError
    end
  end
end
```

Now you might be wondering,&nbsp;**who calls the**&nbsp;**`perform`**&nbsp;**method on your job class?**&nbsp;and that's the question we will try to answer in the first part of the post.

In your application, you can&nbsp;[enqueue a job](https://edgeguides.rubyonrails.org/active_job_basics.html#enqueue-the-job)&nbsp;using&nbsp;[`perform_later`](https://edgeapi.rubyonrails.org/classes/ActiveJob/Enqueuing/ClassMethods.html#method-i-perform_later), which ultimately calls&nbsp;`perform`&nbsp;on the job.

```ruby
CreateInvoiceJob.perform_later(job_id)
```

This is where we'll begin our journey, and trace the path that a background job takes. Let's see what happens when you call this&nbsp;`perform_later`&nbsp;method.

## What Happens When You Call 'perform\_later'

The&nbsp;`perform_later`&nbsp;method enqueues a job to be executed later. It is a class method that comes from the&nbsp;`ActiveJob::Enqueuing`&nbsp;concern.

```ruby
# activejob/lib/active_job/enqueuing.rb

module ActiveJob
  module Enqueuing
    module ClassMethods
      def perform_later(...)
        job = job_or_instantiate(...)
        enqueue_result = job.enqueue

        yield job if block_given?

        enqueue_result
      end
      
      private
        def job_or_instantiate(*args) # :doc:
          args.first.is_a?(self) ? args.first : new(*args)
        end
    end
  end
end
```

Note: By default, the arguments you pass to the&nbsp;`perform_later`&nbsp;method must be one of the following types.

- `String`,&nbsp;`Integer`,&nbsp;`Float`,&nbsp;`BigDecimal`
- `NilClass`,&nbsp;`TrueClass`,&nbsp;`FalseClass`,
- `Symbol`,&nbsp;`Date`,&nbsp;`Time`,&nbsp;`DateTime`,&nbsp;`ActiveSupport::TimeWithZone`,&nbsp;`ActiveSupport::Duration`,
- `Hash`,&nbsp;`ActiveSupport::HashWithIndifferentAccess`,
- `Array`,&nbsp;`Range`&nbsp;or
- `GlobalID::Identification`&nbsp;instances.

> 💡You can extend the supported argument types with&nbsp;[custom serializers](https://edgeguides.rubyonrails.org/active_job_basics.html#serializers).

The&nbsp;`perform_later`&nbsp;method returns an instance of the job class queued with arguments, or&nbsp;`false`&nbsp;if the&nbsp;`enqueue`&nbsp;did not succeed.

## A Job is Enqueued

Now let’s see what the&nbsp;`Job#enqueue`&nbsp;method is doing. It resides in the same&nbsp;`Enqueuing`&nbsp;module as an instance method on the job.

```ruby
# activejob/lib/active_job/enqueuing.rb

module ActiveJob
  module Enqueuing
    def enqueue(options = {})
      set(options)
      
      self.successfully_enqueued = false
      
      run_callbacks :enqueue do
        if scheduled_at
          queue_adapter.enqueue_at self, scheduled_at
        else
          queue_adapter.enqueue self
        end
        self.successfully_enqueued = true
      end
      
      if successfully_enqueued?
        self
      else
        false
      end
    end
  end
end
```

> 💡Notice that this method accepts an options hash as a parameter, but we are not passing any arguments from the perform\_later method. This is used by the ConfiguredJob which we will study later.

First, it runs the callbacks for the&nbsp;`:enqueue`&nbsp;event. Rails will call the&nbsp;`before`&nbsp;and&nbsp;`around`&nbsp;callbacks in the order they were set, yield the block (if one is provided), and then run the after callbacks in reverse order.

**Inside the block, the**&nbsp;**`enqueue`**&nbsp;**method uses the**&nbsp;**`queue_adapter`**&nbsp;**to enqueue the job.**

Finally, if the job was enqueued successfully, it returns the job. Otherwise, it returns&nbsp;`false`.

## Adapters execute the job

At this point, we know how a job gets enqueued by a queue adapter with the&nbsp;`perform_later`&nbsp;method. However, we still haven’t answered who calls the&nbsp;`perform`&nbsp;method on the job class,&nbsp;**which ultimately executes our job.**

For that, let’s look at the implementation of one of the queue adapters. We’ll inspect the inline adapter’s enqueue method to keep things simple.

💡The inline adapter executes the jobs immediately. It doesn’t support enqueuing jobs to be executed in future.

```ruby
# activejob/lib/active_job/queue_adapters/inline_adapter.rb

module ActiveJob
  module QueueAdapters
    class InlineAdapter
      def enqueue(job)
        Base.execute(job.serialize)
      end
    end
  end
end
```

As you can see, the&nbsp;`enqueue`&nbsp;method receives the job instance we passed in the&nbsp;`Job#enqueue`&nbsp;method above. Then it calls the&nbsp;`execute`&nbsp;method on the&nbsp;`Base`&nbsp;class, passing the serialized job data.

## Execute the Job

The&nbsp;`Base.execute`&nbsp;class method is provided by the&nbsp;`Execution`&nbsp;module. It performs the following tasks:

1. Receives the serialized job data
2. Runs the callbacks for the&nbsp;`:execute`&nbsp;event, and yields the block, which
3. Deserializes the serialized job data to build the job instance, and
4. Calls the&nbsp;`Job#perform_now`&nbsp;instance method on the job instance.

```ruby
# activejob/lib/active_job/queue_adapters/inline_adapter.rb

module ActiveJob
  module Execution
    # Includes methods for executing and performing jobs instantly.
    module ClassMethods
      def execute(job_data)
        ActiveJob::Callbacks.run_callbacks(:execute) do
          job = deserialize(job_data)
          job.perform_now
        end
      end
    end
  end
end
```

Okay, we are one step closer, but we still haven’t called the&nbsp;`perform`&nbsp;method yet.

Let’s inspect the&nbsp;`perform_now`&nbsp;instance method, which is in the same module. It calls the&nbsp;`_perform_job`&nbsp;method, a private method defined in the same module.

```ruby
# activejob/lib/active_job/execution.rb

module ActiveJob
  module Execution
    def perform_now
      # ignoring prior code to keep things simple
      _perform_job
    end
    
    private
      def _perform_job
        ActiveSupport::ExecutionContext[:job] = self
        run_callbacks :perform do
          perform(*arguments)
        end
      end
  end
end
```

Finally, we can see that the&nbsp;`_perform_job`&nbsp;method calls the&nbsp;`perform`&nbsp;method, passing the arguments.

Now you might wonder where that&nbsp;`*arguments`&nbsp;is coming from? It comes from the&nbsp;`Core`&nbsp;module. Using it with&nbsp;[the splat (\*) operator](https://stackoverflow.com/questions/918449/what-does-the-unary-operator-do-in-this-ruby-code)&nbsp;passes all the arguments to the&nbsp;`perform`&nbsp;method.

The&nbsp;`arguments`&nbsp;were initialized with whatever data you passed to the&nbsp;`perform_later`&nbsp;method. It created a new job instance and forwarded all that data to it.

See the&nbsp;`job_or_instantiate`&nbsp;method above to refresh your memory.

```ruby
# activejob/lib/active_job/core.rb

module ActiveJob
  module Core
    # Job arguments
    attr_accessor :arguments
    
    # Creates a new job instance. Takes the arguments that will be
    # passed to the perform method.
    def initialize(*arguments)
      @arguments = arguments
      # other data initialization
    end
  end
end
```

Now, we are back to where we started, with the simple job with a&nbsp;`perform`&nbsp;method. Our job completes when the&nbsp;`perform`&nbsp;method is executed.

```ruby
class CreateInvoiceJob < ApplicationJob
  def perform(job_id)
    # Do something later
  end
end
```

## Job Configuration

In the&nbsp;`enqueue`&nbsp;method above, I promised that we will learn about the&nbsp;`ConfiguredJob`&nbsp;and the&nbsp;`set`&nbsp;method later. Let’s do that now.

Before calling&nbsp;`perform_later`&nbsp;on a job, you can use the&nbsp;`set`&nbsp;method to configure a job, like this:

```ruby
# Enqueue a job to be performed tomorrow at noon.
GuestsCleanupJob.set(wait_until: Date.tomorrow.noon).perform_later(guest)
```

The&nbsp;`set`&nbsp;class method comes from the&nbsp;`Core`&nbsp;module. It creates a job preconfigured with the given options.

```ruby
# activejob/lib/active_job/core.rb

module ActiveJob
  module Core
    module ClassMethods
      def set(options = {})
        ConfiguredJob.new(self, options)
      end
    end
  end
end
```

All&nbsp;`set`&nbsp;does is create an instance of the&nbsp;`ConfiguredJob`&nbsp;class, passing itself (the Job class, i.e.&nbsp;`GuestCleanupJob`&nbsp;and not its instance, an important distinction), along with any preconfigured options.

You can use the following options:

- `:wait`&nbsp;- Enqueues the job with the specified delay
- `:wait_until`&nbsp;- Enqueues the job at the time specified
- `:queue`&nbsp;- Enqueues the job on the specified queue
- `:priority`&nbsp;- Enqueues the job with the specified priority

Now let's understand how the&nbsp;`ConfiguredJob`&nbsp;class works.

## Configured Job

**ConfiguredJob**&nbsp;is a very simple class. When created, it saves the&nbsp;`options`&nbsp;and the&nbsp;`job_class`, i.e.&nbsp;`GuestCleanupJob`&nbsp;as instance variables.

It provides two methods,&nbsp;`perform_now`&nbsp;(to execute the job immediately) and&nbsp;`perform_later`&nbsp;(to save it for later).

```ruby
# activejob/lib/active_job/configured_job.rb

module ActiveJob
  class ConfiguredJob
    def initialize(job_class, options = {})
      @options = options
      @job_class = job_class
    end

    def perform_now(...)
      @job_class.new(...).set(@options).perform_now
    end

    def perform_later(...)
      @job_class.new(...).enqueue @options
    end
  end
end
```

When called, these methods create a new instance of the job using the&nbsp;`job_class`, and call the&nbsp;`Job#set`&nbsp;instance method on it. The&nbsp;`set`&nbsp;method is where we actually set the options on the job instance.

```ruby
# activejob/lib/active_job/core.rb

module ActiveJob
  module Core
    # Timestamp when the job should be performed
    attr_accessor :scheduled_at
    
    # Queue in which the job will reside.
    attr_writer :queue_name

    # Priority that the job will have (lower is more priority).
    attr_writer :priority
    
    # Configures the job with the given options.
    def set(options = {}) # :nodoc:
      self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait]
      self.scheduled_at = options[:wait_until].to_f if options[:wait_until]
      self.queue_name   = self.class.queue_name_from_part(options[:queue]) if options[:queue]
      self.priority     = options[:priority].to_i if options[:priority]

      self
    end
  end
end
```

These options are used when the job is enqueued (see the&nbsp;`enqueue`&nbsp;method above). Each queue adapter has a different implementation that uses them differently.

For example, here’re a few implementations for various adapters:

```ruby
queue_adapter.enqueue_at(self, scheduled_at)

# Sidekiq
def enqueue_at(job, timestamp) # :nodoc:
  job.provider_job_id = Sidekiq::Client.push \
    "class"   => JobWrapper,
    "wrapped" => job.class,
    "queue"   => job.queue_name,
    "args"    => [ job.serialize ],
    "at"      => timestamp
end

# Backburner
def enqueue_at(job, timestamp) # :nodoc:
  delay = timestamp - Time.current.to_f
  Backburner::Worker.enqueue(JobWrapper, [job.serialize], queue: job.queue_name, pri: job.priority, delay: delay)
end

# Que
def enqueue_at(job, timestamp) # :nodoc:
  que_job = JobWrapper.enqueue job.serialize, priority: job.priority, queue: job.queue_name, run_at: Time.at(timestamp)
  job.provider_job_id = que_job.attrs["job_id"]
  que_job
end
```

## Setting the Queue Adapter

You can easily set your queuing backend with&nbsp;[`config.active_job.queue_adapter`](https://edgeguides.rubyonrails.org/configuring.html#config-active-job-queue-adapter)

```ruby
# config/application.rb

module YourApp
  class Application < Rails::Application
    # Be sure to have the adapter's gem in your Gemfile
    # and follow the adapter's specific installation
    # and deployment instructions.
    config.active_job.queue_adapter = :sidekiq
  end
end
```

Or, on a per-job basis:

```ruby
class GuestsCleanupJob < ApplicationJob
  self.queue_adapter = :resque
  # ...
end

# Now your job will use `resque` as its backend queue adapter, overriding what
# was configured in `config.active_job.queue_adapter`.
```

Let’s stop before this post gets way too long. We still haven’t explored queues yet, which is quite an important topic, but we will save it for later. For now, I really hope you have a better understanding of the Active Job framework than before you read this post.

### **Further Reading**

If you like reading this article, here're a few more you might enjoy:

- [Learn to Read the Source, Luke](https://blog.codinghorror.com/learn-to-read-the-source-luke/)
- [How to Debug and Step-Through Rails Codebase](/how-to-debug-and-step-through-rails-source-code)
- [Concerns in Rails: Everything You Need to Know](/how-rails-concerns-work-and-how-to-use-them)

