DEV Community

Cover image for Using Redis for API Caching in Go (Speed Up Your Backend)
Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

Using Redis for API Caching in Go (Speed Up Your Backend)

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",
})
Enter fullscreen mode Exit fullscreen mode

πŸ—„οΈ 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))
}
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ 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
Enter fullscreen mode Exit fullscreen mode

With cache:

Client β†’ API β†’ Redis ⚑
             ↓
          Database (less often)
Enter fullscreen mode Exit fullscreen mode

πŸš€ 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
  • Instagram
  • Twitter

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)