Have you ever closely observed a librarian or a bookstore owner?
When you ask for a book, they don’t immediately run to the warehouse. First, they check nearby — on their desk or the closest shelf. If the book is there, they hand it over instantly.
If not, only then do they go deeper into the store or the godown to fetch it.
That nearby space contains a small but frequently used set of books, stored for quick access.
That’s exactly how cache works.
#What Is Cache?
In simple terms, cache is a temporary storage that keeps frequently accessed or already computed results.
So when the same request comes again:
-
We don’t recompute it
-
We return the cached result
-
We save time and resources
This is why caching makes systems faster and more efficient.
#Cache in Computers:
Caching exists at multiple levels:
-
CPU caches (L1, L2, L3)
-
Memory cache
-
Disk cache
-
Page cache
But the idea remains the same:
Keep frequently used data closer for faster access.
#Common Cache Terminologies:
-
Cache Hit → Data found in cache
-
Cache Miss → Data not found, needs to be fetched or computed
#Simple Cache Pseudocode:
function getValue(key):
if cache.contains(key):
return cache.get(key)
else:
value = database.get(key)
cache.put(key, value)
return valueThis works perfectly — but only in a single-threaded or single-machine system.
#The Real Challenge: Distributed Systems:
Problems arise when:
-
Multiple threads or services
-
Multiple concurrent requests
-
Same key requested at the same time
What happens then?
👉 All requests see a cache miss
👉 All compute the same value
👉 Database gets hammered
👉 Cache becomes ineffective
This is often called a cache stampede.
#Solving This with Synchronization:
To solve this, we must control access to the shared resource.
This is where concepts like semaphores or locks help.
A semaphore ensures:
-
Only one request computes the value
-
Others wait
-
Once computed, everyone uses the cached result
This idea is sometimes referred to as debouncing or request coalescing.
#Similar Idea in Frontend (RxJS)
A similar pattern exists in frontend development using RxJS Observables.
Instead of triggering the same computation multiple times:
-
We emit an event
-
The computation runs once
-
All subscribers receive the result
This helps prevent duplicate API calls and improves performance.
Take a look at below pseudocode with semaphore.
fn getValueFromCache(key) :
v = cache.get(key);
if v :
return v;
s = semaphoreMap.get(k);
if s:
s.wait();
v = finalResMap.get(k);
return v;
else :
semaphoreMap[k] = new Semaphore();
semaphoreMap[k].block();
v = db.get(k);
cache.put(k, v);
finalResMap[k] = v;
semaphoreMap[k].signal();
semaphoreMap[k].signal();
return v;#Final Thoughts
A simple idea becomes complex in real systems, and solving it well is what differentiates good engineers from great ones.