Caching in Go: Redis, Memcached, and Built-in Solutions: From A to Z

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Caching in Go: Redis, Memcached, and Built-in Solutions: From A to Z

\n\n

Caching is one of the key tools for improving the performance of web applications and microservices. In Go (Golang), there are many approaches: from simple in-memory maps to powerful distributed systems like Redis and Memcached. In this article, we will cover all popular caching options in Go with code examples, compare their performance, and show best practices for implementation.

\n\n

Why is caching needed in Go?

\n

Without a cache, every data access can lead to expensive operations: database queries, external API calls, or complex computations. Caching allows you to save the result of the first operation and quickly serve it on subsequent requests. This reduces backend load, lowers latency, and improves user experience. In Go, thanks to goroutines and high concurrency, proper cache implementation is especially important.

\n\n

1. Built-in Solutions: sync.Map and bigcache

\n

For small projects or cases where distribution is not required, Go offers built-in caching mechanisms.

\n\n

1.1 sync.Map

\n

sync.Map is a thread-safe map from the Go standard library. It is optimized for cases where keys are written once and read many times. It is ideal for caches with low update frequency.

\n
package main\n\nimport (\n    "fmt"\n    "sync"\n)\n\nfunc main() {\n    var cache sync.Map\n\n    // Write\n    cache.Store("user:1", "Alice")\n    cache.Store("user:2", "Bob")\n\n    // Read\n    if value, ok := cache.Load("user:1"); ok {\n        fmt.Println("Found:", value)\n    }\n\n    // Delete\n    cache.Delete("user:2")\n\n    // Iteration (Range)\n    cache.Range(func(key, value interface{}) bool {\n        fmt.Printf("Key: %v, Value: %v\\n", key, value)\n        return true\n    })\n}
\n

Pros: no external dependencies, simple API, thread-safe.
\nCons: no TTL (time-to-live), no size limit, performance degrades with frequent writes.

\n\n

1.2 BigCache

\n

BigCache is a fast, in-memory caching library specifically designed for Go. It minimizes memory allocations and supports TTL.

\n
package main\n\nimport (\n    "fmt"\n    "time"\n    "github.com/allegro/bigcache/v3"\n)\n\nfunc main() {\n    config := bigcache.Config{\n        Shards:             1024,\n        LifeWindow:         10 * time.Minute,\n        CleanWindow:        5 * time.Minute,\n        MaxEntriesInWindow: 1000,\n        MaxEntrySize:       500,\n        Verbose:            true,\n    }\n\n    cache, err := bigcache.NewBigCache(config)\n    if err != nil {\n        panic(err)\n    }\n\n    // Write\n    cache.Set("session:abc123", []byte("user_data"))\n\n    // Read\n    data, err := cache.Get("session:abc123")\n    if err == nil {\n        fmt.Println("Data:", string(data))\n    }\n}
\n

Pros: high speed, TTL support, low GC (Garbage Collector) overhead.
\nCons: only for a single application instance, no replication.

\n\n

2. Memcached in Go

\n

Memcached is a distributed in-memory caching system. It is simple but very fast and supports TTL. In Go, the driver github.com/bradfitz/gomemcache/memcache is used to work with Memcached.

\n
package main\n\nimport (\n    "fmt"\n    "github.com/bradfitz/gomemcache/memcache"\n)\n\nfunc main() {\n    mc := memcache.New("127.0.0.1:11211")\n\n    // Write\n    err := mc.Set(&memcache.Item{\n        Key:   "user:42",\n        Value: []byte("John Doe"),\n        Expiration: 300, // 5 minutes\n    })\n    if err != nil {\n        panic(err)\n    }\n\n    // Read\n    item, err := mc.Get("user:42")\n    if err == nil {\n        fmt.Println("Value:", string(item.Value))\n    }\n\n    // De                

Blogs

Book Recommendations