PROPOSAL: Cache policy
Proposal: Cache policy
Purpose
To provide the ability to serve results from a cache, instead of executing the governed func.
Scope
- A non-exception handling policy.
- All sync and async variants
- Only result-returning (
Func<TResult>), not void (Action) executions.
Configuration
The cache item expiry duration would be configured on the CachePolicy at configuration time, not passed at execution time:
- This keeps
CachePolicyin line with the Polly model, where the behavioural characteristics of policies are defined at configuration time, not call time. This makes for a cache policy with given behaviour which can be shared across calls. - Adding bespoke
.Execute()overloads onCachePolicywould present problems for the integration ofCachePolicyintoPolicyWrap. (ThePolicyWrap(was Pipeline) feature in its proposed from requires that all policies have common.Execute()etc overloads.)
Configuration syntax
For Policy<TResult> - default cache
CachePolicy<TResult> cachePolicy = Policy
.Cache<TResult>(TimeSpan slidingExpirationTimespan);
For Policy<TResult> - advanced cache
Users may want more control over caching characteristics or to use an alternative cache provider (Http cache or third-party). The following overload is also proposed:
CachePolicy<TResult> cachePolicy = Policy
.Cache<TResult>(IResultCacheProvider<TResult> cacheProvider);
where:
// namespace Polly.Cache
interface IResultCacheProvider<TResult>
{
TResult Get(Context);
void Put(Context, TResult);
}
- The
Contextitself is not the key; it is an execution context that travels with each Execute invocation on a Polly policy. Implementations should derive a cache key to use from elements in theContext. The usual cache key would beContext.ExecutionKey. See #139 - Basing the
IResultCacheProviderGet/Put signatures aroundContextrather than astring cacheKeyallows implementers power to develop a more complex caching strategy around other keys or user information on theContext.
Example execution syntax
// TResult form
TResult result = cachePolicy
.Execute(Func<TResult> executionFunc, new Context(executionKey)); // The executionKey is the cacheKey. See keys proposal.
(and other similar existing overloads taking a Context parameter)
Default implementation
The proposed implementation for the simple cache configuration overload is to use System.Runtime.Memory.MemoryCache.Default and the configured Timespan slidingExpirationTimespan to create a Polly.Cache.MemoryCacheProvider<TResult> : Polly.Cache.IResultCacheProvider<TResult>.
Operation
- Checks the cache for a value stored under the cache key; returns it if so.
- Throws an
InvalidCastExceptionif the value in the cache cannot be cast toTResult
- Throws an
- Invokes
executionFuncif (and only if) a value could not be returned from cache. - Before returning a result from a non-faulting invoking
executionFunc, caches it under the given cache key for the given timespan.
Comments?
Comments? Alternative suggestions? Extra considerations to bear in mind?
Have scenarios to share where you'd use this? (could inform development)
Are the ExecuteAndCapture variants going to be supported?
Are the ExecuteAndCapture variants going to be supported?
Yes - good catch. And since the implementation obviously checks for a cached value before executing the user delegate, makes no difference to the operation of the CachePolicy whether any fault from the func is rethrown/passed to more outer layers, or captured.
I'm happy to work on this, as we will need this for a project I'm working on.
@SeanFarrow Sounds good! Many thanks for your involvement and offering to work up a PR on this! Please do come back to me questions / comments etc as they arise.
Ok, I will. I’m able to start working on this at the end of the month, I’ve got a major project to finish first! What caches do we want, I’m thinking, Redis/Memcached, and the .net memory cache as well as maybe a disc based cache, with the memory cache being the default. Any other caches/thoughts?
I’m able to start working on this at the end of the month
Sure @SeanFarrow . Thanks for all your support and involvement!
What caches do we want, I’m thinking, Redis/Memcached, and the .net memory cache as well as maybe a disc based cache, with the memory cache being the default. Any other caches/thoughts?
All sound like good options!
And with the proposed IResultCacheProvider<TResult> interface, people can of course easily implement others.
Given we'd likely want to avoid taking dependencies on all these in the main Polly package, the individual cache implementations (default memory cache excepted) would probably go out as separate nuget packages Polly.Cache.Redis, Polly.Cache.Memcached etc, do you think? Unless they were each individually so small (in terms of code lines) that providing a wiki page for each was just as much an option - to decide later?
@community : other caches you'd like to see supported?
Definitely separate NuGet packages. That makes more sense in terms of dependencies, as each cache is likely to depend on other NuGet packages. Also, they can then be updated out of band of the main poly package assuming of course that the interface doesn’t change!
I’m also thinking about a Poly.Cache.Core package containing the interface and the memory cache, as per my understanding, the memory cache is baked in to the .net framework—correct me if I’m wrong!
In terms of other caches we may want to support, maybe azure cache/amazon elastic cache, I need to check whether the latter has an api specifically, or whether it’s just memcached compatible.
@SeanFarrow All sounds good.
Only thought: maybe the default MemoryCache option (and IResultCacheProvider<TResult> interface) can just be part of the main Polly package, so that the CachePolicy (based on the MemoryCache default) works out-of-the-box with just the main Polly package. Yes, MemoryCache is part of the runtime at System.Runtime.Caching.MemoryCache
Ok, fair point, we’ll go with that then!
What version of .net are we supporting? I notice that poly supports .net 3.5, but the memory cache is 4.0+. Do people see this as an issue? if so, what should we do for caching in .net 3.5?
Good question. Per #142 we will discontinue .NET3.5 support from Polly v5.0.0, as a number of the other new policies require facilities not in .NET3.5 either.
Ok, cool, can you assign me to the cache policy then?
Hey @SeanFarrow . Hmm. Seems from the github instructions I can't add you with the assignees button (same for Jerome and Bruno) because its scope is limited to AppvNext org members (since AppvNext also broader than Polly, not my position just to add you to AppvNext). No reflection on the importance of your contribution to Polly (great to have you involved!). Consider this assigned. Added the in progress label to indicate that it is spoken for!
Ok, thanks!
Given we're supporting async variants of execute, should we have an async cache provider as well? Also, if the cache doesn't support synchronous functionality, what should our default position be?
Hey @SeanFarrow Great questions. What were your thoughts?
Some thoughts:
Given we're supporting async variants of execute, should we have an async cache provider as well?
[1] Yes good call. Polly having an async cache provider so that async executions through Polly can take advantage of where 3rd-party caches have (mature/stable) async APIs –> we should do that. Feels like two separate interfaces in Polly for sync and async providers, ie IResultCacheProvider<TResult> and IResultCacheProviderAsync<TResult>? That what you thinking? Async interface sthg like:
// namespace Polly.Cache
interface IResultCacheProviderAsync<TResult>
{
TResult GetAsync(Context); // should return: Task<TResult>
void PutAsync(Context, TResult); // should return: Task
}
NB If you think the design of the IResultCacheProvider/Async<TResult> interfaces can be refined, feel free to say.
[2] The config overloads .CacheAsync<TResult>(...) configuring Polly’s async cache policies should probably provide options to take either a sync or an async cache provider tho. Because there might be some cache providers which only have sync APIs but we still want to offer them to async cache policies? (MemoryCache.Default is in this category?)
So:
// Async policy taking async cache provider
CachePolicy<TResult> asyncCachePolicy = Policy
.CacheAsync<TResult>(IResultCacheProviderAsync<TResult> cacheProviderAsync);
// Async policy taking sync cache provider
CachePolicy<TResult> asyncCachePolicy = Policy
.CacheAsync<TResult>(IResultCacheProvider<TResult> cacheProvider);
Re:
if the cache doesn't support synchronous functionality, what should our default position be?
Again, really interested to hear your views. Thinking aloud from my side:
[3] The config overloads configuring Polly's sync cache policy should probably only take sync cache providers. IE just:
// Sync policy taking sync cache provider
CachePolicy<TResult> cachePolicy = Policy
.Cache<TResult>(IResultCacheProvider<TResult> cacheProvider);
(The opposite – providing an overload for a sync cache policy taking an async provider – feels like creating a potentially confusing API. Particularly, there’s a risk people would mistake that syntax for giving them the benefits of async behaviour, when it’d not be: it’d have to be blocking on the calls to the async cache provider to bring it into a sync policy/sync call, no?)
[4] But we could allow the use of third-party caches with async-only interfaces, in Polly’s sync CachePolicys, if desired, by providing an implementation fulfilling Polly’s IResultCacheProvider<TResult> sync interface, just .Wait()-ing (or equiv) on the async calls. (And NB documenting that this is what it does!). Arguments for / against doing that? Doing it that way round, at least there’s no mistaking from the API we provide that you’re getting blocking/sync behaviour.
Hmm. The choice of C# clients for some of these caches has moved on since I was last involved, in some cases. Which of the 3rd-party cache's are currently offering an async-only (no sync) API?
Thoughts on all this?
Ok, thinking out loud:
In my mind the AsyncCachePolicy
Also, whilst I think about it, how do we want to handle the conversion from the cache to the TResult type? Sometimes it may not be as straightforward as doing new T, should we offer the capability to define a delegate/lambda, or a conversion interface?
I’ve got a situation for example where I’m storing a base64-encoded compressed file (zip in this case), so I can’t just do new ZipArchive, or the equivalent, it needs an extra processing step! Also, this may be valid, if you are storing the content of a web response a an array of bytes. Thoughts…?
In my mind the AsyncCachePolicy
should return a Task and Task for get/put methods respectively.
Oops on my part: yes definitely!
(more on other q later)
Hey @SeanFarrow . Great to have all this on the cache policy!
Re:
how do we want to handle the conversion from the cache to the TResult type? [...] should we offer the capability to define a delegate/lambda, or a conversion interface?
Where were you thinking this would sit in the architecture? As part of the CachePolicy configuration overloads, or in the IResultCacheProvider implementations?
My instinct is to keep the main CachePolicy configuration overloads simple-as-possible, ie we have the TimeSpan varieties plus:
.Cache<TResult>(IResultCacheProvider<TResult> cacheProvider) [and]
.CacheAsync<TResult>(IResultCacheProviderAsync<TResult> cacheProviderAsync)
rather than extend those with additional:
.Cache<TResult, TCachedFormat>(IResultCacheProvider<TResult> cacheProvider, ICacheValueFormatter<TResult, TCachedFormat> cacheValueFormatter) [etc]
(The formatter probably makes sense for some kinds of cache but not others. And: IResultCacheProvider<TResult> cacheProvider feels like the correct scope of interface to configure a CachePolicy ... for the policy to use the cache, all you need to know is that you can get and put in and out of it ... if some cache implementations prefer to compress or map to a more cloud-friendly format, that feels like a cache implementation concern. )
So thinking of it structurally as a cache implementation concern, my instinct is for the transform-for-caching functionality being part of IResultCacheProvider/Async implementations where needed, config'd on them where needed.
Sound sensible? / can you see disadvantages? / or just stating the obvious??
:+1: re conversion interface. If we went as above ... and if there were a group of cache implementations (cloud caches?) where this approach might be particularly useful, one could still eg structure that with an abstract base class taking a conversion interface like you say, and some cache implementations deriving from that ...
Further thoughts? (You deep in and may see other angles! )