Cache with TTL
Cache with TTL
Section titled “Cache with TTL”Build a generic, thread-safe cache with time-to-live (TTL) expiration and automatic cleanup.
Background
Section titled “Background”TTL (Time-To-Live) Cache: Items expire after a set duration. Essential for:
- Temporary data storage
- Rate limiting implementations
- Session management
- API response caching
Key features:
- Generic Types: Works with any key/value types
- Automatic Expiration: Items expire after TTL
- Background Cleanup: Goroutine periodically removes expired items
- Thread Safety: RWMutex for concurrent access
Your Task
Section titled “Your Task”Implement a generic TTL cache with:
Set(key, value)- Store item with expiration timeGet(key)- Retrieve item (only if not expired)Delete(key)- Manually remove item- Background cleanup goroutine
- Thread-safe operations
Generic TTL Cache
~45 minhard
Build a cache with time-based expiration and automatic cleanup
Key Concepts
Section titled “Key Concepts”- Generic Data Structures:
Cache[K comparable, V any]works with any key/value types - TTL Expiration: Items automatically expire after time-to-live duration
- Background Cleanup: Goroutine with ticker periodically removes expired items
- Thread Safety: RWMutex allows multiple readers or one writer
- Time Management: Use
time.Now()andtime.After()for expiration checks
Extensions
Section titled “Extensions”- Add per-item custom TTL (override default)
- Implement cache statistics (hits, misses, evictions)
- Add maximum cache size with LRU eviction
- Implement lazy deletion (only clean on access)
- Add persistence (save/load from disk)