redis/redis-py · error · ConnectionError

Invalid Database

Error message

Invalid Database

What it means

Raised as a ConnectionError during on_connect() after sending 'SELECT <db>' (because self.db is set): the server's response was not 'OK'. This indicates the requested logical database index is invalid for the target server. The library refuses to use a connection that is not on the database you asked for, since subsequent commands would silently target the wrong keyspace.

Source

Thrown at redis/asyncio/connection.py:1064

                self.driver_info.lib_version,
                check_health=check_health,
            )
            lib_version_sent = True

        # if a database is specified, switch to it. Also pipeline this
        if self.db:
            await self.send_command("SELECT", self.db, check_health=check_health)

        # read responses from pipeline
        for _ in range(sum([lib_name_sent, lib_version_sent])):
            try:
                await self.read_response()
            except ResponseError:
                pass

        if self.db:
            if str_if_bytes(await self.read_response()) != "OK":
                raise ConnectionError("Invalid Database")

    async def disconnect(
        self,
        nowait: bool = False,
        error: Optional[Exception] = None,
        failure_count: Optional[int] = None,
        health_check_failed: bool = False,
    ) -> None:
        """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()
        # On Python 3.13+, asyncio.timeout() raises RuntimeError when called
        # outside a running Task (e.g. during GC finalization or event-loop
        # callbacks).  In that context we fall back to a synchronous close.
        # See https://github.com/redis/redis-py/issues/3856
        if asyncio.current_task() is None:
            self._parser.on_disconnect()

View on GitHub (pinned to da03cdc7e8)

Solutions

  1. Set db to a valid index (0 by default, or 0..databases-1) for the target server.
  2. For Redis Cluster, use db=0 only; cluster topology forbids other databases.
  3. Increase the server's 'databases N' directive in redis.conf and restart if you genuinely need a higher index.
  4. Remove the /<db> path component from the connection URL.

Example fix

// before
r = redis.asyncio.from_url("redis://host:6379/99")

// after
r = redis.asyncio.from_url("redis://host:6379/0")
Defensive patterns

Strategy: validation

Validate before calling

MAX_DBS = 16  # default; read CONFIG GET databases from server for accuracy
def valid_db(db: int, server_databases: int = MAX_DBS) -> bool:
    return 0 <= db < server_databases

Type guard

def is_valid_db(value) -> bool:
    return isinstance(value, int) and value >= 0

Try / catch

from redis.exceptions import ConnectionError
try:
    await r.ping()
except ConnectionError as e:
    if "Invalid Database" in str(e):
        r = redis.asyncio.Redis(..., db=0)
    else:
        raise

Prevention

When it happens

Trigger: Opening a connection where db is non-zero (Redis(url='redis://host:port/15'), Redis(db=9)) against a server with fewer databases; SELECT returns an error like 'ERR invalid DB index'. The check at line 1063 fires when read_response() != 'OK'.

Common situations: Configuring db higher than the server's 'databases' directive (default 16, indexes 0-15); pointing a db=N config at a Redis Cluster node (cluster mode only allows db 0); a Redis-compatible server with a single database; URL paths like redis://host/99.

Related errors


AI-assisted analysis of redis/redis-py@da03cdc7e8 (2026-08-04). Data as JSON: /data/errors/fdb0f06f8c8f8a36.json. Report an issue: GitHub.