Maintenance Tasks
A Rails engine for queuing and managing maintenance tasks.
By ”maintenance task”, this project means a data migration, i.e. code that
changes data in the database, often to support schema migrations. For example,
in order to introduce a new NOT NULL column, it has to be added as nullable
first, backfilled with values, before finally being changed to NOT NULL. This
engine helps with the second part of this process, backfilling.
Maintenance tasks are collection-based tasks, usually using Active Record, that
update the data in your database. They can be paused or interrupted. Maintenance
tasks can operate in batches and use
throttling to control the load on your database.
Maintenance tasks aren't meant to happen on a regular basis. They're used as
needed, or as one-offs. Normally maintenance tasks are ephemeral, so they are
used briefly and then deleted.
The Rails engine has a web-based UI for listing maintenance tasks, seeing their
status, and starting, pausing and restarting them.

Should I Use Maintenance Tasks?
Maintenance tasks have a limited, specific job UI. While the engine can be used
to provide a user interface for other data changes, such as data changes for
support requests, we recommend you use regular application code for those use
cases instead. These inevitably require more flexibility than this engine will
be able to provide.
If your task shouldn't run as an Active Job, it probably isn't a good match for
this gem. If your task doesn't need to run in the background, consider a runner
script instead. If your task doesn't need to be interruptible, consider a normal
Active Job.
Maintenance tasks can be interrupted between iterations. If your task isn't
collection-based (no CSV file or database
table) or has very large batches, it will get limited benefit from throttling
(pausing between iterations) or interrupting. This might be fine, or the added
complexity of maintenance Tasks over normal Active Jobs may not be worthwhile.
If your task updates your database schema instead of data, use a migration
instead of a maintenance task.
If your task happens regularly, consider Active Jobs with a scheduler or cron,
job-iteration jobs and/or custom rails_admin
UIs instead of the Maintenance Tasks gem. Maintenance
tasks should be ephemeral, to suit their intentionally limited UI. They should
not repeat.
To create seed data for a new application, use the provided Rails db/seeds.rb
file instead.
If your application can't handle a half-completed migration, maintenance tasks
are probably the wrong tool. Remember that maintenance tasks are intentionally
pausable and can be cancelled halfway.
Installation
To install the gem and run the install generator, execute:
bundle add maintenance_tasks
bin/rails generate maintenance_tasks:install
The generator creates and runs a migration to add the necessary table to your
database. It also mounts Maintenance Tasks in your config/routes.rb. By
default the web UI can be accessed in the new /maintenance_tasks path.
This gem uses the Rails Error Reporter to report errors.
If you are using a bug tracking service you may want to subscribe to the
reporter. See Reporting Errors for more information.
Active Job Dependency
The Maintenance Tasks framework relies on Active Job behind the scenes to run
Tasks. The default queuing backend for Active Job is
asynchronous. It is strongly recommended to change this to
a persistent backend so that Task progress is not lost during code or
infrastructure changes. For more information on configuring a queuing backend,
take a look at the Active Job documentation.
Action Controller & Action View Dependency
The Maintenance Tasks framework relies on Action Controller and Action View to
render the UI. If you're using Rails in API-only mode, see Using Maintenance
Tasks in API-only
applications.
Autoloading
The Maintenance Tasks framework does not support autoloading in :classic mode.
Please ensure your application is using Zeitwerk to load your code. For more
information, please consult the Rails guides on autoloading and reloading
constants.
Usage
The typical Maintenance Tasks workflow is as follows:
- Generate a class describing the Task and the work to be
done.
- Run the Task
- Monitor the Task
- either by using the included web UI,
- or by manually checking your task’s run’s status in your database.
- Optionally, delete the Task code if you no longer need it.
Creating a Task
A generator is provided to create tasks. Generate a new task by running:
bin/rails generate maintenance_tasks:task update_posts
This creates the task file app/tasks/maintenance/update_posts_task.rb.
The generated task is a subclass of MaintenanceTasks::Task that implements:
collection: return an Active Record Relation or an Array to be iterated
over.
process: do the work of your maintenance task on a single record
Optionally, tasks can also implement a custom #count method, defining the
number of elements that will be iterated over. Your task’s tick_total will be
calculated automatically based on the collection size, but this value may be
overridden if desired using the #count method (this might be done, for
example, to avoid the query that would be produced to determine the size of your
collection).
Example:
# app/tasks/maintenance/update_posts_task.rb
module Maintenance
class UpdatePostsTask < MaintenanceTasks::Task
def collection
Post.all
end
def process(post)
post.update!(content: "New content!")
end
end
end
Customizing the Batch Size
When processing records from an Active Record Relation, records are fetched in
batches internally, and then each record is passed to the #process method.
Maintenance Tasks will query the database to fetch records in batches of 100 by
default, but the batch size can be modified using the collection_batch_size
macro:
# app/tasks/maintenance/update_posts_task.rb
module Maintenance
class UpdatePostsTask < MaintenanceTasks::Task
# Fetch records in batches of 1000
collection_batch_size(1000)
def collection
Post.all
end
def process(post)
post.update!(content: "New content!")
end
end
end
Creating a CSV Task
You can also write a Task that iterates on a CSV file. Note that writing CSV
Tasks requires Active Storage to be configured. Ensure that the dependency
is specified in your application’s Gemfile, and that you’ve followed the setup
instructions. See also Customizing which Active Storage service
to use.
Generate a CSV Task by running:
bin/rails generate maintenance_tasks:task import_posts --csv
The generated task is a subclass of MaintenanceTasks::Task that implements:
process: do the work of your maintenance task on a CSV::Row
# app/tasks/maintenance/import_posts_task.rb
module Maintenance
class ImportPostsTask < MaintenanceTasks::Task
csv_collection
def process(row)
Post.create!(title: row["title"], content: row["content"])
end
end
end
posts.csv:
title,content
My Title,Hello World!
The files uploaded to your Active Storage service provider will be renamed to
include an ISO 8601 timestamp and the Task name in snake case format.
The implicit #count method loads and parses the entire file to determine the
accurate number of rows. With files with millions of rows, it takes several
seconds to process. Consider skipping the count (defining a count that returns
nil) or use an approximation, eg: count the number of new lines:
def count
csv_content.count("\n") - 1
end
CSV options
Tasks can pass options for Ruby's CSV parser by adding
keyword arguments to csv_collection:
# app/tasks/maintenance/import_posts_task.rb
module Maintenance
class ImportPosts
csv_collection(skip_lines: /^#/, converters: ->(field) { field.strip })
def process(row)
Post.create!(title: row["title"], content: row["content"])
end
end
end
These options instruct Ruby's CSV parser to skip lines that start with a #,
and removes the leading and trailing spaces from any field, so that the
following file will be processed identically as the previous example:
posts.csv:
# A comment
title,content
My Title ,Hello World!
Batch CSV Tasks
Tasks can process CSVs in batches. Add the in_batches option to your task’s
csv_collection macro:
# app/tasks/maintenance/batch_import_posts_task.rb
module Maintenance
class BatchImportPostsTask < MaintenanceTasks::Task
csv_collection(in_batches: 50)
def process(batch_of_rows)
Post.insert_all(post_rows.map(&:to_h))
end
end
end
As with a regular CSV task, ensure you’ve implemented the following method:
process: do the work of your Task on a batch (array of CSV::Row objects).
Note that #count is calculated automatically based on the number of batches in
your collection, and your Task’s progress will be displayed in terms of batches
(not the total number of rows in your CSV).
Non-batched CSV tasks will have an effective batch size of 1, which can reduce
the efficiency of your database operations.
Processing Batch Collections
The Maintenance Tasks gem supports processing Active Records in batches. This
can reduce the number of calls your Task makes to the database. Use
ActiveRecord::Batches#in_batches on the relation returned by your collection
to specify that your Task should process batches instead of records. Active
Record defaults to 1000 records by batch, but a custom size can be specified.
# app/tasks/maintenance/update_posts_in_batches_task.rb
module Maintenance
class UpdatePostsInBatchesTask < MaintenanceTasks::Task
def collection
Post.in_batches
end
def process(batch_of_posts)
batch_of_posts.update_all(content: "New content added on #{Time.now.utc}")
end
end
end
Ensure that you’ve implemented the following methods:
collection: return an ActiveRecord::Batches::BatchEnumerator.
process: do the work of your Task on a batch (ActiveRecord::Relation).
Note that #count is calculated automatically based on the number of batches in
your collection, and your Task’s progress will be displayed in terms of batches
(not the number of records in the relation).
Important! Batches should only be used if #process is performing a batch
operation such as #update_all or #delete_all. If you need to iterate over
individual records, you should define a collection that returns an
ActiveRecord::Relation. This uses batching internally, but
loads the records with one SQL query. Conversely, batch collections load the
primary keys of the records of the batch first, and then perform an additional
query to load the records when calling each (or any Enumerable method)
inside #process.
Tasks that don’t need a Collection
Sometimes, you might want to run a Task that performs a single operation, such
as enqueuing another background job or querying an external API. The gem
supports collection-less tasks.
Generate a collection-less Task by running:
bin/rails generate maintenance_tasks:task no_collection_task --no-collection
The generated task is a subclass of MaintenanceTasks::Task that implements:
process: do the work of your maintenance task
# app/tasks/maintenance/no_collection_task.rb
module Maintenance
class NoCollectionTask < MaintenanceTasks::Task
no_collection
def process
SomeAsyncJob.perform_later
end
end
end
Tasks with Custom Enumerators
If you have a special use case requiring iteration over an unsupported
collection type, such as external resources fetched from some API, you can
implement the enumerator_builder(cursor:) method in your task.
This method should return an Enumerator, yielding pairs of [item, cursor].
Maintenance Tasks takes care of persisting the current cursor position and will
provide it as the cursor argument if your task is interrupted or resumed. The
cursor is stored as a String, so your custom enumerator should handle
serializing/deserializing the value if required. Note that if you've enabled
JSON cursors, the cursor will be automatically serialized and
deserialized. However for this to work, the cursor values must be
JSON-serializable.