Skip to content

Cache with TTL

Build a generic, thread-safe cache with time-to-live (TTL) expiration and automatic cleanup.

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

Implement a generic TTL cache with:

  1. Set(key, value) - Store item with expiration time
  2. Get(key) - Retrieve item (only if not expired)
  3. Delete(key) - Manually remove item
  4. Background cleanup goroutine
  5. Thread-safe operations

Generic TTL Cache

~45 minhard

Build a cache with time-based expiration and automatic cleanup

  • 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() and time.After() for expiration checks
  • 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)