Sobes.tech
Middle+

How was cache consistency ensured in Redis? How did you understand that the cache needed to be updated?

sobes.tech AI

Answer from AI

Cache consistency in Redis is usually maintained through strategies that ensure cached data is not stale and matches the source of truth (e.g., a database).

Main approaches:

  • Cache Aside (Lazy Loading): When a request is made, the cache is checked first. If the data is not present (cache miss), it is loaded from the database, stored in the cache, and returned. When data in the database is updated, the application updates or invalidates the corresponding key in Redis.

  • Write Through / Write Behind: When writing, data is first written to the cache, then to the database (write through), or vice versa with deferred writing (write behind).

  • TTL (Time To Live): Keys are assigned a lifetime, after which the data is automatically removed, reducing the likelihood of staleness.

How to know when to update the cache:

  • When data in the database changes, the application explicitly invalidates or updates the cache.
  • Using events or messages (e.g., via a queue or pub/sub) to notify services of changes.
  • Monitoring TTL and periodically updating data.

Example in Go (cache aside):

func GetUser(id string) (*User, error) {
    data, err := redisClient.Get(ctx, id).Result()
    if err == redis.Nil {
        user, err := db.GetUserByID(id)
        if err != nil {
            return nil, err
        }
        serialized, _ := json.Marshal(user)
        redisClient.Set(ctx, id, serialized, time.Minute*10)
        return user, nil
    } else if err != nil {
        return nil, err
    }
    var user User
    json.Unmarshal([]byte(data), &user)
    return &user, nil
}

In this example, the cache is updated when data is missing, and when the user is changed, the cache should be additionally updated or invalidated.