/blogs/caching-from-cpu-registers-to-distributed-systems

← Back to blogs
Blog

Caching: From CPU Registers to Distributed Systems

Learn how caching works across hardware, networks, and backend applications, including CDNs, Redis, cache-aside patterns, eviction policies, and real-world scaling strategies.

·10 min read·

Caching: From CPU Registers to Distributed Systems

Caching is a mechanism used to decrease the time and computational effort required to perform a task. Technically, it involves keeping a subset of primary data in a faster, more accessible location.

You do not cache everything. You cache based on usage frequency, probability of future access, and the cost of recomputing or fetching the original data. In high-performance backend systems, caching is the difference between a 20-millisecond API response and a 500-millisecond timeout.

This post breaks down how caching operates across network, hardware, and software layers, and how to implement in-memory caching strategies in production backends.

#Real-World Examples of Caching

To understand why caching is critical, look at how massive platforms handle scale.

When you search for "weather in New York," Google does not re-crawl, index, and rank billions of web pages for your specific query. That computation is too expensive. Instead, Google uses a distributed in-memory caching system.

  • Cache Hit: If the query was recently executed, the system returns the cached ranked results instantly.
  • Cache Miss: If the query is new, Google runs the heavy ranking algorithms, returns the result, and stores it in the cache for the next user.

Netflix

Netflix streams massive video files to millions of global users. To prevent buffering and server crashes, they use a Content Delivery Network (CDN). Netflix origin servers hold the master files. They encode these files into multiple resolutions (1080p, 720p, 480p). Instead of forcing a user in India to fetch a video from a server in the US, Netflix caches subsets of popular content at Edge locations (servers geographically closer to the user). This minimizes physical distance, drastically reducing latency.

X (formerly Twitter)

The "Trending" section requires analyzing billions of tweets in real-time using machine learning and trend detection algorithms. If X ran this computation for every single user opening the app, the servers would crash. Because trends do not change every second, X computes the trends periodically (e.g., every few minutes) and stores the aggregated results in an in-memory cache like Redis. When you open the app, the UI fetches the pre-computed trends from the cache, resulting in instant load times.

The Core Pattern

Across all these examples, a pattern emerges: Whenever you need to avoid heavy computation or serve large amounts of data to many users, you use caching.


#The Three Levels of Caching

As a backend engineer, you will encounter caching at three distinct levels: Network, Hardware, and Software.

1. Network-Level Caching

Network caching moves data closer to the user geographically or resolves network routing faster.

Content Delivery Networks (CDN)

A CDN is a globally distributed network of servers that caches web content at Points of Presence (PoPs). A PoP is a physical location containing multiple Edge servers.

Rendering diagram...

The CDN DNS system routes the user to the nearest PoP based on geography and network health. The Edge server checks its local cache. If the resource is missing (Cache Miss), it fetches it from the Origin server, caches it, and serves it to the user. CDNs use TTL (Time To Live) to dictate how long a resource stays in the cache before it must be refreshed from the origin.

DNS Caching

Domain Name System (DNS) resolution relies heavily on caching to avoid traversing the entire DNS hierarchy for every request.

Rendering diagram...

Caching happens at multiple layers: the Operating System, the Browser, and the Recursive Resolver (provided by your ISP or Google/Cloudflare). If the Recursive Resolver has the IP cached, it skips the expensive recursive hunt through Root, TLD, and Authoritative servers.

2. Hardware-Level Caching

Hardware caching manages the speed disparity between the CPU and main memory.

Rendering diagram...
  • L1 Cache: Smallest and fastest, located directly inside the CPU core. Split into instruction and data caches.
  • L2 Cache: Larger, slightly slower, dedicated to the CPU core.
  • L3 Cache: Shared across multiple CPU cores.
  • RAM (Random Access Memory): Volatile main memory. It is much slower than CPU caches but holds the active data for running applications. It is called "random access" because it can read/write any memory address directly via electrical signals, unlike mechanical Hard Disk Drives (HDDs).
  • SSD/HDD: Persistent secondary storage. Slowest, but retains data when power is off.

CPU speeds have scaled much faster than RAM speeds. Without L1/L2/L3 caches, the CPU would spend most of its cycles waiting for RAM to deliver data.

3. Software-Level Caching (Backend Databases)

When backend engineers talk about caching, they are usually referring to software-level, in-memory databases like Redis, Memcached, or AWS ElastiCache.

These are in-memory, key-value, NoSQL databases.

  • In-memory: Data is stored in RAM, not on disk. This makes read/write operations exceptionally fast. (They often use disk for persistence, but active operations happen in RAM).
  • Key-value: No strict schemas, tables, or rows. You store a key (string) and map it to a value (string, list, hash, JSON).
  • NoSQL: They do not enforce relational constraints.

Caching Strategies

When integrating an in-memory cache with your primary relational database (like PostgreSQL), you must choose a strategy for handling reads and writes.

1. Lazy Caching (Cache-Aside Pattern) Used primarily for read operations. The application only queries the cache. If the data is missing, it fetches it from the database, stores it in the cache, and returns it.

Rendering diagram...
  • Pros: Only caches data that is actually requested. Resilient to cache failures (if cache dies, the app just falls back to the DB).
  • Cons: The first request for any data suffers a cache miss penalty.

2. Write-Through Caching Used for write operations. When the application writes data to the database, it synchronously writes the exact same data to the cache in the same execution flow.

Rendering diagram...
  • Pros: The cache is always fresh. You never serve stale data to read requests.
  • Cons: Higher write latency. Every write operation now requires two network calls (DB + Cache) before responding to the client.

Eviction Policies

RAM is limited and expensive. You cannot store your entire database in Redis. When the cache reaches its memory limit, it must delete old data to make room for new data. This is governed by the eviction policy.

  • No Eviction: Returns an error when memory is full and a write is attempted. (Rarely used in production).
  • LRU (Least Recently Used): Evicts the keys that have not been accessed for the longest time. If Key A was accessed today and Key B was accessed last week, Key B is evicted.
  • LFU (Least Frequently Used): Evicts keys based on total access count over time. If Key A was accessed 100 times and Key B was accessed 5 times, Key B is evicted, regardless of when they were last touched.
  • TTL (Time To Live): Keys are assigned an expiration timer. When the timer hits zero, the key is automatically deleted. Often used in combination with LRU/LFU.

#Real-World Backend Use Cases for In-Memory Caches

Understanding the theory is only half the battle. Here is where you actually deploy Redis or Memcached in a production backend.

1. Database Query Caching

If you have a highly read-heavy API that executes a complex SQL query (multiple joins, aggregations over millions of rows), caching the final result is standard practice.

Example: An e-commerce product page. The product details, price, and images rarely change. During a massive sale, millions of users will request the same MacBook page. Hitting PostgreSQL for every request will crash the database. Instead, cache the rendered product data in Redis with a 1-hour TTL. The database only handles inventory updates and order processing.

2. Session Storage

In stateful authentication flows, the server generates a session token for the logged-in user. This token must be validated on every subsequent API request.

Storing session tokens in a relational database adds unnecessary latency to every single request. Storing them in Redis allows for sub-millisecond token validation. When a user logs out, the token is simply deleted from the cache.

3. External API Caching

If your backend aggregates data from third-party APIs (e.g., a weather service, currency exchange rates, or stock prices), you are bound by their rate limits and pricing tiers.

Weather data does not change every second. Instead of calling the external API every time a user loads your dashboard, fetch the data, store it in Redis with a 15-minute TTL, and serve subsequent requests from the cache. This prevents rate-limit bans and reduces external API billing.

4. Rate Limiting

Rate limiting protects your API from abuse and bot traffic. A middleware intercepts incoming requests, checks the user's IP address (via the X-Forwarded-For header), and enforces a limit (e.g., 50 requests per minute).

To track the request count, you need a counter that increments rapidly. Doing this in PostgreSQL creates a massive bottleneck. Instead, use Redis.

  1. Middleware extracts the IP.
  2. Checks Redis for a key like ratelimit:{ip}.
  3. If missing, creates it with a value of 1 and a TTL of 60 seconds.
  4. If present, increments the value.
  5. If the value exceeds 50, return a 429 Too Many Requests HTTP status code.

Because Redis operates in RAM, this check adds virtually zero latency to the API response.


Caching is not a magic fix for poorly written code, but it is a mandatory architectural component for scalable systems. By understanding the memory hierarchy, network routing, and in-memory data structures, you can make informed decisions about where to place your caches.

Start by identifying the read-heavy, compute-expensive, or externally dependent operations in your backend. Implement a simple Cache-Aside pattern using an in-memory store like Redis (or its open-source fork, Valkey). Monitor your cache hit rates, tune your TTLs, and watch your API latencies drop.

1,634 words left