Arc Labs
BrainDocsPricing
GitHubSign inGet Started
LearnGuides

Temporal Context Windows

By Arc Labs Research·May 13, 2026·9 min read
TL;DR

Unbounded memory grows tokens and costs. Use temporal windows—sliding windows (last N hours), session boundaries (reset between user sessions), or recency decay (weight recent memories higher)—to keep agent context focused and costs bounded.

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:

  1. Sliding windows: Keep last N hours, drop older
  2. Session boundaries: Reset memory between user sessions
  3. 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.memories

Decay 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% weight

A 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 SizeMemories KeptTokens/RetrievalQualityCost/Month (100 agents)
No window36,00036,000Best (all history)$1,800
30 days7,2007,200Very good$360
7 days1,2001,200Good$60
24 hours150–3001,500Good (recent)$7.50
1 hour20–50500Fair (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) on encode() and pass the same .session(id) on recall()
  • 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

Related reading

  • GuidesMemory Consolidation Patterns
  • GuidesCost Optimization for Agent Memory
PreviousRetrieval Strategy SelectorNextMemory Consolidation Patterns

Updates from the lab.

Engineering notes, research drops, occasional product updates. Roughly monthly.

Arc Labs

Cognitive infrastructure for AI agents. Open core in Rust. Composable primitives you own.

GitHubX / TwitterDiscussions

Brain

  • Memory Layer
  • Documentation
  • Pricing
  • Changelog
  • Status

Developers

  • Start here
  • TypeScript SDK
  • Python SDK
  • Rust SDK
  • MCP Server

Company

  • About
  • Careers
  • Blog
  • Security
  • Contact
Encode"Priya lives in Berlin."mem_7f3a · storedRecall"where does Priya live?"→ BerlinSupersede"Priya moved to Lisbon."mem_9c21 ⊃ mem_7f3aBerlin→ LisbonARC LABSARC LABSARC LABS
© 2026 ARC LABS · BANGALOREPrivacyTermsDPAApache 2.0