Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

CacheTower

> 数据库
Open source

An efficient multi-layered caching system for .NET

629 stars0 likes1 views
WebsiteGitHub

About

An efficient multi-layered caching system for .NET

Overview

Computers have multiple layers of caching from L1/L2/L3 CPU caches to RAM or even disk caches, each with a different purpose and performance profile.

Why don't we do this with our code?

Cache Tower isn't a single type of cache, its a multi-layer solution to caching with each layer on top of another. A multi-layer cache provides the performance benefits of a fast cache like in-memory with the resilience of a file, database or Redis-backed cache.

This library was inspired by a blog post by Nick Craver about how Stack Overflow do caching. Stack Overflow use a custom 2-layer caching solution with in-memory and Redis.

Features

  • High performance with low allocations (see comparison to other caching solutions).
  • Local system caching with in-memory and file-based caches.
  • Distributed system caching with MongoDB and Redis.
  • Supports one or more cache layers, allowing a cache that has the best of all worlds.
  • Background refreshes of non-expired but "stale" data, helping avoid expired data cache misses.
  • Local refresh locking, guaranteeing only 1 factory call per key locally.
  • Distributed refresh locking, guaranteeing only 1 factory call per key across multiple application instances.
  • Distributed evictions, helping to keep caches across multiple application instances the same.
  • All-async API, ready for high performance workloads.
  • Targets minimum .NET Standard 2.0 for wide compatibility (.NET Framework 4.6.1+, .NET Core 2.0+, .NET 5.0+).

Licensing and Support

Cache Tower is licensed under the MIT license. It is free to use in personal and commercial projects.

There are support plans available that cover all active Turner Software OSS projects. Support plans provide private email support, expert usage advice for our projects, priority bug fixes and more. These support plans help fund our OSS commitments to provide better software for everyone.

Table of Contents

  • Installation
  • Understanding a Multi-Layer Caching System
  • The Cache Layers of Cache Tower
  • Making Your Own Cache Layer
  • Cache Serializers
  • Getting Started
  • Background Refreshing of Stale Data
    • Avoiding Disposed Contexts
  • Cache Tower Extensions
    • Automatic Cleanup
    • Distributed Locking via Redis
    • Distributed Eviction via Redis
  • Performance and Comparisons
  • Advanced Usage
    • Flushing the Cache

Installation

You will need the CacheTower package on NuGet - it provides the core infrastructure for Cache Tower as well as an in-memory cache layer. To add additional cache layers, you will need to install the appropriate packages as listed below.

Package NuGet Downloads
CacheTower
The core library with in-memory and file caching support.
CacheTower.Extensions.Redis
Provides distributed locking & eviction via Redis.
CacheTower.Providers.Database.MongoDB
Provides a cache layer for MongoDB.
CacheTower.Providers.Redis
Provides a cache layer for Redis.
CacheTower.Serializers.NewtonsoftJson
Provides a JSON serializer using Newtonsoft.Json.
CacheTower.Serializers.SystemTextJson
Provides a JSON serializer using System.Text.Json.
CacheTower.Serializers.Protobuf
Provides a Protobuf serializer using protobuf-net.

Understanding a Multi-Layer Caching System

At its most basic level, caching is designed to prevent reprocessing of data by storing the result somewhere. In turn, preventing the reprocessing of data makes our code faster and more scaleable. Depending on the method of storage or transportation, the performance profile can vary drastically. Not only that, limitations of different types of caches can affect what you can do with your application.


In-memory Caching

✔ Pro: The fastest cache you can possible have!

❌ Con: Only lasts the lifetime of the application.

❌ Con: Memory capacity is more limited than other types of storage.

File-based Caching

✔ Pro: Caching huge amounts of data is not just possible, it is usually cheap!

✔ Pro: Resilient to application restarts!

❌ Con: Even with fast SSDs, it can be 1500x slower than in-memory!

Database Caching

✔ Pro: Database can run on the local machine OR a remote machine!

✔ Pro: Resilient to application restarts!

✔ Pro: Can support multiple systems at the same time!

❌ Con: Performance is only as good as the database provider itself. Don't forget network latency either!

Redis Caching

✔ Pro: Redis can run on the local machine OR a remote machine!

✔ Pro: Resilient to application restarts!

✔ Pro: Can support multiple systems at the same time!

✔ Pro: High performance (faster than file-based, slower than in-memory).

❌ Con: Linux only. *

* On Windows, Memurai is your best Redis-compatible alternative - just need to list some sort of con for Redis and what it ran on was all I could think of at the time.


An ideal caching solution should be fast, flexible, resilient and scale with your usage. It is through combining these different cache types that this can be achieved.

Cache Tower supports n-layers of caching with flexibility to even make your own. You "stack" the cache layers from the fastest to slowest for your particular usage.

For example, you might have:

  1. In-memory cache
  2. File-based cache

With this setup, you have:

  • A fast first-layer cache
  • A resilient second-layer cache

If your application restarts and your in-memory cache is empty, your second-layer cache will be checked. If a valid cache entry is found, that will be returned.

Which combination of cache layers you use to build your cache stack is up to you and what is best for your application.

ℹ Don't need a multi-layer cache right now?
Multi-layer caching is only one part of Cache Tower. If you only need one layer of caching, you can still leverage the different types of caches available and take advantage of background refreshing. If later on you need to add more layers, you only need to change the configuration of your cache stack!

The Cache Layers of Cache Tower

Cache Tower has a number of officially supported cache layers that you can use.

MemoryCacheLayer

Bundled with Cache Tower

csharp
builder.AddMemoryCacheLayer();

Allows for fast, local memory caching. The data is kept as a reference in memory and not serialized. It is strongly recommended to treat the cached instance as immutable. Modification of an in-memory cached value won't be updated to other cache layers.

FileCacheLayer

Bundled with Cache Tower

csharp
builder.AddFileCacheLayer(new FileCacheLayerOptions("~/", NewtonsoftJsonCacheSerializer.Instance));

Provides a basic file-based caching solution using your choice of serializer. It stores each serialized cache item into its own file and uses a singular manifest file to track the status of the cache.

MongoDbCacheLayer

powershell
PM> Install-Package CacheTower.Providers.Database.MongoDB
csharp
builder.AddMongoDbCacheLayer(/* MongoDB Connection */);

Allows caching through a MongoDB server. Cache entries are serialized to BSON using MongoDB.Bson.Serialization.BsonSerializer.

RedisCacheLayer

powershell
PM> Install-Package CacheTower.Providers.Redis
csharp
builder.AddRedisCacheLayer(/* Redis Connection */, new RedisCacheLayerOptions(ProtobufCacheSerializer.Instance));

Allows caching of data in Redis using your choice of serializer.

✍ Cache Serializers

The FileCacheLayer and RedisCacheLayer support custom serializers for caching data. Different serializers have different performance profiles as well as different tradeoffs for configuration.

NewtonsoftJsonCacheSerializer

powershell
PM> Install-Package CacheTower.Serializers.NewtonsoftJson

Uses Newtonsoft.Json to perform serialization.

SystemTextJsonCacheSerializer

powershell
PM> Install-Package CacheTower.Serializers.SystemTextJson

Uses System.Text.Json to perform serialization.

ProtobufCacheSerializer

powershell
PM> Install-Package CacheTower.Serializers.Protobuf

The use of protobuf-net requires decorating the class you want to cache with attributes [ProtoContract] and [ProtoMember].

Example with Protobuf Attributes

csharp
[ProtoContract]
public class UserProfile
{
	[ProtoMember(1)]
	public int UserId { get; set; }
	[ProtoMember(2)]
	public string UserName { get; set; }

	...
}

Additionally, as the Protobuf format doesn't have a way to represent an empty collection, these will be returned as null. While this can be inconvienent, using Protobuf ensures high performance and low allocations for serializing.

Making Your Own Cache Layer

You can create your own cache layer by implementing ICacheLayer. With it, you could implement caching layers that talk to SQL databases or cloud-based storage systems.

When making your own cache layer, you will need to keep in mind that your implementation should be thread safe. Cache Stack prevents multiple threads at once calling the value factory, not preventing multiple threads accessing the cache layer.

⭐ Getting Started

In this example, UserContext is a type added to the service collection. It will be retrieved from the service provider every time a cache refresh is required.

Create and configure your CacheStack, this is the backbone for Cache Tower.

csharp
services.AddCacheStack((provider, builder) => builder
	.AddMemoryCacheLayer()
	.AddRedisCacheLayer(/* Your Redis Connection */, new RedisCacheLayerOptions(ProtobufCacheSerializer.Instance))
	.WithCleanupFrequency(TimeSpan.FromMinutes(5))
);

The cache stack will be injected into constructors that accept ICacheStack. Once you have your cache stack, you can call GetOrSetAsync - this is the primary way to access the data in the cache.

csharp
var userId = 17;

await cacheStack.GetOrSetAsync($"user-{userId}", async (old, context) => {
	return await context.GetUserForIdAsync(userId);
}, new CacheSettings(TimeSpan.FromDays(1), TimeSpan.FromMinutes(60));

This call to GetOrSetAsync is configured with a cache expiry of 1 day and an effective stale time after 60 minutes. A good stale time is extremely useful for high performance scenarios where background refreshing is lev

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#cachecachemanagercachingcaching-library

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库