Arc Labs
BrainDocsPricing
GitHubSign inGet Started
LearnGuides

Memory Consolidation Patterns

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

As memory grows, retrieval slows and costs rise. Consolidation reduces noise: summarize many small memories into one ("5 trades → 'Bull market strategy won 4/5'"), filter duplicates, or archive cold data. Trigger consolidation on size (>1K memories), time (weekly), or quality (low-retrieval memories).

The Problem: Memory Bloat

Agent memory grows faster than retrieval slows, creating bloat:

  • Retrieval noise: Searching "customer sentiment" returns 100+ results. Top 10 have low signal. Wastes tokens scoring irrelevant memories.
  • Storage cost: 50K memories × 0.001/vector=0.001/vector = 0.001/vector=50/month per agent. With consolidation: 5K summaries = $5/month.
  • Latency creep: Searching 50K memories is slower than 5K. BM25 and semantic search degrade.

Example: Customer support agent

  • Day 1–30: 100 interactions, 500 memories (5 per interaction)
  • Month 3: 300 interactions, 1,500 memories
  • Month 6: 600 interactions, 3,000 memories

Retrieval "customer sentiment" now searches 3,000 items. Many are duplicates:

  • "Customer angry about shipping" (Day 1)
  • "Customer still angry about shipping" (Day 2)
  • "Customer angry about shipping and billing" (Day 3)

Consolidation: Collapse these 3 into one summary: "Customer upset about shipping delays and billing errors; prefers email contact."

Results:

  • 3,000 memories → 1,000 consolidated summaries (66% reduction)
  • Retrieval latency improves 3x
  • Storage cost drops from 3to3 to 3to1
  • Retrieval quality improves (less noise, more relevant summaries)

Pattern 1: Summarize Similar Memories

Idea: Group similar memories by topic, summarize the group, replace with one consolidated memory.

When to use:

  • Agent stores detailed logs that are repetitive (trading logs, chat turns)
  • You want to reduce noise while preserving facts
  • Long-term memory is more important than detailed history

How it works:

import os
import json
from brain_db_sdk import Auth, BrainClient, EncodeBuilder, RecallBuilder, ForgetBuilder
from anthropic import Anthropic

client = BrainClient.connect(
    "127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
claude = Anthropic(api_key="...")


def consolidate_by_topic(topic: str, original_ids: list) -> dict:
    """
    Consolidate memories matching a topic into a single summary.

    Recall the memories for the topic, summarize them with Claude, encode the
    summary as a new memory, then forget the originals (ids you kept from the
    encode() calls that created them).
    """

    # 1. Recall memories matching the topic
    answer = client.recall(RecallBuilder(topic).limit(100).build())
    memory_texts = [hit.text for hit in answer.memories]

    if len(memory_texts) < 2:
        return {"consolidated": False, "reason": "Less than 2 memories"}

    # 2. Summarize using Claude
    summary = claude.messages.create(
        model="claude-opus-4-1",
        max_tokens=500,
        messages=[
            {
                "role": "user",
                "content": f"""Consolidate these {len(memory_texts)} memories about {topic} into a single summary.
Focus on patterns, key facts, and trends. Preserve specifics.

Memories:
{json.dumps(memory_texts, indent=2)}

Return a single consolidated memory (2-3 sentences max)."""
            }
        ]
    ).content[0].text

    # 3. Encode the consolidated summary as a new memory
    stored = client.encode(EncodeBuilder(summary).build())

    # 4. Forget the original memories
    for memory_id in original_ids:
        client.forget(ForgetBuilder(memory_id).build())

    return {
        "consolidated": True,
        "consolidated_id": stored.memory_id,
        "memories_merged": len(memory_texts),
        "summary": summary,
    }


# Usage
result = consolidate_by_topic("trading_losses", original_ids=[...])
print(f"Consolidated {result['memories_merged']} losses into 1 summary")

Example execution:

Input (5 trading loss memories):
1. "Sold AAPL too early, lost 1.2% on recovery"
2. "Held MSFT too long, got stopped at -2.5%"
3. "TSLA bad entry, exited at -1.8%"
4. "Missed NVDA dip, entered at peak, -2.1%"
5. "Tech sector rotation caught me unprepared, -3.2% total"

Output (1 consolidated summary):
"Lost 10.8% across 5 trades in tech sector (AAPL, MSFT, TSLA, NVDA).
Errors: premature exit, overholding, bad entry, missed dips.
Pattern: Sector rotation without position rotation."

Pattern 2: Filter Duplicates

Idea: Detect and remove near-duplicate memories (same content, slightly different wording).

When to use:

  • Agent stores redundant information (chat bots storing every message + summary)
  • You want to deduplicate without manual review
  • Exact deduplication isn't needed (near-duplicate is fine)

How it works:

import { BrainClient, ForgetBuilder } 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 });

// Brain deduplicates near-identical memories for you. The write path runs
// extraction + supersession + predicate consolidation on every shard, so a
// re-statement of an existing fact supersedes the older one instead of piling
// up a second near-duplicate vector — you rarely need a client-side dedup pass.
//
// When you do want to drop a specific memory you know is redundant, forget it
// by id (the id you kept from the encode() call that created it):
async function forgetDuplicate(memoryId: bigint): Promise<void> {
  await client.forget(new ForgetBuilder(memoryId).build());
}

Pattern 3: Archive Cold Data

Idea: Move rarely-retrieved memories to cold storage (separate table, S3, etc.). Keep hot data in Brain.

When to use:

  • You must keep long history (compliance, audit)
  • But most queries only need recent data
  • Cold storage is much cheaper than active memory

How it works:

import os
import json
import boto3
from datetime import datetime
from brain_db_sdk import Auth, BrainClient, ForgetBuilder

client = BrainClient.connect(
    "127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
s3_client = boto3.client("s3")
S3_BUCKET = "agent_memory_archive"


def archive_cold_memories(cold_memories: list) -> dict:
    """
    Move a set of cold memory records to S3, then forget them in Brain.

    `cold_memories` is the list of records your app has decided are cold—each
    with at least an `id` and `content` (track these as you encode). Brain's
    per-shard decay + retention workers also age out stale memories server-side,
    so this pass is only for data you want in your own cold store.
    """
    if not cold_memories:
        return {"archived": 0, "reason": "No cold memories"}

    # 1. Create archive file
    archive = {
        "archived_at": datetime.utcnow().isoformat(),
        "count": len(cold_memories),
        "memories": cold_memories,
    }

    # 2. Upload to S3
    archive_key = f"archives/{datetime.utcnow().strftime('%Y-%m-%d')}.json"
    s3_client.put_object(
        Bucket=S3_BUCKET,
        Key=archive_key,
        Body=json.dumps(archive),
        ContentType="application/json",
    )

    # 3. Forget from Brain
    forgotten = 0
    for memory in cold_memories:
        client.forget(ForgetBuilder(memory["id"]).build())
        forgotten += 1

    return {
        "archived": len(cold_memories),
        "archive_key": archive_key,
        "forgotten_from_brain": forgotten,
    }

Retrieval from archive (when needed):

def retrieve_from_archive(date: str) -> list:
    """Read archived memories back from S3 if needed"""
    archive_key = f"archives/{date}.json"

    obj = s3_client.get_object(Bucket=S3_BUCKET, Key=archive_key)
    archive = json.loads(obj["Body"].read())

    return archive["memories"]

Consolidation Triggers

When should you consolidate?

TriggerConditionAction
Size-basedMemories > 1,000Consolidate oldest 500 by topic
Time-basedWeekly cron jobConsolidate duplicates, archive >30 days
Quality-basedLow retrieval scoreSummarize 10 low-scoring memories into 1
ManualUser requestRun consolidation on demand

Implementation (size-based trigger):

// Brain doesn't expose a client-side memory count, so track how many memories
// you've encoded and trigger consolidation when your own counter crosses a
// threshold.
let encodedCount = 0;

function onEncoded() {
  encodedCount++;
  if (encodedCount > 1000) {
    console.log(`Reached ${encodedCount} memories. Triggering consolidation...`);
    consolidateByTopic("observed_pattern"); // your consolidation routine
    encodedCount = 0;
  }
}

// Call onEncoded() after each encode(), or run a periodic pass:
setInterval(onEncoded, 1000 * 60 * 60);

Consolidation Patterns: Cost Impact

Consolidate 5 memories into 1; how much do you save?

BeforeAfterSavings
5 memories @ 500 bytes each1 summary @ 200 bytes80% storage, 72% retrieval tokens
50K memories, BM25 search10K summaries, BM25 search80% search time, 80% retrieval cost
3,000 vectors @ $0.001 ea600 summaries @ $0.001 ea$2.40/month per agent

At scale (100 agents, 3K memories each):

  • Before: 300K memories = 300/monthstorage+300/month storage + 300/monthstorage+150/month retrieval = $450/month
  • After: 60K summaries = 60/monthstorage+60/month storage + 60/monthstorage+30/month retrieval = $90/month
  • Savings: $360/month (80%)

Implementation Checklist

  • Choose consolidation pattern: summarize similar (topic-based), deduplicate (near-exact), or archive (cold)
  • If summarizing: identify topics (trading_losses, customer_complaints, decisions)
  • If deduplicating: lean on Brain's server-side supersession + consolidation (re-stated facts supersede older near-duplicates); forget specific redundant ids when needed
  • If archiving: define hot/cold boundaries (30 days hot, >365 days cold)
  • Implement consolidation function with error handling
  • Add consolidation trigger: size-based (>1K), time-based (weekly), or quality-based (low score)
  • Test consolidation on a staging agent before production
  • Monitor: measure token reduction, retrieval latency, cost per agent
  • Document: when consolidation runs, what gets consolidated, where archives live

Next Steps

  • Temporal management: See Temporal Context Windows for time-based memory cleanup
  • Cost optimization: Check Cost Optimization for Agent Memory for the full picture
  • Long-term memory: Read Longterm Memory for strategies that last months/years

Related reading

  • GuidesTemporal Context Windows
  • ProductionLong-Term Memory for Agents
PreviousTemporal Context Windows

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