Skip to content

Valkey Scripting Reference

This page contains code references for working with custom Lua scripts in Valkey GLIDE.

GLIDE’s Script interface offers several advantages over using direct EVAL commands via custom_command.

  1. Automatic Caching: Scripts are cached automatically
  2. Better Error Handling: More specific error types
  3. Cluster Support: Automatic routing in cluster mode
  4. Type Safety: Better integration with GLIDE’s type system
  5. Performance: Optimized execution path

The following shows how to covert your EVAL command to GLIDE’s Script interface.

// Old approach with custom commands (not recommended)
Object result = client.customCommand(new String[]{
"EVAL",
"return redis.call('SET', KEYS[1], ARGV[1])",
"1",
"mykey",
"myvalue"
}).get();
// New approach with Script class (recommended)
import glide.api.models.Script;
import glide.api.models.commands.ScriptOptions;
try (Script script = new Script("return redis.call('SET', KEYS[1], ARGV[1])", false)) {
Object result = client.invokeScript(
script,
ScriptOptions.builder()
.key("mykey")
.arg("myvalue")
.build()
).get();
}

The following are common Lua script patterns used by clients.

rate_limit.lua
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local current = redis.call('GET', key)
if current == false then
redis.call('SET', key, 1)
redis.call('EXPIRE', key, window)
return {1, limit}
end
current = tonumber(current)
if current < limit then
local new_val = redis.call('INCR', key)
local ttl = redis.call('TTL', key)
return {new_val, limit}
else
local ttl = redis.call('TTL', key)
return {current, limit, ttl}
end
import glide.api.models.Script;
import glide.api.models.commands.ScriptOptions;
import java.nio.file.Files;
import java.nio.file.Paths;
// Read script from file
String rateLimit = Files.readString(Paths.get("rate_limit.lua"));
try (Script rateLimitScript = new Script(rateLimit, false)) {
// Usage
Object result = client.invokeScript(
rateLimitScript,
ScriptOptions.builder()
.key("rate_limit:user:123")
.arg("10")
.arg("60") // 10 requests per 60 seconds
.build()
).get();
}
acquire_lock.lua
if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'EX', ARGV[2]) then
return 1
else
return 0
end
release_lock.lua
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
else
return 0
end
import glide.api.models.Script;
import glide.api.models.commands.ScriptOptions;
import java.nio.file.Files;
import java.nio.file.Paths;
// Read scripts from files
String acquireLock = Files.readString(Paths.get("acquire_lock.lua"));
String releaseLock = Files.readString(Paths.get("release_lock.lua"));
try (Script acquireLockScript = new Script(acquireLock, false);
Script releaseLockScript = new Script(releaseLock, false)) {
// Acquire lock
Object lockAcquired = client.invokeScript(
acquireLockScript,
ScriptOptions.builder()
.key("lock:resource:123")
.arg("unique_token")
.arg("30") // 30 second expiration
.build()
).get();
if ((Long) lockAcquired == 1) {
try {
// Do work while holding lock
} finally {
// Release lock
client.invokeScript(
releaseLockScript,
ScriptOptions.builder()
.key("lock:resource:123")
.arg("unique_token")
.build()
).get();
}
}
}
conditional_update.lua
local current = redis.call('GET', KEYS[1])
if current == ARGV[1] then
redis.call('SET', KEYS[1], ARGV[2])
return 1
else
return 0
end
import glide.api.models.Script;
import glide.api.models.commands.ScriptOptions;
import java.nio.file.Files;
import java.nio.file.Paths;
// Read script from file
String conditionalUpdate = Files.readString(Paths.get("conditional_update.lua"));
try (Script conditionalUpdateScript = new Script(conditionalUpdate, false)) {
// Update only if current value matches expected
Object updated = client.invokeScript(
conditionalUpdateScript,
ScriptOptions.builder()
.key("user:123:status")
.arg("pending")
.arg("active") // Change from "pending" to "active"
.build()
).get();
}
import glide.api.models.Script;
import glide.api.models.exceptions.RequestException;
// Handle script execution errors
try (Script script = new Script("return redis.call('INCR', 'not_a_number')", false)) {
try {
Object result = client.invokeScript(script).get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof RequestException) {
String message = cause.getMessage();
if (message.contains("WRONGTYPE") || message.contains("not an integer")) {
System.out.println("Type error in script");
} else if (message.toLowerCase().contains("syntax error")) {
System.out.println("Lua syntax error in script");
} else if (message.toLowerCase().contains("unknown command")) {
System.out.println("Invalid Redis command in script");
} else {
System.out.println("Script error: " + message);
}
}
}
}
import glide.api.GlideClient;
import glide.api.models.configuration.GlideClientConfiguration;
import glide.api.models.configuration.NodeAddress;
import glide.api.models.Script;
import glide.api.models.exceptions.RequestException;
// Configure client timeout for long-running scripts
GlideClientConfiguration config = GlideClientConfiguration.builder()
.address(NodeAddress.builder().host("localhost").port(6379).build())
.requestTimeout(30000) // 30 seconds for long scripts (default is usually 5000ms)
.build();
GlideClient client = GlideClient.createClient(config).get();
// Handle long-running scripts
try (Script longScript = new Script("""
local start = redis.call('TIME')[1]
while redis.call('TIME')[1] - start < 25 do
redis.call('GET', 'dummy_key') -- Read-only operation
end
return 'Done'
""", false)) {
try {
Object result = client.invokeScript(longScript).get();
System.out.println("Script completed: " + result);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof RequestException) {
String message = cause.getMessage();
if (message.toLowerCase().contains("timeout")) {
System.out.println("Client timeout - script may still be running on server!");
System.out.println("Consider increasing request_timeout in client configuration");
} else if (message.contains("Script killed")) {
System.out.println("Script was killed by server (only possible for read-only scripts)");
} else {
System.out.println("Script error: " + message);
}
}
}
}
import glide.api.models.exceptions.RequestException;
// Handle cluster routing errors
try {
Object result = clusterClient.invokeScript(
script,
ScriptOptions.builder()
.key("key1")
.key("key2") // Might be in different slots
.build()
).get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof RequestException && cause.getMessage().contains("CROSSSLOT")) {
System.out.println("Keys are in different slots");
// Use hash tags or route explicitly
}
}

1. Use Scripts for Atomic Non-primitive Operations

Section titled “1. Use Scripts for Atomic Non-primitive Operations”
import glide.api.models.Script;
import glide.api.models.commands.ScriptOptions;
// Good: Conditional update with multiple data structures
try (Script conditionalUpdate = new Script("""
local current = redis.call('GET', KEYS[1])
local threshold = tonumber(ARGV[2])
if current and tonumber(current) >= threshold then
redis.call('SET', KEYS[1], ARGV[1])
redis.call('LPUSH', KEYS[2], ARGV[1])
redis.call('EXPIRE', KEYS[2], ARGV[3])
return 1
else
return 0
end
""", false)) {
Object result = client.invokeScript(
conditionalUpdate,
ScriptOptions.builder()
.key("user:score")
.key("user:history")
.arg("100")
.arg("50")
.arg("86400") // new score, threshold, expire in 1 day
.build()
).get();
}
import glide.api.models.Script;
// Good: Proper nil handling
try (Script safeScript = new Script("""
local val = redis.call('GET', KEYS[1])
if val then
return val
else
return 'default_value'
end
""", false)) {
// Use script
}
import glide.api.models.Script;
// Good: Return appropriate types
try (Script typedScript = new Script("""
local value = redis.call('GET', KEYS[1])
return tonumber(value) or 0 -- Ensure numeric return, default to 0 if nil
""", false)) {
// Use script
}
import glide.api.models.Script;
import glide.api.models.commands.ScriptOptions;
// Good: Use hash tags for related keys
try (Script clusterScript = new Script("""
redis.call('SET', KEYS[1], ARGV[1])
redis.call('SET', KEYS[2], ARGV[2])
return 'OK'
""", false)) {
// Execute with hash tags
clusterClient.invokeScript(
clusterScript,
ScriptOptions.builder()
.key("user:{123}:name")
.key("user:{123}:email")
.arg("John")
.arg("john@example.com")
.build()
).get();
}