Resource and Memory Management Principles
Universal Resource Management Rules
1. Always Clean Up Resources
Resources requiring cleanup:
- Files, network connections, database connections
- Locks, semaphores, mutexes
- Memory allocations (in manual-memory languages)
- OS handles, GPU resources
Clean up in ALL paths:
- Success path: Normal completion
- Error path: Exception thrown, error returned
- Early return path: Guard clauses, validation failures
Use language-appropriate patterns:
- Go: defer statements
- Rust: Drop trait (RAII)
- Python: context managers (with statement)
- TypeScript: try/finally
- Java: try-with-resources
2. Timeout All I/O Operations
Why timeout:
- Network requests can hang indefinitely
- Prevents resource exhaustion (connections, threads)
- Provides predictable failure behavior
Timeout recommendations:
- Network requests: 30s default, shorter (5-10s) for interactive
- Database queries: 10s default, configure per query complexity
- File operations: Usually fast, but timeout on network filesystems
- Message queue operations: Configurable, avoid indefinite blocking
3. Pool Expensive Resources
Resources to pool:
- Database connections: Pool size 5-20 per app instance
- HTTP connections: Reuse with keep-alive
- Thread pools: Size based on CPU count (CPU-bound) or I/O wait (I/O-bound)
Benefits:
- Reduces latency (no connection setup overhead)
- Limits resource consumption (cap on max connections)
- Improves throughput (reuse vs create new)
Connection Pool Best Practices:
- Minimum connections: 5 (ensures pool is warm)
- Maximum connections: 20-50 (prevents overwhelming database)
- Idle timeout: Close connections idle >5-10 minutes
- Validation: Test connections before use (avoid broken connections)
- Monitoring: Track utilization, wait times, timeout rates
4. Avoid Resource Leaks
What is a leak:
- Acquire resource (open file, allocate memory, get connection)
- Never release it (forget to close, exception prevents cleanup)
- Eventually exhaust system resources (OOM, max connections, file descriptors)
Detection:
- Monitor open file descriptors, connection counts, memory usage over time
- Run long-duration tests, verify resource counts stay stable
- Use leak detection tools (valgrind, ASan, heap profilers)
Prevention:
- Use language patterns that guarantee cleanup (RAII, defer, context managers)
- Never rely on manual cleanup alone (use language features)
5. Handle Backpressure
Problem: Producer faster than consumer
- Queue grows unbounded → memory exhaustion
- System becomes unresponsive under load
Solutions:
- Bounded queues: Fixed size, block or reject when full
- Rate limiting: Limit incoming request rate
- Flow control: Consumer signals producer to slow down
- Circuit breakers: Stop accepting requests when overwhelmed
- Drop/reject: Fail fast when overloaded (better than crashing)
Memory Management by Language Type
Garbage Collected (Go, Java, Python, JavaScript, C#):
- Memory automatically freed by GC
- Still must release non-memory resources (files, connections, locks)
- Be aware of GC pauses in latency-sensitive applications
- Profile memory usage to find leaks (retained references preventing GC)
Manual Memory Management (C, C++):
- Explicit malloc/free or new/delete
- Use RAII pattern in C++ (Resource Acquisition Is Initialization)
- Avoid manual management in modern C++ (use smart pointers: unique_ptr, shared_ptr)
Ownership-Based (Rust):
- Compiler enforces memory safety at compile time
- No GC pauses, no manual management
- Ownership rules prevent leaks and use-after-free automatically
- Use reference counting (Arc, Rc) for shared ownership
Related Principles
- Concurrency and Threading Mandate @.claude/rules/concurrency-and-threading-mandate.md
- Concurrency and Threading Principles @.claude/skills/concurrency-and-threading-principles/SKILL.md
- Error Handling Principles @.claude/rules/error-handling-principles.md - Resource cleanup in error paths
1---2name: resources-and-memory-management-33description: Apply resource lifecycle management patterns when working with files, database connections, network sockets, locks, or any resource requiring explicit cleanup. Covers RAII, defer/finally, connection pooling, graceful shutdown, and leak prevention.4---56## Resource and Memory Management Principles78### Universal Resource Management Rules910**1. Always Clean Up Resources**1112**Resources requiring cleanup:**1314- Files, network connections, database connections 15- Locks, semaphores, mutexes 16- Memory allocations (in manual-memory languages) 17- OS handles, GPU resources1819**Clean up in ALL paths:**2021- Success path: Normal completion 22- Error path: Exception thrown, error returned 23- Early return path: Guard clauses, validation failures2425**Use language-appropriate patterns:**2627- Go: defer statements 28- Rust: Drop trait (RAII) 29- Python: context managers (with statement) 30- TypeScript: try/finally 31- Java: try-with-resources3233**2. Timeout All I/O Operations**3435**Why timeout:**3637- Network requests can hang indefinitely 38- Prevents resource exhaustion (connections, threads) 39- Provides predictable failure behavior4041**Timeout recommendations:**4243- Network requests: 30s default, shorter (5-10s) for interactive 44- Database queries: 10s default, configure per query complexity 45- File operations: Usually fast, but timeout on network filesystems 46- Message queue operations: Configurable, avoid indefinite blocking4748**3. Pool Expensive Resources**4950**Resources to pool:**5152- Database connections: Pool size 5-20 per app instance 53- HTTP connections: Reuse with keep-alive 54- Thread pools: Size based on CPU count (CPU-bound) or I/O wait (I/O-bound)5556**Benefits:**5758- Reduces latency (no connection setup overhead) 59- Limits resource consumption (cap on max connections) 60- Improves throughput (reuse vs create new)6162**Connection Pool Best Practices:**6364- Minimum connections: 5 (ensures pool is warm) 65- Maximum connections: 20-50 (prevents overwhelming database) 66- Idle timeout: Close connections idle >5-10 minutes 67- Validation: Test connections before use (avoid broken connections) 68- Monitoring: Track utilization, wait times, timeout rates6970**4. Avoid Resource Leaks**7172**What is a leak:**7374- Acquire resource (open file, allocate memory, get connection) 75- Never release it (forget to close, exception prevents cleanup) 76- Eventually exhaust system resources (OOM, max connections, file descriptors)7778**Detection:**7980- Monitor open file descriptors, connection counts, memory usage over time 81- Run long-duration tests, verify resource counts stay stable 82- Use leak detection tools (valgrind, ASan, heap profilers)8384**Prevention:**8586- Use language patterns that guarantee cleanup (RAII, defer, context managers) 87- Never rely on manual cleanup alone (use language features)8889**5. Handle Backpressure**9091**Problem:** Producer faster than consumer9293- Queue grows unbounded → memory exhaustion 94- System becomes unresponsive under load9596**Solutions:**9798- Bounded queues: Fixed size, block or reject when full 99- Rate limiting: Limit incoming request rate 100- Flow control: Consumer signals producer to slow down 101- Circuit breakers: Stop accepting requests when overwhelmed 102- Drop/reject: Fail fast when overloaded (better than crashing)103104### Memory Management by Language Type105106**Garbage Collected (Go, Java, Python, JavaScript, C#):**107108- Memory automatically freed by GC 109- Still must release non-memory resources (files, connections, locks) 110- Be aware of GC pauses in latency-sensitive applications 111- Profile memory usage to find leaks (retained references preventing GC)112113**Manual Memory Management (C, C++):**114115- Explicit malloc/free or new/delete 116- Use RAII pattern in C++ (Resource Acquisition Is Initialization) 117- Avoid manual management in modern C++ (use smart pointers: unique_ptr, shared_ptr)118119**Ownership-Based (Rust):**120121- Compiler enforces memory safety at compile time 122- No GC pauses, no manual management 123- Ownership rules prevent leaks and use-after-free automatically 124- Use reference counting (Arc, Rc) for shared ownership125126### Related Principles127- Concurrency and Threading Mandate @.claude/rules/concurrency-and-threading-mandate.md128- Concurrency and Threading Principles @.claude/skills/concurrency-and-threading-principles/SKILL.md129- Error Handling Principles @.claude/rules/error-handling-principles.md - Resource cleanup in error paths