Course contentsShow
← Databases & SQL
Lesson 1388 of 1,95312. Key-Value and Caching EnginesFree lesson

Data Structure Composition

Combine multiple primitive structures to build advanced domain models.

In this lesson, you will learn how to synthesize multiple primitive Redis data structures into a unified, high-performance domain model.

The Power of Composition

When working with high-throughput key-value stores, relying on a single data type (like a simple string) often limits your query capabilities. "Data Structure Composition" is the practice of layering multiple primitive structures—such as Hashes, Sets, Lists, and Sorted Sets—to mimic relational schema behavior without sacrificing the performance of a cache.

By decomposing a complex object into its atomic parts and storing them in distinct but linked keys, you gain granular control over updates, memory, and access patterns.

Practical Example: Modeling a User Session

Imagine building a "User Notification System." You could store the entire notification object as a single JSON blob in a key, but updating one "read" status would require downloading, deserializing, modifying, and re-uploading the whole string.

Instead, compose your structure using primitive engines:

  1. Hash: Store the core metadata of the notification (e.g., user:101:notif:50 -> {"title": "Welcome", "read": "false"}).
  2. Sorted Set: Maintain an index of notification IDs for that user, ordered by timestamp (user:101:inbox -> score: 1672531200, member: 50).
# 1. Store metadata in a Hash for O(1) updates
HSET user:101:notif:50 title "Welcome" read "false"

# 2. Add to a Sorted Set for time-based pagination
ZADD user:101:inbox 1672531200 50

# To mark as read, you only touch the specific Hash field:
HSET user:101:notif:50 read "true"

Why this matters

This composition strategy allows for atomic, partial updates. You aren't forcing the database to process the entire object when only one piece of data changes. Furthermore, this approach allows you to perform range queries (e.g., "get the last 10 notifications") on the index while keeping the heavy data payload separate in the Hash. You essentially create a custom, high-speed index for your domain model, giving you the flexibility of a relational structure with the speed of a cache.

Key Takeaway: By decomposing domain models into constituent data structures, you gain the ability to perform surgical updates and efficient range-based queries, significantly reducing I/O overhead and serialization latency.