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

    Hashes

    Hashes map field names to string values under one key — the natural fit for session objects, user profiles, and shopping cart lines where you update individual fields without re…

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

    Introduction

    Hashes map field names to string values under one key — the natural fit for session objects, user profiles, and shopping cart lines where you update individual fields without reading a megabyte JSON blob.

    Small hashes use listpack encoding (extremely compact). HGETALL returns everything; HMGET fetches selected fields in one round trip.

    Netflix-style session stores are typically one hash per sessionId with TTL on the whole key.

    Understanding the topic

    Key concepts

    • HSET key field value — set single or multiple fields.
    • HGET/HMGET — read one or many fields.
    • HGETALL — all fields; watch size on large hashes.
    • HINCRBY — atomic counter on hash field.
    • HDEL, HEXISTS — delete and test field.
    • HSCAN — iterate fields without blocking.

    Step-by-step explanation

    1. Hash stored as listpack or hash table by size.
    2. Field names and values are strings.
    3. TTL applies to entire hash key, not per field.
    4. HSET on new field may trigger encoding upgrade.
    5. Atomic field updates visible atomically to other clients.

    Syntax reference

    Common commands

    • HMGET — partial read without HGETALL.
    • EXPIRE on key — session timeout.
    • HINCRBY — cart quantity updates.
    bash
    HSET session:abc userId 42 device mobile plan pro
    HGET session:abc userId
    HMGET session:abc userId plan
    HINCRBY cart:7 item:sku1 qty 1
    EXPIRE session:abc 3600

    Informative example

    Session hash with Spring — align TTL with JWT expiry:

    java
    @Service
    public class SessionStore {
    private final StringRedisTemplate redis;
    public SessionStore(StringRedisTemplate redis) {
    this.redis = redis;
    }
    public void save(String sessionId, Map<String, String> fields, Duration ttl) {
    String key = "session:" + sessionId;
    redis.opsForHash().putAll(key, fields);
    redis.expire(key, ttl);
    }
    public Map<Object, Object> load(String sessionId) {
    return redis.opsForHash().entries("session:" + sessionId);
    }
    }

    Store userId, roles, device — not PII you wouldn't log. Refresh TTL on each authenticated request.

    Real-world use

    Real-world use cases

    • Web session state — hash per sessionId.
    • Shopping cart — field per line item SKU.
    • User preference flags — HMGET on render path.
    • OAuth token metadata — expires, scope fields.
    • Device fingerprint attributes for fraud scoring.

    Best practices

    • Keep field count modest (<100 fields typical).
    • Use HMGET for partial reads in hot paths.
    • Refresh TTL on activity (sliding session).
    • Don't store multi-KB blobs in hash fields — use string key.
    • Prefix session:userId in key for cluster affinity if needed.
    • HSCAN for admin/debug not production hot path.

    Common mistakes

    • HGETALL on hash with hundreds of large fields.
    • Expecting per-field TTL — only key-level EXPIRE.
    • Storing entire JWT in hash when cookie carries it.
    • No TTL on sessions — zombie keys forever.

    Advanced interview questions

    Q1BeginnerHash vs JSON string?
    Hash allows field-level O(1) update; JSON string rewrites entire value.
    Q2BeginnerHSET vs HMSET?
    HSET accepts multiple field-value pairs; HMSET deprecated alias.
    Q3IntermediateSession storage pattern?
    Hash per sessionId, TTL on key, refresh on request.
    Q4IntermediateHash encoding?
    listpack for small; hash table when large — transparent to client.
    Q5AdvancedScale sessions to 50M concurrent?
    Cluster shard by sessionId; ~2KB/hash; allkeys-lru; Sentinel/Cluster HA.

    Summary

    Hashes model objects with named fields.

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