Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 18

Key-Value Stores for Caching: Architecture & Use Cases

This lesson is built with resources from youtube.com, redis.io and 1 more site.

Hello! Welcome to the next lesson in our module on Distributed Data Storage & Systems.

In our last session, we explored the world of wide-column stores through Apache Cassandra. We saw how its leaderless, disk-based architecture is optimized for massive write throughput and availability, making it a powerhouse for specific use cases like time-series data. The core takeaway was its query-driven modeling, where you denormalize data to fit your application's access patterns.

Today, we turn our attention to a conceptually simpler, yet incredibly powerful, type of NoSQL database: key-value stores. Our learning objective is to describe the architecture and use cases for key-value stores, focusing on Redis and its role in caching.

While Cassandra is about durable, petabyte-scale persistence, key-value stores like Redis are often about ephemeral data and raw speed. They excel at serving data from memory, which dramatically reduces latency. As a software architect, you'll find that understanding how and when to introduce a caching layer is one of the most effective ways to improve system performance and scalability.

What is a Key-Value Store?

A key-value store is the most fundamental type of NoSQL database. It works like a dictionary or a hash map, where you store a piece of data (the "value") and associate it with a unique identifier (the "key"). To retrieve the data, you simply provide its key.

"user:123" -> {"name": "Alice", "email": "alice@example.com"}
"session:xyz" -> "user_id:123,role:admin"

The value can be anything from a simple string or number to a complex object like a JSON document. The database itself is schema-less; it doesn't care what the value is. This simplicity is its greatest strength.

Our focus today is on Redis (REmote DIctionary Server), the most popular key-value store. Let's start with a short video that explains its fundamental characteristics.

Redis Deep Dive w/ a Ex-Meta Senior Manager

This clip from the "Redis Deep Dive" video by Hello Interview explains what makes Redis unique.

Please watch from 00:44 to 04:17. Pay attention to the three core concepts used to describe Redis: Single-threaded: How this simplifies operations. In-memory: The source of its incredible speed. Data structure server: How it goes beyond simple key-value pairs.

To summarize the key points from the video:

  • In-Memory First: Redis keeps the entire dataset in RAM. This is why it can achieve sub-millisecond response times for read and write operations. Disk is used for persistence (which we'll cover later), not for serving queries.
  • Single-Threaded: Redis processes commands sequentially. This avoids the complexity of locks and race conditions, making its behavior predictable. While it might seem counterintuitive for a high-performance system, it's highly effective because in-memory operations are so fast that the bottleneck is typically the network, not the CPU.
  • Data Structure Server: The "value" in Redis isn't just a blob of data. Redis natively supports advanced data structures like lists, sets, sorted sets, and hashes, allowing you to perform complex operations on the server side efficiently.

While Redis is versatile enough to be a primary database for certain workloads, its most common and impactful use case is caching.


The Role of Caching

At its core, caching is about storing frequently accessed data in a faster, closer location to reduce the need to fetch it from a slower, more distant source. In application architecture, this almost always means placing a cache like Redis between your application and your primary database (e.g., PostgreSQL, MongoDB, or Cassandra).

Redis Usage in Caching Architecture
This diagram illustrates the cache-aside pattern. An application first checks the Redis cache. On a cache hit, the data is returned immediately. On a cache miss, the application queries the primary database, stores the result in Redis for next time, and then returns the data.

The primary benefits are:

  1. Reduced Latency: Reading from in-memory Redis is orders of magnitude faster than reading from a disk-based database.
  2. Reduced Load: By handling a large portion of read requests, the cache protects the primary database from being overwhelmed, allowing it to focus on write operations and more complex queries.
  3. Increased Availability: If the primary database experiences a temporary outage, the application may still be able to function in a limited, read-only capacity by serving data from the cache.

Common Caching Strategies

How an application interacts with the cache and the database is defined by a caching strategy. Your choice of strategy has significant implications for performance and data consistency.

Let's watch a video that explains the most common strategies.

How does Caching on the Backend work? (System Design Fundamentals)

The video "How does Caching on the Backend work?" by Software Developer Diaries clearly explains the main caching strategies and their trade-offs.

Please watch from 06:22 to 11:26. This segment covers the three primary strategies: Cache-Aside (Read-Around), Write-Through, and Write-Back. Focus on the flow of data for both read and write operations in each pattern.

Here is a summary of the strategies, framed for an architectural perspective:

Strategy How it Works Pros Cons
Cache-Aside (Lazy Loading) The application is responsible for the logic. Read: Check cache first. If miss, read from DB, then write to cache. Write: Write directly to the DB. Optionally, invalidate the cache. - Cache only contains data that is actually requested.
- Resilient to cache failures (app can fall back to DB).
- Higher latency on the first read (cache miss).
- Potential for stale data if the cache isn't invalidated after a DB write.
Write-Through The application writes to the cache. The cache then synchronously writes to the database. Read: Same as Cache-Aside. - Data in the cache and DB are always consistent.
- Simpler application logic for writes.
- Higher write latency because every write goes to both cache and DB.
- Cache can fill with data that is rarely read.
Write-Back (Write-Behind) The application writes only to the cache. The cache acknowledges the write immediately and then asynchronously writes to the database in the background. - Extremely low write latency.
- Reduces load on the database by batching writes.
- High risk of data loss if the cache fails before data is persisted to the DB.
- Increased complexity.

For most general-purpose application caching, Cache-Aside is the most common and recommended pattern due to its simplicity and resilience.


Managing the Cache: Eviction and Expiration

A cache has finite memory. What happens when it's full? You need a policy to decide which items to remove (evict) to make room for new ones.

Additionally, data in the cache can become stale if the source data in the database changes. To ensure freshness, we set an expiration policy.

  • Time-To-Live (TTL): This is the simplest expiration policy. You set a specific duration for each key (e.g., 60 seconds). After that time, Redis automatically removes the key. This guarantees that stale data is eventually purged.
  • Least Recently Used (LRU): When the cache is full and a new item needs to be added, Redis evicts the item that hasn't been accessed for the longest time. This is effective for keeping "hot" (frequently used) data in the cache. Redis can also be configured for LFU (Least Frequently Used) and other policies.

To see these concepts in action, let's watch a practical demonstration.

How does Caching on the Backend work? (System Design Fundamentals)

This final clip from "How does Caching on the Backend work?" shows a simple Node.js application using Redis for Cache-Aside, including setting a TTL.

Please watch from 15:11 to 20:58. You don't need to be a Node.js expert to follow along. Observe how the application logic checks the cache (redis.get), handles a miss by fetching from an API and populating the cache (redis.set), and includes an expiration time (ex).

The code in the video demonstrates the core GET/SET commands of a key-value store and how easily a TTL can be applied, making Redis a powerful and practical tool for caching.


Architectural Considerations for Redis

As an enterprise architect, deploying a single Redis instance introduces a single point of failure. For production systems, you need to consider high availability and scalability.

Redis Explained

The article "Redis Explained" by Mahdi Yusuf provides a concise, high-level overview of the different ways to deploy Redis to solve for these challenges. Please read the section on Redis Architectures.

Read the section titled "Redis Architectures", which covers Single Instance, Redis HA, Redis Sentinel, and Redis Cluster. Focus on what problem each topology solves.

Here is a summary of the deployment architectures:

  • Single Instance: Simple but has no fault tolerance. Good for development or non-critical use cases.
  • Redis HA (Replication): A primary instance replicates all its writes to one or more secondary (replica) instances. This allows you to scale reads across replicas and provides a hot standby for manual failover.
  • Redis Sentinel: A separate system that monitors the primary/replica cluster. It provides automatic failover by detecting if the primary is down, promoting a replica to be the new primary, and informing the application of the new configuration. This solves for high availability.
  • Redis Cluster: This solves for horizontal scalability (scaling out). It shards (partitions) the data across multiple primary instances. Each primary handles a subset of the keys. This allows you to store datasets larger than a single server's RAM and distribute the write load.

Finally, while caching is often volatile, Redis provides persistence options by saving its in-memory data to disk.

  • RDB (Snapshotting): Creates point-in-time snapshots of your dataset. It's fast for restarts but you can lose data written since the last snapshot.
  • AOF (Append Only File): Logs every write operation. It's more durable but can result in larger files and slower restarts.

Choosing the right architecture and persistence model depends entirely on your application's specific requirements for performance, durability, and availability.

Test your understanding!

You are architecting a social media platform. The "timeline" feed for each user is computationally expensive to generate. Once generated, it doesn't change for 5 minutes. The platform has millions of users, and you want to ensure the feed loads quickly and the system is highly available.

Which Redis deployment architecture would you choose and why? What caching strategy and eviction policy would be most appropriate for the user timelines?

Show answer
  • Deployment Architecture: Redis Cluster is the most suitable choice. Given millions of users, the total cached data will likely exceed the memory of a single server. Redis Cluster allows you to shard the data (e.g., by user_id) across multiple nodes, enabling horizontal scaling for both memory capacity and request throughput. Each shard in the cluster should also have replicas (managed by Sentinel or native Cluster replication) to ensure high availability.

  • Caching Strategy: Cache-Aside is a good fit. When a user requests their timeline, the application first checks the cache. If the timeline isn't there (cache miss), the application generates it, stores it in Redis, and then sends it to the user.

  • Eviction/Expiration Policy: A Time-To-Live (TTL) of 5 minutes is perfect here. We can set the key (e.g., timeline:user_id_123) to expire automatically after 5 minutes. This is simple and effective, guaranteeing that users will see a refreshed timeline after 5 minutes without needing a complex invalidation or eviction mechanism like LRU.


Conclusion

Today we've added a vital tool to our data architecture toolkit: the key-value store, exemplified by Redis. We've seen how its in-memory nature provides a foundation for high-performance caching.

Key Takeaways:

  • Key-value stores are simple, schema-less databases that map a unique key to a value.
  • Redis is an extremely fast, in-memory, single-threaded data structure server, making it ideal for caching.
  • The primary goal of caching is to reduce latency and protect backend systems by serving frequently accessed data from a fast, temporary store.
  • Cache-Aside is the most common caching strategy, where the application manages reading from the cache and populating it on a miss.
  • Expiration (TTL) and eviction (LRU) policies are crucial for managing cache memory and data freshness.
  • Production Redis architectures use replication (for HA) and sharding (for scalability) to overcome the limitations of a single instance.

In our next lesson, we will tie together everything we've learned about document, column-family, and key-value stores. We'll build a decision framework to help you choose the right storage technology based on critical factors like data access patterns, consistency needs, and scalability requirements.