Understanding Redis Memory Model and Its Applications
This article explains Redis's memory model, covering memory statistics, internal structures such as redisObject, SDS, and various object types, their encoding schemes, memory allocation, fragmentation, and provides practical examples for estimating memory usage, optimizing consumption, and monitoring fragmentation in high‑performance applications.
Redis is a popular in‑memory database; this article introduces its memory model, how to inspect memory usage via the INFO command, and key metrics such as used_memory, used_memory_rss, and mem_fragmentation_ratio.
The internal representation consists of redisObject, which stores type, encoding, reference count, LRU, and a pointer to the actual data, and SDS (simple dynamic string) used for keys and string values.
typedef struct redisObject {
unsigned type:4;
unsigned encoding:4;
unsigned lru:REDIS_LRU_BITS;
int refcount;
void *ptr;
} robj;Redis supports five data types—strings, lists, hashes, sets, and sorted sets—each with multiple internal encodings (e.g., int, embstr, raw for strings; ziplist or linkedlist for lists; ziplist or hashtable for hashes; intset or hashtable for sets; ziplist or skiplist for sorted sets). The article details when Redis switches between encodings based on element count and size.
typedef struct dictEntry {
void *key;
union {
void *val;
uint64_t u64;
int64_t s64;
} v;
struct dictEntry *next;
} dictEntry;Memory allocation is performed by jemalloc by default, which groups allocations into size classes to reduce fragmentation. The article explains how to estimate memory consumption for a set of key‑value pairs by accounting for dictEntry, SDS, redisObject, and bucket array sizes.
Practical examples show Java code that inserts 90 000 keys into Redis and measures the memory increase, confirming the theoretical calculation.
Finally, the article offers optimization tips such as using appropriate encodings, leveraging integer storage, sharing common objects, and monitoring mem_fragmentation_ratio to decide when to restart Redis or adjust maxmemory policies.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
