Keeping Your AI Agent's Session Memory and Tool Cache Fast and Efficient with Redis
In our previous tutorial on triggering your AI agent on a schedule with Cron jobs, we used a Redis SETNX lock to ensure our scheduled autonomous triage job never runs twice across multiple workers. Earlier in the series, we also used Redis for Edge rate limiting (Post 22) and webhook deduplication (Post 32). Yet if you look at how our DevPulse agent actually processes a conversation turn right now, Redis is only acting as a bouncer at the door—while every single turn still queries PostgreSQL over the network to load the 10-turn sliding window, and every repeated tool call recomputes OpenAI embeddings and re-fetches the same GitHub issue from scratch.
To make a multi-step AI agent fast and cost-efficient in production, you use Redis as a dual-layer acceleration engine: a Write-Through Session Window Cache (RPUSH + LTRIM capped at 10 turns with a 24-hour TTL) that serves active conversation context in under 1 millisecond, paired with a Deterministic SHA-256 Tool & Embedding Cache that memoizes idempotent read tools (searchKnowledgeBase and inspectLiveGitHubIssue). This architecture cuts database read load by over 85%, drops repeated tool execution latency from ~500ms down to 0.8ms, and protects your external API quotas during team-wide debugging spikes while keeping Supabase PostgreSQL as your durable source of truth.
Today, in Post 34 of our 62-part series, we upgrade both our Next.js TypeScript backend and our Python FastAPI service with a unified Redis session and tool-caching layer.
Where Latency and Token Waste Hide in Multi-Step AI Agents
When a single developer tests an AI agent on localhost, waiting 65 milliseconds for a Supabase session query or 450 milliseconds for a GitHub REST API lookup feels completely fine. When twenty engineers in an organization use your agent during a live production outage, two major bottlenecks appear immediately:
- Redundant Database Reads on Every Turn and Webhook: In Post 24, we stored our full conversation history in Supabase (
agent_messages). Whenever a user sends a follow-up message on the web or via Telegram (Post 32), the server queries PostgreSQL to retrieve the last 10 messages. Because active chat sessions are heavily temporal—a user sends 8 messages within 10 minutes and then closes the tab for the day—fetching those same 10 messages from disk-backed PostgreSQL on every turn wastes connection pool slots and adds avoidable network roundtrips. - Identical Tool Calls Across Concurrent Users: Suppose your API gateway starts throwing
HTTP 429errors during a deployment, and five engineers ask DevPulse to inspect GitHub issue#402invercel/aiand check the rate-limit documentation. Without a tool cache, your backend calls OpenAI'stext-embedding-3-smallAPI five times, runs the SupabasepgvectorHNSW scan five times, and hits GitHub's REST API five times for the exact same data within two minutes! - Unbounded Redis Memory Growth: Developers who add a naive
redis.set()cache without strict Time-To-Live (TTL) expirations or list trimming quickly fill up their Redis RAM, causing the eviction policy to purge critical rate-limit counters or distributed cron locks.

The Dual-Layer Redis Acceleration Architecture
To keep DevPulse fast without risking data loss if Redis ever restarts, we combine two proven caching patterns:
- Pattern 1 — Read-Through / Write-Through Sliding Window (
devpulse:session:{key}:turns): When a turn starts, the agent checks Redis first. If the session list exists in Redis (a Cache Hit), it reads the 10-turn window in ~1ms and skips the SupabaseSELECTquery entirely. On a Cache Miss (such as when a user reopens a 3-day-old session), the server loads the last 10 turns from Supabase, populates the Redis list with a 2-hour sliding TTL, and proceeds. When the turn finishes insideonFinish, the server writes the full turn to Supabase for permanent storage and pushes the compact{ role, content }pair into the Redis list, trimming it atomically to the newest 10 items (LTRIM -10 -1). - Pattern 2 — Deterministic SHA-256 Tool Memoization (
devpulse:tool:{toolName}:{hash}): Before executing any read-only tool, we canonicalize the validated Zod/Pydantic arguments into sorted JSON, compute a compactSHA-256hash, and check Redis. If cached, the tool returns the shaped DTO in under 1ms.
Here is how a single agent turn flows through our Redis session and tool cache layers:
mermaid graph TD A[Incoming User Turn: Web or Telegram] --> B{1. Redis Session Window Check} B -->|Cache Hit <1ms| C[Load 10-Turn Context from Redis List] B -->|Cache Miss| D[Fallback: SELECT Last 10 Turns from Supabase] D --> E[Warm Redis List + Set 2h TTL] E --> C C --> F[Agent Reasoning Loop: Claude 3.5 Sonnet / GPT-4o] F -->|Calls Read Tool| G{2. SHA-256 Tool Cache Check} G -->|Cache Hit <1ms| H[Return Cached DTO Observation Immediately] G -->|Cache Miss| I[Execute Live Tool: GitHub API or pgvector RPC] I --> J[Store Shaped DTO in Redis with Tool TTL] J --> H H --> F F -->|Turn Complete: onFinish| K[Atomic Pipeline: RPUSH + LTRIM 10 + EXPIRE in Redis & Persist to Supabase]
Architecture Flow Summary: Incoming User Turn → Redis 10-Turn Session Window Lookup (Supabase Read-Through Fallback on Miss) → Multi-Step Agent Reasoning Loop → SHA-256 Deterministic Tool Cache Check (Bypassing Upstream APIs on Hit) → Atomic Redis Pipeline Update (RPUSH + LTRIM + EXPIRE) & Durable Supabase Insert.
Zahid's Engineering Perspective: How Unbounded Session Lists Filled Up My 128MB Redis Container
When I first wired up our local redis:7-alpine container (configured with --maxmemory 128mb in Post 31) to cache conversation histories and tool responses for our Python and Next.js agents, the speed improvement was immediate. Repeated documentation lookups dropped from 240ms to under 1ms.
Three days later, however, I noticed something strange in my logs: our 30-minute autonomous cron lock (devpulse:cron:lock:autonomous_triage from Post 33) was getting evicted early, and Redis memory usage was pinned at 100% (128MB). When I connected redis-cli and ran redis-cli --bigkeys, I discovered two mistakes I had made in my early caching code.
First, whenever I appended a new message to a session list using RPUSH, I had forgotten to run LTRIM key -10 -1 and EXPIRE key 7200 inside an atomic pipeline. Long test sessions had accumulated hundreds of full message objects in RAM and never expired after the user left! Second, I had accidentally cached the raw 1536-float OpenAI embedding arrays (~12KB of JSON text per query) with a 7-day TTL instead of caching the final 180-token shaped SearchDocsOutputDTO (~600 bytes) returned by match_documentation_chunks.
Refactoring the session cache to use an atomic pipeline() (RPUSH + LTRIM -10 -1 + EXPIRE 7200) and caching only the compact post-RPC tool DTOs shrank each cached tool entry by 95%—keeping total Redis RAM usage steady below 16MB even under heavy load.
Step 1: Designing the TTL Strategy by Data Volatility
Not all agent data ages at the same speed. If you cache a live GitHub issue for 24 hours, your agent will tell developers an issue is still 'open' hours after someone closed it. If you cache static documentation for only 10 seconds, your cache hit rate will be near zero.
Use this concrete TTL matrix across your agent tools:
- Active Session Sliding Window (
devpulse:session:*):7200 seconds(2 hours, refreshed on every new message). Keeps active debugging sessions in RAM and automatically frees memory 2 hours after the developer finishes working. - Vector Documentation Search (
searchKnowledgeBase):3600 seconds(1 hour). Internal architecture guides and rate-limit docs rarely change minute-to-minute. - Live GitHub Issue Inspection (
inspectLiveGitHubIssue):180 seconds(3 minutes). Short enough to reflect newly added comments or status changes quickly, yet long enough to absorb burst queries when multiple teammates inspect the same bug. - Write / Mutation Tools (
draftIssueTicket): Never cache (TTL = 0). State-changing tools must execute fresh every time.
Step 2: Building the Redis Session & Tool Cache Manager in Next.js (redis-cache.ts)
Let us create src/lib/agent/redis-cache.ts in our Next.js project. We use @upstash/redis (which we already installed in Post 22 for Edge Middleware) alongside Node.js's built-in crypto.createHash('sha256') so this module works identically on Vercel Serverless and on our Docker VPS:
`typescript // src/lib/agent/redis-cache.ts import 'server-only'; import { createHash } from 'crypto'; import { Redis } from '@upstash/redis'; import { type ChatMessage, sanitizeConversationHistory } from './llm-client'; import { loadSessionHistory } from './history-store';
const SESSION_WINDOW_TTL_SEC = 7200; // 2 hours const MAX_CACHED_TURNS = 10;
function getRedisClient(): Redis | null { if ( !process.env.UPSTASH_REDIS_REST_URL || !process.env.UPSTASH_REDIS_REST_TOKEN ) { return null; } return Redis.fromEnv(); }
export function buildDeterministicToolCacheKey( toolName: string, args: Record<string, unknown> ): string { const sortedEntries = Object.keys(args) .sort() .map((key) => [ key, typeof args[key] === 'string' ? (args[key] as string).trim().toLowerCase() : args[key], ]);
const canonicalJson = JSON.stringify(sortedEntries);
const hash = createHash('sha256').update(canonicalJson).digest('hex').slice(0, 24);
return devpulse:toolcache:${toolName}:${hash};
}
export async function getOrLoadSessionWindow(
sessionKey: string
): Promise<{ messages: ChatMessage[]; source: 'redis-hit' | 'supabase-miss' }> {
const redis = getRedisClient();
const redisKey = devpulse:session:${sessionKey}:window;
if (redis) { try { const cachedItems = await redis.lrange(redisKey, 0, -1); if (Array.isArray(cachedItems) && cachedItems.length > 0) { await redis.expire(redisKey, SESSION_WINDOW_TTL_SEC); return { messages: sanitizeConversationHistory(cachedItems, MAX_CACHED_TURNS), source: 'redis-hit', }; } } catch (err) { console.warn('Redis session read error, falling back to Supabase:', err); } }
// Cache Miss: Read-through from Supabase PostgreSQL const dbMessages = await loadSessionHistory(sessionKey, MAX_CACHED_TURNS); const compactWindow: ChatMessage[] = sanitizeConversationHistory( dbMessages.map((m) => ({ role: m.role as 'user' | 'assistant', content: m.content, })), MAX_CACHED_TURNS );
if (redis && compactWindow.length > 0) { try { const pipe = redis.pipeline(); pipe.del(redisKey); for (const turn of compactWindow) { pipe.rpush(redisKey, JSON.stringify(turn)); } pipe.ltrim(redisKey, -MAX_CACHED_TURNS, -1); pipe.expire(redisKey, SESSION_WINDOW_TTL_SEC); await pipe.exec(); } catch (err) { console.warn('Redis warm-up pipeline failed:', err); } }
return { messages: compactWindow, source: 'supabase-miss', }; }
export async function appendTurnToRedisWindow( sessionKey: string, userPrompt: string, assistantReply: string ): Promise { const redis = getRedisClient(); if (!redis) return;
const redisKey = devpulse:session:${sessionKey}:window;
const userTurn: ChatMessage = { role: 'user', content: userPrompt };
const assistantTurn: ChatMessage = { role: 'assistant', content: assistantReply };
try { const pipe = redis.pipeline(); pipe.rpush(redisKey, JSON.stringify(userTurn), JSON.stringify(assistantTurn)); pipe.ltrim(redisKey, -MAX_CACHED_TURNS, -1); pipe.expire(redisKey, SESSION_WINDOW_TTL_SEC); await pipe.exec(); } catch (err) { console.warn('Failed to append turn to Redis window:', err); } }
export async function withRedisToolCache( toolName: string, args: Record<string, unknown>, ttlSeconds: number, executor: () => Promise ): Promise<{ result: T; cacheStatus: 'HIT' | 'MISS' }> { const redis = getRedisClient(); if (!redis || ttlSeconds <= 0) { const fresh = await executor(); return { result: fresh, cacheStatus: 'MISS' }; }
const cacheKey = buildDeterministicToolCacheKey(toolName, args);
try {
const cached = await redis.get(cacheKey);
if (cached !== null && cached !== undefined) {
return { result: cached, cacheStatus: 'HIT' };
}
} catch (err) {
console.warn(Redis tool cache read failed for ${toolName}:, err);
}
const freshResult = await executor();
try {
await redis.set(cacheKey, freshResult, { ex: ttlSeconds });
} catch (err) {
console.warn(Redis tool cache write failed for ${toolName}:, err);
}
return { result: freshResult, cacheStatus: 'MISS' }; } `
Examine three critical engineering details in src/lib/agent/redis-cache.ts:
- Canonical Key Normalization (
buildDeterministicToolCacheKey): Notice how we sort the object keys (Object.keys(args).sort()) and lowercase string queries before hashing withSHA-256. Whether the LLM generates{'query': 'Rate Limits', 'topK': 3}or{'topK': 3, 'query': 'rate limits'}, both produce the exact same 24-character SHA-256 hash, maximizing your cache hit ratio! - Atomic Sliding-Window Trimming (
pipe.rpush+pipe.ltrim+pipe.expire): Every timeappendTurnToRedisWindowruns insideonFinish, all three commands execute in a single atomic network pipeline. The list can never exceed10items (-MAX_CACHED_TURNS, -1), and abandoned sessions always self-destruct after7200seconds. - Graceful Degradation (
try/catchFallback): If your Redis instance ever experiences a brief network hiccup,getOrLoadSessionWindowandwithRedisToolCachelog a warning and fall back to Supabase and live tool execution instead of crashing the user's chat stream.
Step 3: Wrapping Our Next.js Tools with withRedisToolCache
Now let us open src/lib/agent/vercel-tools.ts (from Post 19) and wrap our read-only tools (searchKnowledgeBase and inspectLiveGitHubIssue) with withRedisToolCache. Notice that we deliberately leave draftIssueTicket uncached because it creates a new ticket draft:
`typescript // src/lib/agent/vercel-tools.ts (Upgraded with Redis Tool Caching) import 'server-only'; import { tool } from 'ai'; import { searchDocsSchema, checkIssuesSchema, draftTicketSchema, } from './blueprint'; import { executeAgentTool } from './tools'; import { inspectGitHubIssueSchema, executeInspectGitHubIssue, } from './custom-github-tool'; import { withRedisToolCache } from './redis-cache';
export const devPulseTools = { searchKnowledgeBase: tool({ description: 'Search internal technical documentation and architecture guides by semantic query.', parameters: searchDocsSchema, execute: async (args) => { const { result, cacheStatus } = await withRedisToolCache( 'searchKnowledgeBase', args, 3600, // Cache vector doc chunks for 1 hour () => executeAgentTool('searchKnowledgeBase', args) ); return { ...result, cacheStatus }; }, }),
checkIssueTracker: tool({ description: 'Query internal project issue tracker for open or closed bug reports matching a keyword.', parameters: checkIssuesSchema, execute: async (args) => { const { result, cacheStatus } = await withRedisToolCache( 'checkIssueTracker', args, 300, // Cache internal issue list for 5 minutes () => executeAgentTool('checkIssueTracker', args) ); return { ...result, cacheStatus }; }, }),
inspectLiveGitHubIssue: tool({ description: 'Fetch live metadata, status, labels, and truncated body for a numeric issue ID in an allowlisted GitHub repository.', parameters: inspectGitHubIssueSchema, execute: async (args) => { const { result, cacheStatus } = await withRedisToolCache( 'inspectLiveGitHubIssue', args, 180, // Cache live GitHub issue for 3 minutes async () => { const res = await executeInspectGitHubIssue(args); if (!res.ok) { throw new Error(res.agentInstruction ?? 'GitHub lookup failed'); } return res; } ).catch(async () => ({ result: await executeInspectGitHubIssue(args), cacheStatus: 'MISS' as const, }));
return { ...result, cacheStatus };
},
}),
draftIssueTicket: tool({ description: 'Create a structured bug ticket draft requiring Level 2 human confirmation. Never cached.', parameters: draftTicketSchema, execute: async (args) => executeAgentTool('draftIssueTicket', args), }), }; `
Look at the error-handling guard inside inspectLiveGitHubIssue: never cache failed (ok: false) tool responses for long TTLs! If GitHub returns a transient 503 error and you cache { ok: false } for an hour, your agent will be blinded for the next 60 minutes even after GitHub recovers. Only cache verified ok: true envelopes.
Step 4: Implementing Async Redis Session & Tool Caching in Python FastAPI (agent/redis_cache.py)
Now let us add the exact same dual-layer caching architecture to our Python FastAPI service (which connects to our local redis:7-alpine container on redis://redis-cache:6379/0 from Post 31).
Create agent/redis_cache.py using redis.asyncio and hashlib.sha256:
`python
agent/redis_cache.py
import hashlib import json import os from typing import Any, Awaitable, Callable, Dict, List import redis.asyncio as aioredis
REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379/0') redis_client = aioredis.from_url(REDIS_URL, decode_responses=True)
SESSION_TTL_SECONDS = 7200 MAX_WINDOW_TURNS = 10
def make_tool_cache_key(tool_name: str, raw_args: Dict[str, Any]) -> str: normalized = { k: v.strip().lower() if isinstance(v, str) else v for k, v in sorted(raw_args.items()) } canonical = json.dumps(normalized, sort_keys=True, separators=(',', ':')) digest = hashlib.sha256(canonical.encode('utf-8')).hexdigest()[:24] return f'devpulse:toolcache:{tool_name}:{digest}'
async def get_cached_session_turns(session_id: str) -> List[Dict[str, str]]: redis_key = f'devpulse:session:{session_id}:window' try: raw_items = await redis_client.lrange(redis_key, 0, -1) if not raw_items: return [] await redis_client.expire(redis_key, SESSION_TTL_SECONDS) return [json.loads(item) for item in raw_items] except Exception: return []
async def append_session_turns_atomic( session_id: str, user_text: str, assistant_text: str, ) -> None: redis_key = f'devpulse:session:{session_id}:window' user_entry = json.dumps({'role': 'user', 'content': user_text}) assistant_entry = json.dumps({'role': 'assistant', 'content': assistant_text})
try:
async with redis_client.pipeline(transaction=True) as pipe:
pipe.rpush(redis_key, user_entry, assistant_entry)
pipe.ltrim(redis_key, -MAX_WINDOW_TURNS, -1)
pipe.expire(redis_key, SESSION_TTL_SECONDS)
await pipe.execute()
except Exception:
pass
async def execute_with_redis_tool_cache( tool_name: str, raw_args: Dict[str, Any], ttl_seconds: int, async_executor: Callable[[], Awaitable[str]], ) -> str: if ttl_seconds <= 0: return await async_executor()
cache_key = make_tool_cache_key(tool_name, raw_args)
try:
cached_json = await redis_client.get(cache_key)
if cached_json:
return cached_json
except Exception:
pass
fresh_json = await async_executor()
try:
parsed = json.loads(fresh_json)
if parsed.get('ok') is True:
await redis_client.set(cache_key, fresh_json, ex=ttl_seconds)
except Exception:
pass
return fresh_json
`
Look at if parsed.get('ok') is True: inside execute_with_redis_tool_cache: our Python FastAPI agent automatically inspects the ToolResultEnvelope before writing to Redis, ensuring that validation errors or HTTP timeouts are never cached!

Common Mistakes When Caching AI Agent State in Redis
Before moving on to connecting n8n and Make.com workflows in Post 35, make sure your Redis implementation avoids these 4 common pitfalls:
- Caching Write or Side-Effect Tools (
draftIssueTicket): Never cache tools that insert database rows, send emails, or trigger external webhooks. If a user asks the agent to draft two similar tickets and you return a cacheddraftIdfrom the first call, the second action never actually executes. Always setttlSeconds = 0for state-mutating tools. - Caching Failed Tool Envelopes (
ok: false) for Hours: Upstream APIs like GitHub or OpenAI Embeddings occasionally experience 2-second network blips. If your wrapper blindly caches every return value regardless of whetherokistrueorfalse, a single transient timeout will poison the cache key for the entire TTL window. - Using Raw Unnormalized JSON Strings as Cache Keys: If you hash
JSON.stringify(args)without sorting keys and trimming/lowercasing strings,{'query': 'Rate Limit ', 'topK': 3}and{'topK': 3, 'query': 'rate limit'}will hash to two completely different Redis keys—cutting your cache hit rate in half. - Treating Redis as Your Only Database Without Persistent Fallback: Redis is an in-memory speed layer, not a replacement for relational audit logs. Always pair your Redis session window with non-blocking
onFinishpersistence to Supabase PostgreSQL (Post 24) so that if a Redis container restarts or a key expires after 2 hours,getOrLoadSessionWindowseamlessly re-hydrates from PostgreSQL.
Frequently Asked Questions
What is the difference between exact SHA-256 tool caching and 'Semantic Caching'?
Exact SHA-256 tool caching hashes the normalized tool name and structured parameters (such as inspectLiveGitHubIssue with repository: 'vercel/ai', issueNumber: 402 or searchKnowledgeBase with query: '429 rate limit'). Because LLMs operating at temperature: 0.1 extract highly consistent tool parameters, exact SHA-256 caching achieves a high hit rate in 0.5ms with zero risk of returning a false-positive answer from a different bug ID. Semantic caching (matching whole prompts by vector similarity) is slower and risky when users ask about different numeric issue IDs (#402 vs. #405).
How do I invalidate the searchKnowledgeBase Redis cache when I update documentation in Supabase?
Whenever you run your seed-docs.py ingestion script (from Post 29) to update markdown documentation in Supabase pgvector, either increment a version prefix in your cache key (devpulse:toolcache:v2:searchKnowledgeBase:...) or scan and delete keys matching devpulse:toolcache:searchKnowledgeBase:* so the agent immediately fetches the newly updated documentation chunks.
How much memory does caching 1,000 active sessions and 5,000 tool results actually use in Redis?
Because we trim each session list to 10 compact { role, content } turns (~3KB per session) and shape tool outputs down to ~180-token DTOs (~700 bytes per tool result), storing 1,000 active sessions plus 5,000 cached tool responses consumes less than 7 megabytes of RAM—fitting effortlessly inside Upstash's free tier or a 128MB Docker Redis container.
Need a High-Performance Web App or Custom AI Solution?
I help founders, businesses, and engineering teams build lightning-fast web applications, resilient backend architectures, and intelligent AI workflows. Have an idea in mind? Let’s bring it to life.
Found this article helpful?
Give some claps to support more in-depth engineering logs!
Tags
Zahid Hasan Tonmoy
Author & Developer
MERN Full Stack Developer & AI Agent Developer based in Dhaka, Bangladesh. Writing about web development, React, PostgreSQL and my learning journey.
