Arc Labs
BrainDocsPricing
GitHubSign inGet Started
LearnGuides

Cost Optimization for Agent Memory

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

Memory system costs (storage, compute, APIs) can be cut 30–50% using schema typing, aggressive eviction, deduplication, retrieval caps, and self-hosted-vs-cloud trade-offs—without sacrificing agent quality.

The Problem: Memory Costs Grow Unbounded

Agent memory systems can become expensive:

  • Storage bloat: Every agent session, every conversation turn stored forever. 1000 agents × 100 queries/day × 365 days = 36.5M entries. At $0.10/GB/month, that's expensive.
  • Redundant data: Customer ID "12345" stored 500 times across memory entries. Same semantic concept (e.g., "user prefers Nike") stored in 5 different ways.
  • Expensive retrieval: Semantic search costs (embeddings, compute) charged per query. Retrieving 1000 results to filter down to 5 wastes API budget.
  • Old data kept forever: Memory from 2024 still retrieved and charged for, even though it's irrelevant now.
  • Compute overhead: Cloud memory solutions charge for CPU, storage, and API calls. Self-hosting the open-source server (free software) can save 80% on those fees, but you take on running the infra.

Result: Monthly memory bills grow 20–30% month-over-month, eating into agent profitability.

Five optimization strategies cut costs 30–50% while maintaining quality.

Strategy 1: Schema Typing & Structured Fields

The cost: Unstructured free-text memory requires semantic search (expensive embeddings + compute per query).

The fix: Use typed fields for common queries. Metadata filters are 10–100x cheaper than semantic search.

Example Before (Expensive):

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 });

// One long, unstructured sentence—recall has to lean hard on the semantic retriever
await client.encode(
  new EncodeBuilder(
    "Customer ordered Nike Air Jordan 1 Low on 2026-05-01, size 11, price $150, black color"
  ).build()
);

const answer = await client.recall(
  new RecallBuilder("What Nike shoes did customer buy?").maxResults(5).build()
);

Example After (Efficient):

// Clear, atomic facts—Brain's write-path extractors pull typed entities and
// statements (brand=Nike, product=Air Jordan 1 Low, category=shoes) from the
// text, so recall's graph retriever can anchor on them instead of relying on
// embeddings alone. You write plain text; the structure is built server-side.
await client.encode(new EncodeBuilder("Customer purchased Nike Air Jordan 1 Low, size 11, black.").build());

// Recall fuses semantic + lexical + graph; the extracted entities sharpen it
const answer = await client.recall(
  new RecallBuilder("Nike shoe purchases").maxResults(5).build()
);

Cost reduction: Concise, well-formed memories extract cleanly into the typed graph, so recall resolves on fewer, higher-signal candidates instead of scanning long free-text blobs.

Strategy 2: Aggressive Eviction & TTL

The cost: Storing irrelevant old memory forever.

The fix: Set time-to-live (TTL) and eviction policies by memory type.

Example:

import { ForgetBuilder } from "@brain-db/sdk";

interface EvictionPolicy {
  type: string;
  ttl_days: number;
  keep_most_recent_n: number; // Keep top N even if expired
  reason: string;
}

const policies: EvictionPolicy[] = [
  {
    type: "browsing_session",
    ttl_days: 30,
    keep_most_recent_n: 5,
    reason: "Sessions older than 30d are not predictive; keep 5 most recent for trend analysis",
  },
  {
    type: "purchase_history",
    ttl_days: null, // Never expire
    keep_most_recent_n: 1000,
    reason: "Purchase history is always relevant",
  },
  {
    type: "preference_fact",
    ttl_days: 180,
    keep_most_recent_n: null,
    reason: "Preferences change every ~6 months; older ones are stale",
  },
  {
    type: "temporary_context",
    ttl_days: 7,
    keep_most_recent_n: 1,
    reason: "Temporary context (API rate limits, current task) is short-lived",
  },
];

// Implementation: Brain's per-shard decay + retention workers age out stale
// memories server-side, so you configure aging at deploy time rather than
// running a client-side eviction cron. For explicit, immediate removal of
// entries you've tracked, forget them by id.
async function evict_tracked(staleIds: bigint[]) {
  for (const id of staleIds) {
    await client.forget(new ForgetBuilder(id).build());
  }
  console.log(`Forgot ${staleIds.length} stale entries`);
}

Cost reduction: 40–60% storage reduction by removing old, irrelevant data.

Strategy 3: Deduplication & Consolidation

The cost: Same fact stored multiple times (e.g., "user prefers Nike" stored 5 different ways).

The fix: Deduplicate on write. Merge similar entries into one.

Example:

// BAD: Same preference stored 5 times
[
  "Customer prefers Nike",
  "Customer likes Nike shoes",
  "Nike is customer favorite brand",
  "Customer always buys Nike",
  "Prefers Nike over Adidas",
]

// GOOD: Single consolidated entry with metadata
{
  content: "Customer prefers Nike over competitors",
  type: "preference_fact",
  metadata: {
    preference: "brand",
    value: "Nike",
    strength: "very_strong", // Inferred from frequency
    observed_count: 5, // Deduplicated 5 observations
    first_observed: "2026-01-15",
    last_updated: "2026-05-12",
  },
}

// Implementation: you don't dedupe on the client. Brain's write path runs
// extraction, supersession, and predicate consolidation on every shard, so a
// re-stated fact ("Customer prefers Nike") supersedes the older observation of
// the same fact instead of accumulating a near-duplicate vector. Just encode
// each observation as you see it:
async function record_observation(content: string) {
  await client.encode(new EncodeBuilder(content).build());
}

Cost reduction: 30–40% storage reduction—Brain consolidates re-stated facts server-side instead of storing every rephrasing.

Strategy 4: Retrieval Caps & Caching

The cost: Retrieving 1000 results to use 5 (100 embeddings computed, all charged).

The fix: Cap topK by necessity, cache frequent queries.

Example:

import { LRUCache } from "lru-cache";
import { RecallBuilder } from "@brain-db/sdk";

const recallCache = new LRUCache<string, any>({
  max: 1000, // Cache 1000 queries
  ttl: 1000 * 60 * 5, // 5-minute TTL
});

async function recall_with_caching(query: string, maxResults = 5) {
  // Create cache key
  const cacheKey = `${query}:${maxResults}`;

  // Check cache first
  const cached = recallCache.get(cacheKey);
  if (cached) {
    return cached;
  }

  // Cap maxResults to reduce work
  const cap = Math.min(maxResults, 10); // Never ask for >10, even if requested

  const answer = await client.recall(new RecallBuilder(query).maxResults(cap).build());

  // Cache result
  recallCache.set(cacheKey, answer.memories);

  return answer.memories;
}

// Example: Don't over-fetch. Ask a precise query with a tight cap.
// BEFORE (expensive):
// const all = await client.recall(new RecallBuilder("purchases").maxResults(100).build());
// const nike = all.memories.filter((h) => h.text.includes("Nike")).slice(0, 5);

// AFTER (efficient):
// const nike = await client.recall(new RecallBuilder("Nike purchases").maxResults(5).build());

Cost reduction: 40–80% retrieval cost reduction via caching and strict topK limits.

Strategy 5: Self-Hosted vs. Cloud Trade-Offs

The cost: Cloud memory solutions charge per API call.

The fix: Evaluate self-hosting the open-source server vs. managed cloud.

DeploymentCost per QueryLatencyOps OverheadData SovereigntyBest For
Self-Hosted (single node)$0.00<\10ms (co-located)Low100%≤1000 agents, strict latency SLA, privacy-critical
Cloud (Brain managed, Pinecone)0.001–0.001–0.001–0.01 per query50–200msMinimal (Brain manages)Provider-hosted1000+ agents, scaling budget, dev velocity
Self-Hosted (HA cluster)$0.0001 per query + infra30–100msHigh (ops team manages)Self-hosted10k+ agents, cost-sensitive, custom logic

Decision logic:

// Estimate monthly cost
function estimate_memory_cost(agents: number, queries_per_day: number, deployment: "single_node" | "cloud" | "ha_cluster") {
  const queries_per_month = agents * queries_per_day * 30;
  
  switch (deployment) {
    case "single_node":
      return 0; // Free software, but limited to ~1000 agents per node
    
    case "cloud":
      const cost_per_query = 0.005; // Brain managed: ~$0.005/query
      const monthly_api_cost = queries_per_month * cost_per_query;
      const monthly_storage_cost = agents * 1000 * 0.0001; // $0.0001 per GB/month
      return monthly_api_cost + monthly_storage_cost;
    
    case "ha_cluster":
      const server_cost = 1000; // Modest multi-node cluster + compute: $1000/month
      const self_query_cost = queries_per_month * 0.0001;
      return server_cost + self_query_cost;
  }
}

// Example
const cost_cloud = estimate_memory_cost(5000, 1000, "cloud"); // ~$150/month
const cost_self_hosted = estimate_memory_cost(5000, 1000, "ha_cluster"); // ~$1150/month
// Cloud is cheaper at 5k agents. If you had 50k agents, a self-hosted cluster wins.

Decision flowchart:

Do you have &lt;\1000 agents?
  ├─ YES, low latency critical (&lt;\10ms)?
  │  └─ Self-host a single node (co-located)
  │
  ├─ YES, willing to accept 50–200ms?
  │  └─ Use Cloud (Brain managed, scale later)
  │
  └─ NO, have 1000–10k agents?
     └─ Use Cloud (cost-effective, ops-simple)

Do you have >50k agents AND ops budget?
  └─ Consider a Self-Hosted HA cluster (lower per-query cost)

Cost Comparison Table: Before & After Optimization

ComponentBeforeAfterSavings
Storage (12-month history, 10k agents)250 GB @ 0.10/GB=0.10/GB = 0.10/GB=300/month100 GB @ 0.10/GB=0.10/GB = 0.10/GB=100/month67%
Retrieval API (1M queries/day)1M × 0.005=0.005 = 0.005=5000/month300k queries (caching + caps) × 0.005=0.005 = 0.005=1500/month70%
Deduplication overheadNone10 CPU hours/month to dedupe+$10
TTL/Eviction jobNone5 CPU hours/month+$5
Total Monthly$5300/month$1615/month70% savings

Implementation Checklist

  • Schema audit: Review all memory types. Are high-volume types using semantic search? Move to metadata filters where possible.
  • TTL policy design: Define TTL and keep_most_recent_n for each memory type. Test on staging.
  • Deduplication: Rely on Brain's server-side supersession + predicate consolidation (re-stated facts supersede older near-duplicates); forget() specific ids when you need explicit removal.
  • Retrieval optimization: Set strict maxResults limits (≤10). Add a caching layer with 5–15 minute TTL.
  • Deployment evaluation: Estimate cost for current agent count. Would self-hosting save money?
  • Cost monitoring: Add metrics for queries_per_month, storage_gb, api_cost_per_month. Track weekly.
  • A/B test changes: Deploy schema change to 5% of agents, verify hit rate and latency stay >95% of baseline before rolling out.

Cost Monitoring Dashboard

Track these metrics weekly:

Memory Cost Metrics (Weekly)
├─ Total Queries: 500k (↓10% vs. last week)
├─ Storage: 120 GB (↓5% via TTL)
├─ Estimated Monthly Cost: $1,850 (↓$200 since optimization started)
├─ Cost Per Agent Per Month: $0.37 (target: <$0.50)
├─ Hit Rate: 73% (baseline: 72%)
└─ P99 Latency: 92ms (baseline: 95ms, acceptable)

Next Steps

  • Schema design: See Choosing Your Memory Schema for best practices on typed fields
  • Deployment: Check Self-Hosted vs Managed Cloud for a detailed comparison
  • Monitor: Review Memory Monitoring & Observability to track cost-related metrics

Related reading

  • GuidesChoosing Your Memory Schema
  • GuidesSelf-Hosted vs Managed Cloud
PreviousProduction Deployment ChecklistNextChoosing Your Memory Schema

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