How to Implement a Cache-Aside Pattern in Go

Implement Cache-Aside in Go by checking the cache first, fetching from the database on a miss, and storing the result before returning.

Implement the Cache-Aside pattern by checking your cache first, fetching from the database on a miss, and then populating the cache before returning the result. This ensures the cache is always updated with fresh data whenever it is accessed.

func GetOrFetch(key string, db *sql.DB) (string, error) {
    if val, err := cache.Get(key); err == nil {
        return val, nil
    }
    row := db.QueryRow("SELECT value FROM items WHERE id = $1", key)
    var val string
    if err := row.Scan(&val); err != nil {
        return "", err
    }
    cache.Set(key, val)
    return val, nil
}