{"id":471,"date":"2026-06-03T09:00:00","date_gmt":"2026-06-03T03:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/"},"modified":"2026-06-03T09:00:00","modified_gmt":"2026-06-03T03:30:00","slug":"go-in-memory-cache-ttl","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/","title":{"rendered":"Go In-Memory Cache with TTL, Mutex and Generics"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">A Go in-memory cache keeps recent results inside your program, so you do not repeat slow work. In this post, you will build a small cache with generics, a time to live and a background cleaner. Then we will test it with many goroutines at once.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This lesson builds on <a href=\"https:\/\/smitabharat.com\/blog\/go-generics-examples\/\">Go generics<\/a> and the <a href=\"https:\/\/smitabharat.com\/blog\/go-sync-package-waitgroup-mutex\/\">Go sync package<\/a>. We also use <a href=\"https:\/\/smitabharat.com\/blog\/go-goroutines-beginners-guide\/\">Go goroutines<\/a> and <a href=\"https:\/\/smitabharat.com\/blog\/go-context-beginners-guide\/\">Go context<\/a>. So it helps to read those first.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Is a Go In-Memory Cache?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A cache is a quick place to keep an answer you already worked out. When the same question comes again, you reply from the cache and skip the slow part. The slow part may be a database query, a web call or a heavy calculation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a notebook on your desk. Before you open a big reference book, you check your notebook. When the answer is there, you save time. Otherwise, you look it up and write it down for next time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Likewise, a Go in-memory cache is that notebook inside your program. It is a map that lives in RAM, protected by a lock. Because RAM is fast, a lookup takes only nanoseconds. The cost is that the data disappears when the program stops. Also, each copy of your program has its own cache.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why a Go In-Memory Cache Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Many requests ask for the same data again and again. A product page, a user profile or a currency rate is read far more often than it changes. Here is what a Go in-memory cache gives you.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Speed<\/strong>: a map lookup is much faster than a network call.<\/li>\n\n\n\n<li><strong>Lower load<\/strong>: your database or partner API gets fewer requests.<\/li>\n\n\n\n<li><strong>Lower cost<\/strong>: fewer calls mean smaller bills and fewer rate limit errors.<\/li>\n\n\n\n<li><strong>Resilience<\/strong>: you can serve the last good value when a source is slow.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">However, a cache can also serve old data. Therefore, every entry needs a time to live, which is often shortened to TTL. After the TTL passes, the entry counts as expired and the next request fetches a fresh value.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How a Go In-Memory Cache Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Our cache has three jobs. It stores a value with an expiry time. Then it returns a value only while it is fresh. Finally, it removes dead entries in the background.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-1-1024x640.png\" alt=\"Go In-Memory Cache diagram showing Set, Get, the expiry check and the janitor around a map\" class=\"wp-image-448\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">Set stores a value with an expiry time. Get returns it while fresh and reports a miss after the TTL. A background janitor deletes expired entries on a timer.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Why We Need a Lock<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Because many goroutines may read and write the map at once, we need care. In Go, a plain map is not safe for that, and the program may crash. So we guard it with a <code>sync.RWMutex<\/code>. Many readers can hold the read lock together, but a writer needs the lock alone. This fits a cache well, because reads are far more common than writes.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why We Use Generics<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A cache for strings is different from a cache for users. Without generics, you would copy the code or store <code>any<\/code> and cast it later. With generics, one type works for all. We write <code>Cache[K comparable, V any]<\/code>, and the compiler checks the key and value types for us.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What the Janitor Does<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Expired entries still use memory until someone removes them. A janitor is a goroutine that wakes up on a timer and deletes them. It stops when the context is cancelled, so it never leaks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Go In-Memory Cache vs Other Options<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A map is not the only way to cache. The table below compares common choices.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Option<\/th><th>Where data lives<\/th><th>Shared by many servers<\/th><th>Best for<\/th><\/tr><\/thead><tbody><tr><td>In-memory cache<\/td><td>Inside your program<\/td><td>No<\/td><td>Small, fast, per-copy data<\/td><\/tr><tr><td>Redis<\/td><td>A separate server<\/td><td>Yes<\/td><td>Shared data and large sets<\/td><\/tr><tr><td>Database query cache<\/td><td>Inside the database<\/td><td>Yes<\/td><td>Repeated identical queries<\/td><\/tr><tr><td>HTTP cache<\/td><td>Browser or proxy<\/td><td>Yes<\/td><td>Static files and public pages<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-2-1024x640.png\" alt=\"Go In-Memory Cache diagram showing a cache hit returning at once and a cache miss calling the slow source\" class=\"wp-image-449\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">A request checks the in-memory cache first. A hit returns at once, while a miss calls the slow source and then stores the answer for the next request.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">So a Go in-memory cache is a good first step. Later, when you run many copies and need one shared view, move to Redis. Our <a href=\"https:\/\/smitabharat.com\/blog\/go-redis-caching\/\">Go Redis caching guide<\/a> shows how.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Choosing a TTL for a Go In-Memory Cache<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The right TTL depends on how fast the data changes and how bad old data is. A short TTL keeps data fresh but gives fewer hits. A long TTL gives more hits but risks stale answers. The table below gives a starting point for common data.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Data<\/th><th>How often it changes<\/th><th>Suggested TTL<\/th><\/tr><\/thead><tbody><tr><td>Country or language list<\/td><td>Almost never<\/td><td>24 hours<\/td><\/tr><tr><td>Product details<\/td><td>A few times a day<\/td><td>5 to 15 minutes<\/td><\/tr><tr><td>User profile<\/td><td>Now and then<\/td><td>1 to 5 minutes<\/td><\/tr><tr><td>Stock price or live score<\/td><td>Every second<\/td><td>1 to 5 seconds<\/td><\/tr><tr><td>Permission checks<\/td><td>When roles change<\/td><td>30 to 60 seconds<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">These numbers are only a start, so test them against real traffic. Also, add a small random amount to each TTL. Otherwise, many entries created together expire together, and all the requests hit your database at the same moment. This problem is called a cache stampede, and a little jitter reduces it a lot.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Go In-Memory Cache Hands-On: Build It<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s write the code. We build it in three small steps.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: The Types and Set<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, an <code>entry<\/code> holds a value and an expiry time. Next, the <code>Cache<\/code> holds a mutex, a map and the TTL. The <code>Set<\/code> method locks for writing, then stores the value with its expiry.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type entry[V any] struct {\n\tvalue   V\n\texpires time.Time\n}\n\ntype Cache[K comparable, V any] struct {\n\tmu    sync.RWMutex\n\titems map[K]entry[V]\n\tttl   time.Duration\n}\n\nfunc New[K comparable, V any](ttl time.Duration) *Cache[K, V] {\n\treturn &amp;Cache[K, V]{items: make(map[K]entry[V]), ttl: ttl}\n}\n\nfunc (c *Cache[K, V]) Set(key K, v V) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.items[key] = entry[V]{value: v, expires: time.Now().Add(c.ttl)}\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Get and Len<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Then <code>Get<\/code> takes the read lock. It returns the value only when the key exists and the entry has not expired. Otherwise, it returns the zero value and <code>false<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func (c *Cache[K, V]) Get(key K) (V, bool) {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\te, ok := c.items[key]\n\tif !ok || time.Now().After(e.expires) {\n\t\tvar zero V\n\t\treturn zero, false\n\t}\n\treturn e.value, true\n}\n\nfunc (c *Cache[K, V]) Len() int {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\treturn len(c.items)\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s look at the key lines. The check <code>time.Now().After(e.expires)<\/code> keeps the cache honest. An expired entry looks like a miss even before the janitor removes it. Also, the <code>var zero V<\/code> line gives a zero value of any type. Finally, <code>defer<\/code> releases the lock on every path.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: The Janitor and a Demo<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, <code>StartJanitor<\/code> starts a goroutine with a ticker. On every tick, it takes the write lock and deletes expired keys. The demo uses a 100 millisecond TTL, so we can watch an entry expire.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func (c *Cache[K, V]) StartJanitor(ctx context.Context, every time.Duration) {\n\tgo func() {\n\t\tt := time.NewTicker(every)\n\t\tdefer t.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase &lt;-t.C:\n\t\t\t\tc.mu.Lock()\n\t\t\t\tfor k, e := range c.items {\n\t\t\t\t\tif time.Now().After(e.expires) {\n\t\t\t\t\t\tdelete(c.items, k)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc.mu.Unlock()\n\t\t\tcase &lt;-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc main() {\n\tc := New[string, int](100 * time.Millisecond)\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tc.StartJanitor(ctx, 50*time.Millisecond)\n\n\tc.Set(\"visits\", 42)\n\tv, ok := c.Get(\"visits\")\n\tfmt.Println(\"fresh:\", v, ok, \"len =\", c.Len())\n\n\ttime.Sleep(120 * time.Millisecond)\n\tv, ok = c.Get(\"visits\")\n\tfmt.Println(\"expired:\", v, ok)\n\n\ttime.Sleep(80 * time.Millisecond)\n\tfmt.Println(\"after janitor, len =\", c.Len())\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the real output from our run.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fresh: 42 true len = 1\nexpired: 0 false\nafter janitor, len = 0<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, the fresh value comes back at once. After 120 milliseconds, the entry is expired, so <code>Get<\/code> reports a miss. After another 80 milliseconds, the janitor has removed it, so the length is zero. These three lines show the whole life of a cached value in a Go in-memory cache.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Test It with the Race Detector<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A cache must be safe under load. So we write a test where 50 goroutines call <code>Set<\/code> and <code>Get<\/code> on the same keys. Then we run it with the race detector.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func TestConcurrentUse(t *testing.T) {\n\tc := New[int, int](time.Minute)\n\tvar wg sync.WaitGroup\n\tfor i := 0; i &lt; 50; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j &lt; 100; j++ {\n\t\t\t\tc.Set(j, i)\n\t\t\t\tc.Get(j)\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\tif c.Len() != 100 {\n\t\tt.Fatalf(\"len = %d, want 100\", c.Len())\n\t}\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The command <code>go test -race<\/code> printed this on our machine.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>=== RUN   TestConcurrentUse\n--- PASS: TestConcurrentUse (0.01s)\nPASS<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">No race was reported, so the lock does its job. If you remove the mutex from the Go in-memory cache, the detector will complain at once.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes with a Go In-Memory Cache<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No TTL<\/strong>: entries then live forever and go stale. So give every entry an expiry.<\/li>\n\n\n\n<li><strong>A plain map without a lock<\/strong>: concurrent writes can crash the program. Therefore, always guard the map.<\/li>\n\n\n\n<li><strong>No cleanup<\/strong>: expired entries still fill memory. Instead, run a janitor or limit the size.<\/li>\n\n\n\n<li><strong>Caching errors<\/strong>: a failed call stored as a value keeps failing. So cache only good results.<\/li>\n\n\n\n<li><strong>Forgetting the copy problem<\/strong>: if you store a slice or map, callers can change it. For that reason, store copies or read-only data.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for a Go In-Memory Cache<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Choose the TTL from the data<\/strong>, because prices change faster than country names.<\/li>\n\n\n\n<li>**Use <code>RWMutex<\/code> for read-heavy loads**, since readers do not block each other.<\/li>\n\n\n\n<li><strong>Stop the janitor with a context<\/strong>, which prevents goroutine leaks.<\/li>\n\n\n\n<li><strong>Set a size limit<\/strong> if keys come from users, because an open cache can fill all memory.<\/li>\n\n\n\n<li><strong>Measure the hit rate<\/strong>, so you know the cache really helps.<\/li>\n\n\n\n<li>**Run tests with <code>-race<\/code>**, because locking bugs are easy to miss.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise the Go in-memory cache, add a <code>GetOrLoad<\/code> method. It takes a key and a function. If the key is fresh, it returns the cached value. Otherwise, it calls the function, stores the result and returns it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hint: take the write lock only after a miss. After that, check the key again, because another goroutine may have filled it. Then test with 50 goroutines and count how often your loader runs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These pages describe the packages and language features used in this lesson.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/sync\">sync package documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/go.dev\/doc\/tutorial\/generics\">Go tutorial: Getting started with generics<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/go.dev\/doc\/articles\/race_detector\">Go documentation: Data Race Detector<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>A Go in-memory cache stores answers in RAM to skip slow work.<\/li>\n\n\n\n<li>Every entry needs a TTL, or it will go stale.<\/li>\n\n\n\n<li>Use <code>sync.RWMutex<\/code> to protect the map from concurrent access.<\/li>\n\n\n\n<li>Generics let one cache type hold any key and value types.<\/li>\n\n\n\n<li>A janitor goroutine removes expired entries and stops with the context.<\/li>\n\n\n\n<li>Test with many goroutines and the race detector.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">By now, you can cache data safely inside your program. However, errors travel through many layers on their way to the caller. So next, we will wrap errors and check them with <code>errors.Is<\/code> and <code>errors.As<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next up: <a href=\"https:\/\/smitabharat.com\/blog\/go-error-wrapping-guide\/\">Go error wrapping with errors.Is and errors.As<\/a><\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>A Go in-memory cache keeps recent results inside your program, so you do not repeat slow work. In this post, you will build a&hellip;<\/p>\n","protected":false},"author":1,"featured_media":450,"comment_status":"","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[15],"tags":[90,11,77],"swapz_series":[],"class_list":["post-471","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-lang","tag-go-in-memory-cache","tag-go-lang","tag-intermediate"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go In-Memory Cache with TTL, Mutex and Generics<\/title>\n<meta name=\"description\" content=\"Build a Go in-memory cache with a TTL, an RWMutex and generics. Add a background janitor and test it safely with the race detector.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go In-Memory Cache with TTL, Mutex and Generics\" \/>\n<meta property=\"og:description\" content=\"Build a Go in-memory cache with a TTL, an RWMutex and generics. Add a background janitor and test it safely with the race detector.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-06-03T03:30:00+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go In-Memory Cache with TTL, Mutex and Generics\",\"datePublished\":\"2026-06-03T03:30:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/\"},\"wordCount\":1528,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-in-memory-cache-ttl-featured.png\",\"keywords\":[\"Go In-Memory Cache\",\"Go Lang\",\"Intermediate\"],\"articleSection\":[\"Go Lang\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/\",\"name\":\"Go In-Memory Cache with TTL, Mutex and Generics\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-in-memory-cache-ttl-featured.png\",\"datePublished\":\"2026-06-03T03:30:00+00:00\",\"description\":\"Build a Go in-memory cache with a TTL, an RWMutex and generics. Add a background janitor and test it safely with the race detector.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-in-memory-cache-ttl-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-in-memory-cache-ttl-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go In-Memory Cache featured image: set, get and janitor cards\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-in-memory-cache-ttl\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go In-Memory Cache with TTL, Mutex and Generics\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go In-Memory Cache with TTL, Mutex and Generics","description":"Build a Go in-memory cache with a TTL, an RWMutex and generics. Add a background janitor and test it safely with the race detector.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/","og_locale":"en_US","og_type":"article","og_title":"Go In-Memory Cache with TTL, Mutex and Generics","og_description":"Build a Go in-memory cache with a TTL, an RWMutex and generics. Add a background janitor and test it safely with the race detector.","og_url":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-06-03T03:30:00+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go In-Memory Cache with TTL, Mutex and Generics","datePublished":"2026-06-03T03:30:00+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/"},"wordCount":1528,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-featured.png","keywords":["Go In-Memory Cache","Go Lang","Intermediate"],"articleSection":["Go Lang"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/","url":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/","name":"Go In-Memory Cache with TTL, Mutex and Generics","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-featured.png","datePublished":"2026-06-03T03:30:00+00:00","description":"Build a Go in-memory cache with a TTL, an RWMutex and generics. Add a background janitor and test it safely with the race detector.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-in-memory-cache-ttl-featured.png","width":2400,"height":1260,"caption":"Go In-Memory Cache featured image: set, get and janitor cards"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-in-memory-cache-ttl\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go In-Memory Cache with TTL, Mutex and Generics"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/471","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=471"}],"version-history":[{"count":0,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/471\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/450"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=471"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=471"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=471"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=471"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}