{"id":"fdb0f06f8c8f8a36","repo":"redis/redis-py","slug":"invalid-database","errorCode":null,"errorMessage":"Invalid Database","messagePattern":"Invalid Database","errorType":"exception","errorClass":"ConnectionError","httpStatus":null,"severity":"error","filePath":"redis/asyncio/connection.py","lineNumber":1064,"sourceCode":"                self.driver_info.lib_version,\n                check_health=check_health,\n            )\n            lib_version_sent = True\n\n        # if a database is specified, switch to it. Also pipeline this\n        if self.db:\n            await self.send_command(\"SELECT\", self.db, check_health=check_health)\n\n        # read responses from pipeline\n        for _ in range(sum([lib_name_sent, lib_version_sent])):\n            try:\n                await self.read_response()\n            except ResponseError:\n                pass\n\n        if self.db:\n            if str_if_bytes(await self.read_response()) != \"OK\":\n                raise ConnectionError(\"Invalid Database\")\n\n    async def disconnect(\n        self,\n        nowait: bool = False,\n        error: Optional[Exception] = None,\n        failure_count: Optional[int] = None,\n        health_check_failed: bool = False,\n    ) -> None:\n        \"\"\"Disconnects from the Redis server\"\"\"\n        # The server session is gone, so any HIMPORT fieldsets prepared on this\n        # socket no longer exist; reset the tracking.\n        self._reset_himport_state()\n        # On Python 3.13+, asyncio.timeout() raises RuntimeError when called\n        # outside a running Task (e.g. during GC finalization or event-loop\n        # callbacks).  In that context we fall back to a synchronous close.\n        # See https://github.com/redis/redis-py/issues/3856\n        if asyncio.current_task() is None:\n            self._parser.on_disconnect()","sourceCodeStart":1046,"sourceCodeEnd":1082,"githubUrl":"https://github.com/redis/redis-py/blob/da03cdc7e8731092b13e395605c3c1fb2de25de1/redis/asyncio/connection.py#L1046-L1082","documentation":"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.","triggerScenarios":"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'.","commonSituations":"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.","solutions":["Set db to a valid index (0 by default, or 0..databases-1) for the target server.","For Redis Cluster, use db=0 only; cluster topology forbids other databases.","Increase the server's 'databases N' directive in redis.conf and restart if you genuinely need a higher index.","Remove the /<db> path component from the connection URL."],"exampleFix":"// before\nr = redis.asyncio.from_url(\"redis://host:6379/99\")\n\n// after\nr = redis.asyncio.from_url(\"redis://host:6379/0\")","handlingStrategy":"validation","validationCode":"MAX_DBS = 16  # default; read CONFIG GET databases from server for accuracy\ndef valid_db(db: int, server_databases: int = MAX_DBS) -> bool:\n    return 0 <= db < server_databases","typeGuard":"def is_valid_db(value) -> bool:\n    return isinstance(value, int) and value >= 0","tryCatchPattern":"from redis.exceptions import ConnectionError\ntry:\n    await r.ping()\nexcept ConnectionError as e:\n    if \"Invalid Database\" in str(e):\n        r = redis.asyncio.Redis(..., db=0)\n    else:\n        raise","preventionTips":["Use db=0 for Redis Cluster.","Confirm server 'databases' directive before using a high index.","Avoid non-zero db unless you manage multiple keyspaces on one server."],"tags":["connection","handshake","database","config","async"],"analyzedSha":"da03cdc7e8731092b13e395605c3c1fb2de25de1","analyzedAt":"2026-08-04T20:26:47.563Z","schemaVersion":2}