Memory Cleanup for Long-Running Apps
Long-running multi-agent applications can accumulate memory over time, leading to performance degradation and potential crashes. This guide covers best practices for effective memory management.Understanding Memory Issues
Common Memory Problems
- Memory Leaks: Unreleased references to objects
- Conversation History Accumulation: Growing chat histories
- Cache Overflow: Unbounded caching
- Circular References: Objects referencing each other
- Resource Handles: Unclosed files, connections, etc.
Bounding In-Memory Growth
For long-running agents, prevent unbounded memory growth using theInMemoryAdapter with size limits:
The existing helper class
ResourcePool in this page with max_size=10 is unrelated to the new InMemoryAdapter(max_size=...) parameter. They serve different purposes: ResourcePool manages connection pools, while InMemoryAdapter manages memory entry limits.Memory Management Strategies
1. Conversation History Management
Implement sliding window or summary-based history management:2. Agent Memory Management
Memory construction is now thread-safe and async-safe. ConcurrentTasks sharing a memory_config will coordinate through locks rather than each creating duplicate stores.
3. Resource Pool Management
Implement resource pooling to prevent resource exhaustion:4. Cache Management
Implement LRU cache with memory limits:Memory Monitoring
1. Memory Usage Tracking
2. Automatic Garbage Collection
3. Agent Garbage Collection Safety Net
Since PR #1514,Agent.__del__ runs a best-effort close_connections() during garbage collection as a safety net. However, this may be skipped by the Python interpreter and must not be relied upon. Always use explicit cleanup:
Profiler buffers are bounded
EnablingProfiler no longer leaks memory in long-running processes. All record lists are now deque(maxlen=PRAISONAI_PROFILE_MAX) (default 10,000) which fixes the prior class-level List[...] storage that grew unbounded.
Key improvements:
- Memory-safe: Fixed maximum memory usage per buffer
- Ring buffer: Only keeps the most recent N records
- Configurable: Set
PRAISONAI_PROFILE_MAXenvironment variable - Production-ready: Safe for long-running agents
Best Practices
1. Use Context Managers
Always use context managers for resource management:2. Implement Memory Budgets
Set memory budgets for different components:3. Profile Memory Usage
Regular profiling helps identify memory issues:Common Pitfalls
- Unbounded Collections: Always set limits on collections
- Circular References: Use weak references where appropriate
- Global State: Minimize global state that accumulates data
- Event Listeners: Always unregister event listeners
- Thread Local Storage: Clean up thread-local data

