Databases 8 min read

Understanding Redis Simple Dynamic String (SDS) Implementation and Its Advantages

This article explains Redis's Simple Dynamic String (SDS) data structure, its internal layout, how it differs from traditional C strings, and the performance, memory‑reallocation, and data‑format benefits it brings to Redis's key‑value storage.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Understanding Redis Simple Dynamic String (SDS) Implementation and Its Advantages

At the beginning of 2021, a colleague shared a Redis interview question about the underlying implementation of Redis strings, prompting a detailed explanation of the Simple Dynamic String (SDS) abstraction used by Redis.

The interview highlighted that although Redis is written in C, it does not use raw C strings for its key‑value pairs; instead, it employs SDS, a custom structure that stores the string length, free space, and a character buffer.

When a SET command is executed, both the key and the value are represented by SDS objects. Similarly, list elements created by LPUSH are also stored as SDS strings.

127.0.0.1:6379> set xiaofu "程序员内点事"
127.0.0.1:6379> lpush xiaofu "程序员内点事" "程序员小富"

The SDS structure is defined as:

struct sdshdr{
int free;   // number of unused bytes in buf[]
int len;    // length of the stored string
char buf[]; // actual character array
}

Key advantages of SDS over C strings include O(1) length retrieval, automatic expansion with pre‑allocation of free space, and lazy freeing of unused memory, which reduces the frequency of costly memory reallocations in high‑concurrency scenarios.

Two memory‑reallocation strategies are used: (1) space pre‑allocation adds extra free bytes when a string grows, and (2) lazy space release records unused space after a shrink, allowing future expansions without immediate reallocation.

Because SDS stores the length explicitly and does not rely on a terminating null byte, it can safely contain binary data, unlike C strings which are limited to text.

Understanding these details helps interviewees demonstrate solid fundamentals and can be a decisive factor in technical interviews.

memory managementRediscData StructureString()SDS
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.