AI agents often need information from previous interactions to provide useful responses.
A customer may ask about an order in one conversation, return later, and expect the application to understand the previous context. An employee may start a workflow on one device and continue it from another. A long-running agent may also need to preserve intermediate results between multiple requests.
If the agent keeps all of this information only in application memory, the context disappears when the process restarts or when another application instance handles the next request.
Redis can provide a shared storage layer for this information.
Instead of keeping agent context inside one running process, the application can store selected context in Redis and retrieve it whenever the same agent session continues.
What Does Agent Context Mean?
Agent context is the information an AI agent needs to continue a conversation or workflow.
It can include:
- Conversation history
- User preferences
- Previous tool results
- Workflow state
- Current task
- Important decisions
- Temporary variables
- Session identifiers
- Authentication-related references
- Short-lived application state
Not every piece of information needs to be stored.
For example, storing the entire conversation indefinitely may create unnecessary storage and processing costs. A better design stores the information that is actually useful for future requests.
A simple context object might look like this:
{
"sessionId": "session-1001",
"userId": "user-501",
"currentTask": "order-support",
"lastOrderId": "ORD-1024",
"preferences": {
"language": "en"
}
}
Why Application Memory Is Not Enough
A common first implementation stores agent state in a local variable.
const sessions = new Map();
sessions.set(sessionId, {
currentTask: "order-support",
lastOrderId: "ORD-1024"
});
This works for a small development application, but it has several problems.
If the application restarts, the data is lost.
If multiple application instances are running, each instance has a different session map.
For example:
Request 1
|
v
Server A
|
+---- Session stored locally
Request 2
|
v
Server B
|
+---- Session not available
The agent may therefore behave as though the previous conversation never happened.
A shared Redis store changes this architecture:
+------------+
Request 1 ------>| Server A |
+------+-----+
|
Request 2 ------>+-----v------+
| Redis |
+-----+------+
|
Shared Context
All application instances can access the same session context.
Storing Agent Context in Redis
A straightforward approach is to store the context as JSON.
For example:
const context = {
sessionId: "session-1001",
userId: "user-501",
currentTask: "order-support",
lastOrderId: "ORD-1024"
};
await redis.set(
`agent:context:${context.sessionId}`,
JSON.stringify(context),
{
EX: 3600
}
);
The key identifies the agent session.
The expiration prevents temporary session data from remaining in Redis forever.
The correct expiration period depends on the application's workflow.
For example, a customer support session may need a longer retention period than a temporary tool execution state.
Reading Context for the Next Request
When the next request arrives, the application can retrieve the stored context.
const rawContext = await redis.get(
`agent:context:${sessionId}`
);
const context = rawContext
? JSON.parse(rawContext)
: null;
The agent can then use the context when processing the new request.
For example:
if (context?.lastOrderId) {
console.log(
`Continuing order ${context.lastOrderId}`
);
}
The important part is that the application does not depend on which server instance receives the request.
Updating Context After an Agent Action
Agent context usually changes during a conversation.
Suppose the user asks:
Where is my order?
The agent identifies the order and retrieves its status.
The application can then update the context:
const updatedContext = {
...context,
lastOrderId: "ORD-1024",
currentTask: "tracking-order",
lastAction: "order-status-checked"
};
await redis.set(
`agent:context:${sessionId}`,
JSON.stringify(updatedContext),
{
EX: 3600
}
);
The next request can retrieve this updated state.
This creates a simple session lifecycle:
Request
|
v
Read Context
|
v
Run Agent
|
v
Update Context
|
v
Save Context
Do Not Store the Entire Conversation Automatically
A common mistake is treating Redis as a place to store everything.
For example, an application might store hundreds of complete messages in every session.
That can create unnecessary memory usage and increase the amount of context sent to the AI model.
Instead, separate the information into useful categories.
Short-term context
|
+---- Current task
+---- Recent messages
+---- Temporary tool results
Long-term information
|
+---- User preferences
+---- Important account information
+---- Persistent business data
Redis is particularly useful for short-lived and frequently accessed context.
Persistent business records should generally remain in the application's appropriate database rather than being treated as temporary agent memory.
Storing Conversation History Separately
Sometimes the application needs recent conversation messages.
A Redis list can be used for this type of short-term history.
For example:
await redis.rPush(
`agent:messages:${sessionId}`,
JSON.stringify({
role: "user",
content: "Where is my order?"
})
);
Another message can be added:
await redis.rPush(
`agent:messages:${sessionId}`,
JSON.stringify({
role: "assistant",
content: "Your order is currently being shipped."
})
);
The application can then retrieve the most recent messages:
const messages = await redis.lRange(
`agent:messages:${sessionId}`,
-10,
-1
);
Retrieving only recent messages prevents the agent context from growing without limits.
Combining Session State and Recent Messages
A practical agent session can use separate Redis keys.
agent:context:session-1001
agent:messages:session-1001
agent:workflow:session-1001
This separation makes it easier to manage different types of data.
For example:
Context
↓
Current task and important state
Messages
↓
Recent conversation
Workflow
↓
Current step and pending actions
The agent can retrieve only what it needs for a particular request.
Sharing Context Between Different Agents
Redis becomes more useful when multiple agents participate in the same workflow.
For example:
Customer
|
v
Support Agent
|
v
Order Agent
|
v
Notification Agent
All agents can reference the same session identifier.
For example:
sessionId = session-1001
The support agent can store:
{
"currentTask": "order-support",
"orderId": "ORD-1024"
}
The order agent can retrieve the order ID and add new information:
{
"currentTask": "order-support",
"orderId": "ORD-1024",
"orderStatus": "shipped"
}
The notification agent can then use the same session context to determine what notification needs to be generated.
This creates shared state without requiring each agent to directly communicate with every other agent.
Preventing Lost Updates
Multiple agents may update the same context at nearly the same time.
For example:
Support Agent
|
+---- Update context
|
Redis Context
|
+---- Update context
|
Order Agent
If both agents read the same old value and then write different versions, one update may overwrite the other.
This is a race condition.
For simple applications, updating individual fields rather than rewriting the entire context can reduce this problem.
For more complex workflows, Redis operations that provide atomic behavior can be used to coordinate updates.
The key point is to consider concurrent access when multiple agents share the same session.
Using TTL for Temporary Context
Temporary context should normally have a lifecycle.
Redis supports expiration on keys.
For example:
await redis.set(
`agent:context:${sessionId}`,
JSON.stringify(context),
{
EX: 3600
}
);
The EX value represents the expiration period in seconds.
After the specified period, Redis can remove the key automatically.
This is useful for:
- Temporary conversations
- Login sessions
- Tool execution state
- Short-lived workflows
- Temporary agent coordination
Without expiration, temporary context can remain in Redis indefinitely.
Handling Session Expiration
The application should be prepared for a missing context.
const rawContext = await redis.get(
`agent:context:${sessionId}`
);
if (!rawContext) {
return startNewSession();
}
A missing context does not necessarily mean something went wrong.
The session may have expired naturally.
The application should decide whether to:
- Start a new session
- Restore information from permanent storage
- Ask the user for clarification
- Continue with a reduced context
This fallback behavior should be part of the application design.
Avoid Storing Sensitive Information Carelessly
Agent context may contain sensitive application data.
Examples include:
- Personal information
- Account references
- Business information
- Authentication-related data
- Internal workflow details
The application should store only the information required for the workflow.
Redis access should also be restricted to the services that actually need it.
The AI model does not automatically need direct access to the Redis database.
A safer architecture is:
AI Agent
|
v
Application Service
|
v
Redis
The application controls which context is retrieved and which information is passed to the model.
Versioning Agent Context
As an application evolves, the structure of stored context may change.
For example, an older version may store:
{
"orderId": "ORD-1024"
}
A newer version might expect:
{
"currentOrder": {
"id": "ORD-1024"
}
}
If old sessions remain in Redis, the new application version may not understand them.
A simple solution is to include a version number.
{
"version": 2,
"sessionId": "session-1001",
"currentOrder": {
"id": "ORD-1024"
}
}
The application can then migrate or ignore older context formats safely.
Common Mistakes
Storing Everything in One Redis Key
A single large context object becomes difficult to update and can increase the amount of data transferred on every request.
Separate frequently changing data when appropriate.
Never Expiring Session Data
Temporary agent sessions should not remain forever unless there is a clear reason.
Use expiration for short-lived state.
Sending All Stored Context to the AI Model
The agent does not need every stored field on every request.
Retrieve the required information and construct a focused model context.
Treating Redis as the Permanent Database
Redis is useful for fast shared state, but important business records should not depend solely on temporary agent context.
Ignoring Concurrent Updates
Multiple agents can modify the same session at the same time.
Design the update strategy with concurrency in mind.
Best Practices
- Use a stable session identifier for each agent conversation or workflow.
- Store only context that is useful for future requests.
- Separate short-term messages from session state when appropriate.
- Use TTLs for temporary context.
- Validate stored context before using it.
- Include a context version when the schema may change.
- Handle missing or expired sessions gracefully.
- Limit the amount of conversation history sent to the model.
- Protect Redis access and avoid exposing Redis directly to AI models.
- Design concurrent context updates carefully when multiple agents share a session.
- Keep permanent business data in the appropriate persistent database.
- Monitor Redis memory usage as the number of agent sessions grows.
Advantages and Disadvantages
| Area |
Advantages |
Disadvantages |
| Shared context |
Multiple application instances can access the same state |
Adds shared infrastructure |
| Performance |
Fast access to frequently used session data |
Large context objects can increase memory usage |
| Scalability |
Works well with distributed application instances |
Requires careful data lifecycle management |
| Agent workflows |
Multiple agents can share workflow state |
Concurrent updates require attention |
| Session management |
TTL can automatically remove temporary data |
Expired context may no longer be recoverable |
| Development |
Simple key-based storage model |
Context schema needs versioning as applications evolve |
When Redis Is a Good Fit
Redis is a strong fit when agent context is:
- Frequently accessed
- Short-lived
- Shared across application instances
- Updated during active workflows
- Needed with low latency
For example:
User Request
|
v
Agent Service
|
+---- Read Context
|
v
Redis
|
+---- Session State
+---- Recent Messages
+---- Workflow State
For large historical conversation archives or permanent business records, a dedicated persistent data store may be more appropriate.
Summary
Sharing agent context across sessions becomes important as AI applications move beyond simple one-request interactions.
Redis can provide a shared state layer that allows multiple application instances and specialized agents to access the context required to continue a conversation or workflow.
A reliable implementation should store only useful context, use session identifiers, apply expiration to temporary data, handle concurrent updates, and keep permanent business information in the appropriate database.
The main goal is not to remember everything. It is to preserve the right information so that the agent can continue its work without rebuilding the entire context for every request.
Join the conversation! Your thoughts help the community grow.