Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

A service caches account settings in Redis, and the database keeps a version column that increases on every update. Concurrent loaders and writers sometimes overwrite a newer cached value with an older one.

Write a Redis Lua script that stores a value only if its version is newer than the cached one, and show how the Java side calls it.

We store each cached entry as a Redis hash holding the data and its version, and write it through a small Lua script that reads the cached version and only overwrites when the new version is higher, then sets the TTL. Redis runs the script atomically, so the compare and the set cannot interleave with another client. From Java, Spring Data Redis runs it with RedisScript and StringRedisTemplate.execute, which uses EVALSHA and falls back to EVAL; deletes must also respect versions, for example by writing a short-lived tombstone instead of deleting.

Why this question is asked

When several loaders and writers fill the same cache key at once, the last one to arrive wins, even if it carries older data. A version column tells us which value is newer, but comparing versions in Java with a GET followed by a SET brings the race straight back. Interviewers ask for this script to test whether we understand atomicity in Redis and can connect it to real Spring code. In this answer, we will see the broken check-then-set, write and explain the Lua script, call it from Spring Data Redis, make deletes version-aware, and cover Redis Cluster and metrics.

1Why a GET and a SET From Java Are Not Enough

The obvious approach reads the cached version, compares it in Java, and writes if ours is newer. Two clients can run this at the same moment and interleave.

Java
// loader A holds version 7, loader B holds version 8
String cur = redis.opsForHash().get(key, "v"); // A reads: 6 B reads: 6
if (cur == null || Long.parseLong(cur) < 7) { // A: 6 < 7 true
// ... B runs its whole check and writes version 8 here ...
redis.opsForHash().putAll(key, Map.of("v", "7", "d", jsonV7)); // A overwrites 8 with 7
}

The check and the write are two separate round trips, and nothing stops another client from writing between them. So loader A, which checked against version 6, overwrites B's version 8 with its older version 7. We need the compare and the write to happen as one indivisible step on the server.

2The Lua Script

Redis runs a Lua script atomically: while it executes, no other command from any client runs, so the script sees and changes the data as one step. We keep the value and its version together in a hash, a Redis type that holds several fields under one key, here v for the version and d for the data.

SQL
-- set_if_newer.lua KEYS[1] = cache key, ARGV[1] = version, ARGV[2] = data, ARGV[3] = ttl seconds
local cur = redis.call('HGET', KEYS[1], 'v') -- false if the key or field is missing
if cur and tonumber(cur) >= tonumber(ARGV[1]) then
return 0 -- cached version is the same or newer: reject
end
redis.call('HSET', KEYS[1], 'v', ARGV[1], 'd', ARGV[2]) -- store version and data together
redis.call('EXPIRE', KEYS[1], ARGV[3]) -- keep a TTL as the safety net
return 1 -- stored

Notice three details. A missing field comes back to Lua as false, so the first condition simply skips the comparison for a new key. Arguments always arrive as strings, so tonumber is needed, or the comparison would be by text and 10 would sort before 9. And the TTL is still set on every write, because versioning protects against older values, not against invalidations we never saw.

3Calling the Script From Spring Data Redis

Spring Data Redis wraps a script in a RedisScript object with its result type. Lua integers come back as Long. StringRedisTemplate serialises keys and arguments as plain strings, which is what the script expects.

Java
@Component
class SettingsCache {
private static final RedisScript<Long> SET_IF_NEWER =
RedisScript.of(new ClassPathResource("redis/set_if_newer.lua"), Long.class);
private final StringRedisTemplate redis;
private final MeterRegistry meters;
SettingsCache(StringRedisTemplate redis, MeterRegistry meters) { this.redis = redis; this.meters = meters; }
boolean put(long accountId, long version, String json) {
Long r = redis.execute(SET_IF_NEWER, List.of("settings:" + accountId),
String.valueOf(version), json, "3600");
if (r == 0) meters.counter("cache.settings.stale_write_rejected").increment();
return r == 1; // true: stored, false: a newer version was cached
}
Optional<String> get(long accountId) {
Object d = redis.opsForHash().get("settings:" + accountId, "d");
return Optional.ofNullable((String) d); // empty: miss, load from the database
}
}

The template does not send the script text every time. It computes the script's SHA1 digest and sends EVALSHA with it, and if Redis replies that it does not know the script, for example after a restart, it falls back to EVAL with the full text, which also loads it. So the script costs one round trip like any other command.

4Where the Version Comes From

The version must describe exactly the data we are caching, so the loader reads it in the same query as the data, from the same row: SELECT settings_json, version FROM account_settings WHERE account_id = ?. Reading the version in a separate query could pair new data with an old version or the other way round. Writers increase the version in the same UPDATE that changes the data, for example SET version = version + 1, and JPA's @Version column does exactly this.

5Deletes Must Respect Versions Too

A delete-on-write throws away the version information. If a writer deletes the key after committing version 9, and a slow loader then arrives with version 8, the script finds no cached version and stores 8. The old data is back. The fix is to write a tombstone instead of deleting: a marker entry that records the new version and a short TTL but holds no data.

SQL
-- invalidate.lua KEYS[1] = cache key, ARGV[1] = new version, ARGV[2] = tombstone ttl seconds
local cur = redis.call('HGET', KEYS[1], 'v')
if cur and tonumber(cur) >= tonumber(ARGV[1]) then return 0 end
redis.call('DEL', KEYS[1])
redis.call('HSET', KEYS[1], 'v', ARGV[1], 't', '1') -- tombstone: version only, no data
redis.call('EXPIRE', KEYS[1], ARGV[2]) -- for example 60 seconds
return 1
Step throughA late loader meets a tombstone
WriterSlow loaderRedis
read row: version 8
commit version 9
invalidate.lua version 9
1: tombstone v=9 stored
set_if_newer.lua version 8
0: rejected, 9 is newer

6 messages in order. Play them, or step through them one at a time.

Without the tombstone, the loader's set would find an empty key and store version 8.

Readers treat an entry without d as a miss. The loader for version 9 must still be able to replace the tombstone, so set_if_newer rejects a write only when the cached version is higher, or equal and not a tombstone (HEXISTS of t returns 0), and removes the t field when it stores data. A loader carrying version 8 is still rejected, as the diagram shows.

6Redis Cluster and Measuring the Race

In Redis Cluster every key belongs to one hash slot on one node, and a script may only touch keys in the same slot. Our scripts touch exactly one key, passed in KEYS, so they are safe in a cluster without any hash tags. Passing the key through KEYS rather than building it inside the script matters, because the client uses KEYS to route the call to the right node.

Finally, every rejected write, a 0 result, is a race that would have corrupted the cache. Counting them as a metric, as the Java code does, tells us how often the race really happens, which is useful evidence when someone later asks whether the script is worth keeping.

7Follow-up questions

How would loaders know which version they read from the database?

They select the version column in the same query and the same row as the data, so both come from one consistent snapshot of the row. The writer increases the version in the same UPDATE statement, or JPA does it through a @Version field, so every committed change has a unique, increasing version.

Why not use WATCH and MULTI instead of Lua?

WATCH and MULTI give optimistic locking: the transaction fails if the watched key changed, and the client retries. It works, but it needs extra round trips and retry logic in Java, and under contention it can retry repeatedly. A Lua script does the compare and the write in one atomic step on the server, so it is simpler and faster for this case.

8Conclusion

In this answer, we saw that a GET followed by a SET lets an older loader overwrite a newer value, and replaced it with a Lua script that keeps version and data together in a hash, rejects writes whose version is not newer, and sets a TTL, all atomically. Spring Data Redis runs it with RedisScript and StringRedisTemplate.execute through EVALSHA with an EVAL fallback. Loaders read the version with the data, deletes become versioned tombstones so an old load cannot come back, the single-key scripts are safe in Redis Cluster, and rejected writes are counted as a metric of the race.

What to say in the interviewAbout 90 seconds aloud

Open with

The race comes from doing the version check and the write as two separate commands, so I would move both into one Lua script, because Redis runs a script atomically and nothing can interleave with it.

Then, if they want more

I keep the value and its version together in a hash with fields v and d. The script does HGET of v, and if a version exists and it is greater than or equal to mine, it returns 0. Otherwise it does HSET of v and d, sets an EXPIRE as a safety net, and returns 1.

Arguments arrive as strings, so I use tonumber for the comparison. In Java I create RedisScript.of with the script and Long.class, and call stringRedisTemplate.execute with the key in the keys list and the version, the JSON and the TTL as arguments; the template uses EVALSHA and falls back to EVAL if Redis has not loaded the script.

Loaders must read the version in the same query as the data. Deletes are the catch: if a writer deletes the key, an old loader finds nothing to compare and writes old data back, so I write a short-lived tombstone with the new version instead of deleting.

The script touches a single key, so it works in Redis Cluster, and I count rejected writes as a metric of how often the race happens.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a Redis Lua script that stores a value only if its version is newer than the...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/df62005c7c/