Go Redis caching keeps copies of popular data in fast memory. So your API can answer in a millisecond instead of waiting on the database. In this post, you will learn what a cache is and how the cache-aside pattern works. Then we will add Redis to a Go book API with expiry times and safe invalidation.
So far, every request in our book store went to PostgreSQL, as in Go PostgreSQL with pgx. That is fine for small traffic. However, popular pages ask for the same rows again and again. We also store cached values as JSON, which you learned in Go JSON encoding and decoding.
What Is Go Redis Caching?
A cache is a small, fast store that keeps copies of data you read often. Redis is a popular in-memory data store that works well as that cache. So with Go Redis caching, your service checks Redis first. Then it asks the database only when Redis does not have the answer.
For example, think of a shop counter and a back store room. The shopkeeper keeps the best-selling items on the counter, so most customers get served in seconds. Only rare items need a trip to the back. Similarly, Redis is the counter, and PostgreSQL is the store room.
Redis keeps data in memory, so reads are extremely fast. Also, every key can have an expiry time, after which Redis deletes it automatically.
Why Go Redis Caching Matters
A database is the slowest part of most web requests. Therefore, cutting even a few queries can make a big difference. Here is where Go Redis caching helps most.
- Popular product or book pages: thousands of users read the same few records.
- Expensive reports: a slow query runs once, and the result serves everyone for a few minutes.
- Session data: login sessions live in Redis, so any app server can read them.
- Rate limits and counters: Redis increments numbers safely across many servers.
- Protecting the database: during a traffic spike, the cache absorbs most reads.
In short, Go Redis caching makes your API faster and your database calmer.
How Go Redis Caching Works: Cache-Aside
The most common pattern is called cache-aside, or lazy loading. First, the handler asks Redis for the key. If Redis has it, that is a cache hit, and we return it at once. Otherwise, it is a cache miss. Then we load the data from the database, save a copy in Redis with an expiry time and return it.

When data changes, the cache must not keep the old copy forever. So on every update, we delete the key. As a result, the next read misses, loads fresh data and caches it again.
Key Redis Commands for Caching
Redis has many commands, but caching needs only a few. We ran each of them in redis-cli against Redis 7, and this table shows what they return.
| Command | Example | Result |
|---|---|---|
SET with EX | SET book:1 '{...}' EX 300 | OK, key expires in 300 seconds |
GET | GET book:1 | The stored JSON, or nil if missing |
TTL | TTL book:1 | Seconds left, such as 300 |
DEL | DEL book:1 | 1 if a key was deleted |
SET with NX | SET lock:report 1 NX EX 30 | OK only if the key did not exist |
INCR | INCR views:book:1 | The new count, such as 1, then 2 |
Keys and Naming
Redis keys are plain strings. So pick a clear pattern such as book:42 or user:7:profile. As a result, you can find and delete related keys easily.
TTL: Time To Live
TTL is how long a key lives before Redis removes it. A short TTL means fresher data, while a long TTL means fewer database hits. For most API reads, 1 to 10 minutes is a good start.
Local Map Cache vs Go Redis Caching
You could also cache data in a Go map inside your process. The table below compares the two choices.
| Feature | In-process Go map | Redis |
|---|---|---|
| Speed | Fastest, no network | Very fast, one network hop |
| Shared across servers | No, each server has its own | Yes, one shared cache |
| Survives a restart | No | Yes, with persistence on |
| Built-in expiry | You write it yourself | EX and TTL built in |
| Memory limit | Your app’s memory | A separate server you can size |
| Best for | Tiny, rarely changing data | Most web APIs |

So when should you use which? Use a local map only for small data that rarely changes, such as a country list. Otherwise, use Redis, because every server then sees the same cached values.
Hands-On: Add Go Redis Caching to a Book API
Let’s add Go Redis caching to the book lookup. We will use the official go-redis client.
Step 1: Start Redis and Add the Client
First, run Redis with Docker, then add the Go package.
docker run -d --name redis -p 6379:6379 redis:7
go get github.com/redis/go-redis/v9
Step 2: Connect to Redis
Next, create one client at startup and check the connection.
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
defer rdb.Close()
ctx := context.Background()
if err := rdb.Ping(ctx).Err(); err != nil {
log.Fatalf("cannot reach redis: %v", err)
}
The client keeps its own connection pool. So, like the pgx pool, you create it once and share it across all handlers.
Step 3: The Cache-Aside Function
This function does the full hit and miss logic for one book.
func getBook(ctx context.Context, rdb *redis.Client, db BookStore, id int64) (Book, error) {
key := fmt.Sprintf("book:%d", id)
// 1. Try the cache first.
data, err := rdb.Get(ctx, key).Bytes()
if err == nil {
var b Book
if json.Unmarshal(data, &b) == nil {
log.Println("cache hit", key)
return b, nil
}
} else if !errors.Is(err, redis.Nil) {
log.Println("redis error, using database:", err)
}
// 2. Cache miss: load from the database.
b, err := db.GetBook(ctx, id)
if err != nil {
return Book{}, err
}
// 3. Save a copy for five minutes.
if data, err := json.Marshal(b); err == nil {
if err := rdb.Set(ctx, key, data, 5*time.Minute).Err(); err != nil {
log.Println("cache set failed:", err)
}
}
log.Println("cache miss", key)
return b, nil
}
Let’s walk through the important lines. First, redis.Nil is the special error for “key not found”, so it is a normal miss, not a failure. Next, if Redis itself is down, we log the problem and still serve from the database. Then Set with 5*time.Minute stores the JSON with a TTL. Finally, a failed Set only logs a warning, because the user already has the right data.
Step 4: Invalidate on Update
When a book changes, we update the database first and then delete the cached copy.
func updatePrice(ctx context.Context, rdb *redis.Client, db BookStore, id int64, price int) error {
if err := db.UpdatePrice(ctx, id, price); err != nil {
return err
}
return rdb.Del(ctx, fmt.Sprintf("book:%d", id)).Err()
}
Deleting is safer than writing the new value into the cache. Otherwise, two updates racing each other could leave an old price in Redis.
Step 5: See It Work
To test our Go Redis caching code, call getBook twice for the same ID, update the price, and call it again. If the database lookup takes about 40 ms, the log looks roughly like this.
cache miss book:1 (about 40ms)
cache hit book:1 (under 1ms)
price updated, key book:1 deleted
cache miss book:1 (about 40ms)
The second read skips PostgreSQL completely. Meanwhile, the read after the update misses on purpose, so users never see the old price.
Avoiding a Cache Stampede
Imagine a very popular book page whose key just expired. Suddenly, hundreds of requests miss at the same moment, and all of them hit PostgreSQL together. This is called a cache stampede, and it can overload the database in seconds.
One simple fix uses the SET ... NX command from the table above. Only the request that wins a short lock reloads the data. Meanwhile, the others wait briefly and then read the fresh cache.
ok, err := rdb.SetNX(ctx, "lock:"+key, 1, 10*time.Second).Result()
if err == nil && ok {
defer rdb.Del(ctx, "lock:"+key)
// This request reloads from the database and fills the cache.
} else {
time.Sleep(50 * time.Millisecond)
// Then try reading the cache again.
}
Here, SetNX returns true only for the first caller. Also, the 10 second expiry frees the lock even if that request crashes. For most small apps, you will not need this. However, it is worth knowing once your Go Redis caching layer serves heavy traffic.
Common Mistakes with Go Redis Caching
- No TTL on keys: Redis fills up and serves stale data forever. So always set an expiry.
- **Treating
redis.Nilas an error**: every miss then returns a 500. Check it witherrors.Is. - Failing the request when Redis is down: the cache becomes a single point of failure. Fall back to the database instead.
- Updating the cache instead of deleting it: racing writes can store old values. Delete the key on change.
- Caching per-user secrets under shared keys: users may see each other’s data. Include the user ID in the key.
Best Practices for Go Redis Caching
- Cache data that is read often and changes rarely, because that gives the biggest win.
- Use clear key names with prefixes, so you can debug and clean up easily.
- Add a little random jitter to TTLs, as many keys expiring together can flood the database.
- Set timeouts on the Redis client, since a slow cache should never slow the whole request.
- Measure hit rate, because a cache with a low hit rate only adds work.
Practice Task
Cache the list of books by author under the key books:author:Asha. Then make sure updatePrice also deletes that list key, so the list never shows an old price.
Hint: decide carefully which keys each update can affect.
Official Resources
These pages cover the client and the Redis commands in detail.
Quick Recap
- Go Redis caching stores copies of popular data in fast memory.
- Cache-aside checks Redis first and loads from the database on a miss.
redis.Nilmeans “not found”, so treat it as a normal miss.- Always set a TTL, and delete keys when the data changes.
- Fall back to the database when Redis is slow or down.
- Use Redis instead of a local map when you run more than one server.
What’s Next?
Our API is fast now, so it is time to protect it. Next, we will store user passwords safely with bcrypt before building login.
Next lesson: Go Password Hashing with bcrypt Explained


