{"record":{"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/6a6b581b48225afa0b76912d1028c6035baee932/redis/asyncio/connection.py#L1046-L1082","documentation":"Raised as ConnectionError during on_connect() when SELECT <db> returns a non-OK reply, meaning the server refused the database switch. The library only sends SELECT when self.db is truthy (non-zero). The most frequent cause is requesting a database index that does not exist on the server.","triggerScenarios":"Constructing redis.asyncio.Redis(host=h, db=15) (or from_url('redis://host/15')) against a server configured with fewer than 16 databases, or a Redis Cluster target where SELECT to a non-zero db is not permitted.","commonSituations":"Default redis.conf databases=16 but user sets db=20; connecting to a managed Redis (cluster) that only allows db 0; leftover /N path in a copied URL pointing at an index the new provider does not have.","solutions":["Use db=0 (the only supported index on Redis Cluster and most managed providers).","Raise CONFIG SET databases N / the 'databases' directive in redis.conf and restart, if you genuinely need a higher index on standalone Redis.","Remove the /<db> path component from the connection URL.","If sharding by db is required, switch to multiple client instances each pointing at db 0 on different deployments."],"exampleFix":"// before\nr = redis.asyncio.from_url('redis://host:6379/20')\n// after\nr = redis.asyncio.from_url('redis://host:6379/0')","handlingStrategy":"validation","validationCode":"def safe_db(db: int, max_databases: int = 16) -> int:\n    if db < 0 or db >= max_databases:\n        return 0\n    return db","typeGuard":"from redis.exceptions import ConnectionError\n\ndef is_invalid_db(exc: BaseException) -> bool:\n    return isinstance(exc, ConnectionError) and 'invalid database' in str(exc).lower()","tryCatchPattern":"from redis.exceptions import ConnectionError\n\ntry:\n    await client.select(db)\nexcept ConnectionError as e:\n    if 'invalid database' in str(e).lower():\n        await client.select(0)\n    else:\n        raise","preventionTips":["Use db=0 with Redis Cluster and managed providers.","Match CONFIG databases in redis.conf to the highest index you use.","Strip /<db> from copied URLs when switching providers."],"tags":["database","select","connection","async","handshake","cluster"],"backgroundTag":null,"analyzedSha":"6a6b581b48225afa0b76912d1028c6035baee932","analyzedAt":"2026-08-10T12:52:44.840Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-21T04:17:39.646Z"}