# go-cache — In-Memory Key-Value Cache for Go Applications > A thread-safe in-memory key-value store for Go with expiration support, suitable for single-machine applications that need a simple caching layer without external dependencies like Redis. ## Install Save as a script file and run: # go-cache — In-Memory Key-Value Cache for Go Applications ## Quick Use ```bash go get github.com/patrickmn/go-cache import ( "fmt" "time" "github.com/patrickmn/go-cache" ) func main() { // Create cache with 5-minute default expiration, 10-minute cleanup interval c := cache.New(5*time.Minute, 10*time.Minute) c.Set("user:123", "Alice", cache.DefaultExpiration) c.Set("session:abc", sessionData, 30*time.Minute) if val, found := c.Get("user:123"); found { fmt.Println(val) // "Alice" } } ``` ## Introduction go-cache is an in-memory key-value cache library for Go that stores arbitrary data with optional expiration times. It is designed for single-process applications that need a fast, thread-safe caching layer without the operational overhead of an external cache server. Items expire automatically and are cleaned up by a background goroutine. ## What go-cache Does - Stores any Go value by string key with configurable per-item expiration - Provides thread-safe concurrent access using sync.RWMutex - Runs a background janitor goroutine that removes expired items at a configurable interval - Supports atomic increment and decrement operations on numeric values - Allows serialization of cache contents to and from files for persistence across restarts ## Architecture Overview go-cache wraps a map[string]Item behind a sync.RWMutex for concurrent safety. Each Item holds the value as an interface{} and an expiration timestamp. A separate janitor goroutine periodically scans the map and deletes expired entries. The library keeps the design intentionally simple: no sharding, no eviction policies, and no distributed features, prioritizing ease of use for single-node scenarios. ## Self-Hosting & Configuration - Import the package and create a cache with New(defaultExpiration, cleanupInterval) - Set items with per-key expiration or use cache.DefaultExpiration for the cache-wide default - Use cache.NoExpiration for items that should never expire automatically - Call SaveFile/LoadFile to persist cache state to disk and restore on startup - Set an OnEvicted callback to run custom logic when items are removed ## Key Features - Zero dependencies: pure Go with no external packages required - Thread-safe: concurrent reads and writes are safe out of the box - Flexible expiration: per-item TTLs, default TTL, or no expiration - Atomic counters: Increment and Decrement operations for rate limiting and metrics - Persistence: save and load cache contents to files for crash recovery ## Comparison with Similar Tools - **Ristretto** — more sophisticated cache with admission and eviction policies (TinyLFU); better for high-throughput scenarios where hit ratio optimization matters - **BigCache** — designed for large datasets with reduced GC pressure via byte-level storage; go-cache is simpler for general-purpose use - **FreeCache** — zero-GC cache using pre-allocated memory; trades flexibility for GC performance - **Redis** — external cache server with persistence, replication, and data structures; go-cache avoids network overhead for single-process needs ## FAQ **Q: Is go-cache suitable for production use?** A: Yes, for single-process applications. It is widely used in production for API response caching, session storage, and rate limiting within a single Go service. **Q: How does it handle memory limits?** A: go-cache does not enforce memory limits or eviction policies. If you need bounded memory, consider Ristretto or BigCache which support size-based eviction. **Q: Is the cache shared across multiple Go processes?** A: No. go-cache is in-process only. For shared caching across services, use Redis, Memcached, or a distributed cache. **Q: Can I iterate over all items?** A: Yes. Use the Items() method to get a copy of all unexpired items as a map, or use the cache's internal map with appropriate locking. ## Sources - https://github.com/patrickmn/go-cache - https://pkg.go.dev/github.com/patrickmn/go-cache --- Source: https://tokrepo.com/en/workflows/asset-8ff34ad4 Author: Script Depot