Miha Jakovac

Logo

.NET & DevOps Engineer | Cloud Specialist | Team Enabler

My name is Miha and I've been tinkering with computers for some time now. I remember getting Pentium 100 in the late '90s and that's how it all started.

Specialities:

5 June 2024

Implement IDistributedCache interface for Etcd key-value store

by Miha J.

Applications sometimes need a temporary and faster cache storage to fetch data from instead of going into a database and generate response. With cache implemented, we can return just the response. Using caches brings its own challenges to invalidate it, etc.

You are probably aware of IDistributedCache interface in AspNet framework which is defining the methods for reading and writing the underlying cache infrastructure. I’ve used Redis Cache in the past, but for the sake of exercise, I’ve implemented the Etcd version of it.

Etcd is a distributed key-value store, and it’s a perfect candidate for a cache store. Read more here.

Familiar registration of the service:

builder.Services.AddEtcdCache(options =>
{
    options.ConnectionString = "http://localhost:2379";
    options.Username = "root";
    options.Password = "root";
});

Usage:

public class MyClass
{
    private readonly IDistributedCache _distributedCache;

    public MyClass(IDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }

    public async Task Write(string key, string value)
    {
        //Save to cache
        await _distributedCache.SetAsync(key,
            Encoding.UTF8.GetBytes(value), new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
            });

        //Read from cache
        var cachedValue = await _distributedCache.GetAsync(key);
    }
    
    public async Task<string> Read(string key)
    {
        //Read from cache
        return await _distributedCache.GetAsync(key);
    }
}

You can check my first attempt to implement IDistributedCache for Etcd in my GitHub repo. More work is probably needed to add other authentication type support to the configuration and clustering. I’ll try to fill that in and create the Nuget as well.

Let me know what you think and any PR’s are welcome :).

tags: dotnet, - etcd, - idistributedcache