1. Usage
  2. Cache Keys
  3. Conditional Caching
  4. Event Listeners

Cache policies prevent unnecessary load by caching execution results and returning previous execution results, when possible.


Creating and using a CachePolicy for a cache is simple:

// Store connections under the "connection" key in the cache
cachePolicy := cachePolicy.Builder(cache).
// Get a connection from the cache, else create a new one
connection, err := failsafe.Get(Connect, cachePolicy)

Cache Keys

A CachePolicy can use a key specified at the policy level, as shown above, to store cached execution results. It can also use a cache key provided at execution time, via a Context, allowing different keys to be used for different executions:

ctx := context.WithValue(context.Background(), cachepolicy.CacheKey, "connection")
connection, err := failsafe.NewExecutor(cachePolicy).

Conditional Caching

By default, any non-error execution results will be cached. But a CachePolicy can also be configured only cache results when a condition is met:

builder.CacheIf(func(response *http.Response, err error) bool {
  return response.StatusCode == 200

Event Listeners

A CachePolicy can notify you with an ExecutionEvent when a result is added to the cache:

builder.OnResultCached(func(e failsafe.ExecutionEvent[any]) {
  logger.Info("Cached result", "result", e.LastResult())

It can also notify you when a cache hit or miss occurs:

builder.OnCacheHit(func(e failsafe.ExecutionDoneEvent[any]) {
  logger.Info("Cache hit", "result", e.Result)
}).onCacheMiss(func(e failsafe.ExecutionEvent[any]) {
  logger.Info("Cache miss")