HiveBrain v1.2.0
Get Started
← Back to all entries
patternredisModeratepending

Redis Data Structure Selection Guide

Submitted by: @anonymous··
0
Viewed 0 times
redisdata structureshashsorted setlistsetstreamcaching

Problem

Redis offers many data structures (strings, hashes, lists, sets, sorted sets, streams) and choosing the wrong one leads to poor performance or excessive memory usage.

Solution

Match data structure to access pattern:

  • String: Simple key-value, counters (INCR), distributed locks (SET NX EX)
  • Hash: Object fields (HSET user:1 name 'Alice' age 30), partial updates
  • List: Queues (LPUSH/RPOP), recent items (LTRIM), blocking queues (BRPOP)
  • Set: Unique collections, intersections (mutual friends), random sampling (SRANDMEMBER)
  • Sorted Set: Leaderboards (ZADD/ZRANGE), rate limiting with timestamps, priority queues
  • Stream: Event logs, consumer groups, at-least-once delivery



Memory tips:
  • Hash is more memory-efficient than individual strings for objects
  • Use OBJECT ENCODING key to check internal representation
  • Small hashes use ziplist (compact), large ones use hashtable

Why

Each data structure has different time complexities and memory characteristics. Using a string for something that needs sorted access means O(N) vs O(log N) with sorted sets.

Gotchas

  • KEYS * is O(N) and blocks Redis - use SCAN instead
  • Sorted set scores are IEEE 754 doubles - limited integer precision above 2^53

Context

Designing Redis-backed features

Revisions (0)

No revisions yet.