Redis data and TTL
What you will learn
Redis is a networked data store that can serve as a shared cache. A TTL is a time-to-live attached to a key; it limits how long the key survives without renewal. Use a single write-with-expiry command and distinguish absent keys, persistent keys and transient failures.
- Interpret TTL return values and write-with-expiry behavior.
- Choose bounded Redis keys and serialization.
- Model expiry deterministically without wall-clock sleeps.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. External cache and broker examples require the companion lab or configured infrastructure. Their predicted results are not execution evidence.
Expiry at a logical clock boundary
public class Main { record Entry(int stock,long deadline) {} public static void main(String[] args) {var entry=new Entry(5,60); for(long now:new long[]{0,59,60,61})System.out.println(now+":"+(now<entry.deadline()?entry.stock():"miss")); }}Expected output:
0:559:560:miss61:missLogical time avoids sleeps and tests the selected policy, not Redis expiration scheduling.
Data types and expiry
Redis strings hold byte sequences, hashes group fields, sets represent unique members, sorted sets associate scores, and streams represent append-oriented records. Pick the simplest representation for the query. In Redis 7.4, SET with EX attaches seconds of expiry in the same operation; plain SET replaces the value and clears prior expiry unless KEEPTTL or a new expiration is requested. TTL returns -2 for missing keys and -1 for present keys with no expiry; nonnegative values are remaining seconds. Expiration is not a scheduler or an exact notification mechanism.
Network failure and serialization
A local cache avoids a network trip but lives separately in each replica. A shared cache adds network latency, operational cost and failure modes. Use bounded timeouts, explicit string or schema-validated JSON encodings, limited key cardinality and value size. Redis eviction under maxmemory can remove keys before TTL. Configure security and tenant authorization separately. Spring Data Redis StringRedisTemplate handles string data; RedisCacheConfiguration can configure entryTtl and serializers. A failed write or read can leave uncertain state; never infer absence from a timeout.
Model TTL states
public class Main { record Entry(Long deadline) {} static long ttl(Entry e,long now){if(e==null)return -2;if(e.deadline()==null)return -1;return e.deadline()<=now?-2:e.deadline()-now;} public static void main(String[] args) {System.out.println(ttl(null,10)); System.out.println(ttl(new Entry(null),10)); System.out.println(ttl(new Entry(30L),10)); System.out.println(ttl(new Entry(10L),10)); }}Expected output:
-2-120-2The model uses whole seconds and treats expiry as logical absence; actual Redis timing is not tested.
SET with expiry and TTL inspection
Source-reviewed, NOT RUN. File lab-fixtures/cache-messaging-v44/redis-session.txt; use the companion lab README.
# Individual redis-cli commands on a disposable Redis 7.4 instance.# Not a shell script; run one line at a time after connecting to the isolated lab.SET lab:tenant-a:B1 5 EX 60GET lab:tenant-a:B1TTL lab:tenant-a:B1SET lab:tenant-a:B1 6 KEEPTTLTTL lab:tenant-a:B1DEL lab:tenant-a:B1TTL lab:tenant-a:B1Predicted behavior: OK, value 5, positive TTL, OK, positive TTL, deletion count 1, then -2.
Run promptly on a disposable server; observed TTL depends on elapsed time.
Spring Redis string adapter
Source-reviewed, NOT RUN. File lab-fixtures/cache-messaging-v44/RedisCatalog.java; use the companion lab README.
// Fragment: StringRedisTemplate supplied by a configured Spring Data Redis context.import java.time.Duration;import org.springframework.data.redis.core.StringRedisTemplate;public class RedisCatalog { private final StringRedisTemplate redis; public RedisCatalog(StringRedisTemplate redis) { this.redis = redis; } public void put(String tenant, String sku, int stock) { redis.opsForValue().set(key(tenant, sku), Integer.toString(stock), Duration.ofSeconds(60)); } public String get(String tenant, String sku) { return redis.opsForValue().get(key(tenant, sku)); } public void invalidate(String tenant, String sku) { redis.delete(key(tenant, sku)); } private String key(String tenant, String sku) { if (!tenant.matches("[a-z0-9-]{1,32}") || !sku.matches("[A-Z0-9]{1,16}")) throw new IllegalArgumentException("invalid key component"); return "lab:" + tenant + ":" + sku; }}Predicted behavior: A write stores a string with 60-second TTL; missing get returns null.
Caller must handle connection exceptions distinctly from absent values.
Common mistakes
Do not split SET and EXPIRE if a crash between commands can create a permanent entry. Do not use a Redis key as the only durable deduplication marker if expiry or eviction would repeat a business effect.
Practice
Model a 15-second cache entry created at t=10. Print whether it is fresh at t=24, t=25 and t=26.
Expected output:
truefalsefalseCompare with the manual review criteria.
Official reading: Redis SET · Redis TTL · Redis DEL · Spring Redis. Cache and broker execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Redis data and TTL — knowledge check
Cache and messaging reasoning.
What does Redis TTL -2 mean?
What does TTL -1 mean?
How do you set a string and expiry atomically?
What can evict a key before its TTL?
What does a Redis read timeout establish?