| 1 |
 |
| 2 |
> A sturdy gopher shielding data sources from rapidly incoming requests. |
| 3 |
|
| 4 |
# `sturdyc`: a caching library for building sturdy systems |
| 5 |
|
| 6 |
[](https://github.com/avelino/awesome-go) |
| 7 |
[](https://pkg.go.dev/github.com/viccon/sturdyc) |
| 8 |
[](https://github.com/viccon/sturdyc/blob/master/LICENSE) |
| 9 |
[](https://goreportcard.com/report/github.com/viccon/sturdyc) |
| 10 |
[](https://github.com/viccon/sturdyc/actions/workflows/main.yml) |
| 11 |
[](https://codecov.io/gh/viccon/sturdyc) |
| 12 |
|
| 13 |
|
| 14 |
`sturdyc` eliminates cache stampedes and can minimize data source load in |
| 15 |
high-throughput systems through features such as request coalescing and |
| 16 |
asynchronous refreshes. It combines the speed of in-memory caching with |
| 17 |
granular control over data freshness. At its core, `sturdyc` provides |
| 18 |
**non-blocking reads** and **sharded writes** for minimal lock contention. The |
| 19 |
[xxhash](https://github.com/cespare/xxhash) algorithm is used for efficient key |
| 20 |
distribution. |
| 21 |
|
| 22 |
It has all the functionality you would expect from a caching library, but what |
| 23 |
**sets it apart** are the flexible configurations that have been designed to |
| 24 |
make I/O heavy applications both _robust_ and _highly performant_. |
| 25 |
|
| 26 |
We have been using this package in production to enhance both the performance |
| 27 |
and reliability of our services that retrieve data from distributed caches, |
| 28 |
databases, and external APIs. While the API surface of sturdyc is tiny, it |
| 29 |
offers extensive configuration options. I encourage you to read through this |
| 30 |
README and experiment with the examples in order to understand its full |
| 31 |
capabilities. |
| 32 |
|
| 33 |
This screenshot shows the P95 latency improvements we observed after adding |
| 34 |
this package in front of a distributed key-value store: |
| 35 |
|
| 36 |
|
| 37 |
<img width="1554" alt="Screenshot 2024-05-10 at 10 15 18" src="https://github.com/viccon/sturdyc/assets/12787673/adad1d4c-e966-4db1-969a-eda4fd75653a"> |
| 38 |
|
| 39 |
|
| 40 |
And through a combination of inflight-tracking, asynchronous refreshes, and |
| 41 |
refresh coalescing, we reduced load on underlying data sources by more than |
| 42 |
90%. This reduction in outgoing requests has enabled us to operate with fewer |
| 43 |
containers and significantly cheaper database clusters. |
| 44 |
|
| 45 |
# Table of contents |
| 46 |
|
| 47 |
Below is the table of contents for what this README is going to cover. However, |
| 48 |
if this is your first time using this package, I encourage you to **read these |
| 49 |
examples in the order they appear**. Most of them build on each other, and many |
| 50 |
share configurations. |
| 51 |
|
| 52 |
- [**installing**](https://github.com/viccon/sturdyc?tab=readme-ov-file#installing) |
| 53 |
- [**creating a cache client**](https://github.com/viccon/sturdyc?tab=readme-ov-file#creating-a-cache-client) |
| 54 |
- [**evictions**](https://github.com/viccon/sturdyc?tab=readme-ov-file#evictions) |
| 55 |
- [**get or fetch**](https://github.com/viccon/sturdyc?tab=readme-ov-file#get-or-fetch) |
| 56 |
- [**stampede protection**](https://github.com/viccon/sturdyc?tab=readme-ov-file#stampede-protection) |
| 57 |
- [**early refreshes**](https://github.com/viccon/sturdyc?tab=readme-ov-file#early-refreshes) |
| 58 |
- [**deletions**](https://github.com/viccon/sturdyc?tab=readme-ov-file#deletions) |
| 59 |
- [**caching non-existent records**](https://github.com/viccon/sturdyc?tab=readme-ov-file#non-existent-records) |
| 60 |
- [**caching batch endpoints per record**](https://github.com/viccon/sturdyc?tab=readme-ov-file#batch-endpoints) |
| 61 |
- [**cache key permutations**](https://github.com/viccon/sturdyc?tab=readme-ov-file#cache-key-permutations) |
| 62 |
- [**refresh coalescing**](https://github.com/viccon/sturdyc?tab=readme-ov-file#refresh-coalescing) |
| 63 |
- [**request passthrough**](https://github.com/viccon/sturdyc?tab=readme-ov-file#passthrough) |
| 64 |
- [**distributed storage**](https://github.com/viccon/sturdyc?tab=readme-ov-file#distributed-storage) |
| 65 |
- [**custom metrics**](https://github.com/viccon/sturdyc?tab=readme-ov-file#custom-metrics) |
| 66 |
- [**generics**](https://github.com/viccon/sturdyc?tab=readme-ov-file#generics) |
| 67 |
|
| 68 |
# Installing |
| 69 |
|
| 70 |
```sh |
| 71 |
go get github.com/viccon/sturdyc |
| 72 |
``` |
| 73 |
|
| 74 |
# Creating a cache client |
| 75 |
|
| 76 |
The first thing you will have to do is to create a cache client to hold your |
| 77 |
configuration: |
| 78 |
|
| 79 |
```go |
| 80 |
// Maximum number of entries in the cache. Exceeding this number will trigger |
| 81 |
// an eviction (as long as the "evictionPercentage" is greater than 0). |
| 82 |
capacity := 10000 |
| 83 |
// Number of shards to use. Increasing this number will reduce write lock collisions. |
| 84 |
numShards := 10 |
| 85 |
// Time-to-live for cache entries. |
| 86 |
ttl := 2 * time.Hour |
| 87 |
// Percentage of entries to evict when the cache reaches its capacity. Setting this |
| 88 |
// to 0 will make writes a no-op until an item has either expired or been deleted. |
| 89 |
evictionPercentage := 10 |
| 90 |
|
| 91 |
// Create a cache client with the specified configuration. |
| 92 |
cacheClient := sturdyc.New[int](capacity, numShards, ttl, evictionPercentage) |
| 93 |
|
| 94 |
cacheClient.Set("key1", 99) |
| 95 |
log.Println(cacheClient.Size()) |
| 96 |
log.Println(cacheClient.Get("key1")) |
| 97 |
|
| 98 |
cacheClient.Delete("key1") |
| 99 |
log.Println(cacheClient.Size()) |
| 100 |
log.Println(cacheClient.Get("key1")) |
| 101 |
``` |
| 102 |
|
| 103 |
|
| 104 |
The `New` function is variadic, and as the final argument we're also able to |
| 105 |
provide a wide range of configuration options, which we will explore in detail |
| 106 |
in the sections to follow. |
| 107 |
|
| 108 |
# Evictions |
| 109 |
|
| 110 |
The cache has two eviction strategies. One is a background job which |
| 111 |
continuously evicts expired records from each shard. However, there are options |
| 112 |
to both tweak the interval at which the job runs: |
| 113 |
|
| 114 |
```go |
| 115 |
cacheClient := sturdyc.New[int](capacity, numShards, ttl, evictionPercentage, |
| 116 |
sturdyc.WithEvictionInterval(time.Second), |
| 117 |
) |
| 118 |
``` |
| 119 |
|
| 120 |
as well as disabling the functionality altogether: |
| 121 |
|
| 122 |
```go |
| 123 |
cacheClient := sturdyc.New[int](capacity, numShards, ttl, evictionPercentage, |
| 124 |
sturdyc.WithNoContinuousEvictions() |
| 125 |
) |
| 126 |
``` |
| 127 |
|
| 128 |
The latter can give you a slight performance boost in situations where you're |
| 129 |
unlikely to ever exceed the capacity you've assigned to your cache. |
| 130 |
|
| 131 |
However, if the capacity is reached, the second eviction strategy is triggered. |
| 132 |
This process performs evictions on a per-shard basis, selecting records for |
| 133 |
removal based on recency. The eviction algorithm uses |
| 134 |
[quickselect](https://en.wikipedia.org/wiki/Quickselect), which has an O(N) |
| 135 |
time complexity without the overhead of requiring write locks on reads to |
| 136 |
update a recency list, as many LRU caches do. |
| 137 |
|
| 138 |
Next, we'll start to look at some of the more _advanced features_. |
| 139 |
|
| 140 |
# Get or fetch |
| 141 |
|
| 142 |
I have tried to design the API in a way that should make the process of |
| 143 |
integrating `sturdyc` with any data source as straightforward as possible. |
| 144 |
While it provides the basic get/set methods you would expect from a cache, the |
| 145 |
advanced functionality is accessed through just two core functions: |
| 146 |
`GetOrFetch` and `GetOrFetchBatch` |
| 147 |
|
| 148 |
As an example, let's say that we had the following code for fetching orders |
| 149 |
from an API: |
| 150 |
|
| 151 |
```go |
| 152 |
func (c *Client) Order(ctx context.Context, id string) (Order, error) { |
| 153 |
timeoutCtx, cancel := context.WithTimeout(ctx, c.timeout) |
| 154 |
defer cancel() |
| 155 |
|
| 156 |
var response Order |
| 157 |
err := requests.URL(c.orderURL). |
| 158 |
Pathf("/order/%s", id). |
| 159 |
ToJSON(&response). |
| 160 |
Fetch(timeoutCtx) |
| 161 |
|
| 162 |
return response, err |
| 163 |
} |
| 164 |
``` |
| 165 |
|
| 166 |
All we would have to do is wrap the lines of code that retrieves the data in a |
| 167 |
function, and then hand that over to our cache client: |
| 168 |
|
| 169 |
```go |
| 170 |
func (c *Client) Order(ctx context.Context, id string) (Order, error) { |
| 171 |
fetchFunc := func(ctx context.Context) (Order, error) { |
| 172 |
timeoutCtx, cancel := context.WithTimeout(ctx, c.timeout) |
| 173 |
defer cancel() |
| 174 |
|
| 175 |
var response Order |
| 176 |
err := requests.URL(c.orderURL). |
| 177 |
Pathf("/order/%s", id). |
| 178 |
ToJSON(&response). |
| 179 |
Fetch(timeoutCtx) |
| 180 |
|
| 181 |
return response, err |
| 182 |
} |
| 183 |
|
| 184 |
return c.cache.GetOrFetch(ctx, id, fetchFunc) |
| 185 |
} |
| 186 |
``` |
| 187 |
|
| 188 |
The cache is going to return the value from memory if it's available, and |
| 189 |
otherwise will call the `fetchFn` to retrieve the data from the underlying data |
| 190 |
source. |
| 191 |
|
| 192 |
Most of our examples are going to be retrieving data from HTTP APIs, but it's |
| 193 |
just as easy to wrap a database query, a remote procedure call, a disk read, or |
| 194 |
any other I/O operation. |
| 195 |
|
| 196 |
The `fetchFn` that we pass to `GetOrFetch` has the following function |
| 197 |
signature: |
| 198 |
|
| 199 |
```go |
| 200 |
type FetchFn[T any] func(ctx context.Context) (T, error) |
| 201 |
``` |
| 202 |
|
| 203 |
For data sources capable of handling requests for multiple records at once, |
| 204 |
we'll use `GetOrFetchBatch`: |
| 205 |
|
| 206 |
```go |
| 207 |
type KeyFn func(id string) string |
| 208 |
|
| 209 |
type BatchFetchFn[T any] func(ctx context.Context, ids []string) (map[string]T, error) |
| 210 |
|
| 211 |
func (c *Client[T]) GetOrFetchBatch(ctx context.Context, ids []string, keyFn KeyFn, fetchFn BatchFetchFn[T]) (map[string]T, error) { |
| 212 |
// ... |
| 213 |
} |
| 214 |
``` |
| 215 |
|
| 216 |
There are a few things to unpack here, so let's start with the `KeyFn`. When |
| 217 |
adding an in-memory cache to an API client capable of calling multiple |
| 218 |
endpoints, it's highly unlikely that an ID alone is going to be enough to |
| 219 |
uniquely identify a record. |
| 220 |
|
| 221 |
To illustrate, let's say that we're building a Github client and want to use |
| 222 |
this package to get around their rate limit. The username itself wouldn't make |
| 223 |
for a good cache key because we could use it to fetch gists, commits, |
| 224 |
repositories, etc. Therefore, `GetOrFetchBatch` takes a `KeyFn` that prefixes |
| 225 |
each ID with something to identify the data source so that we don't end up with |
| 226 |
cache key collisions: |
| 227 |
|
| 228 |
```go |
| 229 |
gistPrefixFn := cacheClient.BatchKeyFn("gists") |
| 230 |
commitPrefixFn := cacheClient.BatchKeyFn("commits") |
| 231 |
gists, err := cacheClient.GetOrFetchBatch(ctx, userIDs, gistPrefixFn, fetchGists) |
| 232 |
commits, err := cacheClient.GetOrFetchBatch(ctx, userIDs, commitPrefixFn, fetchCommits) |
| 233 |
``` |
| 234 |
|
| 235 |
We're now able to use the _same_ cache for _multiple_ data sources, and |
| 236 |
internally we'd get cache keys of this format: |
| 237 |
|
| 238 |
``` |
| 239 |
gists-ID-viccon |
| 240 |
gists-ID-some-other-user |
| 241 |
commits-ID-viccon |
| 242 |
commits-ID-some-other-user |
| 243 |
``` |
| 244 |
|
| 245 |
Now, let's use a bit of our imagination because Github doesn't actually allow |
| 246 |
us to fetch gists from multiple users at once. However, if they did, our client |
| 247 |
would probably look something like this: |
| 248 |
|
| 249 |
```go |
| 250 |
func (client *GithubClient) Gists(ctx context.Context, usernames []string) (map[string]Gist, error) { |
| 251 |
cacheKeyFn := client.cache.BatchKeyFn("gists") |
| 252 |
fetchFunc := func(ctx context.Context, cacheMisses []string) (map[string]Gist, error) { |
| 253 |
timeoutCtx, cancel := context.WithTimeout(ctx, client.timeout) |
| 254 |
defer cancel() |
| 255 |
|
| 256 |
var response map[string]Gist |
| 257 |
err := requests.URL(c.baseURL). |
| 258 |
Path("/gists"). |
| 259 |
Param("usernames", strings.Join(cacheMisses, ",")). |
| 260 |
ToJSON(&response). |
| 261 |
Fetch(timeoutCtx) |
| 262 |
return response, err |
| 263 |
} |
| 264 |
return sturdyc.GetOrFetchBatch(ctx, client.cache, usernames, cacheKeyFn, fetchFunc) |
| 265 |
} |
| 266 |
``` |
| 267 |
|
| 268 |
In the example above, the `fetchFunc` would get called for users where we don't |
| 269 |
have their gists in our cache, and the cacheMisses slice would contain their |
| 270 |
actual usernames (without the prefix from the keyFn). |
| 271 |
|
| 272 |
The map that we return from our `fetchFunc` should have the IDs (in this case the |
| 273 |
usernames) as keys, and the actual data that we want to cache (the gist) as the |
| 274 |
value. |
| 275 |
|
| 276 |
Later, we'll see how we can use closures to pass query parameters and options |
| 277 |
to our fetch functions, as well as how to use the `PermutatedBatchKeyFn` to |
| 278 |
create unique cache keys for each permutation of them. |
| 279 |
|
| 280 |
# Stampede protection |
| 281 |
|
| 282 |
`sturdyc` provides automatic protection against cache stampedes (also known as |
| 283 |
thundering herd) - a situation that occurs when many requests for a particular |
| 284 |
piece of data, which has just expired or been evicted from the cache, come in |
| 285 |
at once. |
| 286 |
|
| 287 |
Preventing this has been one of the key objectives. We do not want to cause a |
| 288 |
significant load on an underlying data source every time one of our keys |
| 289 |
expire. To address this, `sturdyc` performs _in-flight_ tracking for every key. |
| 290 |
|
| 291 |
We can demonstrate this using the `GetOrFetch` function which, as I mentioned |
| 292 |
earlier, takes a key, and a function for retrieving the data if it's not in the |
| 293 |
cache. The cache is going to ensure that we never have more than a single |
| 294 |
in-flight request per key: |
| 295 |
|
| 296 |
```go |
| 297 |
var count atomic.Int32 |
| 298 |
fetchFn := func(_ context.Context) (int, error) { |
| 299 |
// Increment the count so that we can assert how many times this function was called. |
| 300 |
count.Add(1) |
| 301 |
time.Sleep(time.Second) |
| 302 |
return 1337, nil |
| 303 |
} |
| 304 |
|
| 305 |
// Fetch the same key from 5 goroutines. |
| 306 |
var wg sync.WaitGroup |
| 307 |
for i := 0; i < 5; i++ { |
| 308 |
wg.Add(1) |
| 309 |
go func() { |
| 310 |
// We'll ignore the error here for brevity. |
| 311 |
val, _ := cacheClient.GetOrFetch(context.Background(), "key2", fetchFn) |
| 312 |
log.Printf("got value: %d\n", val) |
| 313 |
wg.Done() |
| 314 |
}() |
| 315 |
} |
| 316 |
wg.Wait() |
| 317 |
|
| 318 |
log.Printf("fetchFn was called %d time\n", count.Load()) |
| 319 |
log.Println(cacheClient.Get("key2")) |
| 320 |
|
| 321 |
``` |
| 322 |
|
| 323 |
Running this program we can see that we were able to retrieve the value for all |
| 324 |
5 goroutines, and that the fetchFn only got called once: |
| 325 |
|
| 326 |
```sh |
| 327 |
❯ go run . |
| 328 |
2024/05/21 08:06:29 got value: 1337 |
| 329 |
2024/05/21 08:06:29 got value: 1337 |
| 330 |
2024/05/21 08:06:29 got value: 1337 |
| 331 |
2024/05/21 08:06:29 got value: 1337 |
| 332 |
2024/05/21 08:06:29 got value: 1337 |
| 333 |
2024/05/21 08:06:29 fetchFn was called 1 time |
| 334 |
2024/05/21 08:06:29 1337 true |
| 335 |
``` |
| 336 |
|
| 337 |
The in-flight tracking works for batch operations too where the cache is able |
| 338 |
to deduplicate a batch of cache misses, and then assemble the response by |
| 339 |
picking records from **multiple** in-flight requests. |
| 340 |
|
| 341 |
To demonstrate this, we'll use the `GetOrFetchBatch` function, which as mentioned |
| 342 |
earlier, can be used to retrieve data from a data source capable of handling |
| 343 |
requests for multiple records at once. |
| 344 |
|
| 345 |
We'll start by creating a mock function that sleeps for `5` seconds, and then |
| 346 |
returns a map with a numerical value for every ID: |
| 347 |
|
| 348 |
```go |
| 349 |
var count atomic.Int32 |
| 350 |
fetchFn := func(_ context.Context, ids []string) (map[string]int, error) { |
| 351 |
// Increment the counter so that we can assert how many times this function was called. |
| 352 |
count.Add(1) |
| 353 |
time.Sleep(time.Second * 5) |
| 354 |
|
| 355 |
response := make(map[string]int, len(ids)) |
| 356 |
for _, id := range ids { |
| 357 |
num, _ := strconv.Atoi(id) |
| 358 |
response[id] = num |
| 359 |
} |
| 360 |
|
| 361 |
return response, nil |
| 362 |
} |
| 363 |
``` |
| 364 |
|
| 365 |
Next, we'll need some batches to test with, so here I've created three batches |
| 366 |
with five IDs each: |
| 367 |
|
| 368 |
```go |
| 369 |
batches := [][]string{ |
| 370 |
{"1", "2", "3", "4", "5"}, |
| 371 |
{"6", "7", "8", "9", "10"}, |
| 372 |
{"11", "12", "13", "14", "15"}, |
| 373 |
} |
| 374 |
``` |
| 375 |
|
| 376 |
and we can now request each batch in a separate goroutine: |
| 377 |
|
| 378 |
```go |
| 379 |
for _, batch := range batches { |
| 380 |
go func() { |
| 381 |
res, _ := cacheClient.GetOrFetchBatch(context.Background(), batch, keyPrefixFn, fetchFn) |
| 382 |
log.Printf("got batch: %v\n", res) |
| 383 |
}() |
| 384 |
} |
| 385 |
|
| 386 |
// Just to ensure that these batches are in fact in-flight, we'll sleep to give the goroutines a chance to run. |
| 387 |
time.Sleep(time.Second * 2) |
| 388 |
``` |
| 389 |
|
| 390 |
At this point, the cache should have 3 in-flight requests for IDs 1-15: |
| 391 |
|
| 392 |
```sh |
| 393 |
[1,2,3,4,5] => REQUEST 1 (IN-FLIGHT) |
| 394 |
[6,7,8,9,10] => REQUEST 2 (IN-FLIGHT) |
| 395 |
[11,12,13,14,15] => REQUEST 3 (IN-FLIGHT) |
| 396 |
``` |
| 397 |
|
| 398 |
Knowing this, let's test the stampede protection by launching another five |
| 399 |
goroutines. Each of these goroutines will request two random IDs from our |
| 400 |
previous batches. For example, they could request one ID from the first |
| 401 |
request, and another from the second or third. |
| 402 |
|
| 403 |
```go |
| 404 |
// Launch another 5 goroutines that are going to pick two random IDs from any of our in-flight batches. |
| 405 |
// e.g: |
| 406 |
// [1,8] |
| 407 |
// [4,11] |
| 408 |
// [14,2] |
| 409 |
// [6,15] |
| 410 |
|
| 411 |
func pickRandomValue(batches [][]string) string { |
| 412 |
batch := batches[rand.IntN(len(batches))] |
| 413 |
return batch[rand.IntN(len(batch))] |
| 414 |
} |
| 415 |
|
| 416 |
var wg sync.WaitGroup |
| 417 |
for i := 0; i < 5; i++ { |
| 418 |
wg.Add(1) |
| 419 |
go func() { |
| 420 |
ids := []string{pickRandomValue(batches), pickRandomValue(batches)} |
| 421 |
res, _ := cacheClient.GetOrFetchBatch(context.Background(), ids, keyPrefixFn, fetchFn) |
| 422 |
log.Printf("got batch: %v\n", res) |
| 423 |
wg.Done() |
| 424 |
}() |
| 425 |
} |
| 426 |
|
| 427 |
wg.Wait() |
| 428 |
log.Printf("fetchFn was called %d times\n", count.Load()) |
| 429 |
``` |
| 430 |
|
| 431 |
Running this program, and looking at the logs, we'll see that the cache is able |
| 432 |
to resolve all of the ids from these new goroutines without generating any |
| 433 |
additional requests even though we're picking IDs from different in-flight |
| 434 |
requests: |
| 435 |
|
| 436 |
```sh |
| 437 |
❯ go run . |
| 438 |
2024/05/21 09:14:23 got batch: map[8:8 9:9] |
| 439 |
2024/05/21 09:14:23 got batch: map[4:4 9:9] <---- NOTE: ID 4 and 9 are part of different batches |
| 440 |
2024/05/21 09:14:23 got batch: map[11:11 12:12 13:13 14:14 15:15] |
| 441 |
2024/05/21 09:14:23 got batch: map[1:1 7:7] <---- NOTE: ID 1 and 7 are part of different batches |
| 442 |
2024/05/21 09:14:23 got batch: map[10:10 6:6 7:7 8:8 9:9] |
| 443 |
2024/05/21 09:14:23 got batch: map[3:3 9:9] <---- NOTE: ID 3 and 9 are part of different batches |
| 444 |
2024/05/21 09:14:23 got batch: map[1:1 2:2 3:3 4:4 5:5] |
| 445 |
2024/05/21 09:14:23 got batch: map[4:4 9:9] <---- NOTE: ID 4 and 9 are part of different batches |
| 446 |
2024/05/21 09:14:23 fetchFn was called 3 times <---- NOTE: We only generated 3 outgoing requests. |
| 447 |
``` |
| 448 |
|
| 449 |
The entire example is available [here.](https://github.com/viccon/sturdyc/tree/main/examples/basic) |
| 450 |
|
| 451 |
# Early refreshes |
| 452 |
|
| 453 |
Serving data from memory is typically at least one to two orders of magnitude |
| 454 |
faster than reading from disk, and if you have to retrieve the data across a |
| 455 |
network the difference can grow even larger. Consequently, we're often able to |
| 456 |
significantly improve our applications performance by adding an in-memory |
| 457 |
cache. |
| 458 |
|
| 459 |
However, one has to be aware of the usual trade-offs. Suppose we use a TTL of |
| 460 |
10 seconds. That means the cached data can be up to 10 seconds old. In many |
| 461 |
applications this may be acceptable, but in others it can introduce stale |
| 462 |
reads. Additionally, once the cached value expires, the first request after |
| 463 |
expiration must refresh the cache, resulting in a longer response time for that |
| 464 |
user. This can make the average latency look very different from the P90–P99 |
| 465 |
tail latencies, since those percentiles capture the delays of having to go to |
| 466 |
the actual data source in order to refresh the cache. This in turn can make it |
| 467 |
difficult to configure appropriate alarms for your applications response times. |
| 468 |
|
| 469 |
`sturdyc` aims to give you a lot of control over these choices when you enable |
| 470 |
the **early refreshes** functionality. It will prevent your most frequently |
| 471 |
used records from ever expiring by continuously refreshing them in the |
| 472 |
background. This can have a significant impact on your applications latency. |
| 473 |
We've seen the P99 of some of our applications go from 50ms down to 1. |
| 474 |
|
| 475 |
One thing to note about these background refreshes is that they are scheduled |
| 476 |
if a key is **requested again** after a configurable amount of time has passed. |
| 477 |
This is an important distinction because it means that the cache doesn't just |
| 478 |
naively refresh every key it's ever seen. Instead, it only refreshes the |
| 479 |
records that are actually in active rotation, while allowing unused keys to be |
| 480 |
deleted once their TTL expires. This also means that the request that gets |
| 481 |
chosen to refresh the value won’t retrieve the updated data right away as the |
| 482 |
refresh happens asynchronously. |
| 483 |
|
| 484 |
However, asynchronous refreshes present challenges with infrequently requested |
| 485 |
keys. While background refreshes keep latency low by serving cached values |
| 486 |
during updates, this can lead to perpetually stale data. If a key isn't |
| 487 |
requested again before its next scheduled refresh, we remain permanently one |
| 488 |
update behind, as each read triggers a refresh that won't be seen until the |
| 489 |
next request. This is similar to a burger restaurant that prepares a new burger |
| 490 |
after each customer's order - if the next customer arrives too late, they'll |
| 491 |
receive a cold burger, despite the restaurant's proactive cooking strategy. |
| 492 |
|
| 493 |
To solve this, you also get to provide a synchronous refresh time. This |
| 494 |
essentially tells the cache: "If the data is older than x, I want the refresh |
| 495 |
to be blocking and have the user wait for the response." Or using the burger |
| 496 |
analogy: if a burger has been sitting for more than X minutes, the restaurant |
| 497 |
starts making a fresh one while the customer waits. Unlike a real restaurant |
| 498 |
though, the cache keeps the old value as a fallback - if the refresh fails, |
| 499 |
we'll still serve the "cold burger" rather than letting the customer go hungry. |
| 500 |
|
| 501 |
Below is an example configuration that you can use to enable this |
| 502 |
functionality: |
| 503 |
|
| 504 |
```go |
| 505 |
func main() { |
| 506 |
// Set a minimum and maximum refresh delay for the records. This is used to |
| 507 |
// spread out the refreshes of our records evenly over time. If we're running |
| 508 |
// our application across 100 containers, we don't want to send a spike of |
| 509 |
// refreshes from every container every 30 ms. Instead, we'll use some |
| 510 |
// randomization to spread them out evenly between 10 and 30 ms. |
| 511 |
minRefreshDelay := time.Millisecond * 10 |
| 512 |
maxRefreshDelay := time.Millisecond * 30 |
| 513 |
// Set a synchronous refresh delay for when we want a refresh to happen synchronously. |
| 514 |
synchronousRefreshDelay := time.Second * 30 |
| 515 |
// The base used for exponential backoff when retrying a background refresh. |
| 516 |
// Most of the time, we perform refreshes well in advance of the records |
| 517 |
// expiry time. Hence, we can use this to make it easier for a system that |
| 518 |
// is having trouble to get back on it's feet by making fewer refreshes when |
| 519 |
// we're seeing a lot of errors. Once we receive a successful response, the |
| 520 |
// refreshes return to their original frequency. You can set this to 0 |
| 521 |
// if you don't want this behavior. |
| 522 |
retryBaseDelay := time.Millisecond * 10 |
| 523 |
|
| 524 |
// Create a cache client with the specified configuration. |
| 525 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 526 |
sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, retryBaseDelay), |
| 527 |
) |
| 528 |
} |
| 529 |
``` |
| 530 |
|
| 531 |
Let's build a simple API client that embeds the cache using our configuration: |
| 532 |
|
| 533 |
```go |
| 534 |
type API struct { |
| 535 |
*sturdyc.Client[string] |
| 536 |
} |
| 537 |
|
| 538 |
func NewAPI(c *sturdyc.Client[string]) *API { |
| 539 |
return &API{c} |
| 540 |
} |
| 541 |
|
| 542 |
func (a *API) Get(ctx context.Context, key string) (string, error) { |
| 543 |
// This could be an API call, a database query, etc. |
| 544 |
fetchFn := func(_ context.Context) (string, error) { |
| 545 |
log.Printf("Fetching value for key: %s\n", key) |
| 546 |
return "value", nil |
| 547 |
} |
| 548 |
return a.GetOrFetch(ctx, key, fetchFn) |
| 549 |
} |
| 550 |
``` |
| 551 |
|
| 552 |
Now we can return to our `main` function to create an instance of it, and then |
| 553 |
call the `Get` method in a loop: |
| 554 |
|
| 555 |
```go |
| 556 |
func main() { |
| 557 |
// ... |
| 558 |
|
| 559 |
cacheClient := sturdyc.New[string](...) |
| 560 |
|
| 561 |
// Create a new API instance with the cache client. |
| 562 |
api := NewAPI(cacheClient) |
| 563 |
|
| 564 |
// We are going to retrieve the values every 10 milliseconds, however the |
| 565 |
// logs will reveal that actual refreshes fluctuate randomly within a 10-30 |
| 566 |
// millisecond range. |
| 567 |
for i := 0; i < 100; i++ { |
| 568 |
val, err := api.Get(context.Background(), "key") |
| 569 |
if err != nil { |
| 570 |
log.Println("Failed to retrieve the record from the cache.") |
| 571 |
continue |
| 572 |
} |
| 573 |
log.Printf("Value: %s\n", val) |
| 574 |
time.Sleep(minRefreshDelay) |
| 575 |
} |
| 576 |
} |
| 577 |
``` |
| 578 |
|
| 579 |
Running this program, we're going to see that the value gets refreshed |
| 580 |
asynchronously once every 2-3 retrievals: |
| 581 |
|
| 582 |
```sh |
| 583 |
cd examples/refreshes |
| 584 |
go run . |
| 585 |
2024/04/07 09:05:29 Fetching value for key: key |
| 586 |
2024/04/07 09:05:29 Value: value |
| 587 |
2024/04/07 09:05:29 Value: value |
| 588 |
2024/04/07 09:05:29 Fetching value for key: key |
| 589 |
2024/04/07 09:05:29 Value: value |
| 590 |
2024/04/07 09:05:29 Value: value |
| 591 |
2024/04/07 09:05:29 Value: value |
| 592 |
2024/04/07 09:05:29 Fetching value for key: key |
| 593 |
... |
| 594 |
``` |
| 595 |
|
| 596 |
If this was a real application it would have reduced our response times |
| 597 |
significantly because none of our users would have to wait for the I/O |
| 598 |
operation that refreshes the data. It's always performed in the background as |
| 599 |
long as the key is being continuously requested. |
| 600 |
|
| 601 |
We don't have to be afraid that the data for infrequently used keys gets stale |
| 602 |
either, given that we set the synchronous refresh delay like this: |
| 603 |
|
| 604 |
```go |
| 605 |
synchronousRefreshDelay := time.Second * 30 |
| 606 |
``` |
| 607 |
|
| 608 |
Which means that if a key isn't requested again within 30 seconds, the cache |
| 609 |
will make the refresh synchronous. Even if a minute has passed and 1,000 |
| 610 |
requests suddenly come in for this key, the stampede protection will kick in |
| 611 |
and make the refresh synchronous for all of them, while also ensuring that only |
| 612 |
a single request is made to the underlying data source. |
| 613 |
|
| 614 |
Sometimes I like to use this feature to provide a degraded experience when an |
| 615 |
upstream system encounters issues. For this, I choose a high TTL and a low |
| 616 |
refresh time, so that when everything is working as expected, the records are |
| 617 |
refreshed continuously. However, if the upstream system stops responding, I can |
| 618 |
rely on cached records for the entire duration of the TTL. |
| 619 |
|
| 620 |
This also brings us to the final argument of the `WithEarlyRefreshes` function |
| 621 |
which is the retry base delay. This delay is used to create an exponential |
| 622 |
backoff for our background requests if a data source starts to return errors. |
| 623 |
Please note that this **only** applies to background refreshes. If we reach a |
| 624 |
point where all of the records are older than the synchronous refresh time, |
| 625 |
we're going to send a steady stream of outgoing requests. That is because I |
| 626 |
think of the synchronous refresh time as "I really don’t want the data to be |
| 627 |
older than this, but I want the possibility of using an even higher TTL in |
| 628 |
order to serve stale." Therefore, if a synchronous refresh fails, I want the |
| 629 |
very next request for that key to attempt another refresh. |
| 630 |
|
| 631 |
Also, if you don't want any of this serve stale functionality you could just |
| 632 |
use short TTLs. The cache will never return a record where the TTL has expired. |
| 633 |
I'm just trying to showcase some different ways to leverage this functionality! |
| 634 |
|
| 635 |
The entire example is available [here.](https://github.com/viccon/sturdyc/tree/main/examples/refreshes) |
| 636 |
|
| 637 |
# Deletions |
| 638 |
|
| 639 |
What if a record gets deleted at the underlying data source? Our cache might |
| 640 |
use a 2-hour-long TTL, and we definitely don't want it to take that long for |
| 641 |
the deletion to propagate. |
| 642 |
|
| 643 |
However, if we were to modify our client from the previous example so that it |
| 644 |
returns an error after the first request: |
| 645 |
|
| 646 |
```go |
| 647 |
type API struct { |
| 648 |
count int |
| 649 |
*sturdyc.Client[string] |
| 650 |
} |
| 651 |
|
| 652 |
func NewAPI(c *sturdyc.Client[string]) *API { |
| 653 |
return &API{0, c} |
| 654 |
} |
| 655 |
|
| 656 |
func (a *API) Get(ctx context.Context, key string) (string, error) { |
| 657 |
fetchFn := func(_ context.Context) (string, error) { |
| 658 |
a.count++ |
| 659 |
log.Printf("Fetching value for key: %s\n", key) |
| 660 |
if a.count == 1 { |
| 661 |
return "value", nil |
| 662 |
} |
| 663 |
return "", errors.New("error this key does not exist") |
| 664 |
} |
| 665 |
return a.GetOrFetch(ctx, key, fetchFn) |
| 666 |
} |
| 667 |
``` |
| 668 |
|
| 669 |
and then run the program again: |
| 670 |
|
| 671 |
```sh |
| 672 |
cd examples/refreshes |
| 673 |
go run . |
| 674 |
``` |
| 675 |
|
| 676 |
We'll see that the exponential backoff kicks in, delaying our background |
| 677 |
refreshes which results in more iterations for every refresh, but the value is |
| 678 |
still being printed: |
| 679 |
|
| 680 |
```sh |
| 681 |
2024/05/09 13:22:03 Fetching value for key: key |
| 682 |
2024/05/09 13:22:03 Value: value |
| 683 |
2024/05/09 13:22:03 Value: value |
| 684 |
2024/05/09 13:22:03 Value: value |
| 685 |
2024/05/09 13:22:03 Value: value |
| 686 |
2024/05/09 13:22:03 Value: value |
| 687 |
2024/05/09 13:22:03 Value: value |
| 688 |
2024/05/09 13:22:03 Value: value |
| 689 |
2024/05/09 13:22:04 Value: value |
| 690 |
2024/05/09 13:22:04 Value: value |
| 691 |
2024/05/09 13:22:04 Value: value |
| 692 |
2024/05/09 13:22:04 Value: value |
| 693 |
2024/05/09 13:22:04 Value: value |
| 694 |
2024/05/09 13:22:04 Value: value |
| 695 |
2024/05/09 13:22:04 Value: value |
| 696 |
2024/05/09 13:22:04 Value: value |
| 697 |
2024/05/09 13:22:04 Value: value |
| 698 |
2024/05/09 13:22:04 Value: value |
| 699 |
2024/05/09 13:22:04 Value: value |
| 700 |
2024/05/09 13:22:04 Value: value |
| 701 |
2024/05/09 13:22:04 Value: value |
| 702 |
2024/05/09 13:22:04 Value: value |
| 703 |
2024/05/09 13:22:04 Value: value |
| 704 |
2024/05/09 13:22:04 Value: value |
| 705 |
2024/05/09 13:22:04 Value: value |
| 706 |
2024/05/09 13:22:04 Value: value |
| 707 |
2024/05/09 13:22:04 Value: value |
| 708 |
2024/05/09 13:22:04 Value: value |
| 709 |
2024/05/09 13:22:04 Value: value |
| 710 |
2024/05/09 13:22:04 Value: value |
| 711 |
2024/05/09 13:22:04 Value: value |
| 712 |
2024/05/09 13:22:04 Fetching value for key: key |
| 713 |
``` |
| 714 |
|
| 715 |
This is a bit tricky because how you determine if a record has been deleted |
| 716 |
could vary based on your data source. It could be a status code, zero value, |
| 717 |
empty list, specific error message, etc. There is no easy way for the cache to |
| 718 |
figure this out implicitly. |
| 719 |
|
| 720 |
It couldn't simply delete a record every time it receives an error. If an |
| 721 |
upstream system goes down, we want to be able to serve the data for the |
| 722 |
duration of the TTL, while reducing the frequency of our refreshes to make it |
| 723 |
easier for them to recover. |
| 724 |
|
| 725 |
Therefore, if a record is deleted, we'll have to explicitly inform the cache |
| 726 |
about it by returning a custom error: |
| 727 |
|
| 728 |
```go |
| 729 |
fetchFn := func(_ context.Context) (string, error) { |
| 730 |
a.count++ |
| 731 |
log.Printf("Fetching value for key: %s\n", key) |
| 732 |
if a.count == 1 { |
| 733 |
return "value", nil |
| 734 |
} |
| 735 |
return "", sturdyc.ErrNotFound |
| 736 |
} |
| 737 |
``` |
| 738 |
|
| 739 |
This tells the cache that the record is no longer available at the underlying data source. |
| 740 |
|
| 741 |
If we run this application again we'll see that it works, and that we're no |
| 742 |
longer getting any cache hits. This leads to outgoing requests for every |
| 743 |
iteration: |
| 744 |
|
| 745 |
```go |
| 746 |
2024/05/09 13:40:47 Fetching value for key: key |
| 747 |
2024/05/09 13:40:47 Value: value |
| 748 |
2024/05/09 13:40:47 Value: value |
| 749 |
2024/05/09 13:40:47 Value: value |
| 750 |
2024/05/09 13:40:47 Fetching value for key: key |
| 751 |
2024/05/09 13:40:47 Failed to retrieve the record from the cache. |
| 752 |
2024/05/09 13:40:47 Fetching value for key: key |
| 753 |
2024/05/09 13:40:47 Failed to retrieve the record from the cache. |
| 754 |
2024/05/09 13:40:47 Fetching value for key: key |
| 755 |
2024/05/09 13:40:47 Failed to retrieve the record from the cache. |
| 756 |
2024/05/09 13:40:47 Fetching value for key: key |
| 757 |
2024/05/09 13:40:47 Failed to retrieve the record from the cache. |
| 758 |
``` |
| 759 |
|
| 760 |
**Please note** that we only have to return the `sturdyc.ErrNotFound` when |
| 761 |
we're using `GetOrFetch`. For `GetOrFetchBatch`, we'll simply omit the key from the |
| 762 |
map we're returning. I think this inconsistency is a little unfortunate, but it |
| 763 |
was the best API I could come up with. Having to return an error like this if |
| 764 |
just a single ID wasn't found: |
| 765 |
|
| 766 |
```go |
| 767 |
batchFetchFn := func(_ context.Context, cacheMisses []string) (map[string]string, error) { |
| 768 |
response, err := myDataSource(cacheMisses) |
| 769 |
for _, id := range cacheMisses { |
| 770 |
// NOTE: Don't do this, it's just an example. |
| 771 |
if response[id]; !id { |
| 772 |
return response, sturdyc.ErrNotFound |
| 773 |
} |
| 774 |
} |
| 775 |
return response, nil |
| 776 |
} |
| 777 |
``` |
| 778 |
|
| 779 |
and then have the cache either swallow that error and return nil, or return the |
| 780 |
map with the error, felt much less intuitive. |
| 781 |
|
| 782 |
This code is based on the example available [here.](https://github.com/viccon/sturdyc/tree/main/examples/refreshes) |
| 783 |
|
| 784 |
# Non-existent records |
| 785 |
|
| 786 |
In the example above, we could see that once we delete the key, the following |
| 787 |
iterations lead to a continuous stream of outgoing requests. This would also |
| 788 |
happen for every ID that doesn't exist at the underlying data source. If we |
| 789 |
can't retrieve it, we can't cache it. If we can't cache it, we can't serve it |
| 790 |
from memory. If this happens frequently, we'll experience a lot of I/O |
| 791 |
operations, which will significantly increase our system's latency. |
| 792 |
|
| 793 |
The reasons why someone might request IDs that don't exist can vary. It could |
| 794 |
be due to a faulty CMS configuration, or perhaps it's caused by a slow |
| 795 |
ingestion process where it takes time for a new entity to propagate through a |
| 796 |
distributed system. Regardless, this will negatively impact our systems |
| 797 |
performance. |
| 798 |
|
| 799 |
To address this issue, we can instruct the cache to mark these IDs as missing |
| 800 |
records. If you're using this functionality in combination with the |
| 801 |
`WithEarlyRefreshes` option, they are going to get refreshed at the same |
| 802 |
frequency as regular records. Hence, if an ID is continuously requested, and |
| 803 |
the upstream eventually returns a valid response, we'll see it propagate to our |
| 804 |
cache. |
| 805 |
|
| 806 |
To illustrate, I'll make some small modifications to the code from the previous |
| 807 |
example. I'm going to to make the API client return a `ErrNotFound` for the |
| 808 |
first three requests: |
| 809 |
|
| 810 |
```go |
| 811 |
type API struct { |
| 812 |
*sturdyc.Client[string] |
| 813 |
count int |
| 814 |
} |
| 815 |
|
| 816 |
func NewAPI(c *sturdyc.Client[string]) *API { |
| 817 |
return &API{c, 0} |
| 818 |
} |
| 819 |
|
| 820 |
func (a *API) Get(ctx context.Context, key string) (string, error) { |
| 821 |
fetchFn := func(_ context.Context) (string, error) { |
| 822 |
a.count++ |
| 823 |
log.Printf("Fetching value for key: %s\n", key) |
| 824 |
if a.count > 3 { |
| 825 |
return "value", nil |
| 826 |
} |
| 827 |
// This error tells the cache that the data does not exist at the source. |
| 828 |
return "", sturdyc.ErrNotFound |
| 829 |
} |
| 830 |
return a.GetOrFetch(ctx, key, fetchFn) |
| 831 |
} |
| 832 |
``` |
| 833 |
|
| 834 |
Next, we'll just have to enable missing record storage which tells the cache |
| 835 |
that anytime it gets a `ErrNotFound` error it should mark the key as missing: |
| 836 |
|
| 837 |
```go |
| 838 |
func main() { |
| 839 |
// ... |
| 840 |
|
| 841 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 842 |
sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, retryBaseDelay), |
| 843 |
sturdyc.WithMissingRecordStorage(), |
| 844 |
) |
| 845 |
|
| 846 |
api := NewAPI(cacheClient) |
| 847 |
|
| 848 |
// ... |
| 849 |
for i := 0; i < 100; i++ { |
| 850 |
val, err := api.Get(context.Background(), "key") |
| 851 |
// The cache returns ErrMissingRecord for any key that has been marked as missing. |
| 852 |
// You can use this to exit-early, or return some type of default state. |
| 853 |
if errors.Is(err, sturdyc.ErrMissingRecord) { |
| 854 |
log.Println("Record does not exist.") |
| 855 |
} |
| 856 |
if err == nil { |
| 857 |
log.Printf("Value: %s\n", val) |
| 858 |
} |
| 859 |
time.Sleep(minRefreshDelay) |
| 860 |
} |
| 861 |
} |
| 862 |
``` |
| 863 |
|
| 864 |
Running this program, we'll see that the record is missing during the first 3 |
| 865 |
refreshes, and then transitions into having a value: |
| 866 |
|
| 867 |
```sh |
| 868 |
❯ go run . |
| 869 |
2024/05/09 21:25:28 Fetching value for key: key |
| 870 |
2024/05/09 21:25:28 Record does not exist. |
| 871 |
2024/05/09 21:25:28 Record does not exist. |
| 872 |
2024/05/09 21:25:28 Record does not exist. |
| 873 |
2024/05/09 21:25:28 Fetching value for key: key |
| 874 |
2024/05/09 21:25:28 Record does not exist. |
| 875 |
2024/05/09 21:25:28 Record does not exist. |
| 876 |
2024/05/09 21:25:28 Fetching value for key: key |
| 877 |
2024/05/09 21:25:28 Record does not exist. |
| 878 |
2024/05/09 21:25:28 Record does not exist. |
| 879 |
2024/05/09 21:25:28 Fetching value for key: key |
| 880 |
2024/05/09 21:25:28 Value: value // Look, the value exists now! |
| 881 |
2024/05/09 21:25:28 Value: value |
| 882 |
2024/05/09 21:25:28 Value: value |
| 883 |
2024/05/09 21:25:28 Fetching value for key: key |
| 884 |
... |
| 885 |
``` |
| 886 |
|
| 887 |
**Please note** that this functionality is _implicit_ for `GetOrFetchBatch`. |
| 888 |
You simply just have to omit the key from the map: |
| 889 |
|
| 890 |
```go |
| 891 |
batchFetchFn := func(_ context.Context, cacheMisses []string) (map[string]string, error) { |
| 892 |
// The cache will check if every ID in cacheMisses is present in the response. |
| 893 |
// If it finds any IDs that are missing it will proceed to mark them as missing |
| 894 |
// if missing record storage is enabled. |
| 895 |
response, err := myDataSource(cacheMisses) |
| 896 |
return response, nil |
| 897 |
} |
| 898 |
``` |
| 899 |
|
| 900 |
The entire example is available [here.](https://github.com/viccon/sturdyc/tree/main/examples/missing) |
| 901 |
|
| 902 |
# Batch endpoints |
| 903 |
|
| 904 |
One challenge with caching batchable endpoints is that you have to find a way |
| 905 |
to reduce the number of cache keys. Consider an endpoint that allows fetching |
| 906 |
10,000 records in batches of 20. The IDs for the batch are supplied as query |
| 907 |
parameters, for example, `https://example.com?ids=1,2,3,4,5,...20`. If we were |
| 908 |
to use this as the cache key, the way many CDNs would, we could quickly |
| 909 |
calculate the number of keys we would generate like this: |
| 910 |
|
| 911 |
$$ C(n, k) = \binom{n}{k} = \frac{n!}{k!(n-k)!} $$ |
| 912 |
|
| 913 |
For $n = 10,000$ and $k = 20$, this becomes: |
| 914 |
|
| 915 |
$$ C(10,000, 20) = \binom{10,000}{20} = \frac{10,000!}{20!(10,000-20)!} $$ |
| 916 |
|
| 917 |
This results in an approximate value of: |
| 918 |
|
| 919 |
$$ \approx 4.032 \times 10^{61} $$ |
| 920 |
|
| 921 |
and this is if we're sending perfect batches of 20. If we were to do 1 to 20 |
| 922 |
IDs (not just exactly 20 each time) the total number of combinations would be |
| 923 |
the sum of combinations for each k from 1 to 20. |
| 924 |
|
| 925 |
At this point, the hit rate for each key would be so low that we'd have better |
| 926 |
odds of winning the lottery. |
| 927 |
|
| 928 |
To prevent this, `sturdyc` pulls the response apart and caches each record |
| 929 |
individually. This effectively prevents super-polynomial growth in the number |
| 930 |
of cache keys because the batch itself is never going to be included in the |
| 931 |
key. |
| 932 |
|
| 933 |
To get a better feeling for how this works, we can look at the function signature |
| 934 |
for the `GetOrFetchBatch` function: |
| 935 |
|
| 936 |
```go |
| 937 |
func (c *Client[T]) GetOrFetchBatch(ctx context.Context, ids []string, keyFn KeyFn, fetchFn BatchFetchFn[T]) (map[string]T, error) {} |
| 938 |
``` |
| 939 |
|
| 940 |
What the cache does is that it takes the IDs, applies the `keyFn` to them, and |
| 941 |
then checks each key individually if it's present in the cache. The keys that |
| 942 |
aren't present will be passed to the `fetchFn`. |
| 943 |
|
| 944 |
The `fetchFn` has this signature where it returns a map where the ID is the |
| 945 |
key: |
| 946 |
|
| 947 |
```go |
| 948 |
type BatchFetchFn[T any] func(ctx context.Context, ids []string) (map[string]T, error) |
| 949 |
``` |
| 950 |
|
| 951 |
The cache can use this to iterate through the response map, again apply the |
| 952 |
`keyFn` to each ID, and then store each record individually. |
| 953 |
|
| 954 |
Sometimes, the function signature for the `BatchFetchFn` can feel too limited. |
| 955 |
You may need additional options and not just the IDs to retrieve the data. But |
| 956 |
don't worry, we'll look at how to solve this in the next section! |
| 957 |
|
| 958 |
For now, to get some code to play around with, let's once again build a small |
| 959 |
example application. This time, we'll start with the API client: |
| 960 |
|
| 961 |
```go |
| 962 |
type API struct { |
| 963 |
*sturdyc.Client[string] |
| 964 |
} |
| 965 |
|
| 966 |
func NewAPI(c *sturdyc.Client[string]) *API { |
| 967 |
return &API{c} |
| 968 |
} |
| 969 |
|
| 970 |
func (a *API) GetBatch(ctx context.Context, ids []string) (map[string]string, error) { |
| 971 |
// We are going to pass a cache a key function that prefixes each id with |
| 972 |
// the string "some-prefix", and adds an -ID- separator before the actual |
| 973 |
// id. This makes it possible to save the same id for different data |
| 974 |
// sources as the keys would look something like this: some-prefix-ID-1234 |
| 975 |
cacheKeyFn := a.BatchKeyFn("some-prefix") |
| 976 |
|
| 977 |
// The fetchFn is only going to retrieve the IDs that are not in the cache. Please |
| 978 |
// note that the cacheMisses is going to contain the actual IDs, not the cache keys. |
| 979 |
fetchFn := func(_ context.Context, cacheMisses []string) (map[string]string, error) { |
| 980 |
log.Printf("Cache miss. Fetching ids: %s\n", strings.Join(cacheMisses, ", ")) |
| 981 |
// Batch functions should return a map where the key is the id of the record. |
| 982 |
response := make(map[string]string, len(cacheMisses)) |
| 983 |
for _, id := range cacheMisses { |
| 984 |
response[id] = "value" |
| 985 |
} |
| 986 |
return response, nil |
| 987 |
} |
| 988 |
|
| 989 |
return a.GetOrFetchBatch(ctx, ids, cacheKeyFn, fetchFn) |
| 990 |
} |
| 991 |
``` |
| 992 |
|
| 993 |
and we're going to use the same cache configuration as the previous example, so |
| 994 |
I've omitted it for brevity: |
| 995 |
|
| 996 |
```go |
| 997 |
func main() { |
| 998 |
// ... |
| 999 |
|
| 1000 |
// Create a new API instance with the cache client. |
| 1001 |
api := NewAPI(cacheClient) |
| 1002 |
|
| 1003 |
// Make an initial call to make sure that IDs 1-10 are retrieved and cached. |
| 1004 |
log.Println("Seeding ids 1-10") |
| 1005 |
ids := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"} |
| 1006 |
api.GetBatch(context.Background(), ids) |
| 1007 |
log.Println("Seed completed") |
| 1008 |
|
| 1009 |
// To demonstrate that the records have been cached individually, we can continue |
| 1010 |
// fetching a random subset of records from the original batch, plus a new |
| 1011 |
// ID. By examining the logs, we should be able to see that the cache only |
| 1012 |
// fetches the ID that wasn't present in the original batch, indicating that |
| 1013 |
// the batch itself isn't part of the key. |
| 1014 |
for i := 1; i <= 100; i++ { |
| 1015 |
// Get N ids from the original batch. |
| 1016 |
recordsToFetch := rand.IntN(10) + 1 |
| 1017 |
batch := make([]string, recordsToFetch) |
| 1018 |
copy(batch, ids[:recordsToFetch]) |
| 1019 |
// Add a random ID between 1 and 100 to the batch. |
| 1020 |
batch = append(batch, strconv.Itoa(rand.IntN(1000)+10)) |
| 1021 |
values, _ := api.GetBatch(context.Background(), batch) |
| 1022 |
// Print the records we retrieved from the cache. |
| 1023 |
log.Println(values) |
| 1024 |
} |
| 1025 |
} |
| 1026 |
``` |
| 1027 |
|
| 1028 |
Running this code, we can see that we only end up fetching the randomized ID, |
| 1029 |
while continuously getting cache hits for IDs 1-10, regardless of what the |
| 1030 |
batch looks like: |
| 1031 |
|
| 1032 |
```sh |
| 1033 |
2024/04/07 11:09:58 Seed completed |
| 1034 |
2024/04/07 11:09:58 Cache miss. Fetching ids: 173 |
| 1035 |
2024/04/07 11:09:58 map[1:value 173:value 2:value 3:value 4:value] |
| 1036 |
2024/04/07 11:09:58 Cache miss. Fetching ids: 12 |
| 1037 |
2024/04/07 11:09:58 map[1:value 12:value 2:value 3:value 4:value] |
| 1038 |
2024/04/07 11:09:58 Cache miss. Fetching ids: 730 |
| 1039 |
2024/04/07 11:09:58 map[1:value 2:value 3:value 4:value 730:value] |
| 1040 |
2024/04/07 11:09:58 Cache miss. Fetching ids: 520 |
| 1041 |
2024/04/07 11:09:58 map[1:value 2:value 3:value 4:value 5:value 520:value 6:value 7:value 8:value] |
| 1042 |
... |
| 1043 |
``` |
| 1044 |
|
| 1045 |
The entire example is available [here.](https://github.com/viccon/sturdyc/tree/main/examples/batch) |
| 1046 |
|
| 1047 |
# Cache key permutations |
| 1048 |
|
| 1049 |
As I mentioned in the previous section, the function signature for the |
| 1050 |
`BatchFetchFn`, which the `GetOrFetchBatch` function uses, can feel too limited: |
| 1051 |
|
| 1052 |
```go |
| 1053 |
type BatchFetchFn[T any] func(ctx context.Context, ids []string) (map[string]T, error) |
| 1054 |
``` |
| 1055 |
|
| 1056 |
What if you're fetching data from some endpoint that accepts a variety of query |
| 1057 |
parameters? Or perhaps you're doing a database query and want to apply some |
| 1058 |
ordering and filtering to the data? |
| 1059 |
|
| 1060 |
Closures provide an elegant solution to this limitation. Let's illustrate this |
| 1061 |
by looking at an actual API client I've written: |
| 1062 |
|
| 1063 |
```go |
| 1064 |
const moviesByIDsCacheKeyPrefix = "movies-by-ids" |
| 1065 |
|
| 1066 |
type MoviesByIDsOpts struct { |
| 1067 |
IncludeUpcoming bool |
| 1068 |
IncludeUpsell bool |
| 1069 |
} |
| 1070 |
|
| 1071 |
func (c *Client) MoviesByIDs(ctx context.Context, ids []string, opts MoviesByIDsOpts) (map[string]Movie, error) { |
| 1072 |
cacheKeyFunc := c.cache.PermutatedBatchKeyFn(moviesByIDsCacheKeyPrefix, opts) |
| 1073 |
fetchFunc := func(ctx context.Context, cacheMisses []string) (map[string]Movie, error) { |
| 1074 |
timeoutCtx, cancel := context.WithTimeout(ctx, c.timeout) |
| 1075 |
defer cancel() |
| 1076 |
|
| 1077 |
var response map[string]Movie |
| 1078 |
err := requests.URL(c.baseURL). |
| 1079 |
Path("/movies"). |
| 1080 |
Param("ids", strings.Join(cacheMisses, ",")). |
| 1081 |
Param("include_upcoming", strconv.FormatBool(opts.IncludeUpcoming)). |
| 1082 |
Param("include_upsell", strconv.FormatBool(opts.IncludeUpsell)). |
| 1083 |
ToJSON(&response). |
| 1084 |
Fetch(timeoutCtx) |
| 1085 |
return response, err |
| 1086 |
} |
| 1087 |
return sturdyc.GetOrFetchBatch(ctx, c.cache, ids, cacheKeyFunc, fetchFunc) |
| 1088 |
} |
| 1089 |
``` |
| 1090 |
|
| 1091 |
The API clients `MoviesByIDs` method calls an external API to fetch movies by |
| 1092 |
IDs, and the `BatchFetchFn` that we're passing to `sturdyc` has a closure over |
| 1093 |
the query parameters we need. |
| 1094 |
|
| 1095 |
However, one **important** thing to note here is that the ID is **no longer** |
| 1096 |
enough to _uniquely_ identify a record in our cache even with the basic prefix |
| 1097 |
function we've used before. It will no longer work to just have cache keys that |
| 1098 |
looks like this: |
| 1099 |
|
| 1100 |
``` |
| 1101 |
movies-ID-1 |
| 1102 |
movies-ID-2 |
| 1103 |
movies-ID-3 |
| 1104 |
``` |
| 1105 |
|
| 1106 |
Now why is that? If you think about it, the query parameters will most likely |
| 1107 |
be used by the system we're calling to transform the data in various ways. |
| 1108 |
Hence, we need to store a movie not only once per ID, but also once per |
| 1109 |
transformation. In other terms, we should cache each movie once for each |
| 1110 |
permutation of our options: |
| 1111 |
|
| 1112 |
``` |
| 1113 |
ID 1 IncludeUpcoming: true IncludeUpsell: true |
| 1114 |
ID 1 IncludeUpcoming: false IncludeUpsell: false |
| 1115 |
ID 1 IncludeUpcoming: true IncludeUpsell: false |
| 1116 |
ID 1 IncludeUpcoming: false IncludeUpsell: true |
| 1117 |
``` |
| 1118 |
|
| 1119 |
This is what the `PermutatedBatchKeyFn` is used for. It takes a prefix and a |
| 1120 |
struct which internally it uses reflection on in order to concatenate the |
| 1121 |
**exported** fields to form a unique cache key that would look like this: |
| 1122 |
|
| 1123 |
``` |
| 1124 |
// movies-by-ids is our prefix that we passed as the |
| 1125 |
// first argument to the PermutatedBatchKeyFn function. |
| 1126 |
movies-by-ids-true-true-ID-1 |
| 1127 |
movies-by-ids-false-false-ID-1 |
| 1128 |
movies-by-ids-true-false-ID-1 |
| 1129 |
movies-by-ids-false-true-ID-1 |
| 1130 |
``` |
| 1131 |
|
| 1132 |
Please note that the struct should be flat without nesting. The fields can be |
| 1133 |
`time.Time` values, as well as any basic types, pointers to these types, and |
| 1134 |
slices containing them. |
| 1135 |
|
| 1136 |
Once again, I'll provide a small example application that you can play around |
| 1137 |
with to get a deeper understanding of this functionality. We're essentially |
| 1138 |
going to use the same API client as before, but this time we're going to use |
| 1139 |
the `PermutatedBatchKeyFn` rather than the `BatchKeyFn`: |
| 1140 |
|
| 1141 |
```go |
| 1142 |
type OrderOptions struct { |
| 1143 |
CarrierName string |
| 1144 |
LatestDeliveryTime string |
| 1145 |
} |
| 1146 |
|
| 1147 |
type OrderAPI struct { |
| 1148 |
*sturdyc.Client[string] |
| 1149 |
} |
| 1150 |
|
| 1151 |
func NewOrderAPI(c *sturdyc.Client[string]) *OrderAPI { |
| 1152 |
return &OrderAPI{c} |
| 1153 |
} |
| 1154 |
|
| 1155 |
func (a *OrderAPI) OrderStatus(ctx context.Context, ids []string, opts OrderOptions) (map[string]string, error) { |
| 1156 |
// We use the PermutedBatchKeyFn when an ID isn't enough to uniquely identify a |
| 1157 |
// record. The cache is going to store each id once per set of options. |
| 1158 |
cacheKeyFn := a.PermutatedBatchKeyFn("key", opts) |
| 1159 |
|
| 1160 |
// We'll create a fetchFn with a closure that captures the options. For this |
| 1161 |
// simple example, it logs and returns the status for each order, but you could |
| 1162 |
// just as easily have called an external API. |
| 1163 |
fetchFn := func(_ context.Context, cacheMisses []string) (map[string]string, error) { |
| 1164 |
log.Printf("Fetching: %v, carrier: %s, delivery time: %s\n", cacheMisses, opts.CarrierName, opts.LatestDeliveryTime) |
| 1165 |
response := map[string]string{} |
| 1166 |
for _, id := range cacheMisses { |
| 1167 |
response[id] = fmt.Sprintf("Available for %s", opts.CarrierName) |
| 1168 |
} |
| 1169 |
return response, nil |
| 1170 |
} |
| 1171 |
return a.GetOrFetchBatch(ctx, ids, cacheKeyFn, fetchFn) |
| 1172 |
} |
| 1173 |
``` |
| 1174 |
|
| 1175 |
Now, let's try to use this client: |
| 1176 |
|
| 1177 |
```go |
| 1178 |
func main() { |
| 1179 |
// ... |
| 1180 |
|
| 1181 |
// Create a new cache client with the specified configuration. |
| 1182 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 1183 |
sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, retryBaseDelay), |
| 1184 |
) |
| 1185 |
|
| 1186 |
// We will fetch these IDs using three different option sets. |
| 1187 |
ids := []string{"id1", "id2", "id3"} |
| 1188 |
optionSetOne := OrderOptions{CarrierName: "FEDEX", LatestDeliveryTime: "2024-04-06"} |
| 1189 |
optionSetTwo := OrderOptions{CarrierName: "DHL", LatestDeliveryTime: "2024-04-07"} |
| 1190 |
optionSetThree := OrderOptions{CarrierName: "UPS", LatestDeliveryTime: "2024-04-08"} |
| 1191 |
|
| 1192 |
orderClient := NewOrderAPI(cacheClient) |
| 1193 |
ctx := context.Background() |
| 1194 |
|
| 1195 |
// Next, we'll call the orderClient to make sure that we've retrieved and cached |
| 1196 |
// these IDs for all of our option sets. |
| 1197 |
log.Println("Filling the cache with all IDs for all option sets") |
| 1198 |
orderClient.OrderStatus(ctx, ids, optionSetOne) |
| 1199 |
orderClient.OrderStatus(ctx, ids, optionSetTwo) |
| 1200 |
orderClient.OrderStatus(ctx, ids, optionSetThree) |
| 1201 |
log.Println("Cache filled") |
| 1202 |
} |
| 1203 |
``` |
| 1204 |
|
| 1205 |
At this point, the cache has stored each record individually for each option |
| 1206 |
set. The keys would look something like this: |
| 1207 |
|
| 1208 |
``` |
| 1209 |
FEDEX-2024-04-06-ID-1 |
| 1210 |
DHL-2024-04-07-ID-1 |
| 1211 |
UPS-2024-04-08-ID-1 |
| 1212 |
etc.. |
| 1213 |
``` |
| 1214 |
|
| 1215 |
Next, we'll add a sleep to make sure that all of the records are due for a |
| 1216 |
refresh, and then request the ids individually for each set of options: |
| 1217 |
|
| 1218 |
```go |
| 1219 |
func main() { |
| 1220 |
// ... |
| 1221 |
|
| 1222 |
// Sleep to make sure that all records are due for a refresh. |
| 1223 |
time.Sleep(maxRefreshDelay + 1) |
| 1224 |
|
| 1225 |
// Fetch each id for each option set. |
| 1226 |
for i := 0; i < len(ids); i++ { |
| 1227 |
// NOTE: We're using the same ID for these requests. |
| 1228 |
orderClient.OrderStatus(ctx, []string{ids[i]}, optionSetOne) |
| 1229 |
orderClient.OrderStatus(ctx, []string{ids[i]}, optionSetTwo) |
| 1230 |
orderClient.OrderStatus(ctx, []string{ids[i]}, optionSetThree) |
| 1231 |
} |
| 1232 |
|
| 1233 |
// Sleep for a second to allow the refresh logs to print. |
| 1234 |
time.Sleep(time.Second) |
| 1235 |
} |
| 1236 |
``` |
| 1237 |
|
| 1238 |
Running this program, we can see that the records are refreshed once per unique |
| 1239 |
id+option combination: |
| 1240 |
|
| 1241 |
```sh |
| 1242 |
go run . |
| 1243 |
2024/04/07 13:33:56 Filling the cache with all IDs for all option sets |
| 1244 |
2024/04/07 13:33:56 Fetching: [id1 id2 id3], carrier: FEDEX, delivery time: 2024-04-06 |
| 1245 |
2024/04/07 13:33:56 Fetching: [id1 id2 id3], carrier: DHL, delivery time: 2024-04-07 |
| 1246 |
2024/04/07 13:33:56 Fetching: [id1 id2 id3], carrier: UPS, delivery time: 2024-04-08 |
| 1247 |
2024/04/07 13:33:56 Cache filled |
| 1248 |
2024/04/07 13:33:58 Fetching: [id1], carrier: FEDEX, delivery time: 2024-04-06 |
| 1249 |
2024/04/07 13:33:58 Fetching: [id1], carrier: UPS, delivery time: 2024-04-08 |
| 1250 |
2024/04/07 13:33:58 Fetching: [id1], carrier: DHL, delivery time: 2024-04-07 |
| 1251 |
2024/04/07 13:33:58 Fetching: [id2], carrier: UPS, delivery time: 2024-04-08 |
| 1252 |
2024/04/07 13:33:58 Fetching: [id2], carrier: FEDEX, delivery time: 2024-04-06 |
| 1253 |
2024/04/07 13:33:58 Fetching: [id2], carrier: DHL, delivery time: 2024-04-07 |
| 1254 |
2024/04/07 13:33:58 Fetching: [id3], carrier: FEDEX, delivery time: 2024-04-06 |
| 1255 |
2024/04/07 13:33:58 Fetching: [id3], carrier: UPS, delivery time: 2024-04-08 |
| 1256 |
2024/04/07 13:33:58 Fetching: [id3], carrier: DHL, delivery time: 2024-04-07 |
| 1257 |
``` |
| 1258 |
|
| 1259 |
The entire example is available [here.](https://github.com/viccon/sturdyc/tree/main/examples/permutations) |
| 1260 |
|
| 1261 |
# Refresh coalescing |
| 1262 |
|
| 1263 |
As you may recall, our client is using the `WithEarlyRefreshes` option to |
| 1264 |
refresh the records in the background whenever their keys are requested again |
| 1265 |
after a certain amount of time has passed. And as seen in the example above, |
| 1266 |
we're successfully storing and refreshing the records once for every |
| 1267 |
permutation of the options we used to retrieve it. However, we're not taking |
| 1268 |
advantage of the endpoint's batch capabilities. |
| 1269 |
|
| 1270 |
To make this more efficient, we can enable the **refresh coalescing** |
| 1271 |
functionality, but before we'll update our example to use it let's just take a |
| 1272 |
moment to understand how it works. |
| 1273 |
|
| 1274 |
To start, we need to understand what determines whether two IDs can be |
| 1275 |
coalesced for a refresh: *the options*. E.g, do we want to perform the same |
| 1276 |
data transformations for both IDs? If so, they can be sent in the same batch. |
| 1277 |
This applies when we use the cache in front of a database too. Do we want to |
| 1278 |
use the same filters, sorting, etc? |
| 1279 |
|
| 1280 |
If we look at the movie example from before, you can see that I've extracted |
| 1281 |
these options into a struct: |
| 1282 |
|
| 1283 |
```go |
| 1284 |
const moviesByIDsCacheKeyPrefix = "movies-by-ids" |
| 1285 |
|
| 1286 |
type MoviesByIDsOpts struct { |
| 1287 |
IncludeUpcoming bool |
| 1288 |
IncludeUpsell bool |
| 1289 |
} |
| 1290 |
|
| 1291 |
func (c *Client) MoviesByIDs(ctx context.Context, ids []string, opts MoviesByIDsOpts) (map[string]Movie, error) { |
| 1292 |
cacheKeyFunc := c.cache.PermutatedBatchKeyFn(moviesByIDsCacheKeyPrefix, opts) |
| 1293 |
fetchFunc := func(ctx context.Context, cacheMisses []string) (map[string]Movie, error) { |
| 1294 |
// ... |
| 1295 |
defer cancel() |
| 1296 |
} |
| 1297 |
return sturdyc.GetOrFetchBatch(ctx, c.cache, ids, cacheKeyFunc, fetchFunc) |
| 1298 |
} |
| 1299 |
``` |
| 1300 |
|
| 1301 |
And as I mentioned before, the `PermutatedBatchKeyFn` is going to perform |
| 1302 |
reflection on this struct to create cache keys that look something like this: |
| 1303 |
|
| 1304 |
``` |
| 1305 |
movies-by-ids-true-true-ID-1 |
| 1306 |
movies-by-ids-false-false-ID-1 |
| 1307 |
movies-by-ids-true-false-ID-1 |
| 1308 |
movies-by-ids-false-true-ID-1 |
| 1309 |
``` |
| 1310 |
|
| 1311 |
What the refresh coalescing functionality then does is that it removes the ID |
| 1312 |
but keeps the permutation string and uses it to create and uniquely |
| 1313 |
identifiable buffer where it can gather IDs that should be refreshed with the |
| 1314 |
same options: |
| 1315 |
|
| 1316 |
``` |
| 1317 |
movies-by-ids-true-true |
| 1318 |
movies-by-ids-false-false |
| 1319 |
movies-by-ids-true-false |
| 1320 |
movies-by-ids-false-true |
| 1321 |
``` |
| 1322 |
|
| 1323 |
The only change we have to make to the previous example is to enable this |
| 1324 |
feature: |
| 1325 |
|
| 1326 |
```go |
| 1327 |
func main() { |
| 1328 |
// ... |
| 1329 |
|
| 1330 |
// With refresh coalescing enabled, the cache will buffer refreshes |
| 1331 |
// until the batch size is reached or the buffer timeout is hit. |
| 1332 |
batchSize := 3 |
| 1333 |
batchBufferTimeout := time.Second * 30 |
| 1334 |
|
| 1335 |
// Create a new cache client with the specified configuration. |
| 1336 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 1337 |
sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, retryBaseDelay), |
| 1338 |
sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout), |
| 1339 |
) |
| 1340 |
|
| 1341 |
// ... |
| 1342 |
} |
| 1343 |
``` |
| 1344 |
|
| 1345 |
So now we're saying that we want to coalesce the refreshes for each |
| 1346 |
permutation, and try to process them in batches of 3. However, if it's not able |
| 1347 |
to reach that size within 30 seconds we want the refresh to happen anyway. |
| 1348 |
|
| 1349 |
The previous output revealed that the refreshes happened one by one: |
| 1350 |
|
| 1351 |
```sh |
| 1352 |
go run . |
| 1353 |
2024/04/07 13:33:56 Filling the cache with all IDs for all option sets |
| 1354 |
2024/04/07 13:33:56 Fetching: [id1 id2 id3], carrier: FEDEX, delivery time: 2024-04-06 |
| 1355 |
2024/04/07 13:33:56 Fetching: [id1 id2 id3], carrier: DHL, delivery time: 2024-04-07 |
| 1356 |
2024/04/07 13:33:56 Fetching: [id1 id2 id3], carrier: UPS, delivery time: 2024-04-08 |
| 1357 |
2024/04/07 13:33:56 Cache filled |
| 1358 |
2024/04/07 13:33:58 Fetching: [id1], carrier: FEDEX, delivery time: 2024-04-06 |
| 1359 |
2024/04/07 13:33:58 Fetching: [id1], carrier: UPS, delivery time: 2024-04-08 |
| 1360 |
2024/04/07 13:33:58 Fetching: [id1], carrier: DHL, delivery time: 2024-04-07 |
| 1361 |
2024/04/07 13:33:58 Fetching: [id2], carrier: UPS, delivery time: 2024-04-08 |
| 1362 |
2024/04/07 13:33:58 Fetching: [id2], carrier: FEDEX, delivery time: 2024-04-06 |
| 1363 |
2024/04/07 13:33:58 Fetching: [id2], carrier: DHL, delivery time: 2024-04-07 |
| 1364 |
2024/04/07 13:33:58 Fetching: [id3], carrier: FEDEX, delivery time: 2024-04-06 |
| 1365 |
2024/04/07 13:33:58 Fetching: [id3], carrier: UPS, delivery time: 2024-04-08 |
| 1366 |
2024/04/07 13:33:58 Fetching: [id3], carrier: DHL, delivery time: 2024-04-07 |
| 1367 |
``` |
| 1368 |
|
| 1369 |
We'll now try to run this code again, but with the `WithRefreshCoalescing` |
| 1370 |
option enabled: |
| 1371 |
|
| 1372 |
```sh |
| 1373 |
go run . |
| 1374 |
2024/04/07 13:45:42 Filling the cache with all IDs for all option sets |
| 1375 |
2024/04/07 13:45:42 Fetching: [id1 id2 id3], carrier: FEDEX, delivery time: 2024-04-06 |
| 1376 |
2024/04/07 13:45:42 Fetching: [id1 id2 id3], carrier: DHL, delivery time: 2024-04-07 |
| 1377 |
2024/04/07 13:45:42 Fetching: [id1 id2 id3], carrier: UPS, delivery time: 2024-04-08 |
| 1378 |
2024/04/07 13:45:42 Cache filled |
| 1379 |
2024/04/07 13:45:44 Fetching: [id1 id2 id3], carrier: FEDEX, delivery time: 2024-04-06 |
| 1380 |
2024/04/07 13:45:44 Fetching: [id1 id3 id2], carrier: DHL, delivery time: 2024-04-07 |
| 1381 |
2024/04/07 13:45:44 Fetching: [id1 id2 id3], carrier: UPS, delivery time: 2024-04-08 |
| 1382 |
``` |
| 1383 |
|
| 1384 |
The number of refreshes went from **9** to **3**. Imagine what a batch size of |
| 1385 |
50 could do for your applications performance! |
| 1386 |
|
| 1387 |
There is more information about this in the section about metrics, but for our |
| 1388 |
production applications we're also using the `WithMetrics` option so that we |
| 1389 |
can monitor how well our refreshes are performing: |
| 1390 |
|
| 1391 |
<img width="941" alt="Screenshot 2024-05-04 at 12 38 04" src="https://github.com/viccon/sturdyc/assets/12787673/b1359867-f1ef-4a09-8c75-d7d2360726f1"> |
| 1392 |
This chart shows the batch sizes for our coalesced refreshes. |
| 1393 |
|
| 1394 |
<img width="940" alt="Screenshot 2024-05-04 at 12 38 20" src="https://github.com/viccon/sturdyc/assets/12787673/de7f00ee-b14d-443b-b69e-91e19665c252"> |
| 1395 |
This chart shows the average batch size of our refreshes for two different data sources |
| 1396 |
|
| 1397 |
The entire example is available [here.](https://github.com/viccon/sturdyc/tree/main/examples/buffering) |
| 1398 |
|
| 1399 |
Another point to note is how effectively the options we've seen so far can be |
| 1400 |
combined to create high-performing, flexible, and robust caching solutions: |
| 1401 |
|
| 1402 |
```go |
| 1403 |
capacity := 10000 |
| 1404 |
numShards := 10 |
| 1405 |
ttl := 2 * time.Hour |
| 1406 |
evictionPercentage := 10 |
| 1407 |
minRefreshDelay := time.Second |
| 1408 |
maxRefreshDelay := time.Second * 2 |
| 1409 |
synchronousRefreshDelay := time.Second * 120 // 2 minutes. |
| 1410 |
retryBaseDelay := time.Millisecond * 10 |
| 1411 |
batchSize := 10 |
| 1412 |
batchBufferTimeout := time.Second * 15 |
| 1413 |
|
| 1414 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 1415 |
sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryBaseDelay), |
| 1416 |
sturdyc.WithRefreshCoalescing(batchSize, batchBufferTimeout), |
| 1417 |
) |
| 1418 |
``` |
| 1419 |
|
| 1420 |
With the configuration above, the keys in active rotation are going to be |
| 1421 |
scheduled for a refresh every 1-2 seconds. For batchable data sources, where we |
| 1422 |
are making use of the `GetOrFetchBatch` function, we'll ask the cache (using |
| 1423 |
the `WithRefreshCoalescing` option) to delay them for up to 15 seconds or until |
| 1424 |
a batch size of 10 is reached. |
| 1425 |
|
| 1426 |
What if we get a request for a key that hasn't been refreshed in the last 120 |
| 1427 |
seconds? Given the `synchronousRefreshDelay` passed to the `WithEarlyRefreshes` |
| 1428 |
option, the cache will skip any background refresh and instead perform a |
| 1429 |
synchronous refresh to ensure that the data is fresh. Did 1000 requests |
| 1430 |
suddenly arrive for this key? No problem, the in-flight tracking makes sure |
| 1431 |
that we only make **one** request to the underlying data source. This works for |
| 1432 |
refreshes too by the way. If 1000 requests arrived for a key that was 3 seconds |
| 1433 |
old (greater than our `maxRefreshDelay`) we would only schedule a single |
| 1434 |
refresh for it. |
| 1435 |
|
| 1436 |
Is the underlying data source experiencing downtime? With our TTL of two-hours |
| 1437 |
we'll be able to provide a degraded experience to our users by serving the data |
| 1438 |
we have in our cache. |
| 1439 |
|
| 1440 |
# Passthrough |
| 1441 |
|
| 1442 |
There are times when you want to always retrieve the latest data from the |
| 1443 |
source and only use the in-memory cache as a _fallback_. In such scenarios, you |
| 1444 |
can use the `Passthrough` and `PassthroughBatch` functions. The cache will |
| 1445 |
still perform in-flight tracking and deduplicate your requests. |
| 1446 |
|
| 1447 |
# Distributed storage |
| 1448 |
|
| 1449 |
It's important to read the previous sections before jumping here in order to |
| 1450 |
understand how `sturdyc` works when it comes to creating cache keys, tracking |
| 1451 |
in-flight requests, refreshing records in the background, and |
| 1452 |
buffering/coalescing requests to minimize the number of round trips we have to |
| 1453 |
make to an underlying data source. As you'll soon see, we'll leverage all of |
| 1454 |
these features for the distributed storage too. |
| 1455 |
|
| 1456 |
However, let's first understand when this functionality can be useful. This |
| 1457 |
feature is particularly valuable when building applications that can achieve a |
| 1458 |
high cache hit rate while also being subject to large bursts of requests. |
| 1459 |
|
| 1460 |
As an example, I've used this in production for a large streaming application. |
| 1461 |
The content was fairly static - new movies, series, and episodes were only |
| 1462 |
ingested a couple of times an hour. This meant that we could achieve a very |
| 1463 |
high hit rate for our data sources. However, during the evenings, when a |
| 1464 |
popular football match or TV show was about to start, our traffic could spike |
| 1465 |
by a factor of 20 within less than a minute. |
| 1466 |
|
| 1467 |
To illustrate the problem further, let’s say the hit rate for our in-memory |
| 1468 |
cache was 99.8%. Then, when we received that large burst of traffic, our |
| 1469 |
auto-scaling would begin provisioning new containers. These containers would |
| 1470 |
obviously be brand new, with an initial hit rate of 0%. This would cause a |
| 1471 |
significant load on our underlying data sources as soon as they came online, |
| 1472 |
because every request they received led to a cache miss so that we had to make |
| 1473 |
an outgoing request to the data source. And these data sources had gotten used |
| 1474 |
to being shielded from most of the traffic by the older containers high |
| 1475 |
hit-rate and refresh coalescing usage. Hence, what was a 20x spike for us could |
| 1476 |
easily become a 200x spike for them until our new containers had warmed their |
| 1477 |
caches. |
| 1478 |
|
| 1479 |
Therefore, I decided to add the ability to have the containers sync their |
| 1480 |
in-memory cache with a distributed key-value store that would have an easier |
| 1481 |
time absorbing these bursts. |
| 1482 |
|
| 1483 |
Adding distributed storage to the cache is, from the package's point of view, |
| 1484 |
essentially just another data source with a higher priority. Hence, we're still |
| 1485 |
able to take great advantage of all the features we've seen so far, and these |
| 1486 |
efficiency gains will hopefully allow us to use a much cheaper cluster. |
| 1487 |
|
| 1488 |
A bit simplified, we can think of the cache's interaction with the |
| 1489 |
distributed storage like this: |
| 1490 |
|
| 1491 |
```go |
| 1492 |
// NOTE: This is an example. The cache has similar functionality internally. |
| 1493 |
func (o *OrderAPI) OrderStatus(ctx context.Context, id string) (string, error) { |
| 1494 |
cacheKey := "order-status-" + id |
| 1495 |
fetchFn := func(ctx context.Context) (string, error) { |
| 1496 |
// Check Redis cache first. |
| 1497 |
if orderStatus, ok := o.redisClient.Get(cacheKey); ok { |
| 1498 |
return orderStatus, nil |
| 1499 |
} |
| 1500 |
|
| 1501 |
// Fetch the order status from the underlying data source. |
| 1502 |
var response OrderStatusResponse |
| 1503 |
err := requests.URL(o.baseURL). |
| 1504 |
Param("id", id). |
| 1505 |
ToJSON(&response). |
| 1506 |
Fetch(ctx) |
| 1507 |
if err != nil { |
| 1508 |
return "", err |
| 1509 |
} |
| 1510 |
|
| 1511 |
// Add the order status to the Redis cache so that it becomes available for the other containers. |
| 1512 |
go func() { o.RedisClient.Set(cacheKey, response.OrderStatus, time.Hour) }() |
| 1513 |
|
| 1514 |
return response.OrderStatus, nil |
| 1515 |
} |
| 1516 |
|
| 1517 |
return o.GetOrFetch(ctx, id, fetchFn) |
| 1518 |
} |
| 1519 |
``` |
| 1520 |
|
| 1521 |
The real implementation interacts with the distributed storage through an |
| 1522 |
abstraction so that you're able to use any key-value store you want. All you |
| 1523 |
would have to do is implement this interface: |
| 1524 |
|
| 1525 |
```go |
| 1526 |
type DistributedStorage interface { |
| 1527 |
Get(ctx context.Context, key string) ([]byte, bool) |
| 1528 |
Set(ctx context.Context, key string, value []byte) |
| 1529 |
GetBatch(ctx context.Context, keys []string) map[string][]byte |
| 1530 |
SetBatch(ctx context.Context, records map[string][]byte) |
| 1531 |
} |
| 1532 |
``` |
| 1533 |
|
| 1534 |
and then pass it to the `WithDistributedStorage` option when you create your |
| 1535 |
cache client: |
| 1536 |
|
| 1537 |
```go |
| 1538 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 1539 |
// Other options... |
| 1540 |
sturdyc.WithDistributedStorage(storage), |
| 1541 |
) |
| 1542 |
``` |
| 1543 |
|
| 1544 |
**Please note** that you are responsible for configuring the TTL and eviction |
| 1545 |
policies of this storage. `sturdyc` will only make sure that it queries this |
| 1546 |
data source first, and then writes the keys and values to this storage as soon |
| 1547 |
as it has gone out to an underlying data source and refreshed them. Therefore, |
| 1548 |
I'd advice you to use the configuration above with short TTLs for the |
| 1549 |
distributed storage, or things might get too stale. I mostly think it's useful |
| 1550 |
if you're consuming data sources that are rate limited or don't handle brief |
| 1551 |
bursts from new containers very well. |
| 1552 |
|
| 1553 |
I've included an example to showcase this functionality |
| 1554 |
[here.](https://github.com/viccon/sturdyc/tree/main/examples/distribution) |
| 1555 |
|
| 1556 |
When running that application, you should see output that looks something like |
| 1557 |
this: |
| 1558 |
|
| 1559 |
```go |
| 1560 |
❯ go run . |
| 1561 |
2024/06/07 10:32:56 Getting key shipping-options-1234-asc from the distributed storage |
| 1562 |
2024/06/07 10:32:56 Fetching shipping options from the underlying data source |
| 1563 |
2024/06/07 10:32:56 The shipping options were retrieved successfully! |
| 1564 |
2024/06/07 10:32:56 Writing key shipping-options-1234-asc to the distributed storage |
| 1565 |
2024/06/07 10:32:56 The shipping options were retrieved successfully! |
| 1566 |
2024/06/07 10:32:57 The shipping options were retrieved successfully! |
| 1567 |
2024/06/07 10:32:57 Getting key shipping-options-1234-asc from the distributed storage |
| 1568 |
2024/06/07 10:32:57 The shipping options were retrieved successfully! |
| 1569 |
2024/06/07 10:32:57 Getting key shipping-options-1234-asc from the distributed storage |
| 1570 |
2024/06/07 10:32:57 The shipping options were retrieved successfully! |
| 1571 |
2024/06/07 10:32:57 The shipping options were retrieved successfully! |
| 1572 |
2024/06/07 10:32:57 Getting key shipping-options-1234-asc from the distributed storage |
| 1573 |
2024/06/07 10:32:58 The shipping options were retrieved successfully! |
| 1574 |
2024/06/07 10:32:58 The shipping options were retrieved successfully! |
| 1575 |
2024/06/07 10:32:58 Getting key shipping-options-1234-asc from the distributed storage |
| 1576 |
2024/06/07 10:32:58 The shipping options were retrieved successfully! |
| 1577 |
2024/06/07 10:32:58 Getting key shipping-options-1234-asc from the distributed storage |
| 1578 |
2024/06/07 10:32:58 The shipping options were retrieved successfully! |
| 1579 |
``` |
| 1580 |
|
| 1581 |
Above we can see that the underlying data source was only visited **once**, and |
| 1582 |
that the remaining background refreshes that the in-memory cache performed only |
| 1583 |
went to the distributed storage. |
| 1584 |
|
| 1585 |
# Distributed storage early refreshes |
| 1586 |
|
| 1587 |
As I mentioned before, the configuration from the section above works well as |
| 1588 |
long as you're using short TTLs for the distributed key-value store. However, |
| 1589 |
I've also built systems where I wanted to leverage the distributed storage as |
| 1590 |
an additional robustness feature with long TTLs. That way, if an upstream |
| 1591 |
system goes down, newly provisioned containers could still retrieve the latest |
| 1592 |
data that the old containers had cached from something like a Redis. |
| 1593 |
|
| 1594 |
If you have a similar use case, you could use the following |
| 1595 |
configuration instead: |
| 1596 |
|
| 1597 |
```go |
| 1598 |
cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage, |
| 1599 |
sturdyc.WithDistributedStorageEarlyRefreshes(storage, time.Minute), |
| 1600 |
) |
| 1601 |
``` |
| 1602 |
|
| 1603 |
With a configuration like this, I would usually set the TTL for the distributed |
| 1604 |
storage to something like an hour. However, if `sturdyc` queries the |
| 1605 |
distributed storage and finds that a record is older than 1 minute (the second |
| 1606 |
argument to the function), it will refresh the record from the underlying data |
| 1607 |
source, and then write the updated value back to it. So the interaction with |
| 1608 |
the distributed storage would look something like this: |
| 1609 |
|
| 1610 |
- Start by trying to retrieve the key from the distributeted storage. If the |
| 1611 |
data is fresh, it's returned immediately and written to the in-memory cache. |
| 1612 |
- If the key was found in the distributed storage, but wasn't fresh enough, |
| 1613 |
we'll visit the underlying data source, and then write the response to both |
| 1614 |
the distributed cache and the one we have in-memory. |
| 1615 |
- If the call to refresh the data failed, the cache will use the value from the |
| 1616 |
distributed storage as a fallback. |
| 1617 |
|
| 1618 |
However, there is one more scenario we must cover now that requires two |
| 1619 |
additional methods to be implemented: |
| 1620 |
|
| 1621 |
```go |
| 1622 |
type DistributedStorageEarlyRefreshes interface { |
| 1623 |
DistributedStorage |
| 1624 |
Delete(ctx context.Context, key string) |
| 1625 |
DeleteBatch(ctx context.Context, keys []string) |
| 1626 |
} |
| 1627 |
``` |
| 1628 |
|
| 1629 |
These delete methods will be called when a refresh occurs, and the cache |
| 1630 |
notices that it can no longer retrieve the key at the underlying data source. |
| 1631 |
This indicates that the key has been deleted, and we will want this change to |
| 1632 |
propagate to the distributed key-value store as soon as possible, and not have |
| 1633 |
to wait for the TTL to expire. |
| 1634 |
|
| 1635 |
**Please note** that you are still responsible for setting the TTL and eviction |
| 1636 |
policies for the distributed store. The cache will only invoke the delete |
| 1637 |
methods when a record has gone missing from the underlying data source. If |
| 1638 |
you're using **missing record storage**, it will write the key as a missing |
| 1639 |
record instead. |
| 1640 |
|
| 1641 |
I've included an example to showcase this functionality |
| 1642 |
[here.](https://github.com/viccon/sturdyc/tree/main/examples/distributed-early-refreshes) |
| 1643 |
|
| 1644 |
# Custom metrics |
| 1645 |
|
| 1646 |
The cache can be configured to report custom metrics for: |
| 1647 |
|
| 1648 |
- Size of the cache |
| 1649 |
- Cache hits |
| 1650 |
- Cache misses |
| 1651 |
- Background refreshes |
| 1652 |
- Synchronous refreshes |
| 1653 |
- Missing records |
| 1654 |
- Evictions |
| 1655 |
- Forced evictions |
| 1656 |
- The number of entries evicted |
| 1657 |
- Shard distribution |
| 1658 |
- The batch size of a coalesced refresh |
| 1659 |
|
| 1660 |
There are also distributed metrics if you're using the cache with a |
| 1661 |
_distributed storage_, which adds the following metrics in addition to what |
| 1662 |
we've seen above: |
| 1663 |
|
| 1664 |
- Distributed cache hits |
| 1665 |
- Distributed cache misses |
| 1666 |
- Distributed refreshes |
| 1667 |
- Distributed missing records |
| 1668 |
- Distributed stale fallback |
| 1669 |
|
| 1670 |
All you have to do is implement one of these interfaces: |
| 1671 |
|
| 1672 |
```go |
| 1673 |
type MetricsRecorder interface { |
| 1674 |
CacheHit() |
| 1675 |
CacheMiss() |
| 1676 |
AsynchronousRefresh() |
| 1677 |
SynchronousRefresh() |
| 1678 |
MissingRecord() |
| 1679 |
ForcedEviction() |
| 1680 |
EntriesEvicted(int) |
| 1681 |
ShardIndex(int) |
| 1682 |
CacheBatchRefreshSize(size int) |
| 1683 |
ObserveCacheSize(callback func() int) |
| 1684 |
} |
| 1685 |
|
| 1686 |
type DistributedMetricsRecorder interface { |
| 1687 |
MetricsRecorder |
| 1688 |
DistributedCacheHit() |
| 1689 |
DistributedCacheMiss() |
| 1690 |
DistributedRefresh() |
| 1691 |
DistributedMissingRecord() |
| 1692 |
DistributedFallback() |
| 1693 |
} |
| 1694 |
``` |
| 1695 |
|
| 1696 |
and pass it as an option when you create the client: |
| 1697 |
|
| 1698 |
```go |
| 1699 |
cacheBasicMetrics := sturdyc.New[any]( |
| 1700 |
cacheSize, |
| 1701 |
shardSize, |
| 1702 |
cacheTTL, |
| 1703 |
evictWhenFullPercentage, |
| 1704 |
sturdyc.WithMetrics(metricsRecorder), |
| 1705 |
) |
| 1706 |
|
| 1707 |
cacheDistributedMetrics := sturdyc.New[any]( |
| 1708 |
cacheSize, |
| 1709 |
shardSize, |
| 1710 |
cacheTTL, |
| 1711 |
evictWhenFullPercentage, |
| 1712 |
sturdyc.WithDistributedStorage(metricsRecorder), |
| 1713 |
sturdyc.WithDistributedMetrics(metricsRecorder), |
| 1714 |
) |
| 1715 |
``` |
| 1716 |
|
| 1717 |
Below are a few images where some of these metrics have been visualized in Grafana: |
| 1718 |
|
| 1719 |
<img width="939" alt="Screenshot 2024-05-04 at 12 36 43" src="https://github.com/viccon/sturdyc/assets/12787673/1f630aed-2322-4d3a-9510-d582e0294488"> |
| 1720 |
Here we can how often we're able to serve from memory. |
| 1721 |
|
| 1722 |
<img width="942" alt="Screenshot 2024-05-04 at 12 37 39" src="https://github.com/viccon/sturdyc/assets/12787673/25187529-28fb-4c4e-8fe9-9fb48772e0c0"> |
| 1723 |
This image displays the number of items we have cached. |
| 1724 |
|
| 1725 |
<img width="941" alt="Screenshot 2024-05-04 at 12 38 04" src="https://github.com/viccon/sturdyc/assets/12787673/b1359867-f1ef-4a09-8c75-d7d2360726f1"> |
| 1726 |
This chart shows the batch sizes for the buffered refreshes. |
| 1727 |
|
| 1728 |
<img width="940" alt="Screenshot 2024-05-04 at 12 38 20" src="https://github.com/viccon/sturdyc/assets/12787673/de7f00ee-b14d-443b-b69e-91e19665c252"> |
| 1729 |
And lastly, we can see the average batch size of our refreshes for two different data sources. |
| 1730 |
|
| 1731 |
# Generics |
| 1732 |
|
| 1733 |
Personally, I tend to create caches based on how frequently the data needs to |
| 1734 |
be refreshed rather than what type of data it stores. I'll often have one |
| 1735 |
transient cache which refreshes the data every 2-5 milliseconds, and another |
| 1736 |
cache where I'm fine if the data is up to a minute old. |
| 1737 |
|
| 1738 |
Hence, I don't want to tie the cache to any specific type so I'll often just |
| 1739 |
use `any`: |
| 1740 |
|
| 1741 |
```go |
| 1742 |
cacheClient := sturdyc.New[any](capacity, numShards, ttl, evictionPercentage, |
| 1743 |
sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, retryBaseDelay), |
| 1744 |
sturdyc.WithRefreshCoalescing(10, time.Second*15), |
| 1745 |
) |
| 1746 |
``` |
| 1747 |
|
| 1748 |
However, having all client methods return `any` can quickly add a lot of |
| 1749 |
boilerplate if you're storing more than a handful of types, and need to make |
| 1750 |
type assertions. |
| 1751 |
|
| 1752 |
If you want to avoid this, you can use any of the package level exports: |
| 1753 |
|
| 1754 |
- [`GetOrFetch`](https://pkg.go.dev/github.com/viccon/sturdyc#GetOrFetch) |
| 1755 |
- [`GetOrFetchBatch`](https://pkg.go.dev/github.com/viccon/sturdyc#GetOrFetchBatch) |
| 1756 |
- [`Passthrough`](https://pkg.go.dev/github.com/viccon/sturdyc#Passthrough) |
| 1757 |
- [`PassthroughBatch`](https://pkg.go.dev/github.com/viccon/sturdyc#PassthroughBatch) |
| 1758 |
|
| 1759 |
They will take the cache, call the function for you, and perform the type |
| 1760 |
conversions internally. If the type conversions were to fail, you'll get a |
| 1761 |
[`ErrInvalidType`](https://pkg.go.dev/github.com/viccon/sturdyc#pkg-variables) error. |
| 1762 |
|
| 1763 |
Below is an example of what an API client that uses these functions could look |
| 1764 |
like: |
| 1765 |
|
| 1766 |
```go |
| 1767 |
type OrderAPI struct { |
| 1768 |
cacheClient *sturdyc.Client[any] |
| 1769 |
} |
| 1770 |
|
| 1771 |
func NewOrderAPI(c *sturdyc.Client[any]) *OrderAPI { |
| 1772 |
return &OrderAPI{cacheClient: c} |
| 1773 |
} |
| 1774 |
|
| 1775 |
func (a *OrderAPI) OrderStatus(ctx context.Context, ids []string) (map[string]string, error) { |
| 1776 |
cacheKeyFn := a.cacheClient.BatchKeyFn("order-status") |
| 1777 |
fetchFn := func(_ context.Context, cacheMisses []string) (map[string]string, error) { |
| 1778 |
response := make(map[string]string, len(ids)) |
| 1779 |
for _, id := range cacheMisses { |
| 1780 |
response[id] = "Order status: pending" |
| 1781 |
} |
| 1782 |
return response, nil |
| 1783 |
} |
| 1784 |
return sturdyc.GetOrFetchBatch(ctx, a.cacheClient, ids, cacheKeyFn, fetchFn) |
| 1785 |
} |
| 1786 |
|
| 1787 |
func (a *OrderAPI) DeliveryTime(ctx context.Context, ids []string) (map[string]time.Time, error) { |
| 1788 |
cacheKeyFn := a.cacheClient.BatchKeyFn("delivery-time") |
| 1789 |
fetchFn := func(_ context.Context, cacheMisses []string) (map[string]time.Time, error) { |
| 1790 |
response := make(map[string]time.Time, len(ids)) |
| 1791 |
for _, id := range cacheMisses { |
| 1792 |
response[id] = time.Now() |
| 1793 |
} |
| 1794 |
return response, nil |
| 1795 |
} |
| 1796 |
return sturdyc.GetOrFetchBatch(ctx, a.cacheClient, ids, cacheKeyFn, fetchFn) |
| 1797 |
} |
| 1798 |
``` |
| 1799 |
|
| 1800 |
The entire example is available [here.](https://github.com/viccon/sturdyc/tree/main/examples/generics) |