DEV Community

Satish Patil
Satish Patil

Posted on

Implementing Distributed Caching with PostgreSQL in .NET: Sats.PostgresDistributedCache

Introduction

In modern applications, caching is essential to improve performance, reduce latency, and decrease the load on databases. Traditional in-memory caches like Redis or Memcached are widely used, but what if you already have PostgreSQL as your data store and want to leverage it for distributed caching as well? Introducing Sats.PostgresDistributedCache, a custom distributed cache implementation that uses PostgreSQL as the backing store.

This article walks through how to set up Sats.PostgresDistributedCache, a lightweight, high-performance distributed cache using PostgreSQL, and how to integrate it into your .NET application.

Key Features of Sats.PostgresDistributedCache:

  • PostgreSQL as the Backing Store: Store cache entries in a PostgreSQL database, utilizing the power and reliability of PostgreSQL.
  • Expiration Support: Cache entries can have expiration times, after which they will be automatically removed.
  • Basic Caching Operations: Set, get, remove, and refresh cache entries using simple methods.
  • Integration with .NET: Easy integration into your .NET application with minimal configuration.

Why Use PostgreSQL for Distributed Caching?

Using PostgreSQL for caching has several advantages:

  • Familiarity: If you already use PostgreSQL in your project, adding caching support doesn’t require new infrastructure or technology.
  • Scalability: PostgreSQL can scale vertically and horizontally, and using it for caching allows you to consolidate your data store.
  • Persistence: Unlike in-memory caches, PostgreSQL ensures that cached data is stored persistently and can be recovered in case of server failures.

Installation and Setup

To get started, you’ll need to install the Sats.PostgresDistributedCache NuGet package in your .NET project. You can do this by running the following command:

dotnet add package Sats.PostgresDistributedCache --version 1.2.0
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can use the NuGet Package Manager in Visual Studio for a more graphical experience.

NuGet Badge

Configuring the Cache in .NET

After installing the package, add the following configuration in your Startup.cs or Program.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Add PostgreSQL distributed cache with your connection string
    services.AddPostgresDistributedCache(options =>
    {
        options.ConnectionString = "Host=myserver;Port=5432;Database=mydb;Username=myuser;Password=mypassword";
    });

    // Add other services as needed
}
Enter fullscreen mode Exit fullscreen mode

Now, you can inject the IPostgreSqlDistributedCache interface into any class and use it for caching.

How to Use the Cache

Once configured, you can use the cache like any other distributed cache. Here is an example of setting and getting cache values using Sats.PostgresDistributedCache:

public class MyService
{
    private readonly IPostgreSqlDistributedCache _distributedCache;

    public MyService(IPostgreSqlDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }

    public async Task<string> GetFromCacheAsync(string key)
    {
        var data = await _distributedCache.GetAsync(key);
        return data != null ? Encoding.UTF8.GetString(data) : null;
    }

    public async Task SetInCacheAsync(string key, string value)
    {
        var data = Encoding.UTF8.GetBytes(value);
        await _distributedCache.SetAsync(key, data, expiration: TimeSpan.FromMinutes(10));
    }
}
Enter fullscreen mode Exit fullscreen mode

Cache Table Schema

The cache is stored in a PostgreSQL table named Cache, which can be created with the following schema:

CREATE TABLE IF NOT EXISTS public."Cache"
(
    "key" character varying(255) NOT NULL,
    "value" text NOT NULL,
    "expiration" timestamp with time zone,
    CONSTRAINT "PK_Cache" PRIMARY KEY ("key"),
    CONSTRAINT "UQ_Cache_Key" UNIQUE ("key")
);
Enter fullscreen mode Exit fullscreen mode

Columns:

  • Key: A unique identifier for each cache entry.
  • Value: The cached data stored as text.
  • Expiration: The expiration timestamp for each cache entry.

Supported .NET Versions

This package supports the following .NET versions:

  • .NET 6.0
  • .NET 7.0
  • .NET 8.0
  • .NET 9.0

Ensure that your project is targeting one of these versions for compatibility with Sats.PostgresDistributedCache.

License

The Sats.PostgresDistributedCache package is licensed under the MIT License, allowing you to freely use, modify, and distribute it in your projects.

Links

Billboard image

The fastest way to detect downtimes

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitoring.

Get started now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay