Temporal Context Windows
The Problem: Unbounded Memory
Agent memory grows linearly with time. Without limits:
- Token explosion: Agent stores 1000 messages. Context window = 4K tokens. Agent can no longer fit conversation + memory + reasoning. Costs 5x higher.
- Retrieval noise: Retrieving "customer sentiment" returns memories from 2 years ago—irrelevant to today's conversation. Wastes tokens on stale context.
- Cost spiral: Older memories still retrieved (BM25 rank them high if keywords match). Cost per agent per month grows unbounded.
Example: Customer support agent
- Day 1: 100 memories, retrieve top 5 → 500 tokens
- Month 1: 3000 memories, retrieve top 5 → 3000 tokens (same 5 from 2x larger corpus)
- Year 1: 36K memories, retrieve top 5 → 36K tokens (BM25 searches entire history)
Costs grow 360x without temporal boundaries.
Temporal windows bound memory and costs. Three patterns:
- Sliding windows: Keep last N hours, drop older
- Session boundaries: Reset memory between user sessions
- Recency decay: Rank recent memories higher (exponentially decay older)
Pattern 1: Sliding Windows
Idea: Keep only the last N hours of memory. Older memories are archived (or deleted).
When to use:
- Stateless agent loops (chat bots, customer support) where context resets
- Real-time systems (trading, monitoring) where yesterday's data is stale
- Cost is critical; token budgets are tight
How it works:
import os
from brain_db_sdk import Auth, BrainClient, RecallBuilder, ForgetBuilder
client = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
def sliding_window_retrieve(query: str, window_hours: int = 24) -> list:
"""Recall the most relevant recent memories.
Brain's rank fusion blends semantic relevance with recency, and the
per-shard decay + retention workers age out stale memories server-side,
so the effective window is maintained for you—recall returns recent,
relevant hits without a manual timestamp filter.
"""
answer = client.recall(RecallBuilder(query).limit(10).build())
return answer.memories
def forget_stale(stale_memory_ids: list) -> None:
"""Immediately drop specific memories you tracked at encode time."""
for memory_id in stale_memory_ids:
client.forget(ForgetBuilder(memory_id).build())Cleanup schedule: Brain's retention and decay workers prune aged memories on
every shard, so no external cron is required for time-based cleanup. Call
client.forget(...) only when you need to drop specific memories immediately.
Cost impact:
- Without window: 36K memories, 36K tokens to search → $0.18/retrieval
- With 24h window: 50–100 memories, 500 tokens to search → $0.0025/retrieval
- Savings: 72x reduction
Pattern 2: Session Boundaries
Idea: Reset memory at session boundaries (e.g., end of chat, end of day, end of trading session).
When to use:
- Conversational agents (each conversation is independent)
- Daily-reset systems (trading agents reset at market close)
- Each session has its own context; no cross-session learning
How it works:
import { BrainClient, EncodeBuilder, RecallBuilder } from "@brain-db/sdk";
const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });
class ConversationAgent {
private sessionId: bigint;
constructor() {
// A monotonically-increasing session id groups one conversation's memories
this.sessionId = BigInt(Date.now());
}
async storeInConversation(content: string) {
// Tag every memory with the current session id
await client.encode(
new EncodeBuilder(content).session(this.sessionId).build()
);
}
async retrieveInSession(query: string, maxResults = 5) {
// Scope recall to the current session only
const answer = await client.recall(
new RecallBuilder(query).sessions([this.sessionId]).maxResults(maxResults).build()
);
return answer.memories;
}
endSession() {
// Rotate to a fresh session; past sessions stay stored but out of scope.
this.sessionId = BigInt(Date.now());
}
}
// Usage
const agent = new ConversationAgent();
await agent.storeInConversation("Customer is frustrated about late delivery");
await agent.storeInConversation("Offered 20% discount, customer accepted");
// Retrieve only within this conversation
const context = await agent.retrieveInSession("customer sentiment", 10);
// End session, rotate to a new one
agent.endSession();Cost impact:
- Without boundaries: Agent retrieves from 36K lifetime memories → 36K tokens
- With session boundaries: Agent retrieves from <100 session memories → 500 tokens
- Savings: 72x reduction, plus cleaner agent behavior
Pattern 3: Recency Decay
Idea: Don't delete old memories, but weight recent ones higher. Exponentially decay older memories' relevance.
When to use:
- Long-term learning is needed (trading strategies learned over months)
- You want to keep history but focus on recent context
- Compliance/audit requires keeping all records
How it works:
import os
from brain_db_sdk import Auth, BrainClient, RecallBuilder
client = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
def retrieve_with_recency(query: str, max_results: int = 10) -> list:
"""Recall relevant memories with recency already folded into the ranking.
Brain's rank fusion combines semantic similarity with a recency signal, so
recent memories surface above older, equally-relevant ones without a manual
exponential-decay re-rank pass. Ask for the number of hits you want and use
them directly.
"""
answer = client.recall(RecallBuilder(query).limit(max_results).build())
return answer.memoriesDecay schedule:
Day 0 (today): decay = 1.0 → full weight
Day 1: decay = 0.90 → 90% weight
Day 7: decay = 0.49 → 49% weight
Day 30: decay = 0.05 → 5% weightA memory from 30 days ago is weighted at 5% of its original retrieval score.
Cost impact:
- Without decay: All 36K memories scored equally high for old + new queries → 36K tokens
- With decay: Recent memories ranked higher; fewer old memories in top-10 → 1K tokens (focus on recent)
- Savings: 36x reduction in retrieval tokens
Comparison: Window Size vs Cost vs Recall Quality
How do different window sizes affect cost and retrieval quality?
| Window Size | Memories Kept | Tokens/Retrieval | Quality | Cost/Month (100 agents) |
|---|---|---|---|---|
| No window | 36,000 | 36,000 | Best (all history) | $1,800 |
| 30 days | 7,200 | 7,200 | Very good | $360 |
| 7 days | 1,200 | 1,200 | Good | $60 |
| 24 hours | 150–300 | 1,500 | Good (recent) | $7.50 |
| 1 hour | 20–50 | 500 | Fair (very recent) | $2.50 |
Trade-off: Larger window = more context but higher cost. Start with 7–24 hour windows; expand if agents need longer memory.
Production Implementation
Combine patterns for optimal behavior:
import { BrainClient, RecallBuilder } from "@brain-db/sdk";
const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });
async function productionRetrieve(
query: string,
options: { sessionId?: bigint; maxResults?: number } = {}
) {
const { sessionId, maxResults = 10 } = options;
let builder = new RecallBuilder(query).maxResults(maxResults);
// Session boundary: scope recall to one conversation when provided
if (sessionId !== undefined) {
builder = builder.sessions([sessionId]);
}
// Brain's fusion already blends relevance with recency, so no manual
// time-window filter or client-side decay re-rank is needed here.
const answer = await client.recall(builder.build());
return answer.memories;
}Implementation Checklist
- Choose window pattern: sliding window (stateless), session boundary (conversations), or recency decay (long-term learning)
- Set window size: 24 hours for stateless, 1 day per session for conversations, 30 days for long-term
- Group related memories into sessions so recall can be scoped by conversation
- If session boundary: tag each memory with
.session(id)onencode()and pass the same.session(id)onrecall() - Cleanup: lean on Brain's decay + retention workers for time-based pruning; call
client.forget(...)for immediate, targeted removals - If recency decay: rely on Brain's recency-weighted fusion—recall already ranks recent memories higher
- Monitor cost: track tokens/retrieval, confirm savings
- Test: verify agent behavior with and without temporal limits
Next Steps
- Consolidation: See Memory Consolidation Patterns for summarizing memories before archiving
- Cost optimization: Check Cost Optimization for Agent Memory for the full cost picture
- Retrieval strategies: Read Retrieval Strategy Guide for advanced filtering