RingDotNetfor Ring

Caching

A cache keeps the result of slow work for a while, so the next request gets it at once. This lesson uses MemoryCache with absolute and sliding expiration, GetOrCreate with a Ring function that makes the value, and Remove and Clear — and says when a cache is the wrong tool.

What you will learn#

The tutorial Speed — measure first measured how fast calls are. The fastest call is the one you do not make: a result that was already calculated, fetched or read can be reused.

The program#

samples/UsingDotNet/tutorials/ch09_memory_cache.ring
# caching - MemoryCache, absolute and sliding expiration, remove and update, and when a cache is a bad idea
load "dotnet.ring"

using {
	"System"
	"System.Threading"
	"Microsoft.Extensions.Caching.Memory"
}

nRuns = 0

func main

	# A cache keeps the result of slow work (a database query, a web request, a big calculation) for a while, so the next request
	# gets it at once. MemoryCache keeps the values in memory, with a key for each one and rules for when a value must go.
	oCache = new MemoryCache(new MemoryCacheOptions())

	# 1. Set stores a value under a key. TryGetValue answers [ found, value ].
	cacheSet(oCache,"user:1","Ann",NULL)
	aResult = oCache.TryGetValue("user:1")
	? "1. found: " + aResult[1] + ", value: " + aResult[2]
	? "   a key that was never stored: found = " + oCache.TryGetValue("user:99")[1]
	? "   entries in the cache: " + oCache.Count

	# 2. Absolute expiration: the value lives for a fixed time after it was stored. After that it is gone, even if it was used.
	oOptions = new MemoryCacheEntryOptions()
	oLimit = new TimeSpan().FromMilliseconds(500)
	oOptions.AbsoluteExpirationRelativeToNow = oLimit
	cacheSet(oCache,"price",9.99,oOptions)
	? nl + "2. right after storing, the price is there:  " + oCache.TryGetValue("price")[1]
	sleepMs(900)
	? "   after 900 ms (the limit was 500 ms):   " + oCache.TryGetValue("price")[1]

	# 3. Sliding expiration: the time starts again every time the value is READ. A value that is used often stays, one that is
	#    not used goes. (Good for sessions and for caches of things that are used in bursts.)
	oSliding = new MemoryCacheEntryOptions()
	oWindow = new TimeSpan().FromMilliseconds(1000)
	oSliding.SlidingExpiration = oWindow
	cacheSet(oCache,"session","token-123",oSliding)
	cResult = ""
	for i = 1 to 4
		sleepMs(300)                                  # 300 ms each time: less than 1000, so every read renews the time
		cResult += "" + oCache.TryGetValue("session")[1] + " "
	next
	? nl + "3. read every 300 ms with sliding time of 1000 ms: " + cResult + "(it stays: 1 = found)"
	sleepMs(1500)
	? "   not read for 1500 ms: found = " + oCache.TryGetValue("session")[1]

	# 4. GetOrCreate: "give me the value, and make it if it is missing". The function that makes the value is the slow work: it runs
	#    only on the first request (a Ring function that .NET calls during this call).
	cFirst = oCache.GetOrCreate([ :key = "report", :factory = dnCallback("slowReport") ])
	cSecond = oCache.GetOrCreate([ :key = "report", :factory = dnCallback("slowReport") ])
	? nl + "4. the report was made " + nRuns + " time(s) for two requests: " + cFirst + " / " + cSecond

	# 5. Remove and Clear (Compact removes a part): a value that changed in the database must leave the cache, or the old one is served
	oCache.Remove("user:1")
	? nl + "5. after Remove, user:1 is found: " + oCache.TryGetValue("user:1")[1]
	oCache.Clear()
	? "   after Clear, entries: " + oCache.Count

	# 6. A cache does not know when the real data changes. Two rules: never cache what must be exact (a bank balance), and give every
	#    value an expiration, so that the worst case is a value that is a few seconds old.
	oCache.Dispose()

func sleepMs nMilliseconds

	new Thread().Sleep(nMilliseconds)

func slowReport aArguments

	nRuns++                         # (nRuns is a global variable of the program)
	return "report #" + nRuns

# Set has two forms: with and without the options of the entry
func cacheSet oCache,cKey,xValue,oOptions

	if isNull(oOptions)
		return oCache.Set([ :key = cKey, :value = xValue ])
	ok
	return oCache.Set([ :key = cKey, :value = xValue, :options = oOptions ])
Output
1. found: 1, value: Ann
   a key that was never stored: found = 0
   entries in the cache: 1

2. right after storing, the price is there:  1
   after 900 ms (the limit was 500 ms):   0

3. read every 300 ms with sliding time of 1000 ms: 1 1 1 1 (it stays: 1 = found)
   not read for 1500 ms: found = 0

4. the report was made 1 time(s) for two requests: report #1 / report #1

5. after Remove, user:1 is found: 0
   after Clear, entries: 0
Note

This program uses a generic function (dnStatic) where a class cannot be used. The lesson The generic functions explains them.

How it works#

The cache#

MemoryCache (namespace Microsoft.Extensions.Caching.Memory) is a dictionary with rules. Each value has a key (a text such as "user:1") and may have an expiration. TryGetValue(key) answers [ found, value ] (the tutorial Network tools explains the out value). A cache is made with options (MemoryCacheOptions), for example a size limit; the defaults are fine for this lesson.

Extension methods#

Set and GetOrCreate are extension methods of the static class CacheExtensions, not methods of MemoryCache itself, but the class MemoryCache has them, so they are called on the cache like its own methods: oCache.Set([ :key = "user:1", :value = "Ann" ]). They have several forms (with or without the options of the entry), so a name takes one parameter: the names of the parameters choose the form, as for every overloaded method (Core concepts). The program wraps Set in the function cacheSet. The same holds for many helpers of Microsoft.Extensions.*; the class reference lists them with the class that they extend (Class reference).

Absolute expiration#

AbsoluteExpirationRelativeToNow = TimeSpan removes the value a fixed time after it was stored, even if it was used all the time. After 900 ms a value with a limit of 500 ms is gone. Use it when the value goes stale: a price list, a weather report, a result of a query that can change.

Sliding expiration#

SlidingExpiration = TimeSpan starts the time again every time the value is read. In step 3 the session is read every 300 ms and the limit is 1000 ms, so it stays; after 1500 ms without a read it is gone. Use it for things that should live while they are used: sessions, a cache of recent items. A value with only a sliding time can live for ever if it is always used, so combine it with an absolute limit (both can be set) when the data must be renewed.

GetOrCreate#

GetOrCreate(key, factory) says: give me the value, and make it if it is missing. The factory is the slow work. It is a Ring function that .NET calls during the call, made with dnCallback("slowReport"); it receives the arguments in a list and returns the value. For two requests the report is made once. (In a program with many threads two requests could both find the value missing and both make it; MemoryCache does not stop that, a cache that must make a value exactly once needs a lock.)

Remove and Clear#

When the real data changes (a record is updated in the database), remove its key (Remove), or the old value is served until it expires. Clear removes everything; Compact(0.25) removes a part. A change, then Remove, then the next read makes the fresh value: that is the usual pattern.

When not to cache#

A cache gives old data on purpose. Do not cache what must be exact (a bank balance, a stock count at the moment of an order), give every value an expiration so that the worst case is a value that is only a few seconds old, and watch the size: a cache without a limit that keeps a value for every user is a memory leak (the tutorial Memory and the garbage collector). Also remember that the cache lives inside the program: two copies of the program have two caches that can disagree.

What you learned#

Exercises#

  1. Cache the result of a slow function (the tutorial Speed — measure first) and measure the time of the first and the second call.
  2. Combine a sliding and an absolute expiration for a session.
  3. Count how often GetOrCreate found the value (a hit) and how often it made it (a miss) and print the hit rate.
  4. Set a size limit (MemoryCacheOptions.SizeLimit) and see what happens when entries are added without a size.

Next#

Dependency injection

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.