Back to Caching: Spring Cache & Redis
Q3Question 3 of 5

What are Redis data structures and when do you use each one

Answer: Redis provides five core data structures: String for single values, Hash for object fields, List for ordered sequences, Set for unique collections, and Sorted Set for score-ordered rankings, each optimized for specific access patterns in a banking application.

Key Concepts
  • Redis String stores a single value (text, number, or serialized JSON) and is the simplest data type, used for session tokens and cached balances.
  • Redis Hash stores field-value pairs under one key, ideal for representing an object like an account profile without serializing the entire object.
  • Redis List is an ordered, doubly-linked list used for recent transaction feeds and audit logs.
  • Redis Set is an unordered collection of unique members, perfect for tracking active users or unique login IPs.
  • Redis Sorted Set (ZSet) orders members by a numeric score, ideal for leaderboards, rate limiting counters, and priority queues.
  • Each data structure has specific time complexity guarantees that determine which one to choose for a given use case.
  • Spring Data Redis provides RedisTemplate and StringRedisTemplate to interact with all five data structures from Java.

Definition

Redis provides five core data structures: String for single values, Hash for object fields, List for ordered sequences, Set for unique collections, and Sorted Set for score-ordered rankings, each optimized for specific access patterns in a banking application.
  • String is the most basic Redis type. It holds a single value up to 512 MB: text, numbers, serialized JSON, or binary data.
  • Hash stores multiple field-value pairs under one key, like a mini dictionary. Ideal for caching object properties without serializing the whole object.
  • List is a doubly-linked list of string values. Supports push/pop from both ends, making it ideal for queues and recent-activity feeds.
  • Set is an unordered collection of unique strings. Supports membership checks, unions, intersections, and differences.
  • Sorted Set (ZSet) is a set where each member has a numeric score. Members are automatically sorted by score, making it ideal for leaderboards and time-based expiry.

Think of National Bank of India's back office. A String is a sticky note with one piece of information (Rajesh's session token). A Hash is a customer folder with labeled tabs (name, email, balance, status). A List is the stack of recent transaction slips on the teller's desk, newest on top. A Set is the attendance register of today's unique visitors (no duplicates). A Sorted Set is the VIP customer ranking board sorted by total deposits.

Understanding the Concepts

What is a Redis String?

A String is the simplest Redis data type. It holds a single value: text, a number, serialized JSON, or binary data. The maximum size is 512 MB.

Common banking use cases: session tokens, cached account balances, rate limiting counters, distributed locks.

JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.math.BigDecimal;

@Service
public class SessionService {

    private final StringRedisTemplate redisTemplate;

    public SessionService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void createSession(String sessionId, String customerId) {
        String key = "session:" + sessionId;
        redisTemplate.opsForValue().set(key, customerId,
            Duration.ofMinutes(30));
    }

    public String getCustomerId(String sessionId) {
        return redisTemplate.opsForValue().get("session:" + sessionId);
    }

    public void cacheBalance(String accountId, BigDecimal balance) {
        String key = "balance:" + accountId;
        redisTemplate.opsForValue().set(key, balance.toPlainString(),
            Duration.ofSeconds(60));
    }

    public BigDecimal getCachedBalance(String accountId) {
        String value = redisTemplate.opsForValue()
            .get("balance:" + accountId);
        return value != null ? new BigDecimal(value) : null;
    }
}
TEXT
Redis commands executed:
SET session:abc123 "CUST001" EX 1800
GET session:abc123 -> "CUST001"
SET balance:SAV2001 "75000.00" EX 60
GET balance:SAV2001 -> "75000.00"
OperationCommandTime Complexity
Set valueSET key valueO(1)
Get valueGET keyO(1)
IncrementINCR keyO(1)
Set with expirySET key value EX secondsO(1)

What is a Redis Hash?

A Hash stores multiple field-value pairs under one key. It is like a Java Map stored in Redis. You can get or set individual fields without fetching the entire object.

Banking use case: caching an account profile. You can update the balance field without re-caching the entire account.

JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Map;

@Service
public class AccountCacheService {

    private final StringRedisTemplate redisTemplate;

    public AccountCacheService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void cacheAccount(String accountId, String holderName,
            BigDecimal balance, String type) {
        String key = "account:" + accountId;
        redisTemplate.opsForHash().putAll(key, Map.of(
            "holderName", holderName,
            "balance", balance.toPlainString(),
            "type", type,
            "status", "ACTIVE"
        ));
        redisTemplate.expire(key, java.time.Duration.ofMinutes(10));
    }

    public String getAccountField(String accountId, String field) {
        String key = "account:" + accountId;
        Object value = redisTemplate.opsForHash().get(key, field);
        return value != null ? value.toString() : null;
    }

    public void updateBalance(String accountId, BigDecimal newBalance) {
        String key = "account:" + accountId;
        redisTemplate.opsForHash().put(key, "balance",
            newBalance.toPlainString());
    }

    public Map<Object, Object> getFullAccount(String accountId) {
        return redisTemplate.opsForHash()
            .entries("account:" + accountId);
    }
}
TEXT
Redis commands:
HSET account:SAV2001 holderName "Rajesh Kumar" balance "75000.00" type "SAVINGS" status "ACTIVE"
HGET account:SAV2001 balance -> "75000.00"
HSET account:SAV2001 balance "70000.00"
HGETALL account:SAV2001 -> {holderName: "Rajesh Kumar", balance: "70000.00", type: "SAVINGS", status: "ACTIVE"}
OperationCommandTime Complexity
Set one fieldHSET key field valueO(1)
Get one fieldHGET key fieldO(1)
Set multiple fieldsHMSET key f1 v1 f2 v2O(n)
Get all fieldsHGETALL keyO(n)

What is a Redis List?

A List is a doubly-linked list of string values. You can push to the head (LPUSH) or tail (RPUSH) and pop from either end. It supports range queries by index.

Banking use case: recent transaction feed. Push new transactions to the head and trim to keep only the latest 50.

JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;

@Service
public class RecentTransactionService {

    private static final int MAX_RECENT = 50;
    private final StringRedisTemplate redisTemplate;

    public RecentTransactionService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void addTransaction(String accountId, String txnType,
            BigDecimal amount, String description) {
        String key = "recent-txns:" + accountId;
        String entry = txnType + ":" + amount.toPlainString()
            + ":" + description;

        // Push to head (newest first)
        redisTemplate.opsForList().leftPush(key, entry);

        // Trim to keep only the latest 50
        redisTemplate.opsForList().trim(key, 0, MAX_RECENT - 1);
    }

    public List<String> getRecentTransactions(
            String accountId, int count) {
        String key = "recent-txns:" + accountId;
        return redisTemplate.opsForList().range(key, 0, count - 1);
    }
}
TEXT
Redis commands:
LPUSH recent-txns:SAV2001 "CREDIT:50000.00:Salary deposit"
LTRIM recent-txns:SAV2001 0 49
LPUSH recent-txns:SAV2001 "DEBIT:5000.00:ATM withdrawal"
LTRIM recent-txns:SAV2001 0 49

LRANGE recent-txns:SAV2001 0 4
-> ["DEBIT:5000.00:ATM withdrawal", "CREDIT:50000.00:Salary deposit", ...]
OperationCommandTime Complexity
Push to headLPUSH key valueO(1)
Push to tailRPUSH key valueO(1)
Range queryLRANGE key start stopO(n)
TrimLTRIM key start stopO(n)

What is a Redis Set?

A Set is an unordered collection of unique strings. Duplicate values are automatically ignored. It supports membership checks, intersections, unions, and differences.

Banking use case: tracking active users online, unique login IPs for fraud detection, and customers eligible for a promotion.

JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;

@Service
public class ActiveUserService {

    private final StringRedisTemplate redisTemplate;

    public ActiveUserService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void markActive(String customerId) {
        redisTemplate.opsForSet().add("active-users", customerId);
    }

    public void markInactive(String customerId) {
        redisTemplate.opsForSet().remove("active-users", customerId);
    }

    public boolean isActive(String customerId) {
        Boolean member = redisTemplate.opsForSet()
            .isMember("active-users", customerId);
        return Boolean.TRUE.equals(member);
    }

    public long countActiveUsers() {
        Long size = redisTemplate.opsForSet().size("active-users");
        return size != null ? size : 0;
    }

    public Set<String> getActiveUsers() {
        return redisTemplate.opsForSet().members("active-users");
    }

    public void trackLoginIp(String customerId, String ip) {
        redisTemplate.opsForSet()
            .add("login-ips:" + customerId, ip);
    }

    public Set<String> getLoginIps(String customerId) {
        return redisTemplate.opsForSet()
            .members("login-ips:" + customerId);
    }
}
TEXT
Redis commands:
SADD active-users "CUST001" "CUST002" "CUST003"
SISMEMBER active-users "CUST001" -> true
SCARD active-users -> 3
SMEMBERS active-users -> {"CUST001", "CUST002", "CUST003"}

SADD login-ips:CUST001 "192.168.1.10" "10.0.0.5" "192.168.1.10"
SMEMBERS login-ips:CUST001 -> {"192.168.1.10", "10.0.0.5"}
// Duplicate "192.168.1.10" was ignored automatically.
OperationCommandTime Complexity
Add memberSADD key memberO(1)
Check membershipSISMEMBER key memberO(1)
Count membersSCARD keyO(1)
All membersSMEMBERS keyO(n)
IntersectionSINTER key1 key2O(n*m)

What is a Redis Sorted Set (ZSet)?

A Sorted Set is like a Set, but each member has a numeric score. Members are automatically sorted by score. Ties are broken alphabetically.

Banking use case: top depositor leaderboard, rate limiting with sliding windows, and priority queues for payment processing.

JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import java.util.Set;

@Service
public class LeaderboardService {

    private final StringRedisTemplate redisTemplate;

    public LeaderboardService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void recordDeposit(String customerId, double amount) {
        // ZINCRBY adds to the existing score
        redisTemplate.opsForZSet()
            .incrementScore("leaderboard:deposits",
                customerId, amount);
    }

    public Set<ZSetOperations.TypedTuple<String>> getTopDepositors(
            int count) {
        // Top N by score, descending
        return redisTemplate.opsForZSet()
            .reverseRangeWithScores("leaderboard:deposits",
                0, count - 1);
    }

    public Long getRank(String customerId) {
        // 0-based rank, highest score = rank 0
        return redisTemplate.opsForZSet()
            .reverseRank("leaderboard:deposits", customerId);
    }

    public Double getTotalDeposits(String customerId) {
        return redisTemplate.opsForZSet()
            .score("leaderboard:deposits", customerId);
    }
}
TEXT
Redis commands:
ZINCRBY leaderboard:deposits 50000 "CUST001"
ZINCRBY leaderboard:deposits 120000 "CUST002"
ZINCRBY leaderboard:deposits 30000 "CUST003"
ZINCRBY leaderboard:deposits 25000 "CUST001"

ZREVRANGE leaderboard:deposits 0 2 WITHSCORES
-> ["CUST002": 120000, "CUST001": 75000, "CUST003": 30000]

ZREVRANK leaderboard:deposits "CUST001" -> 1 (second place)
ZSCORE leaderboard:deposits "CUST001" -> 75000
OperationCommandTime Complexity
Add/updateZADD key score memberO(log n)
Increment scoreZINCRBY key increment memberO(log n)
RankZREVRANK key memberO(log n)
Top NZREVRANGE key 0 NO(log n + N)
ScoreZSCORE key memberO(1)

How do you choose the right data structure?

Use CaseBest StructureWhy
Session tokenStringSingle value, TTL for expiry
Cached account balanceStringSingle number with TTL
Account profile cacheHashMultiple fields, update one at a time
Recent transactionsListOrdered, push/trim, range query
Active users onlineSetUnique members, fast membership check
Unique login IPs (fraud)SetAutomatic deduplication
Top depositor leaderboardSorted SetScore-based ranking
Rate limiting (sliding window)Sorted SetTimestamp as score, range count
Payment processing queueList (or Stream)FIFO with RPUSH/LPOP
Feature flagsString or HashSimple key-value or grouped flags
JAVA
// Quick reference: which RedisTemplate method to use
redisTemplate.opsForValue()  // String
redisTemplate.opsForHash()   // Hash
redisTemplate.opsForList()   // List
redisTemplate.opsForSet()    // Set
redisTemplate.opsForZSet()   // Sorted Set
TEXT
// Spring Boot Redis configuration
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.timeout=2000ms
spring.data.redis.lettuce.pool.max-active=20
spring.data.redis.lettuce.pool.max-idle=10

What are common mistakes with Redis data structures?

Mistake 1: Storing entire objects as String JSON when Hash is better

WRONG: Serializing the whole account as JSON to update one field.

JAVA
// WRONG: To update the balance, you must:
// 1. GET the entire JSON
// 2. Deserialize
// 3. Update the field
// 4. Serialize
// 5. SET the entire JSON back
String json = redisTemplate.opsForValue().get("account:SAV2001");
Account account = objectMapper.readValue(json, Account.class);
account.setBalance(new BigDecimal("70000.00"));
redisTemplate.opsForValue().set("account:SAV2001",
    objectMapper.writeValueAsString(account));

CORRECT: Use Hash to update individual fields.

JAVA
// CORRECT: Update only the balance field. No serialization needed.
redisTemplate.opsForHash().put("account:SAV2001",
    "balance", "70000.00");

Mistake 2: Using KEYS * in production

WRONG: Scanning all keys blocks Redis.

JAVA
// WRONG: KEYS * scans every key in the database.
// This blocks Redis for seconds on large datasets.
Set<String> allKeys = redisTemplate.keys("*");

CORRECT: Use SCAN for iterative, non-blocking key discovery.

JAVA
// CORRECT: SCAN iterates incrementally without blocking.
import org.springframework.data.redis.core.ScanOptions;

var cursor = redisTemplate.scan(
    ScanOptions.scanOptions().match("account:*").count(100).build());
while (cursor.hasNext()) {
    String key = cursor.next();
    // process key
}
cursor.close();

What should a senior or principal engineer know?

- Redis Streams. For event-driven banking systems, Redis Streams (XADD, XREAD, XREADGROUP) provide a persistent, consumer-group-aware message log. They are a better choice than Lists for pub-sub and event sourcing.

- Memory optimization. Use OBJECT ENCODING to check how Redis stores a key. Small Hashes use ziplist encoding (compact), but large ones switch to hashtable (more memory). Tune hash-max-ziplist-entries and hash-max-ziplist-value for your data sizes.

- Redis Cluster sharding. Redis Cluster distributes keys across 16384 hash slots. Use hash tags {account}:SAV2001 and {account}:SAV2002 to ensure related keys land on the same shard.

- Pipelining. Batch multiple Redis commands in a single round trip using executePipelined(). This reduces network latency from N round trips to 1.

- Lua scripts for atomicity. When you need to read and write multiple keys atomically, use a Redis Lua script (EVAL). Redis executes the entire script as a single atomic operation.

JAVA
package com.bank.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AtomicTransferService {

    private final StringRedisTemplate redisTemplate;

    private static final String TRANSFER_SCRIPT =
        "local from = KEYS[1]\n" +
        "local to = KEYS[2]\n" +
        "local amount = tonumber(ARGV[1])\n" +
        "local balance = tonumber(redis.call('get', from) or '0')\n" +
        "if balance < amount then return 0 end\n" +
        "redis.call('decrby', from, amount)\n" +
        "redis.call('incrby', to, amount)\n" +
        "return 1";

    public AtomicTransferService(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public boolean transfer(String fromAccount, String toAccount,
            long amount) {
        DefaultRedisScript<Long> script = new DefaultRedisScript<>(
            TRANSFER_SCRIPT, Long.class);
        Long result = redisTemplate.execute(script,
            List.of("balance:" + fromAccount,
                    "balance:" + toAccount),
            String.valueOf(amount));
        return result != null && result == 1;
    }
}
TEXT
// Atomic transfer: SAV2001 -> SAV2002, amount 5000
// Either both DECRBY and INCRBY execute, or neither does.
balance:SAV2001 = 75000 -> 70000
balance:SAV2002 = 120000 -> 125000
Result: 1 (success)

What are common interview follow-up questions?

  • What is the difference between a Hash and a String storing JSON?
  • When would you use a List vs a Stream?
  • How does a Sorted Set maintain order internally (skip list)?
  • How do you implement rate limiting with a Sorted Set?
  • What is Redis pipelining and when do you use it?
  • How do you ensure atomicity across multiple Redis commands?
  • What is the difference between KEYS and SCAN?
  • How does Redis Cluster distribute keys across shards?

Visual Overview

TEXT
  Redis Data Structures
  =====================

  String: key -> "value"
  +------------------+
  | session:abc123   | -> "CUST001"
  | balance:SAV2001  | -> "75000.00"
  +------------------+

  Hash: key -> {field: value, ...}
  +------------------+
  | account:SAV2001  | -> holderName: "Rajesh Kumar"
  |                  |    balance: "75000.00"
  |                  |    type: "SAVINGS"
  +------------------+

  List: key -> [value, value, ...] (ordered)
  +------------------+
  | recent-txns:     | -> ["DEBIT:5000", "CREDIT:50000", ...]
  | SAV2001          |
  +------------------+

  Set: key -> {value, value, ...} (unique)
  +------------------+
  | active-users     | -> {"CUST001", "CUST002", "CUST003"}
  +------------------+

  Sorted Set: key -> {value:score, ...} (sorted by score)
  +------------------+
  | leaderboard:     | -> CUST002:120000
  | deposits         |    CUST001:75000
  |                  |    CUST003:30000
  +------------------+

Key Takeaway

Redis provides five core data structures, and choosing the right one for each use case is the key to an efficient caching layer. Strings hold single values like session tokens and cached balances. Hashes store object properties as separate fields, letting you update one field without re-serializing the whole object. Lists maintain ordered sequences like recent transaction feeds. Sets track unique members like active users and login IPs. Sorted Sets rank members by score for leaderboards and rate limiting.

Each structure has specific time complexity guarantees. String GET/SET is O(1). Hash HGET/HSET is O(1). Set membership check (SISMEMBER) is O(1). Sorted Set operations are O(log n) because of the underlying skip list. These guarantees mean Redis stays fast even with millions of entries.

In a banking application at National Bank of India, you might use a String for Rajesh's session token, a Hash for his account profile, a List for his last 50 transactions, a Set for unique IP addresses he has logged in from, and a Sorted Set for the branch's top depositor leaderboard.

For production systems, use pipelining to batch commands, Lua scripts for atomic multi-key operations, SCAN instead of KEYS to avoid blocking, and Redis Cluster for horizontal scaling. Spring Data Redis provides clean abstractions through StringRedisTemplate and RedisTemplate that map directly to each data structure.

Remember one sentence: String for values, Hash for objects, List for sequences, Set for uniqueness, and Sorted Set for rankings.

---

Share
Use ← → arrow keys to navigate