Skip to main content

Chapter 3: Data Structures

Redis isn’t just a key-value store — it’s a data structure server. In this chapter, we’ll implement Lists, Sets, Hashes, and Sorted Sets, learning powerful data structures along the way. This distinction is what makes Redis special. A plain key-value store is like a filing cabinet where every drawer holds a single sheet of paper. Redis is a filing cabinet where drawers can hold sorted binders, index cards, or entire sub-cabinets. By pushing data structure logic into the server, Redis eliminates the “read-modify-write” round trip that plagues naive caching patterns. Instead of fetching a list, appending to it in your application, and writing it back (three network calls, plus a race condition), you send a single RPUSH command and the server handles it atomically.
Prerequisites: Chapter 2: TCP Server
Further Reading: DSA Patterns
Time: 4-5 hours
Outcome: Full support for Redis data types

Redis Data Structures Overview


Part 1: Lists

Redis lists are implemented as doubly-linked lists for O(1) push/pop at both ends. Why not an array? Because arrays have O(n) insertion at the head (every element must shift). For a message queue or activity feed where you constantly push to one end and pop from the other, a doubly-linked list is the right tool. The trade-off is that random access by index (LINDEX) becomes O(n) — you have to walk from the head or tail. Real Redis optimizes this further with a “quicklist” (a linked list of small arrays), but the pure linked list is the right starting point for understanding the design.

List Structure

internal/store/list.go

Part 2: Sets

Sets use a hash map for O(1) membership tests and operations.
internal/store/set.go

Part 3: Hashes

Hashes are maps of field-value pairs within a key.
internal/store/hash.go

Part 4: Sorted Sets with Skip Lists

Sorted Sets are the most complex data structure - they maintain elements sorted by score while allowing O(log n) operations.

What is a Skip List?

Skip List Implementation

internal/store/skiplist.go

Sorted Set Wrapper

internal/store/zset.go

Exercises

Add insertion before/after a pivot:
Implement set operations as commands:
Get the rank of a member in a sorted set:

Key Takeaways

Linked Lists

O(1) push/pop at ends, O(n) access by index

Hash Sets

O(1) membership test using hash maps

Skip Lists

Probabilistic O(log n) sorted structure

Composite Structures

ZSet combines skip list + hash map for best of both

Further Reading

Hash Maps

Deep dive into hash table implementations

Linked Lists

Understanding linked list patterns

What’s Next?

In Chapter 4: Persistence, we’ll implement:
  • RDB snapshots (point-in-time backups)
  • AOF logging (append-only file)
  • Crash recovery

Next: Persistence

Learn how Redis survives restarts