ruby
27 lines · 7 steps
Purging stale exports with an Active Job in Rails
A Rails background job batch-deletes old exports and their attachments, with retry policies and a rake task to enqueue it.
Explained by
highlit
1class PurgeStaleExportsJob < ApplicationJob
2 queue_as :maintenance
3
4 retry_on ActiveRecord::Deadlocked, wait: :polynomially_longer, attempts: 5
5 retry_on Aws::S3::Errors::ServiceError, wait: 30.seconds, attempts: 3
6 discard_on ActiveJob::DeserializationError
7
8 RETENTION = 7.days
9
10 def perform(older_than: RETENTION.ago)
11 Export.completed.where(created_at: ..older_than).in_batches(of: 200) do |batch|
12 batch.each do |export|
13 export.file.purge_later if export.file.attached?
14 end
15
16 deleted = batch.delete_all
17 Rails.logger.info("[PurgeStaleExports] removed #{deleted} exports")
18 end
19 end
20end
21
22namespace :exports do
23 desc "Enqueue cleanup of stale exports (run hourly via cron/whenever)"
24 task cleanup: :environment do
25 PurgeStaleExportsJob.perform_later
26 end
27end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Processing records in batches keeps memory bounded and avoids locking huge row sets at once.
- 2Declarative retry_on and discard_on rules let a job tolerate transient failures without custom rescue logic.
- 3Purging attachments separately from deleting rows prevents orphaned files in your storage backend.
Related explainers
ruby
class ApplicationController < ActionController::Base ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze def store_return_to(location = request.fullpath)
Safe post-login redirects in Rails
open-redirect
session
authentication
Intermediate
9 steps
ruby
require 'set' class DirectoryWatcher def initialize(path, pattern: '**/*', interval: 1.0)
Polling for file changes in Ruby
polling
filesystem
diffing
Intermediate
7 steps
javascript
import { Component } from 'react'; import { reportError } from './services/telemetry'; export class ErrorBoundary extends Component {
How a React ErrorBoundary works
error-handling
lifecycle-methods
render-props
Intermediate
8 steps
rust
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::{DecodeError, Engine}; pub fn encode_standard(data: &[u8]) -> String {
Base64 encode and decode in Rust
base64
encoding
error-handling
Beginner
7 steps
ruby
class HashDiff Change = Struct.new(:from, :to) def self.call(before, after)
Diffing two hashes in Ruby
set-operations
struct
enumerable
Intermediate
7 steps
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/purging-stale-exports-with-an-active-job-in-rails-explained-ruby-edda/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.