After building APIs in Go, the next big question is:
π How do you make them faster?
This is where Redis comes in.
In this post, weβll:
- Connect Go with Redis
- Cache API responses
- Reduce database load
- Improve performance
π§ What is Redis?
Redis is an in-memory database used for:
- Caching
- Sessions
- Queues
- Real-time systems
Think of Redis like:
π βSuper-fast temporary storageβ
Instead of hitting PostgreSQL every time:
- First request β DB
- Next requests β Redis cache β‘
βοΈ Install Redis Package
```bash id="gq78f0"
go get github.com/redis/go-redis/v9
---
## π¦ Connect Redis
```go id="lb7m2n"
package main
import (
"context"
"github.com/redis/go-redis/v9"
)
var ctx = context.Background()
var rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
ποΈ Example API Response
Normally:
```go id="1h9v4t"
func getUsersFromDB() string {
return "Users from PostgreSQL"
}
But hitting DB repeatedly is expensive.
---
## β‘ Add Redis Caching
```go id="h4m92g"
func getUsers(w http.ResponseWriter, r *http.Request) {
cachedData, err := rdb.Get(ctx, "users").Result()
if err == nil {
w.Write([]byte("Cache Hit π\n" + cachedData))
return
}
data := getUsersFromDB()
rdb.Set(ctx, "users", data, time.Minute*5)
w.Write([]byte("DB Hit π\n" + data))
}
π₯ Whatβs Happening Here?
First Request
- Redis has no data
- Fetch from DB
- Store in Redis
Next Requests
- Redis already has data
- Return instantly β‘
π Why Caching Matters
Without cache:
Client β API β Database
With cache:
Client β API β Redis β‘
β
Database (less often)
π Benefits of Redis
- Faster APIs
- Reduced DB load
- Better scalability
- Improved user experience
β οΈ Important Production Notes
Donβt cache forever.
Always:
- Set expiration time
- Clear cache after updates
- Avoid stale data
π§ Real-World Usage
Redis is used in:
- Authentication systems
- Rate limiting
- API caching
- Queues
- Real-time apps
Companies like:
- Netflix
use Redis heavily.
π¬ Final Thought
Caching is one of the easiest ways to improve backend performance.
You donβt always need:
- Bigger servers
- More CPUs
Sometimesβ¦
π You just need smarter architecture.
π Coming Next
π Rate Limiting in Go API
π Background Jobs with Redis
π Redis Pub/Sub in Go
Top comments (0)