Databases 8 min read

Redis Simple Dynamic String (SDS) Implementation Overview

Redis implements its own Simple Dynamic String (SDS) instead of plain C strings because SDS stores length for O(1) queries, pre‑allocates extra space and lazily reuses freed bytes, prevents buffer overflows, handles binary data, and uniformly backs all string keys, values and container elements.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Redis Simple Dynamic String (SDS) Implementation Overview

An interview question asks why Redis uses its own SDS (Simple Dynamic String) instead of plain C strings. The answer is that Redis is written in C, but it needs a mutable string type that records its length and can grow efficiently.

In Redis, both keys and values that are strings are stored as SDS objects. The SDS structure consists of three fields:

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

The len field allows O(1) length retrieval, unlike C strings that require a full scan (O(N)). This improves performance for commands such as STRLEN in high‑concurrency scenarios.

When a string needs to be modified, Redis checks whether the current free space is sufficient. If not, it expands the buffer and updates free . Two memory‑management strategies are used:

Pre‑allocation : on growth, extra unused space ( free ) is allocated (up to 1 MiB for large strings) to reduce future reallocations.

Lazy free : on shrinkage, the buffer is not immediately released; the freed space is recorded in free and can be reused later.

Examples:

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

The key xiaofu and the value 程序员内点事 are each stored as separate SDS objects.

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

Here the list element objects are also SDS strings, demonstrating that even complex data types rely on the same underlying structure.

Compared with C strings, SDS avoids buffer overflows, supports binary data (no \0 termination limitation), and provides faster length queries, making it well‑suited for Redis’s in‑memory database workload.

Memory ManagementDatabaseRedisC languageSDSSimple Dynamic String
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

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.