Fix Sidekiq::Shutdown: Sidekiq worker killed due to excessive memory usage (RSS: 1.2GB) in Sidekiq
This error means your Sidekiq process consumed too much memory and was killed. Memory leaks in Sidekiq jobs are often caused by accumulating objects in class variables, not releasing large data structures, or loading too many records without batching. Use tools like derailed_benchmarks to profile memory and ensure jobs release resources after processing.
Reading the Stack Trace
Here's what each line means:
- sidekiq (7.2.1) lib/sidekiq/manager.rb:95:in `check_memory': Sidekiq's memory watchdog detected the process exceeded the configured memory limit.
- app/jobs/report_generation_job.rb:35:in `perform': The report generation job accumulates data in memory without releasing it.
- sidekiq (7.2.1) lib/sidekiq/processor.rb:88:in `kill': The processor kills the current job and signals the worker for shutdown.
Common Causes
1. Accumulating data in instance variable
A job stores processed data in an instance variable that grows with each iteration.
class ReportGenerationJob
include Sidekiq::Job
def perform
@results = []
Order.find_each do |order|
@results << build_report_row(order) # Grows unbounded
end
save_report(@results)
end
end
2. Class-level cache never cleared
A class variable caches data across job executions and never gets cleared.
class DataProcessingJob
include Sidekiq::Job
@@cache = {}
def perform(key)
@@cache[key] = expensive_computation(key) # Grows forever
end
end
3. Large file read into memory
The job reads an entire large file into a string without streaming.
class ImportJob
include Sidekiq::Job
def perform(file_url)
content = URI.open(file_url).read # Reads entire file into memory
process(content)
end
end
The Fix
Stream report data to a temporary file instead of accumulating it in memory. Use find_each with a batch size to limit how many records are loaded at once. The temp file is automatically cleaned up after the block.
class ReportGenerationJob
include Sidekiq::Job
def perform
@results = []
Order.find_each do |order|
@results << build_report_row(order)
end
save_report(@results)
end
end
class ReportGenerationJob
include Sidekiq::Job
def perform
Tempfile.create(['report', '.csv']) do |file|
csv = CSV.new(file)
csv << report_headers
Order.find_each(batch_size: 500) do |order|
csv << build_report_row(order)
end
file.rewind
upload_report(file)
end
end
end
Testing the Fix
require 'rails_helper'
require 'sidekiq/testing'
RSpec.describe ReportGenerationJob do
before { Sidekiq::Testing.inline! }
it 'generates report without excessive memory' do
create_list(:order, 10)
before_memory = GetProcessMem.new.mb
ReportGenerationJob.perform_async
after_memory = GetProcessMem.new.mb
expect(after_memory - before_memory).to be < 50
end
it 'produces a valid CSV report' do
create_list(:order, 5)
expect_any_instance_of(ReportGenerationJob).to receive(:upload_report)
ReportGenerationJob.perform_async
end
end
Run your tests:
bundle exec rspec spec/jobs/report_generation_job_spec.rb
Pushing Through CI/CD
git checkout -b fix/sidekiq-memory-leak,git add app/jobs/report_generation_job.rb,git commit -m "fix: stream report to file to prevent memory leak in Sidekiq job",git push origin fix/sidekiq-memory-leak
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ['5432:5432']
redis:
image: redis:7
ports: ['6379:6379']
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: '3.3'
bundler-cache: true
- run: bin/rails db:setup
- run: bundle exec rspec
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
gem install bugstack
Step 2: Initialize
require 'bugstack'
Bugstack.init(api_key: ENV['BUGSTACK_API_KEY'])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Refactor jobs to stream data instead of accumulating in memory.
- Remove class-level caches or add size limits.
- Profile memory usage with get_process_mem.
- Open a pull request.
- Merge and monitor Sidekiq RSS in production.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other components are affected before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Use the get_process_mem gem or check RSS via /proc/self/status on Linux. Sidekiq Enterprise includes built-in memory monitoring.
You can use sidekiq-cron or a process manager to restart workers that exceed a memory threshold. However, fixing the root cause is better than periodic restarts.