Definition
- 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.
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;
}
}
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"
| Operation | Command | Time Complexity |
|---|---|---|
| Set value | SET key value | O(1) |
| Get value | GET key | O(1) |
| Increment | INCR key | O(1) |
| Set with expiry | SET key value EX seconds | O(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.
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);
}
}
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"}
| Operation | Command | Time Complexity |
|---|---|---|
| Set one field | HSET key field value | O(1) |
| Get one field | HGET key field | O(1) |
| Set multiple fields | HMSET key f1 v1 f2 v2 | O(n) |
| Get all fields | HGETALL key | O(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.
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);
}
}
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", ...]
| Operation | Command | Time Complexity |
|---|---|---|
| Push to head | LPUSH key value | O(1) |
| Push to tail | RPUSH key value | O(1) |
| Range query | LRANGE key start stop | O(n) |
| Trim | LTRIM key start stop | O(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.
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);
}
}
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.
| Operation | Command | Time Complexity |
|---|---|---|
| Add member | SADD key member | O(1) |
| Check membership | SISMEMBER key member | O(1) |
| Count members | SCARD key | O(1) |
| All members | SMEMBERS key | O(n) |
| Intersection | SINTER key1 key2 | O(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.
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);
}
}
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
| Operation | Command | Time Complexity |
|---|---|---|
| Add/update | ZADD key score member | O(log n) |
| Increment score | ZINCRBY key increment member | O(log n) |
| Rank | ZREVRANK key member | O(log n) |
| Top N | ZREVRANGE key 0 N | O(log n + N) |
| Score | ZSCORE key member | O(1) |
How do you choose the right data structure?
| Use Case | Best Structure | Why |
|---|---|---|
| Session token | String | Single value, TTL for expiry |
| Cached account balance | String | Single number with TTL |
| Account profile cache | Hash | Multiple fields, update one at a time |
| Recent transactions | List | Ordered, push/trim, range query |
| Active users online | Set | Unique members, fast membership check |
| Unique login IPs (fraud) | Set | Automatic deduplication |
| Top depositor leaderboard | Sorted Set | Score-based ranking |
| Rate limiting (sliding window) | Sorted Set | Timestamp as score, range count |
| Payment processing queue | List (or Stream) | FIFO with RPUSH/LPOP |
| Feature flags | String or Hash | Simple key-value or grouped flags |
// Quick reference: which RedisTemplate method to use
redisTemplate.opsForValue() // String
redisTemplate.opsForHash() // Hash
redisTemplate.opsForList() // List
redisTemplate.opsForSet() // Set
redisTemplate.opsForZSet() // Sorted Set
// 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.
// 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.
// 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.
// 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.
// 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.
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;
}
}
// 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
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.
---