workflows/background-job/SKILL.md
Orchestrates robust background job implementation: design job → TDD implementation → configure retry/discard strategies → test failure scenarios → production monitoring. Use when adding async processing, implementing background jobs, or configuring job queues. Trigger: background job, async processing, sidekiq, solid queue, active job, job queue, worker.
npx skillsauth add igmarin/rails-agent-skills background-jobInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Orchestrates robust background job implementation with TDD discipline, proper retry/discard strategies, comprehensive failure scenario testing, and production monitoring to ensure reliable async processing.
Objective: Design background job with clear responsibilities and error handling strategy.
Steps:
Job Design Guidelines:
HARD GATE — Job Design Complete:
If gate fails: Job design is incomplete. Clarify requirements before implementation.
Example Job Design:
# Background Job Design: OrderConfirmationEmail
## Purpose
Send order confirmation email when order is completed
## Trigger
Event-based: Order.status transitions to 'completed'
## Input
- order_id (Integer)
- customer_email (String)
- order_total (Float)
## Output
- Email sent via external API
- Order email_sent_at timestamp updated
## Idempotency
- Check if email already sent before sending
- Use unique job key: "order_confirmation_#{order_id}"
- Update email_sent_at only after successful send
## Error Classification
- Transient: Email API timeout (retry with exponential backoff)
- Transient: Rate limit exceeded (retry with longer delay)
- Permanent: Invalid email address (discard with error logging)
- Permanent: Order not found (discard)
- Configuration: Missing API credentials (alert team)
## Queue
default (normal priority)
## Timeout
30 seconds
Objective: Implement background job using TDD discipline.
Before implementing job logic:
HARD GATE — Test Verification:
If test fails for wrong reason: Fix test (not implementation) to accurately test job behavior.
Example Job Test:
# spec/jobs/order_confirmation_email_job_spec.rb
RSpec.describe OrderConfirmationEmailJob do
let(:order) { create(:order, :completed) }
it 'sends confirmation email' do
expect(EmailService).to receive(:send_confirmation).with(order.id, order.customer_email, order.total)
described_class.perform_now(order.id, order.customer_email, order.total)
end
it 'is idempotent' do
expect(EmailService).to receive(:send_confirmation).once
described_class.perform_now(order.id, order.customer_email, order.total)
described_class.perform_now(order.id, order.customer_email, order.total)
end
it 'handles email service errors with retry' do
allow(EmailService).to receive(:send_confirmation).and_raise(EmailService::TimeoutError)
expect { described_class.perform_now(order.id, order.customer_email, order.total) }.to raise_error(EmailService::TimeoutError)
end
end
Example Job Implementation:
# app/jobs/order_confirmation_email_job.rb
class OrderConfirmationEmailJob < ApplicationJob
queue_as :default
# Retry on transient errors
retry_on EmailService::TimeoutError, wait: :exponentially_longer, attempts: 5
retry_on EmailService::RateLimitError, wait: :exponentially_longer, attempts: 3
# Discard on permanent errors
discard_on ActiveRecord::RecordNotFound
discard_on EmailService::InvalidEmailError
def perform(order_id, customer_email, order_total)
order = Order.find(order_id)
# Idempotency check
return if order.email_sent_at.present?
# Send email
EmailService.send_confirmation(order_id, customer_email, order_total)
# Update timestamp
order.update(email_sent_at: Time.current)
rescue EmailService::TimeoutError, EmailService::RateLimitError => e
Rails.logger.error("Email service error: #{e.message}")
Rails.logger.error(e.backtrace.first(5).join("\n"))
raise # Will trigger retry
rescue ActiveRecord::RecordNotFound, EmailService::InvalidEmailError => e
Rails.logger.warn("Permanent email error: #{e.message}")
# Will trigger discard
end
end
Objective: Configure robust retry and discard strategies for production reliability.
Steps:
retry_on for transient errors (network timeouts, rate limits)discard_on for permanent errors (not found, invalid data)Retry Strategy Guidelines:
HARD GATE — Retry Strategy Configured:
If gate fails: Job is not production-ready. Configure retry/discard strategy.
Example Configuration (Solid Queue - Rails 8+):
# config/initializers/solid_queue.rb
Rails.application.config.after_initialize do
SolidQueue.configure do |config|
config.worker = {
processes: 2,
threads: 5,
polling_interval: 1
}
end
end
# config/recurring.yml
order_confirmation_cleanup:
class: OrderConfirmationCleanupJob
schedule: every 1.day
queue: critical
Example Configuration (Sidekiq):
# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
config.redis = { url: ENV['REDIS_URL'] }
config.server_middleware do |chain|
chain.add Sidekiq::Throttler, rate: { limit: 100, period: 1.minute }
end
end
# app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base
# Default retry configuration
retry_on StandardError, wait: :exponentially_longer, attempts: 5
end
Objective: Test failure scenarios and set up production monitoring.
Steps:
HARD GATE — Failure Scenarios Tested:
If gate fails: Job is not production-ready. Address failure scenarios.
Example Failure Scenario Tests:
# spec/jobs/order_confirmation_email_job_failure_spec.rb
RSpec.describe OrderConfirmationEmailJob, :focus do
let(:order) { create(:order, :completed) }
it 'retries on transient errors' do
allow(EmailService).to receive(:send_confirmation)
.and_raise(EmailService::TimeoutError)
.then_return(true)
expect(EmailService).to receive(:send_confirmation).twice
described_class.perform_now(order.id, order.customer_email, order.total)
end
it 'discards on permanent errors' do
allow(EmailService).to receive(:send_confirmation)
.and_raise(EmailService::InvalidEmailError)
expect(EmailService).to receive(:send_confirmation).once
expect { described_class.perform_now(order.id, "invalid-email", order.total) }.not_to raise_error
end
it 'logs retry attempts' do
allow(EmailService).to receive(:send_confirmation)
.and_raise(EmailService::TimeoutError)
expect(Rails.logger).to receive(:error).with(/Email service error/)
described_class.perform_now(order.id, order.customer_email, order.total)
end
end
Example Monitoring Setup:
# app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base
around_perform do |job, block|
start_time = Time.current
block.call
duration = Time.current - start_time
# Track job metrics
StatsD.timing("jobs.#{job.class.name.underscore}.duration", duration)
StatsD.increment("jobs.#{job.class.name.underscore}.success")
rescue StandardError => e
StatsD.increment("jobs.#{job.class.name.underscore}.failure")
raise
end
end
| Predecessor | This Workflow | Successor | |-------------|---------------|-----------| | implement-background-job | background-job | production-monitoring | | tdd | background-job | quality | | None (standalone) | background-job | deployment |
implement-background-jobimplement-background-job firstNEVER deploy background job to production before:
If gate fails: Job is not production-ready. Address issues before deployment.
If job fails repeatedly in production:
If queue backs up:
# Background Job Implementation Report — [Date]
## Job
- **Name:** OrderConfirmationEmailJob
- **Purpose:** Send order confirmation emails
- **Trigger:** Order.status = 'completed'
- **Queue:** default
## Design
- **Idempotency:** ✓ Implemented (email_sent_at check)
- **Error Classification:** ✓ Complete
- **Transient Errors:** Timeout, RateLimit (retry)
- **Permanent Errors:** RecordNotFound, InvalidEmail (discard)
## Implementation
- **Job Tests:** 3/3 passing
- **Idempotency Tests:** ✓ PASS
- **Failure Scenario Tests:** ✓ PASS
- **Total Coverage:** 95%
## Configuration
- **Retry Strategy:** ✓ Configured (exponential backoff, 5 attempts)
- **Discard Strategy:** ✓ Configured (permanent errors)
- **Timeouts:** ✓ Configured (30 seconds)
- **Monitoring:** ✓ Configured (StatsD metrics)
- **Workers:** ✓ Configured (2 processes, 5 threads each)
## Performance
- **Execution Time:** 1.2 seconds (acceptable)
- **Throughput:** 100 jobs/minute
- **Concurrent Jobs:** ✓ Tested (10 concurrent jobs)
- **Load Test:** ✓ PASS
## Status
**PRODUCTION READY** — All failure scenarios tested, monitoring configured
development
Entry point for Rails development workflows covering TDD, RSpec, Service Objects, DDD, GraphQL, Engines, and Code Quality. Use when the user asks about Ruby on Rails development patterns, needs RSpec test suites generated, wants service objects scaffolded, is setting up GraphQL schemas, performing Rails code review, refactoring .rb files, working with domain-driven design, implementing background jobs, conducting Rails security checks, or building Rails engines. Generates RSpec tests, structures service objects, enforces TDD workflows, configures GraphQL schemas, and coordinates domain-driven design patterns. Trigger keywords: Rails, RSpec, TDD, Rails testing, Rails refactor, Rails API, Rails code review, domain driven design, service objects, GraphQL, Rails engine, Ruby, .rb, background jobs, Rails migrations, Rails security check.
development
Use when shipping a Rails engine gem — FIRST run full test suite (`bundle exec rspec`) and fix ALL failures, verify gemspec metadata and dependencies match tested Rails/Ruby versions, dry-run: `gem build *.gemspec && gem push --dry-run *.gem` and verify contents, generate CHANGELOG.md organized by category (added/changed/deprecated/removed/fixed), produce step-by-step upgrade notes with before/after code, set semantic version in `lib/[engine_name]/version.rb`, document deprecations with migration paths, load release assets conditionally and state which one informed the output. Trigger words: version bump, changelog, deprecation, gemspec, upgrade, release, publish gem, ship gem.
development
Orchestrates the full Rails TDD cycle with hard gates: test MUST exist, be run, and FAIL for the correct reason (e.g. undefined method, not syntax error) before any implementation code — propose minimal implementation and wait for user approval → verify test PASSES → run full suite with rubocop, brakeman, rspec all green → produce YARD documentation and self-reviewed PR; phases context/test design→implementation→iterate→finish. Use when practicing test-driven development, red-green-refactor, TDD workflow, writing tests before code, adding tests first, or building a Rails feature where specs must gate implementation.
development
Complete Rails project setup loop with hard gates: verify Ruby version matches .ruby-version, Bundler installed, database connection successful, all env vars loaded, and ALL external CI actions pinned to immutable commit SHAs (never mutable tags like @v4) → configure CI/CD pipeline with linting, testing, and security scanning → validate end-to-end with bundle install, db:create, db:migrate, rspec, and write SETUP_CHECKLIST.md; phases context/onboarding→CI/CD configuration→environment validation. Use when starting a new Rails project, running `rails new`, configuring a Gemfile or .ruby-version, setting up a development environment, or wiring up CI/CD for a Ruby on Rails app. Trigger: setup project, new Rails app, configure CI/CD, dev environment setup, rails new, Gemfile setup, .ruby-version, Ruby on Rails project bootstrap.