How to Fix Redis Connection Error in Python
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 pingbefore connecting. - Set
socket_connect_timeoutto avoid hanging. - Use connection pooling for production applications.
- Set
decode_responses=Trueto get strings instead of bytes. - Handle
RedisErrorand its subclasses in production code.
Common Mistakes with redis error
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[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
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro