Hopp til hovedinnhold

I've tried out FusionCache and really liked it so I wrote this article to show you how to use their failsafe caching mechanism.

I've been working on an application that relies on data from an external service to work. We used to cache the data with IMemoryCache but had some problems as the external service was a bit unreliable. The data we were using was crucial for our application to make sense and so if the external service shut down for some reason so would our application. We tried caching for longer, but then again you don't want outdated data to stick around for too long.

When we found FusionCashe we realized that it solved all of our problems 🤩

FusionCache lets you do failsafe caching, meaning that if it receives an error it will continue to use the old data for as long as you want while retrying the request.

Here is an example of how we have used it in our code base

public class DataService
{
    private readonly IExternalServiceAdapter _externalServiceAdapter;
    private readonly IFusionCache _cache;

    public DataService(IExternalServiceAdapter externalServiceAdapter, IFusionCache cache)
    {
        _externalServiceAdapter = externalServiceAdapter;
        _cache = cache;
    }


    public async Task<IEnumerable<IData>> GetAll()
    {
        var result = await _cache.GetOrSetAsync(
            "my-unique-key",
            _ => _externalServiceAdapter.FetchData(),
            options => options
                .SetDuration(TimeSpan.FromHours(6))
                .SetFailSafe(true, TimeSpan.FromDays(7), TimeSpan.FromMinutes(5))
        );

        return result!;
    }
    
}

This means that we cache for 6 hours at a time before refreshing our cache. If our external service is unavailable it will keep the old data for up to 7 days while retrying fetching data every 5 minutes.

FusionCache also have many more features that might suite your needs. I highly recommend checking it out. Check out the link below

Relevant resources recommended by the author

Did you like the post?

Feel free to share it with friends and colleagues