Skip to content

Load and Execute Functions

Valkey scripting allows you to execute Lua code directly on the Valkey server. This guide will go over executing custom Lua scripts with GLIDE.

  • Running Valkey server (standalone or cluster)
  • GLIDE installed.

Valkey Functions is an alternative for persistent server-side Lua code. The following example shows a simple example of loading and executing a Valkey Function using GLIDE.

  1. Define the lua script.

    lua_code = """#!lua name=example_module
    server.register_function('set_then_get', function(key, value)
    server.call('SET', key, value)
    return server.call('GET', key)
    end)
    """
  2. Load the function to Valkey.

    await client.function_load(lua_code, replace=True)
  3. Call the function.

    await client.set("page:home:visits", "0")
    result = await client.fcall("set_then_get", keys=["page:home:visits"], args=["1"])
    print(result) # b'1'
Full Example
import asyncio
from glide import Script, GlideClient, GlideClientConfiguration, NodeAddress
async def main():
config = GlideClientConfiguration(addresses=[NodeAddress("localhost", 6379)])
client = await GlideClient.create(config)
# lua code that updates a key and returns its new value
lua_code = """#!lua name=page_visits
server.register_function('update_visits', function(visits)
server.call('INCR', visits[1])
return server.call('GET', visits[1])
end)
"""
# loading the function to valkey
await client.function_load(lua_code, replace=True)
await client.set("page:home:visits", "0")
# calling the previously loaded function
result = await client.fcall("update_visits", keys=["page:home:visits"])
print(result) # b'1'
if __name__ == "__main__":
asyncio.run(main())

GLIDE clients implement FCALL_RO command to execute read-only functions.

result = await client.fcall_ro("get_value", keys=["mykey"])

With Routing (Cluster Mode)

from glide.routes import AllNodes, AllPrimaries, RandomNode
# Route to all nodes
result = await client.fcall_ro_route("get_value", AllNodes())
# Route to all primary nodes
result = await client.fcall_ro_route("get_value", AllPrimaries())
# Route to a random node
result = await client.fcall_ro_route("get_value", RandomNode())

For more on Valkey Function, visit the Valkey documentations.