Sobes.tech
Junior — Middle

Can you give examples of algorithms used when updating data in cache?

sobes.tech AI

Answer from AI

The following algorithms are often used when updating data in cache:

  • Write-through: data is written simultaneously to the cache and the main storage.
  • Write-back (Write-behind): data is first written to the cache, and the update to the main storage occurs later.
  • Cache invalidation: when data in the main storage changes, the cache is marked as stale and updated upon the next request.
  • Time-to-live (TTL): the cache automatically updates or deletes after a specified time expires.

Example in Go for TTL cache update:

cache := make(map[string]CacheItem)

// CacheItem contains data and expiration time

type CacheItem struct {
    Data      interface{}
    ExpiresAt time.Time
}

func GetFromCache(key string) (interface{}, bool) {
    item, found := cache[key]
    if !found || time.Now().After(item.ExpiresAt) {
        return nil, false
    }
    return item.Data, true
}

func SetToCache(key string, data interface{}, duration time.Duration) {
    cache[key] = CacheItem{Data: data, ExpiresAt: time.Now().Add(duration)}
}