{
  "id": "redis-py",
  "title": "Redis session store with redis-py",
  "url": "https://redis.io/docs/latest/develop/use-cases/session-store/redis-py/",
  "summary": "Implement a Redis-backed session store in Python with redis-py",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-04-16T13:29:55-07:00",
  "children": [],
  "page_type": "content",
  "content_hash": "5f234280e66fbaeb61a1d20e58eef333e5d137e2c1a0c0bb0dd4d9c394f522bf",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "This guide shows you how to implement a Redis-backed session store in Python with [`redis-py`](https://redis.io/docs/latest/develop/clients/redis-py). It includes a small local web server built with the Python standard library so you can see the session lifecycle end to end."
    },
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "Session storage is a common Redis use case for web applications. Instead of keeping session state in local process memory, you store it in Redis and send the browser only an opaque session ID in a cookie.\n\nThat gives you:\n\n* Shared sessions across multiple app servers\n* Automatic expiration using Redis TTLs\n* Fast reads and updates for small pieces of per-user state\n* A clean separation between browser cookies and server-side session data\n\nIn this example, each session is stored as a Redis hash with a key like `session:{session_id}`. The hash holds lightweight fields such as the username, page view count, timestamps, and the configured session TTL. The key also has an expiration so inactive sessions are removed automatically."
    },
    {
      "id": "how-it-works",
      "title": "How it works",
      "role": "content",
      "text": "The flow looks like this:\n\n1. A user submits a login form\n2. The server generates a random session ID with Python's `secrets` module\n3. The server stores session data in Redis under `session:{id}`\n4. The server sends a `sid` cookie containing only the session ID\n5. Later requests read the cookie, load the hash from Redis, and refresh the TTL\n6. Logging out deletes the Redis key and clears the cookie\n\nBecause the cookie only contains an opaque identifier, the browser never receives the actual session data. That stays in Redis."
    },
    {
      "id": "the-python-session-store",
      "title": "The Python session store",
      "role": "content",
      "text": "The `RedisSessionStore` class wraps the basic session operations\n([source](session_store.py)):\n\n[code example]"
    },
    {
      "id": "data-model",
      "title": "Data model",
      "role": "content",
      "text": "Each session is stored in a Redis hash:\n\n[code example]\n\nThe implementation uses:\n\n* [`HSET`](https://redis.io/docs/latest/commands/hset) to create and update session fields\n* [`HGETALL`](https://redis.io/docs/latest/commands/hgetall) to load the session\n* [`HINCRBY`](https://redis.io/docs/latest/commands/hincrby) to update counters\n* [`EXPIRE`](https://redis.io/docs/latest/commands/expire) to implement sliding expiration\n* [`DEL`](https://redis.io/docs/latest/commands/del) to remove a session on logout\n\nThe store treats `created_at`, `last_accessed_at`, and `session_ttl` as reserved internal fields, so caller-provided session data cannot overwrite them."
    },
    {
      "id": "session-store-implementation",
      "title": "Session store implementation",
      "role": "content",
      "text": "The `create_session()` method generates a random session ID, writes the initial hash fields, and sets the TTL:\n\n[code example]\n\nWhen the application reads a session, it refreshes the configured TTL so active users stay logged in:\n\n[code example]\n\nThis is a simple and effective pattern for many apps. For more complex requirements, you might add separate metadata keys, rotate session IDs after login, or store less frequently accessed data elsewhere."
    },
    {
      "id": "prerequisites",
      "title": "Prerequisites",
      "role": "content",
      "text": "Before running the demo, make sure that:\n\n* Redis is running and accessible. By default, the demo connects to `localhost:6379`.\n* The `redis` Python package is installed:\n\n[code example]\n\nIf your Redis server is running elsewhere, start the demo with `--redis-host` and `--redis-port`."
    },
    {
      "id": "running-the-demo",
      "title": "Running the demo",
      "role": "content",
      "text": "A local demo server is included to show the session store in action\n([source](demo_server.py)):\n\n[code example]\n\nThe demo server uses only Python standard library features for HTTP handling:\n\n* [`http.server`](https://docs.python.org/3/library/http.server.html) for the web server\n* [`http.cookies`](https://docs.python.org/3/library/http.cookies.html) for cookie parsing and response cookies\n* [`urllib.parse`](https://docs.python.org/3/library/urllib.parse.html) for form decoding\n\nIt exposes a small interactive page where you can:\n\n* Start a session with a username\n* Choose a short TTL and watch the session expire\n* See the Redis-backed session data rendered in the browser\n* Increment a page-view counter stored in Redis\n* Change the active session TTL from the page\n* Log out and delete the session\n\nAfter starting the server, visit `http://localhost:8080`."
    },
    {
      "id": "cookie-handling",
      "title": "Cookie handling",
      "role": "content",
      "text": "The browser cookie should contain only the session ID:\n\n[code example]\n\nAvoid storing user profiles, roles, or other sensitive session data directly in cookies. Keep that information in Redis and let the cookie act only as a lookup token."
    },
    {
      "id": "production-usage",
      "title": "Production usage",
      "role": "content",
      "text": "This guide uses a deliberately small local demo so you can focus on the Redis session pattern. In production, you will usually want to harden the cookie, session lifecycle, and deployment details around it."
    },
    {
      "id": "secure-the-session-cookie",
      "title": "Secure the session cookie",
      "role": "content",
      "text": "Set cookie attributes that match your deployment and threat model:\n\n* Keep `HttpOnly` enabled so JavaScript cannot read the session cookie\n* Use the `Secure` attribute when serving your app over HTTPS\n* Choose an appropriate `SameSite` policy for your login flow and cross-site behavior\n* Consider a browser cookie lifetime that matches how you want the session to behave on the client side"
    },
    {
      "id": "rotate-session-ids-after-authentication-changes",
      "title": "Rotate session IDs after authentication changes",
      "role": "content",
      "text": "When a user logs in, logs out, or their privilege level changes, consider rotating to a new session ID instead of continuing to use the existing one. This reduces the risk of session fixation and gives you a clean point to re-issue the browser cookie."
    },
    {
      "id": "store-only-small-frequently-accessed-session-data",
      "title": "Store only small, frequently accessed session data",
      "role": "content",
      "text": "Redis-backed sessions work well for small, frequently accessed state such as:\n\n* User identifiers\n* Lightweight preferences\n* CSRF-related state\n* Simple counters or timestamps\n\nAvoid treating the session as a general-purpose profile store. Large or rarely used data is often better kept in your main database or another dedicated store."
    },
    {
      "id": "add-csrf-protection-when-needed",
      "title": "Add CSRF protection when needed",
      "role": "content",
      "text": "If your application uses cookie-based authentication, make sure your form and API design includes appropriate CSRF protections where needed. The right approach depends on your framework, request patterns, and whether the application accepts cross-site requests."
    },
    {
      "id": "namespace-session-keys-in-shared-redis-deployments",
      "title": "Namespace session keys in shared Redis deployments",
      "role": "content",
      "text": "If multiple applications or environments share the same Redis deployment, use a clear key prefix strategy such as `session:app-a:` or `session:staging:`. Namespacing helps avoid collisions, simplifies cleanup, and makes it easier to inspect keys during operations or debugging."
    },
    {
      "id": "inspect-sessions-directly-in-redis",
      "title": "Inspect sessions directly in Redis",
      "role": "content",
      "text": "When testing or troubleshooting, inspect the stored session key directly to confirm that the application is writing the fields and TTL you expect. For example, after creating a session, you can verify the hash contents and expiration with `redis-cli`:\n\n[code example]"
    },
    {
      "id": "learn-more",
      "title": "Learn more",
      "role": "related",
      "text": "* [redis-py guide](https://redis.io/docs/latest/develop/clients/redis-py) - Install and use the Python Redis client\n* [EXPIRE command](https://redis.io/docs/latest/commands/expire) - Set key expiration\n* [HSET command](https://redis.io/docs/latest/commands/hset) - Set hash fields\n* [HGETALL command](https://redis.io/docs/latest/commands/hgetall) - Read a full session hash\n* [HINCRBY command](https://redis.io/docs/latest/commands/hincrby) - Increment counters in a session"
    }
  ],
  "examples": [
    {
      "id": "the-python-session-store-ex0",
      "language": "python",
      "code": "import redis\nfrom session_store import RedisSessionStore\n\nr = redis.Redis(host=\"localhost\", port=6379, decode_responses=True)\nstore = RedisSessionStore(redis_client=r, ttl=1800)\n\nsession_id = store.create_session(\n    {\n        \"username\": \"andrew\",\n        \"page_views\": \"0\",\n    }\n)\n\nsession = store.get_session(session_id)\nprint(session[\"username\"])\n\nstore.increment_field(session_id, \"page_views\")\nstore.delete_session(session_id)",
      "section_id": "the-python-session-store"
    },
    {
      "id": "data-model-ex0",
      "language": "text",
      "code": "session:abc123...\n  username = andrew\n  page_views = 3\n  session_ttl = 15\n  created_at = 2026-04-02T12:34:56+00:00\n  last_accessed_at = 2026-04-02T12:40:10+00:00",
      "section_id": "data-model"
    },
    {
      "id": "session-store-implementation-ex0",
      "language": "python",
      "code": "def create_session(\n    self,\n    data: Optional[dict[str, str]] = None,\n    ttl: Optional[int] = None,\n) -> str:\n    session_id = secrets.token_urlsafe(32)\n    key = self._session_key(session_id)\n    now = self._timestamp()\n    session_ttl = self._normalize_ttl(ttl)\n\n    payload = {}\n    if data:\n        payload.update(\n            {\n                field: str(value)\n                for field, value in data.items()\n                if field not in RESERVED_SESSION_FIELDS\n            }\n        )\n    payload.update(\n        {\n            \"created_at\": now,\n            \"last_accessed_at\": now,\n            \"session_ttl\": str(session_ttl),\n        }\n    )\n\n    pipeline = self.redis.pipeline()\n    pipeline.hset(key, mapping=payload)\n    pipeline.expire(key, session_ttl)\n    pipeline.execute()\n    return session_id",
      "section_id": "session-store-implementation"
    },
    {
      "id": "session-store-implementation-ex1",
      "language": "python",
      "code": "def get_session(self, session_id: str, refresh_ttl: bool = True) -> Optional[dict[str, str]]:\n    key = self._session_key(session_id)\n\n    session_ttl = self.get_configured_ttl(session_id)\n    if session_ttl is None:\n        return None\n\n    if not refresh_ttl:\n        session = self.redis.hgetall(key)\n        return session or None\n\n    now = self._timestamp()\n    pipeline = self.redis.pipeline()\n    pipeline.hset(key, mapping={\"last_accessed_at\": now})\n    pipeline.expire(key, session_ttl)\n    pipeline.hgetall(key)\n    _, _, session = pipeline.execute()\n\n    return session or None",
      "section_id": "session-store-implementation"
    },
    {
      "id": "prerequisites-ex0",
      "language": "bash",
      "code": "pip install redis",
      "section_id": "prerequisites"
    },
    {
      "id": "running-the-demo-ex0",
      "language": "bash",
      "code": "python demo_server.py",
      "section_id": "running-the-demo"
    },
    {
      "id": "cookie-handling-ex0",
      "language": "python",
      "code": "cookie = SimpleCookie()\ncookie[\"sid\"] = session_id\ncookie[\"sid\"][\"path\"] = \"/\"\ncookie[\"sid\"][\"httponly\"] = True\ncookie[\"sid\"][\"samesite\"] = \"Lax\"",
      "section_id": "cookie-handling"
    },
    {
      "id": "inspect-sessions-directly-in-redis-ex0",
      "language": "bash",
      "code": "redis-cli HGETALL session:<session_id>\nredis-cli TTL session:<session_id>",
      "section_id": "inspect-sessions-directly-in-redis"
    }
  ]
}
