redis/redis-py · error · ConnectionError
Invalid Database
Error message
Invalid Database
What it means
Raised in on_connect (connection.py:1237-1240) when db is set and the SELECT reply is not 'OK'. After authenticating, the library issues SELECT <db> to move to the configured logical database; a non-OK reply means the database index is invalid or unavailable, so the connection is aborted rather than silently running on db 0.
Solutions
- Use a db index within [0, databases-1] (default 0-15).
- Check CONFIG GET databases on the server and lower your db index accordingly.
- Omit db to default to 0.
- Prefer separate Redis instances/key prefixes over high db indexes.
Example fix
# before r = redis.Redis(host=h, port=p, db=20) # after r = redis.Redis(host=h, port=p, db=10) # within 0-15
Defensive patterns
Strategy: validation
Validate before calling
def resolve_db(raw, max_dbs=16):
db = int(raw)
if not (0 <= db < max_dbs):
raise ValueError(f'db must be in [0,{max_dbs-1}], got {db}')
return db
# optionally read the server limit:
maxdbs = redis.Redis(host=h, port=p).config_get('databases').get('databases', 16)
r = redis.Redis(host=h, port=p, db=resolve_db(raw_db, int(maxdbs))) Type guard
def is_valid_db(v, max_dbs=16) -> bool:
try:
return 0 <= int(v) < max_dbs
except (TypeError, ValueError):
return False Try / catch
from redis.exceptions import ConnectionError
try:
r = redis.Redis(host=h, port=p, db=db_index)
r.ping()
except ConnectionError as e:
if 'Invalid Database' in str(e):
r = redis.Redis(host=h, port=p, db=0) # safe default
else:
raise Prevention
- Validate db against the server's 'databases' config before connecting.
- Default to db 0 and use key-prefixing for namespacing instead of high indexes.
- Re-check db bounds after changing redis.conf.
When it happens
Trigger: Passing db=16 (or any index >= the configured number of databases) — default Redis ships 16 databases (0-15); passing a negative db; a server configured with fewer databases than the requested index.
Common situations: Migrating from another system with more logical DBs; typo in db index; reducing 'databases' in redis.conf without updating clients.
Related errors
- Error setting client name
- Cache must implement CacheInterface
- Cannot enable maintenance notifications for connection…
- Invalid SSL Certificate Requirements Flag
- Invalid ssl verify flag
AI-assisted analysis of redis/redis-py@6a6b581b48 (2026-08-10).
Data as JSON: /api/errors/09a15ae9d7c80ae6.
Report an issue: GitHub.
Appendix: source
Thrown at redis/connection.py:1240
try:
if self.driver_info and self.driver_info.lib_version:
self.send_command(
"CLIENT",
"SETINFO",
"LIB-VER",
self.driver_info.lib_version,
check_health=check_health,
)
self.read_response()
except ResponseError:
pass
# if a database is specified, switch to it
if self.db:
self.send_command("SELECT", self.db, check_health=check_health)
if str_if_bytes(self.read_response()) != "OK":
raise ConnectionError("Invalid Database")
def disconnect(self, *args, **kwargs):
"Disconnects from the Redis server"
# The server session is gone, so any HIMPORT fieldsets prepared on this
# socket no longer exist; reset the tracking.
self._reset_himport_state()
self._parser.on_disconnect()
conn_sock = self._sock
self._sock = None
# reset the reconnect flag
self.reset_should_reconnect()
if conn_sock is None:
return
if os.getpid() == self.pid:
try:View on GitHub (pinned to 6a6b581b48)