Define short-term versus long-term retention so the store stays fresh.
While building memory systems, we realized their size grows fast. Session notes, temporary context, chat history - everything starts accumulating and bogging down the system. This pollutes search results and increase storage costs. Not every memory needs to persist forever.In this cookbook, we’ll go through how to use short-term vs long-term memories and see where it’s best to use them.
By default, Mem0 memories persist forever. This works for user preferences and core facts, but temporary data should expire automatically.In this tutorial, we will:
from mem0 import MemoryClientfrom datetime import datetime, timedeltaclient = MemoryClient(api_key="your-api-key")
Import datetime and timedelta to calculate expiration dates. Without these imports, you’ll need to manually format ISO timestamps—error-prone and harder to read.
# Store user preferenceclient.add("User prefers dark mode", user_id="sarah")# Store session contextclient.add("Currently browsing electronics category", user_id="sarah")# 6 months later - both still existresults = client.get_all(filters={"user_id": "sarah"})print(f"Total memories: {len(results['results'])}")
Output:
Copy
Ask AI
Total memories: 2
Both the preference and session context persist. The preference is useful, but the 6-month-old session context is not.
Without expiration, memories accumulate forever. Session notes from weeks ago mix with current preferences. Storage grows, search results get polluted with irrelevant old context, and retrieval quality degrades.
Memory bloat degrades search quality. When “User prefers dark mode” competes with “Currently browsing electronics” from 6 months ago, semantic search returns stale session data instead of actual preferences. Old memories pollute retrieval.
from datetime import datetime, timedelta# Session context - expires in 7 daysexpires_at = (datetime.now() + timedelta(days=7)).isoformat()client.add( "Currently browsing electronics category", user_id="sarah", expiration_date=expires_at)# User preference - no expiration, persists foreverclient.add( "User prefers dark mode", user_id="sarah")
Expected behavior: After 7 days, the session context automatically disappears—no cron jobs, no manual cleanup. The preference persists forever. Mem0 handles expiration transparently.
Memories with expiration_date are automatically removed after expiring. No cleanup job needed - Mem0 handles it.
Start conservative with short expiration windows (7 days), then extend them based on usage patterns. It’s easier to increase retention than to clean up over-retained stale data. Monitor search quality to find the right balance.
client.add("User prefers email notifications", user_id="sarah")client.add("User's birthday is March 15th", user_id="sarah")client.add("User completed onboarding on Jan 5th", user_id="sarah")
results = client.get_all(filters={"user_id": "sarah"})for memory in results['results']: exp_date = memory.get('expiration_date') if exp_date: print(f"Temporary: {memory['memory']}") print(f" Expires: {exp_date}\\n") else: print(f"Permanent: {memory['memory']}\\n")
Output:
Copy
Ask AI
Temporary: Browsing electronics Expires: 2025-11-01T10:30:00ZTemporary: Viewed MacBook Pro and Dell XPS Expires: 2025-11-01T10:30:00ZPermanent: User prefers dark modePermanent: User prefers email notifications
Memory expiration keeps storage clean and search results relevant. Use expiration_date for temporary data (session context, recent chats), skip it for permanent facts (preferences, account info). Mem0 handles cleanup automatically—no background jobs required.Start by identifying what’s temporary versus permanent, then set conservative expiration windows and adjust based on retrieval quality.
Control Memory Ingestion
Pair expirations with ingestion rules so only trusted context persists.
Export Memories Safely
Build compliant archives once your retention windows are dialed in.