Skip to content

How to Fix Redis Connection Error in Python

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about How to Fix Redis Connection Error in Python. We cover key concepts, practical examples, and best practices.

Python Redis client raises ConnectionError or RedisError when the client cannot connect to the Redis server.

The Wrong Way

import redis

r = redis.Redis(host="localhost", port=6379)
r.set("key", "value")

This produces:

redis.exceptions.ConnectionError: Error 111 connecting to localhost:6379. Connection refused.

The Right Way

Check the connection and add error handling:

import redis
from redis.exceptions import ConnectionError

try:
    r = redis.Redis(host="localhost", port=6379, socket_connect_timeout=3)
    r.ping()  # test the connection
    print("Connected to Redis")
except ConnectionError:
    print("Cannot connect to Redis -- is the server running?")

Step-by-Step Fix

1. Verify Redis is running

redis-cli ping
# Should return PONG

2. Use a connection URL

import redis

redis_url = "redis://localhost:6379/0"
r = redis.from_url(redis_url, socket_timeout=5)

try:
    r.ping()
    print("Connected")
except redis.ConnectionError:
    print("Connection failed")

3. Handle authentication

import redis

try:
    r = redis.Redis(
        host="localhost",
        port=6379,
        password="your_password",
        decode_responses=True
    )
    r.ping()
except redis.AuthenticationError:
    print("Wrong password")
except redis.ConnectionError:
    print("Cannot connect")

4. Use a connection pool

import redis

pool = redis.ConnectionPool(
    host="localhost",
    port=6379,
    max_connections=10,
    socket_timeout=5
)

r = redis.Redis(connection_pool=pool)
try:
    r.set("key", "value")
    print(r.get("key"))
except redis.RedisError as e:
    print(f"Redis error: {e}")

5. Retry on connection failure

import time
import redis

def connect_redis(retries=3, delay=1):
    for attempt in range(retries):
        try:
            r = redis.Redis(host="localhost", port=6379, socket_timeout=5)
            r.ping()
            return r
        except redis.ConnectionError:
            if attempt < retries - 1:
                time.sleep(delay)
            else:
                raise

Prevention Tips

  • Verify Redis is running with redis-cli ping before connecting.
  • Set socket_connect_timeout to avoid hanging.
  • Use connection pooling for production applications.
  • Set decode_responses=True to get strings instead of bytes.
  • Handle RedisError and its subclasses in production code.

Common Mistakes with redis error

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What does "Connection refused" mean for Redis?

The Redis server is not running on the specified host and port. Start Redis with redis-server or check the service status. Also verify that bind and protected-mode settings allow connections.

How do I connect to Redis over SSL?

Use redis.Redis(host='...', port=6380, ssl=True, ssl_ca_certs='/path/to/ca.pem'). Some Redis cloud services use port 6380 for SSL connections with a different CA certificate.

What is the difference between StrictRedis and Redis?

StrictRedis and Redis are the same class in modern redis-py. StrictRedis was the original class name. Redis is now an alias. Use redis.Redis() for all new code.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro