Redis Foundations & Data Structures

[!NOTE] This module explores the core principles of Redis Foundations & Data Structures, deriving solutions from first principles and hardware constraints to build world-class, production-ready expertise.

1. What is Redis?

REmote DIctionary Server. It is an in-memory Key-Value store.

  • Fast: Data lives in RAM. Access is ~100 microseconds.
  • Persisted: Can save to disk (RDB/AOF), but primary purpose is performance.
  • Atomic: All operations are atomic.

2. The Single-Threaded Architecture

Redis uses one CPU core to handle all requests.

  • Why?: No locks. No context switching. No race conditions on data.
  • How?: It uses I/O Multiplexing (epoll/kqueue). It handles thousands of concurrent connections but processes commands sequentially.

[!WARNING] Trap: Never run a slow command (like KEYS * or a heavy LUA script) in production. It blocks everyone.


3. Interactive: Data Structure Explorer

Click a structure to see its use case and complexity.

String
List
Set
Hash
Sorted Set
Select a Data Structure above.

4. Code Example: Caching Pattern (Cache-Aside)

public User getUser(String userId) {
    // 1. Check Cache
    String cacheKey = "user:" + userId;
    String cached = redis.get(cacheKey);
    if (cached != null) return deserialize(cached);

    // 2. Cache Miss -> DB
    User user = db.find(userId);

    // 3. Write Back to Cache (with TTL)
    if (user != null) {
        redis.setex(cacheKey, 3600, serialize(user));
    }
    return user;
}

5. Summary

  • Fast: RAM + Single Threaded Event Loop.
  • Versatile: Not just key-value strings; use Hashes for objects and ZSets for ranking.
  • Transient: Always assume Redis can lose data (it’s a cache first).