Debian Codegraph @

examples/refreshes/main.go

raw
1 package main
2
3 import (
4 "context"
5 "log"
6 "time"
7
8 "github.com/viccon/sturdyc"
9 )
10
11 type API struct {
12 *sturdyc.Client[string]
13 }
14
15 func NewAPI(c *sturdyc.Client[string]) *API {
16 return &API{c}
17 }
18
19 func (a *API) Get(ctx context.Context, key string) (string, error) {
20 // This could be an API call, a database query, etc. The only requirement is
21 // that the function adheres to the `sturdyc.FetchFn` signature. Remember
22 // that you can use closures to capture additional values.
23 fetchFn := func(_ context.Context) (string, error) {
24 log.Printf("Fetching value for key: %s\n", key)
25 return "value", nil
26 }
27 return a.GetOrFetch(ctx, key, fetchFn)
28 }
29
30 func main() {
31 // ===========================================================
32 // ===================== Basic configuration =================
33 // ===========================================================
34 // Maximum number of entries in the sturdyc.
35 capacity := 10000
36 // Number of shards to use for the sturdyc.
37 numShards := 10
38 // Time-to-live for cache entries.
39 ttl := 2 * time.Hour
40 // Percentage of entries to evict when the cache is full. Setting this
41 // to 0 will make set a no-op if the cache has reached its capacity.
42 evictionPercentage := 10
43
44 // ===========================================================
45 // ===================== Early refreshes ====================
46 // ===========================================================
47 // Set a minimum and maximum refresh delay for the records. This is used to
48 // spread out the refreshes of our records evenly over time. If we're running
49 // our application across 100 containers, we don't want to send a spike of
50 // refreshes from every container every 30 ms. Instead, we'll use some
51 // randomization to spread them out evenly between 10 and 30 ms.
52 minRefreshDelay := time.Millisecond * 10
53 maxRefreshDelay := time.Millisecond * 30
54 // Set a synchronous refresh delay for when we want a refresh to happen synchronously.
55 synchronousRefreshDelay := time.Second * 30
56 // The base used for exponential backoff when retrying a background refresh.
57 // Most of the time, we perform refreshes well in advance of the records
58 // expiry time. Hence, we can use this to make it easier for a system that
59 // is having trouble to get back on it's feet by making fewer refreshes when
60 // we're seeing a lot of errors. Once we receive a successful response, the
61 // refreshes return to their original frequency. You can set this to 0
62 // if you don't want this behavior.
63 retryBaseDelay := time.Millisecond * 10
64
65 // Create a cache client with the specified configuration.
66 cacheClient := sturdyc.New[string](capacity, numShards, ttl, evictionPercentage,
67 sturdyc.WithEarlyRefreshes(minRefreshDelay, maxRefreshDelay, synchronousRefreshDelay, retryBaseDelay),
68 )
69
70 // Create a new API instance with the cache client.
71 api := NewAPI(cacheClient)
72
73 // We are going to retrieve the values every 10 milliseconds, however the
74 // logs will reveal that actual refreshes fluctuate randomly within a 10-30
75 // millisecond range. Even if this loop is executed across multiple goroutines,
76 // the API call frequency will maintain this variability.
77 for i := 0; i < 100; i++ {
78 val, err := api.Get(context.Background(), "key")
79 if err != nil {
80 log.Println("Failed to retrieve the record from the cache.")
81 continue
82 }
83 log.Printf("Value: %s\n", val)
84 time.Sleep(minRefreshDelay)
85 }
86 }