Fix Redis::CannotConnectError: Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED) in Rails
This error means your Rails application cannot connect to the Redis server. Redis may not be running, the connection URL may be wrong, or the server is overloaded. Start Redis with redis-server, verify the connection URL in your configuration, and check that the Redis port is accessible from your application server.
Reading the Stack Trace
Here's what each line means:
- redis (5.1.0) lib/redis/client.rb:68:in `connect': The Redis gem is unable to establish a TCP connection to the Redis server.
- redis (5.1.0) lib/redis/client.rb:34:in `establish_connection': The connection attempt fails with ECONNREFUSED, meaning the server is not listening on the expected port.
- actionpack (7.1.3) lib/action_dispatch/middleware/session/cache_store.rb:55:in `get_session': Rails is trying to use Redis as a session store but cannot connect.
Common Causes
1. Redis server not running
The Redis service is not started on the machine or container.
# Redis is not running
# $ redis-cli ping
# Could not connect to Redis at 127.0.0.1:6379: Connection refused
2. Wrong Redis URL in configuration
The application is configured with an incorrect Redis host, port, or URL.
# config/initializers/redis.rb
$redis = Redis.new(host: 'localhost', port: 6380) # Wrong port, Redis is on 6379
3. Redis connection pool exhausted
Too many connections are open and the pool is full.
# config/initializers/redis.rb
$redis = ConnectionPool.new(size: 2) { Redis.new } # Pool too small for concurrent requests
The Fix
Use the REDIS_URL environment variable for configuration and add timeout and reconnection settings. This makes the connection configurable per environment and more resilient to transient failures.
# config/initializers/redis.rb
$redis = Redis.new(host: 'localhost', port: 6380)
# config/initializers/redis.rb
$redis = Redis.new(
url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0'),
connect_timeout: 5,
read_timeout: 1,
write_timeout: 1,
reconnect_attempts: 3
)
Testing the Fix
require 'rails_helper'
RSpec.describe 'Redis connection' do
it 'connects to Redis successfully' do
expect { Redis.new(url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0')).ping }.not_to raise_error
end
it 'returns PONG on ping' do
redis = Redis.new(url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0'))
expect(redis.ping).to eq('PONG')
end
it 'handles connection failure gracefully' do
bad_redis = Redis.new(url: 'redis://localhost:9999/0', connect_timeout: 1)
expect { bad_redis.ping }.to raise_error(Redis::CannotConnectError)
end
end
Run your tests:
bundle exec rspec spec/integration/redis_spec.rb
Pushing Through CI/CD
git checkout -b fix/rails-redis-connection,git add config/initializers/redis.rb,git commit -m "fix: use REDIS_URL env var with timeout and reconnect settings",git push origin fix/rails-redis-connection
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)
- Ensure Redis is running and accessible.
- Set the REDIS_URL environment variable.
- Run integration specs to verify the connection.
- Open a pull request.
- Merge and verify Redis connectivity in staging.
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.
Each Puma worker opens connections based on your pool size. A typical setup needs pool_size * puma_workers connections. Monitor with redis-cli info clients.
Redis supports data structures, persistence, and pub/sub. Memcached is simpler and faster for plain key-value caching. Use Redis if you also need it for ActionCable or Sidekiq.