Skip to content

Valkey Scripting

Valkey GLIDE provide a scripting interface through the Script class, allowing you to manage and execute custom logic directly on the server. This page will explain how GLIDE handles Valkey scripting and its features.

For more detail on just Valkey scripting, visit the Valkey documentation.

GLIDE script provide the following advantages:

  • Automatic Caching: Scripts are cached server-side using SHA1 hashes, improving performance and reducing overhead
  • Cluster Support: Scripts work seamlessly in both standalone and cluster modes
  • Management: Built-in support for script routing and lifecycle management

Valkey GLIDE provides a Script class that wraps Valkey’s Lua scripts and handles their execution efficiently.

import glide.api.GlideClient;
import glide.api.models.Script;
import glide.api.models.configuration.GlideClientConfiguration;
import glide.api.models.configuration.NodeAddress;
// Create a client
GlideClientConfiguration config = GlideClientConfiguration.builder()
.address(NodeAddress.builder().host("localhost").port(6379).build())
.build();
GlideClient client = GlideClient.createClient(config).get();
// Create a simple script
Script script = new Script("return 'Hello, Valkey!'", false);
CompletableFuture<Object> result = client.invokeScript(script);
System.out.println(result.get()); // Hello, Valkey!

Valkey provides KEYS and ARGV to handle input parameters:

  • KEYS: Used to pass key names in Valkey (e.g., product:123)
  • ARGV: Used for general input parameters
import glide.api.models.commands.ScriptOptions;
String productKey = "product:shoe:stock";
String buyQuantity = "3";
CompletableFuture<Object> result = client.invokeScript(
purchaseScript,
ScriptOptions.builder()
.key(productKey) // Maps to KEYS[1] in Lua
.arg(buyQuantity) // Maps to ARGV[1] in Lua
.build()
);

Scripts are executed physically on a node and thus it is important for the node to contain the keys being accessed.

GLIDE handle this by send the script to the correct node based on the KEYS provided. If no KEYS are provided, GLIDE will route the script to a random node for execution. Thus, hardcoding the keys will most likely lead to errors.

For proper execution, make sure to:

  • Pass all accessed keys via the KEYS argument
  • Only interact with keys listed in KEYS
  • KEYS must belong to the same slot (use hashtags like user:{100}:name if needed)

Another benefit is that using ARGV and KEYS allows for efficient caching of scripts. Since Valkey caches scripts based on their SHA1 hash of the code, hardcoding changing values directly into the script would create unique scripts each time, preventing effective caching.

// Bad: Creates a new hash for each quantity
Script badScript = new Script("return redis.call('DECRBY', " + productKey + ", " + buyQuantity + ")", false);
// Good: Reuses the same cached script
Script goodScript = new Script("return redis.call('DECRBY', KEYS[1], ARGV[1])", false);
CompletableFuture<Object> result = client.invokeScript(
goodScript,
ScriptOptions.builder().key(productKey).arg(buyQuantity).build()
);

When you create a Script object in GLIDE, it is hashed using SHA1. GLIDE then automatically caches scripts with each invoke_script() call.

Script script = new Script("return 'Hello'", false);
String hashValue = script.getHash();
System.out.println("Script hash: " + hashValue); // SHA1 hash of the script

Scripts with identical code produce identical hashes, enabling efficient caching and reuse.

Script script1 = new Script("return 'Hello'", false);
Script script2 = new Script("return 'Hello'", false);
assert script1.getHash().equals(script2.getHash()); // Same hash

Scripts remain cached on the Valkey server until:

  • The server restarts
  • Memory pressure triggers eviction
  • You explicitly flush the cache with script_flush() All of which are handled automatically by GLIDE.

To learn more about script lifecycle, see Valkey’s documentation.

A script can be safely killed if it has only performed read-only operations. However, once it executes any write operation, it becomes uninterruptible and must either run to completion or reach a timeout. This prevents data corruption as once a script modifies data it must complete to ensure consistency.

read-only.lua
-- Read-only script
local start = server.call('TIME')[1]
while server.call('TIME')[1] - start < 10 do
server.call('GET', 'some_key') -- Read-only
end
return 'Done'
with-write.lua
-- This script writes data - cannot be killed after the SET
server.call('SET', 'temp', 'value') -- Write operation
local start = server.call('TIME')[1]
while server.call('TIME')[1] - start < 10 do
-- Long operation after write
end
return 'Done'

Valkey executes scripts atomically in a single-threaded manner. While a script runs:

  • No other commands can execute
  • The script has exclusive access to the data
  • All operations within the script are guaranteed to complete without interruption

In cluster mode, Valkey distributes data across multiple nodes using hash slots. Each key is mapped to one of 16,384 slots based on its hash:

slot = CRC16(key) mod 16384

GLIDE automatically route scripts to the appropriate nodes. When executing a script in cluster mode, all KEYS must belong to the same shard.

// This works the same in cluster mode
Script script = new Script("return redis.call('SET', KEYS[1], ARGV[1])", false);
CompletableFuture<Object> result = clusterClient.invokeScript(
script,
ScriptOptions.builder()
.key("user:1000") // Routed based on key hash
.arg("John")
.build()
);

GLIDE provide options for explicit control over script routing in cluster mode.

import static glide.api.models.configuration.RequestRoutingConfiguration.Route.ALL_PRIMARIES;
import glide.api.models.configuration.RequestRoutingConfiguration.SlotKeyRoute;
import glide.api.models.configuration.RequestRoutingConfiguration.SlotType;
// Route to the node holding a specific key's slot
SlotKeyRoute route = new SlotKeyRoute("user:1000", SlotType.PRIMARY);
// Route to all primary nodes
CompletableFuture<Object> result = clusterClient.invokeScript(script, ALL_PRIMARIES);

In cluster mode, scripts that access multiple keys must ensure all keys belong to the same slot. Adding a hash tag {} in the key allow you to specify the specific slot.

// Both keys hash to the same slot because of {1000}
String[] keys = {"user:{1000}:name", "user:{1000}:email"};

To lean more about hash tags, see the documentation.

Currently, invoke_script is not supported in batch operations (pipelines/transactions). To use Lua scripts within an atomic batch (MULTI/EXEC transaction), you must use the EVAL command with custom_command.

// Script with keys and arguments
Transaction transaction = new Transaction();
transaction.customCommand(new String[]{
"EVAL",
"return redis.call('SET', KEYS[1], ARGV[1])",
"1", // Number of keys
"script-key", // Key
"script-value" // Argument
});
transaction.get("script-key");
CompletableFuture<Object[]> results = client.exec(transaction);
System.out.println("EVAL result: " + results.get()[0]); // OK
System.out.println("GET result: " + results.get()[1]); // script-value

To learn how execute custom scripts in practice, check out the guide on Valkey scripting.

See our reference page for more examples of custom scripts in GLIDE.

You can learn more about Valkey scripting in the Valkey documentation.