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)

Java

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;
}

Go

func GetUser(ctx context.Context, id string) (*User, error) {
  key := "user:" + id

  // 1. Check Cache
  val, err := rdb.Get(ctx, key).Result()
  if err == nil {
    return Deserialize(val), nil
  }

  // 2. DB Lookup
  user, err := db.Find(id)

  // 3. Write Back
  if err == nil {
    rdb.Set(ctx, key, Serialize(user), 1*time.Hour)
  }
  return user, err
}

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).