Search code examples
.netcontentful

Contentful .NET caching


Does anyone know if there is an existing way to use caching with the .NET Contentful SDK, such as what you can do with the PHP one? Or is the only option to roll your own caching mechanism?


Solution

  • That type of caching is currently not available in the .NET SDK.

    It would be fairly easy to just extend the IContentfulClient interface with your own implementation, say CachingContentfulClient, that would just in session or application storage store each entry by id and only fetch entries that are not present in the cache.

    Something like:

    public class CachingContentfulClient {
        private IContentfulClient _inner;
        public CachingContentfulClient(IContentfulClient inner) {
            _inner = inner;
        }
    
       public async Task<ContentfulCollection<T>> GetEntries<T>(string queryString = null, CancellationToken cancellationToken = default)
            {
         //if cache contains stuff, return stuff
         //else get stuff from Contentful
         if(cacheContainsStuffBasedOnQuery) {
             return cachedStuff;
         }
    
         return _inner.GetEntries<T>(queryString, cancellationToken);
       }
    }
    

    If you're running ASP.NET Core you can then use a decorator pattern to initialize your client in startup.cs (there's no oob support for this so you'd have to do it sort of manualy).

    services.AddTransient<IContentfulClient>((s) => {
                var httpClient = s.GetService<HttpClient>();
                var options = s.GetService<IOptions<ContentfulOptions>>();
                var contentfulClient = new ContentfulClient(httpClient, options);
                var cachingClient = new CachingContentfulClient(contentfulClient);
    
                return cachingClient;
            });
    

    All that said, a typical response from Contentful returns very, very quickly. I have several benchmark tests set up to measure this type of thing. Here's the latest version of getting a space (which is a very simple operation, getting entries and assets are of course slightly slower, but not by much).

             Method |     Mean |     Error |   StdDev |    Median |
    --------------- |---------:|----------:|---------:|----------:|
           GetSpace | 4.489 ms | 0.9696 ms | 20.82 ms | 2.0922 ms |
     GetSpaceCached | 2.075 ms | 0.9627 ms | 20.68 ms | 0.0003 ms |
    

    So while it's obviously extremely fast to fetch something from the cache (the average is skewed here because the first request needs to fill the cache, once the cache is filled it's around 3-4 nano seconds), the average time to fetch a space is 4 ms. Typically you have other bottlenecks in your code that require more attention than caching the Contentful response.