Redis Tutorial 0/42 lessons ~6 min read Lesson 8

    Strings

    Strings are Redis's simplest and most-used type — binary-safe blobs up to 512MB.

    Course progress0%
    Focus
    10 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Strings are Redis's simplest and most-used type — binary-safe blobs up to 512MB. They power API caches, atomic counters, distributed locks (SET NX EX), and feature flags.

    Under the hood Redis optimizes small strings with embstr (embedded string) and integers with a dedicated int encoding — no heap allocation for SET counter 42.

    Master SET options (EX, NX, XX) and you cover 80% of cache and coordination patterns in production microservices.

    Understanding the topic

    Key concepts

    • SET key value — create or overwrite; GET retrieves.
    • INCR/DECR — atomic integer math without read-modify-write races.
    • SET NX EX — compare-and-set with TTL; foundation of locks.
    • MSET/MGET — batch multiple keys in one round trip.
    • APPEND and GETRANGE — treat string as mutable buffer.
    • Embstr for ≤44 bytes; raw SDS for larger values.

    Step-by-step explanation

    1. SET stores SDS (Simple Dynamic String) or int encoding.
    2. INCR parses value as integer; errors if not numeric.
    3. TTL attached via EX/PX/EXAT on SET or separate EXPIRE.
    4. GET returns bulk string or nil if missing.
    5. Memory reclaimed on DEL/UNLINK or expiry.

    Syntax reference

    Common commands

    • EX on SET — always TTL cache keys.
    • SET NX EX — lock acquire pattern.
    • MGET — batch reads without pipeline setup.
    bash
    SET product:42 "{"sku":"X"}" EX 3600
    GET product:42
    INCR pageviews:home
    SET lock:order:99 token NX EX 30
    MGET product:1 product:2 product:3

    Informative example

    Cache-aside product lookup with StringRedisTemplate:

    java
    @Service
    public class ProductCache {
    private final StringRedisTemplate redis;
    public ProductCache(StringRedisTemplate redis) {
    this.redis = redis;
    }
    public Optional<Product> get(String sku) {
    String key = "product:" + sku;
    String json = redis.opsForValue().get(key);
    if (json != null) return Optional.of(parse(json));
    return db.findBySku(sku).map(p -> {
    redis.opsForValue().set(key, serialize(p), Duration.ofHours(1));
    return p;
    });
    }
    }

    Serialize once; set with Duration TTL. On update, delete key or write-through.

    Real-world use

    Real-world use cases

    • API response cache — JSON string keyed by request hash.
    • Page view counter — INCR with daily key suffix.
    • Distributed lock token — SET NX EX.
    • OAuth state parameter — short TTL string.
    • Config snapshot — versioned string for feature rollout.

    Best practices

    • Always EX on cache strings.
    • Keep JSON payloads small; compress if >10KB.
    • Use MGET for batch product lookups.
    • Prefix keys: catalog:product:sku.
    • Invalidate on write — don't rely on TTL alone for strong consistency needs.
    • Use StringRedisTemplate for plain text/JSON.

    Common mistakes

    • INCR on non-integer string — command error.
    • Giant JSON blobs blocking event loop.
    • Cache without TTL — memory leak.
    • SET NX lock without unique token — unsafe unlock.

    Advanced interview questions

    Q1BeginnerMax string size in Redis?
    512 MB per key (practical limit much lower).
    Q2BeginnerWhat does INCR do?
    Atomically increments integer string; creates at 0 if missing.
    Q3IntermediateSET NX vs XX?
    NX set only if not exists; XX set only if exists.
    Q4IntermediateString vs hash for user object?
    Hash for field updates; string JSON for read-mostly cache blob.
    Q5AdvancedImplement idempotent lock with strings?
    SET lock:resource uuid NX EX 30; release via Lua comparing uuid.

    Summary

    Strings = cache blobs, counters, locks.

    Ready to mark this lesson complete?Track your journey across the entire course.