{
  "schema_version": 2,
  "id": "develop/clients/redis-py/connect",
  "title": "Connect to the server",
  "url": "https://redis.io/docs/latest/develop/clients/redis-py/connect/",
  "summary": "Connect your Python application to a Redis database",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-10-12T14:48:04+01:00",
  "page_type": "content",
  "content_hash": "cb30d74eaf324ee40dcfff85dc628bf4e6a5b51b271ef37941d2c66b4d869312",
  "sections": [
    {
      "id": "basic-connection",
      "title": "Basic connection",
      "role": "overview",
      "text": "Connect to localhost on port 6379, set a value in Redis, and retrieve it. All responses are returned as bytes in Python. To receive decoded strings, set `decode_responses=True`. For more connection options, see [these examples](https://redis.readthedocs.io/en/stable/examples.html).\n\n[code example]\n\n> [!NOTE]\n> redis-py supports [connection URLs](https://redis.io/docs/latest/develop/clients/connection-urls#redis-py-python) through `redis.from_url()`.\n> A URL can set the host, port, credentials, database, and whether to use TLS,\n> so you can use one instead of passing those options separately.\n\nStore and retrieve a simple string.\n\n[code example]\n\nStore and retrieve a dict.\n\n[code example]"
    },
    {
      "id": "connect-to-a-redis-cluster",
      "title": "Connect to a Redis cluster",
      "role": "content",
      "text": "To connect to a Redis cluster, use `RedisCluster`.\n\n[code example]\nFor more information, see [redis-py Clustering](https://redis.readthedocs.io/en/stable/clustering.html)."
    },
    {
      "id": "connect-to-redis-sentinel",
      "title": "Connect to Redis Sentinel",
      "role": "content",
      "text": "To connect through [Redis Sentinel](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel),\ncreate a `Sentinel` object with a list of Sentinel addresses. Then call `master_for()` with\nthe name of the primary that the Sentinels monitor. The client asks the Sentinels for the\ncurrent address of the primary.\n\n[code example]\n\nThe Sentinels and the data nodes have separate credentials. Pass the Sentinel credentials\nin `sentinel_kwargs`, and the credentials for the primary and replicas to `master_for()`:\n\n[code example]\n\nIf you set `sentinel_kwargs`, the Sentinel connections don't inherit `socket_timeout` or the\nother `socket_*` options, so add any that you need to `sentinel_kwargs`.\n\nTo send read-only commands to a replica, use `slave_for()`. Replication is asynchronous, so\na replica can return stale data.\n\n[code example]\n\nredis-py doesn't listen for failover announcements from the Sentinels. After a failover,\nthe client keeps using the old primary until Sentinel reconfigures it as a replica and it\nstarts rejecting writes. Any writes that the old primary accepts during that time are lost."
    },
    {
      "id": "connect-to-your-production-redis-with-tls",
      "title": "Connect to your production Redis with TLS",
      "role": "content",
      "text": "When you deploy your application, use TLS and follow the [Redis security](https://redis.io/docs/latest/operate/oss_and_stack/management/security) guidelines.\n\n[code example]\nFor more information, see [redis-py TLS examples](https://redis.readthedocs.io/en/stable/examples/ssl_connection_examples.html)."
    },
    {
      "id": "connect-using-client-side-caching",
      "title": "Connect using client-side caching",
      "role": "content",
      "text": "Client-side caching is a technique to reduce network traffic between\nthe client and server, resulting in better performance. See\n[Client-side caching introduction](https://redis.io/docs/latest/develop/clients/client-side-caching)\nfor more information about how client-side caching works and how to use it effectively.\n\nTo enable client-side caching, add some extra parameters when you connect\nto the server:\n\n-   `protocol`: (Required) You must pass a value of `3` here because\n    client-side caching requires the [RESP3](https://redis.io/docs/latest/develop/reference/protocol-spec#resp-versions)\n    protocol.\n-   `cache_config`: (Required) Pass `cache_config=CacheConfig()` here to enable client-side caching.\n\nThe example below shows the simplest client-side caching connection to the default host and port,\n`localhost:6379`.\nAll of the connection variants described above accept these parameters, so you can\nuse client-side caching with a connection pool or a cluster connection in exactly the same way.\n\n> [!NOTE]\n> Client-side caching requires redis-py v5.1.0 or later.\n> To maximize compatibility with all Redis products, client-side caching\n> is supported by Redis v7.4 or later.\n>\n> The [Redis server products](https://redis.io/docs/latest/operate) support\n> [opt-in/opt-out](https://redis.io/docs/latest/develop/reference/client-side-caching#opt-in-and-opt-out-caching) mode\n> and [broadcasting mode](https://redis.io/docs/latest/develop/reference/client-side-caching#broadcasting-mode)\n> for CSC, but these modes are not currently implemented by `redis-py`.\n\n[code example]\n\nYou can see the cache working if you connect to the same Redis database\nwith [`redis-cli`](https://redis.io/docs/latest/develop/tools/cli) and run the\n[`MONITOR`](https://redis.io/docs/latest/commands/monitor) command. If you run the\ncode above with the `cache_config` line commented out, you should see\nthe following in the CLI among the output from `MONITOR`:\n\n[code example]\n\nThe server responds to both `get(\"city\")` calls.\nIf you run the code again with `cache_config` uncommented, you will see\n\n[code example]\n\nThe first `get(\"city\")` call contacted the server but the second\ncall was satisfied by the cache."
    },
    {
      "id": "removing-items-from-the-cache",
      "title": "Removing items from the cache",
      "role": "content",
      "text": "You can remove individual keys from the cache with the\n`delete_by_redis_keys()` method. This removes all cached items associated\nwith the keys, so all results from multi-key commands (such as\n[`MGET`](https://redis.io/docs/latest/commands/mget)) and composite data structures\n(such as [hashes](https://redis.io/docs/latest/develop/data-types/hashes)) will be\ncleared at once. The example below shows the effect of removing a single\nkey from the cache:\n\n[code example]\n\nYou can also clear all cached items using the `flush()`\nmethod:\n\n[code example]\n\nThe client will also flush the cache automatically\nif any connection (including one from a connection pool)\nis disconnected."
    },
    {
      "id": "connect-with-a-connection-pool",
      "title": "Connect with a connection pool",
      "role": "content",
      "text": "For production usage, you should use a connection pool to manage\nconnections rather than opening and closing connections individually.\nA connection pool maintains several open connections and reuses them\nefficiently. When you open a connection from a pool, the pool allocates\none of its open connections. When you subsequently close the same connection,\nit is not actually closed but simply returned to the pool for reuse.\nThis avoids the overhead of repeated connecting and disconnecting.\nSee\n[Connection pools and multiplexing](https://redis.io/docs/latest/develop/clients/pools-and-muxing)\nfor more information.\n\nUse the following code to connect with a connection pool:\n\n[code example]"
    },
    {
      "id": "retrying-connections",
      "title": "Retrying connections",
      "role": "content",
      "text": "A connection will sometimes fail because of a transient problem, such as a\nnetwork outage or a server that is temporarily unavailable. In these cases,\nretrying the connection after a short delay will usually succeed. `redis-py` uses\na simple retry strategy by default, but there are various ways you can customize\nthis behavior to suit your use case. See\n[Retries](https://redis.io/docs/latest/develop/clients/redis-py/produsage#retries)\nfor more information about custom retry strategies, with example code."
    },
    {
      "id": "connect-using-smart-client-handoffs-sch",
      "title": "Connect using Smart client handoffs (SCH)",
      "role": "content",
      "text": "*Smart client handoffs (SCH)* is a feature of Redis Cloud and\nRedis Software servers that lets them actively notify clients\nabout planned server maintenance shortly before it happens. This\nlets a client take action to avoid disruptions in service.\nSee [Smart client handoffs](https://redis.io/docs/latest/develop/clients/sch)\nfor more information about SCH.\n\n> [!NOTE]\n> Using SCH with redis-py requires v7.0.0 or later for\n> standard routing, and v7.2.0 or later for\n> [OSS Cluster API](https://redis.io/docs/latest/operate/rs/databases/configure/oss-cluster-api) connections.\n\nBy default, `redis-py` always attempts to connect via SCH but falls back to\na non-SCH connection if the server doesn't support it. However, you can configure SCH\nexplicitly by passing a `MaintNotificationsConfig` object during the connection,\nas shown in the following example:\n\n[code example]\n\nTo disable SCH, pass `enabled=False` in the `MaintNotificationsConfig` object:\n\n[code example]\n\n> [!NOTE]\n> SCH requires the [RESP3](https://redis.io/docs/latest/develop/reference/protocol-spec#resp-versions)\n> protocol, so you must set `protocol=3` explicitly when you connect.\n\nThe `MaintNotificationsConfig` constructor accepts the following parameters:\n\n| Name | Type | Default | Description |\n|------|------|---------|-------------|\n| `enabled` | `bool` | `True` | Whether or not to enable SCH. |\n| `proactive_reconnect` | `bool` | `True` | Whether or not to automatically reconnect when a node is replaced. |\n| `endpoint_type` | `EndpointType` | Auto-detect | The type of endpoint to use for the connection. The options are `EndpointType.EXTERNAL_IP`, `EndpointType.INTERNAL_IP`, `EndpointType.EXTERNAL_FQDN`, `EndpointType.INTERNAL_FQDN`, and `EndpointType.NONE`. |\n| `relaxed_timeout` | `int` | `20` | The timeout (in seconds) to use while the server is performing maintenance. A value of `-1` disables the relax timeout and just uses the normal timeout during maintenance. |\n\n> [!NOTE]\n> Redis Cloud supports relaxed timeouts *only* (and not pre-handoffs) for SCH if you are using\n> either [AWS PrivateLink](https://redis.io/docs/latest/operate/rc/security/aws-privatelink) or\n> [Google Cloud Private Service Connect](https://redis.io/docs/latest/operate/rc/security/private-service-connect)\n> (see [Smart client handoffs](https://redis.io/docs/latest/develop/clients/sch#redis-cloud) for more information).\n> To use relaxed timeouts with these services, you should set `endpoint_type=EndpointType.NONE`\n> when you connect. All other configurations have full support for both relaxed timeouts and pre-handoffs."
    }
  ],
  "examples": [
    {
      "id": "basic-connection-ex0",
      "language": "python",
      "code": "r = redis.Redis(host='localhost', port=6379, decode_responses=True)",
      "section_id": "basic-connection"
    },
    {
      "id": "basic-connection-ex1",
      "language": "python",
      "code": "r.set('foo', 'bar')\n# True\nr.get('foo')\n# bar",
      "section_id": "basic-connection"
    },
    {
      "id": "basic-connection-ex2",
      "language": "python",
      "code": "r.hset('user-session:123', mapping={\n    'name': 'John',\n    \"surname\": 'Smith',\n    \"company\": 'Redis',\n    \"age\": 29\n})\n# True\n\nr.hgetall('user-session:123')\n# {'surname': 'Smith', 'name': 'John', 'company': 'Redis', 'age': '29'}",
      "section_id": "basic-connection"
    },
    {
      "id": "connect-to-a-redis-cluster-ex0",
      "language": "python",
      "code": "from redis.cluster import RedisCluster\n\nrc = RedisCluster(host='localhost', port=16379)\n\nprint(rc.get_nodes())\n# [[host=127.0.0.1,port=16379,name=127.0.0.1:16379,server_type=primary,redis_connection=Redis<ConnectionPool<Connection<host=127.0.0.1,port=16379,db=0>>>], ...\n\nrc.set('foo', 'bar')\n# True\n\nrc.get('foo')\n# b'bar'",
      "section_id": "connect-to-a-redis-cluster"
    },
    {
      "id": "connect-to-redis-sentinel-ex0",
      "language": "python",
      "code": "from redis.sentinel import Sentinel\n\nsentinel = Sentinel([('localhost', 26379), ('localhost', 26380), ('localhost', 26381)])\nr = sentinel.master_for('mymaster', decode_responses=True)\n\nr.set('foo', 'bar')\n# True\n\nr.get('foo')\n# bar",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-redis-sentinel-ex1",
      "language": "python",
      "code": "from redis.sentinel import Sentinel\n\nsentinel = Sentinel(\n    [('localhost', 26379), ('localhost', 26380), ('localhost', 26381)],\n    sentinel_kwargs={'password': 'sentinel-secret'},  # use your Sentinel password\n)\nr = sentinel.master_for(\n    'mymaster',\n    username='default',  # use your Redis user\n    password='secret',  # use your Redis password\n    decode_responses=True,\n)",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-redis-sentinel-ex2",
      "language": "python",
      "code": "replica = sentinel.slave_for('mymaster', decode_responses=True)\n\nreplica.get('foo')\n# bar",
      "section_id": "connect-to-redis-sentinel"
    },
    {
      "id": "connect-to-your-production-redis-with-tls-ex0",
      "language": "python",
      "code": "import redis\n\nr = redis.Redis(\n    host=\"my-redis.cloud.redislabs.com\", port=6379,\n    username=\"default\", # use your Redis user. More info https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/\n    password=\"secret\", # use your Redis password\n    ssl=True,\n    ssl_certfile=\"./redis_user.crt\",\n    ssl_keyfile=\"./redis_user_private.key\",\n    ssl_ca_certs=\"./redis_ca.pem\",\n)\nr.set('foo', 'bar')\n# True\n\nr.get('foo')\n# b'bar'",
      "section_id": "connect-to-your-production-redis-with-tls"
    },
    {
      "id": "connect-using-client-side-caching-ex0",
      "language": "python",
      "code": "import redis\nfrom redis.cache import CacheConfig\n\nr = redis.Redis(\n    protocol=3,\n    cache_config=CacheConfig(),\n    decode_responses=True\n)\n\nr.set(\"city\", \"New York\")\ncityNameAttempt1 = r.get(\"city\")    # Retrieved from Redis server and cached\ncityNameAttempt2 = r.get(\"city\")    # Retrieved from cache",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex1",
      "language": "plaintext",
      "code": "1723109720.268903 [...] \"SET\" \"city\" \"New York\"\n1723109720.269681 [...] \"GET\" \"city\"\n1723109720.270205 [...] \"GET\" \"city\"",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "connect-using-client-side-caching-ex2",
      "language": "plaintext",
      "code": "1723110248.712663 [...] \"SET\" \"city\" \"New York\"\n1723110248.713607 [...] \"GET\" \"city\"",
      "section_id": "connect-using-client-side-caching"
    },
    {
      "id": "removing-items-from-the-cache-ex0",
      "language": "python",
      "code": "r.hget(\"person:1\", \"name\") # Read from the server\nr.hget(\"person:1\", \"name\") # Read from the cache\n\nr.hget(\"person:2\", \"name\") # Read from the server\nr.hget(\"person:2\", \"name\") # Read from the cache\n\ncache = r.get_cache()\ncache.delete_by_redis_keys([\"person:1\"])\n\nr.hget(\"person:1\", \"name\") # Read from the server\nr.hget(\"person:1\", \"name\") # Read from the cache\n\nr.hget(\"person:2\", \"name\") # Still read from the cache",
      "section_id": "removing-items-from-the-cache"
    },
    {
      "id": "removing-items-from-the-cache-ex1",
      "language": "python",
      "code": "r.hget(\"person:1\", \"name\") # Read from the server\nr.hget(\"person:1\", \"name\") # Read from the cache\n\nr.hget(\"person:2\", \"name\") # Read from the cache\nr.hget(\"person:2\", \"name\") # Read from the cache\n\ncache = r.get_cache()\ncache.flush()\n\nr.hget(\"person:1\", \"name\") # Read from the server\nr.hget(\"person:1\", \"name\") # Read from the cache\n\nr.hget(\"person:2\", \"name\") # Read from the server\nr.hget(\"person:2\", \"name\") # Read from the cache",
      "section_id": "removing-items-from-the-cache"
    },
    {
      "id": "connect-with-a-connection-pool-ex0",
      "language": "python",
      "code": "import redis\n\npool = redis.ConnectionPool().from_url(\"redis://localhost\")\nr1 = redis.Redis().from_pool(pool)\nr2 = redis.Redis().from_pool(pool)\nr3 = redis.Redis().from_pool(pool)\n\nr1.set(\"wind:1\", \"Hurricane\")\nr2.set(\"wind:2\", \"Tornado\")\nr3.set(\"wind:3\", \"Mistral\")\n\nr1.close()\nr2.close()\nr3.close()\n\npool.close()",
      "section_id": "connect-with-a-connection-pool"
    },
    {
      "id": "connect-using-smart-client-handoffs-sch-ex0",
      "language": "py",
      "code": "import redis\nfrom redis.maint_notifications import MaintNotificationsConfig, EndpointType\n\nr = redis.Redis(\n    decode_responses=True,\n    protocol=3,\n    maint_notifications_config=MaintNotificationsConfig(\n        proactive_reconnect=True,\n        relaxed_timeout=10,\n        endpoint_type=EndpointType.EXTERNAL_IP\n    ),\n    ...\n)",
      "section_id": "connect-using-smart-client-handoffs-sch"
    },
    {
      "id": "connect-using-smart-client-handoffs-sch-ex1",
      "language": "python",
      "code": "r = redis.Redis(\n    maint_notifications_config=MaintNotificationsConfig(\n        enabled=False,\n    ),\n    ...\n)",
      "section_id": "connect-using-smart-client-handoffs-sch"
    }
  ]
}
