An efficient multi-layered caching system for .NET
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.
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.
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. |
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.
✔ 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.
✔ 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!
✔ 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!
✔ 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:
With this setup, you have:
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! |
Cache Tower has a number of officially supported cache layers that you can use.
Bundled with Cache Tower
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.
Bundled with Cache Tower
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.
PM> Install-Package CacheTower.Providers.Database.MongoDBbuilder.AddMongoDbCacheLayer(/* MongoDB Connection */);Allows caching through a MongoDB server.
Cache entries are serialized to BSON using MongoDB.Bson.Serialization.BsonSerializer.
PM> Install-Package CacheTower.Providers.Redisbuilder.AddRedisCacheLayer(/* Redis Connection */, new RedisCacheLayerOptions(ProtobufCacheSerializer.Instance));Allows caching of data in Redis using your choice of serializer.
The FileCacheLayer and RedisCacheLayer support custom serializers for caching data.
Different serializers have different performance profiles as well as different tradeoffs for configuration.
PM> Install-Package CacheTower.Serializers.NewtonsoftJsonUses Newtonsoft.Json to perform serialization.
PM> Install-Package CacheTower.Serializers.SystemTextJsonUses System.Text.Json to perform serialization.
PM> Install-Package CacheTower.Serializers.ProtobufThe use of protobuf-net requires decorating the class you want to cache with attributes [ProtoContract] and [ProtoMember].
Example with Protobuf Attributes
[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.
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.
In this example,
UserContextis 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.
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.
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
No open issues yet, or sync has not completed.