---
title: "Google ADK: Bridging Redis as a Distributed Caching Layer for ADK Sessions"
date: "2026-12-04T08:51:58+07:00"
description: "Put Redis in front of ADK SessionService to cut session-read latency across replicas. A tutorial with a read-through cache wrapper, TTL tuning, and invalidation on append_event."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-redis-distributed-caching-layer.jpg"
alt: "Architecture diagram showing ADK Runner reading sessions through a Redis cache layer backed by a persistent session database"
tags: ['google-adk', 'redis', 'caching', 'sessions', 'distributed-systems']
---

Every ADK agent turn starts with the same I/O: the `Runner` fetches a `Session` — its `events` history and `state` — before your model ever sees a token. With `InMemorySessionService` that read is free but evaporates on restart; with `DatabaseSessionService` or `VertexAiSessionService` it survives, yet every replica in your deployment now hits the same database for the same hot session on every single turn. At one conversation that is noise. At ten thousand concurrent conversations with multi-turn agents, it is your latency budget.

Redis is the conventional answer, and ADK gives you the seam to attach it. This tutorial builds a read-through, write-through Redis cache that wraps a persistent `SessionService`, without replacing the concurrency guarantees the framework already provides. We will cover where Redis fits versus where it does not, how to wire `redis-py`, how to invalidate correctly on `append_event`, and how to tune TTLs against eviction.

## Prerequisites

- ADK Python installed: `pip install google-adk[db]` (for `DatabaseSessionService`)
- A Redis server running locally (`redis-server`) or Redis Cloud, and `pip install redis`
- Familiarity with ADK `Runner`, `Session`, and `SessionService` basics

## 1. Understand what a session read actually costs

A `Session` (`google.adk.sessions.Session`) carries three things that grow with conversation length:

- `events`: every user message, model response, and tool call in the thread
- `state`: the serializable key-value scratchpad, including `user:` and `app:` scoped keys
- `last_update_time`: activity tracking

`DatabaseSessionService` persists all of it — and, importantly, serializes writes with an in-process lock plus row-level locking (`SELECT ... FOR UPDATE`) on PostgreSQL/MySQL. That machinery is exactly why you should **not** hand-roll a Redis-backed `SessionService` from scratch: you would be reimplementing (and likely breaking) the concurrency story. The safer pattern is a cache *in front of* the real service.

| Option | Persistence | Read latency | Cross-replica | Notes |
| --- | --- | --- | --- | --- |
| `InMemorySessionService` | None | ~0 | No | Lost on restart |
| `DatabaseSessionService` | Yes | Sub-ms to ms | Yes | Locking included; DB becomes hot spot |
| `VertexAiSessionService` | Yes | Network-bound | Yes | Managed, requires GCP setup |
| Redis cache + DB service | Yes | Sub-ms typical | Yes | Cache absorbs repeated reads |

## 2. Install and connect redis-py

Per the official redis-py guide, install the client and open a connection with decoded strings:

```bash
pip install redis          # or: pip install redis[hiredis] for the faster parser
```

```python
import redis

# decode_responses=True returns str instead of bytes — recommended for JSON payloads
r = redis.Redis(host="localhost", port=6379, decode_responses=True)

r.set("foo", "bar")
print(r.get("foo"))        # 'bar'
```

Redis also offers hash structures, which we will use to store per-session metadata alongside the payload:

```python
r.hset("user-session:123", mapping={
    "name": "John",
    "surname": "Smith",
    "company": "Redis",
    "age": 29,
})
print(r.hgetall("user-session:123"))
# {'surname': 'Smith', 'name': 'John', 'company': 'Redis', 'age': '29'}
```

## 3. Build a read-through session cache

The wrapper delegates every authoritative operation to the underlying service and only short-circuits reads when Redis holds a fresh copy. `Session` is a Pydantic model, so serialization is one line each way.

```python
import json
import time
import redis
from google.adk.sessions import DatabaseSessionService, Session

class RedisSessionCache:
    """Read-through cache in front of a persistent ADK SessionService."""

    def __init__(self, session_service, ttl_seconds: int = 900):
        self._inner = session_service
        self._redis = redis.Redis(host="localhost", port=6379, decode_responses=True)
        self._ttl = ttl_seconds
        self.hits = 0
        self.misses = 0

    @staticmethod
    def _key(app_name: str, user_id: str, session_id: str) -> str:
        return f"adk:session:{app_name}:{user_id}:{session_id}"

    async def get_session(self, *, app_name: str, user_id: str,
                          session_id: str) -> Session | None:
        key = self._key(app_name, user_id, session_id)
        cached = self._redis.get(key)
        if cached:
            self.hits += 1
            # Rehydrate the Pydantic model straight from the cached JSON
            return Session.model_validate_json(cached)

        self.misses += 1
        session = await self._inner.get_session(
            app_name=app_name, user_id=user_id, session_id=session_id
        )
        if session is not None:
            # Only cache completed reads; TTL bounds staleness after external writes
            self._redis.set(key, session.model_dump_json(), ex=self._ttl)
        return session

    async def append_event(self, session: Session, event) -> None:
        # Authoritative write first — locking and state_delta live in the inner service
        await self._inner.append_event(session, event)
        # Write-through: refresh (or drop) the cached snapshot immediately
        key = self._key(session.app_name, session.user_id, session.id)
        self._redis.set(key, session.model_dump_json(), ex=self._ttl)
```

Two rules keep this honest:

1. **Writes always go to the inner service first.** `append_event` is where ADK applies `EventActions.state_delta` and updates `state`; the cache never becomes the source of truth.
2. **TTL is your safety net.** If another process mutates the session (or you delete it), a stale snapshot expires on its own instead of poisoning reads forever.

## 4. Invalidate on every state mutation

State changes only flow through events — the ADK docs are explicit that mutating `session.state` on a fetched session bypasses event tracking. That is good news for caching: if *every* mutation passes through `append_event`, a single invalidation point covers all state writes, including `output_key` updates and `user:`/`app:`-scoped deltas.

Wire the wrapper into your `Runner` setup by passing it wherever your code fetches sessions:

```python
from google.adk.runners import Runner
from google.adk.agents import LlmAgent

agent = LlmAgent(
    name="support_agent",
    model="gemini-flash-latest",
    instruction="Answer using the session state. Theme: {user:theme}",
)

cache = RedisSessionCache(
    session_service=DatabaseSessionService(db_url="postgresql+asyncpg://..."),
    ttl_seconds=900,
)

# Application code calls cache.get_session(...) before runner.run(...),
# and cache.append_event(...) whenever an event is produced.
```

For sessions deleted via `delete_session`, remember to drop the key explicitly: `cache._redis.delete(cache._key(app_name, user_id, session_id))` — TTL alone would leave a resurrectable ghost for up to the TTL window.

## 5. Cache more than sessions

Session snapshots are the big win, but two lighter payloads pair well:

- **Hot state keys.** Frequently read `user:`-scoped preferences can live in a Redis hash keyed by `user:{id}` with an `ex` TTL, mirroring the state prefix semantics ADK already defines.
- **Tool results.** Expensive, deterministic tool calls (lookups, rate-limited APIs) can be memoized in Redis keyed by a hash of the function arguments — a classic semantic-cache pattern Redis is marketed for ("lower latency & LLM costs with fully managed semantic caching").

What should **not** go in Redis: non-serializable state values. ADK requires state to be serializable for exactly this reason — anything you cannot round-trip through JSON does not belong in a shared cache either.

## 6. Tune TTLs against hit rate

| Workload | Suggested TTL | Rationale |
| --- | --- | --- |
| Interactive chat, single region | 10–15 min | Covers a burst of turns; user pauses longer than TTL re-fetch once |
| Long agent workflows, multi-step | 30–60 min | Sessions stay active across many invocations |
| Batch / ambient agents | Short (1–5 min) | Read-once patterns gain little; avoid evicting hot keys |
| Cross-region replicas | 5–10 min | Bounds cross-region staleness if a write bypasses the wrapper |

Track `hits / (hits + misses)` from the wrapper's counters. A hit rate under 70% usually means your TTL is shorter than your conversation cadence — or that your `Runner` fetches sessions through a code path that bypasses the cache.

## Checklist

- [ ] Persistent `SessionService` (`DatabaseSessionService` or `VertexAiSessionService`) remains the source of truth
- [ ] `redis-py` installed with `decode_responses=True` and a connection you actually close
- [ ] Cache wrapper intercepts `get_session` and delegates misses to the inner service
- [ ] Every mutation flows through `append_event` with write-through refresh
- [ ] `delete_session` also deletes the Redis key
- [ ] TTL sized to conversation cadence, not guessed
- [ ] Non-serializable objects never stored in Redis or session state
- [ ] Hit rate logged and reviewed after deployment

## Conclusion

ADK's session model already separates persistence from runtime: the `SessionService` owns durability and locking, while `session.state` and `events` stay serializable by design. Redis slots in cleanly as a distributed read cache in front of that service — absorbing the repetitive per-turn reads that otherwise funnel every replica into one database.

The pattern's discipline is its simplicity: reads may be served from cache, writes never are, and TTL bounds every mistake. Do that, and session latency stops scaling with your database's connection pool.

## References

- https://redis.io/
- https://redis.io/docs/latest/develop/
- https://redis.io/docs/latest/develop/clients/redis-py
- https://adk.dev/sessions/session/
- https://adk.dev/sessions/state/
- https://adk.dev/runtime/
