Caching in Go (Golang): Redis and Other Tools
Caching is one of the key mechanisms for optimizing the performance of web applications and microservices. In the Go (Golang) ecosystem, there are many libraries for implementing caching, from simple in-memory solutions to distributed systems based on Redis. In this article, we will thoroughly examine three main approaches: built-in data structures (sync.Map), popular in-memory libraries (go-cache, freecache, bigcache), and integration with Redis.
1. Built-in Tools: sync.Map
Go provides a thread-safe map — sync.Map. It is suitable for simple caching with a small amount of data and infrequent updates. However, its performance under high loads is inferior to specialized libraries.
Example of using sync.Map:
package main
import ( "fmt" "sync" "time")
func main() { var cache sync.Map
// Write cache.Store("user:42", map[string]interface{}{ "name": "Alice", "age": 30, })
// Read with check if val, ok := cache.Load("user:42"); ok { fmt.Println("Cache found:", val) }
// Delete cache.Delete("user:42")
// Caching with TTL (must be implemented manually) cache.Store("session:abc", time.Now().Unix())}Disadvantages: lack of automatic TTL, limited set of operations, potential performance issues with frequent writes.
2. In-memory Libraries
For more complex scenarios, use specialized libraries. Let's look at three popular ones:
2.1 go-cache
A simple library with TTL support. Ideal for small projects.
import "github.com/patrickmn/go-cache"
func main() { c := cache.New(5*time.Minute, 10*time.Minute) // default TTL, cleanup interval
c.Set("key", "value", cache.DefaultExpiration) val, found := c.Get("key") if found { fmt.Println(val) }}2.2 freecache
A library with a fixed memory size (no GC overhead). Supports TTL and high performance.
import "github.com/coocood/freecache"
func main() { cache := freecache.NewCache(100 * 1024 * 1024) // 100 MB
cache.Set([]byte("mykey"), []byte("myvalue"), 60) // TTL 60 sec val, err := cache.Get([]byte("mykey")) if err == nil { fmt.Println(string(val)) }}2.3 bigcache
Optimized for storing large amounts of data without GC pauses. Works with serialized data.
import "github.com/allegro/bigcache/v3"
func main() { cache, _ := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute))
cache.Set("key", []byte("value")) val, _ := cache.Get("key") fmt.Println(string(val))}3. Redis: Distributed Caching
For distributed systems and microservices, Redis remains the de facto standard. In Go, use the go-redis/redis library (v9+).
Connection and basic operations:
import ( "context" "fmt" "github.com/redis/go-redis/v9")
func main() { ctx := context.Background() rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, })
// Set value with TTL err := rdb.Set(ctx, "user:42", `{"name":"Bob"}`, 10*time.Minute).Err() if err != nil { panic(err) }
// Read val, err := rdb.Get(ctx, "user:42").Result() if err == redis.Nil { fmt.Println("Cache not found") } else if err != nil { panic(err) } else { fmt.Println("Value:", val) }}Advanced Redis features in Go:
- Pipeline
Also in library
Data Validation in Swift (iOS/macOS): Libraries and Approaches
Creating CLI Applications in TypeScript: Overview of Frameworks and Tools
Working with CSV in C++: Libraries, Parsing, and Data Writing
NHibernate for C# (.NET): Complete Guide with Examples