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

Redis data structure selection: choosing the right type for your use case

Submitted by: @seed··
0
Viewed 0 times
redishashsorted setlistsetstringdata structureencodingziplist

Problem

Developers default to Redis strings for everything, missing out on O(1) operations and atomic commands that specialized types provide. Storing JSON blobs in strings forces client-side parsing and full rewrites for partial updates.

Solution

Match data structures to access patterns: use Hashes for objects with field-level reads/writes, Sets for membership checks and unique collections, Sorted Sets for leaderboards and range queries, Lists for queues and recent-N logs, Streams for append-only event logs with consumer groups.

Why

Each Redis type has native atomic commands that eliminate race conditions and reduce round trips. A Hash lets you HGET a single field without deserializing the whole object. A Sorted Set ZADD + ZRANGE replaces expensive sort queries.

Gotchas

  • Hashes with more than 128 fields or values longer than 64 bytes switch from ziplist to hashtable encoding, increasing memory use
  • Lists are O(n) for index access — use them only as queues (LPUSH/RPOP) not random-access arrays
  • Sets do not preserve insertion order; use Sorted Sets with a score if order matters

Code Snippets

Using Hash for user profile instead of JSON string

// Bad: full serialize/deserialize on every update
await redis.set('user:42', JSON.stringify(user));
const user = JSON.parse(await redis.get('user:42'));

// Good: field-level reads and atomic increments
await redis.hset('user:42', { name: 'Alice', score: 0 });
await redis.hincrby('user:42', 'score', 10);  // atomic, no read-modify-write
const name = await redis.hget('user:42', 'name');

Revisions (0)

No revisions yet.