> ## Documentation Index
> Fetch the complete documentation index at: https://upstash.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# FUNCTION LOAD

> Load a library.

Use `FUNCTION LOAD` to register a library of functions in the database.

The payload is the library source code. It must begin with a shebang line naming the engine and the library, such as `#!lua name=mylib`, and register each function with `redis.register_function`, giving it a name, a callback, and optional flags such as `no-writes`. The reply is the library name.

`allow-key-locking` is one of those flags. It opts a function out of the global lock so that a call locks only the keys passed in its key list, which lets calls on disjoint keys run in parallel. Unlike Lua scripts, where the flag goes on the shebang line, it is declared per function in `redis.register_function`, and it is fixed until the library is loaded again. See [Key-Based Locking](/docs/redis/features/key-locking).

Whether or not you set that flag, write functions so that every key they touch arrives in the key list rather than being assembled from `ARGV` inside the function, since an undeclared key can force a disk read while the lock is held. See [Dynamic Keys and Latency](/docs/redis/features/key-locking#dynamic-keys-and-latency).

Loading fails when the library name is already in use unless `REPLACE` is given, which is how you deploy a new version of a library. Once loaded, functions are called by name with [`FCALL`](/docs/redis/commands/functions/fcall) or [`FCALL_RO`](/docs/redis/commands/functions/fcall-ro). Unlike scripts cached by [`SCRIPT LOAD`](/docs/redis/commands/scripting/script-load), libraries are part of the dataset, so they survive restarts and do not need to be re-sent by clients.

## Syntax

```redis theme={"system"}
FUNCTION LOAD [REPLACE] <function-code>
```

## Arguments

| Argument          | Required | Repeatable | Description                                                   |
| ----------------- | -------- | ---------- | ------------------------------------------------------------- |
| `REPLACE`         | No       | No         | Allow replacement of an existing destination.                 |
| `<function-code>` | Yes      | No         | Library source, including its `#!lua name=<library>` shebang. |

## Response

The reply reports the result of the operation. Error replies have the same shape in RESP2 and RESP3 and are surfaced as exceptions by the SDKs below.

| Protocol | Reply       |
| -------- | ----------- |
| RESP2    | Bulk string |
| RESP3    | Bulk string |

<Note>
  Client libraries often decode bulk strings, maps, sets, and numeric strings into language-native values. The table describes the Redis wire reply.
</Note>

## Examples

TCP examples use the TLS `REDIS_URL` from the Upstash console. REST examples use `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.

<AccordionGroup>
  <Accordion title="Redis CLI" icon="terminal">
    ```bash theme={"system"}
    FUNCTION LOAD "#!lua name=mylib\nredis.register_function('helloworld', function() return 'Hello World!' end)"
    ```
  </Accordion>

  <Accordion title="@upstash/redis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import { Redis } from "@upstash/redis";

    const redis = Redis.fromEnv();

    const code = `#!lua name=mylib

      -- Simple function that returns a string
      redis.register_function(
        'helloworld',
        function() return 'Hello World!' end
      )

      -- Complex function that modifies data with logic
      local function my_hset(keys, args)
        local hash = keys[1]
        local time = redis.call('TIME')[1]
        return redis.call('HSET', hash, '_last_modified_', time, unpack(args))
      end

      redis.register_function('my_hset', my_hset)
    `;

    const libraryName = await redis.functions.load({ code, replace: true });

    console.log(libraryName); // "mylib"
    ```
  </Accordion>

  <Accordion title="upstash_redis" icon="python" iconType="brands">
    <Note>
      This command is not supported yet in `upstash_redis`.
    </Note>
  </Accordion>

  <Accordion title="ioredis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import Redis from "ioredis";

    const redis = new Redis(process.env.REDIS_URL!);
    const result = await redis.function("LOAD", "function-code");
    console.log(result);
    ```
  </Accordion>

  <Accordion title="node-redis" icon="node-js" iconType="brands">
    ```ts theme={"system"}
    import { createClient } from "redis";

    const client = await createClient({ url: process.env.REDIS_URL })
      .on("error", console.error)
      .connect();
    const result = await client.functionLoad("function-code");
    console.log(result);
    ```
  </Accordion>

  <Accordion title="redis-py" icon="python" iconType="brands">
    ```python theme={"system"}
    import os
    import redis

    client = redis.from_url(os.environ["REDIS_URL"])
    result = client.function_load("function-code")
    print(result)
    ```
  </Accordion>

  <Accordion title="go-redis" icon="golang" iconType="brands">
    ```go theme={"system"}
    package main

    import (
        "context"
        "fmt"
        "os"

        "github.com/redis/go-redis/v9"
    )

    func main() {
        opts, err := redis.ParseURL(os.Getenv("REDIS_URL"))
        if err != nil {
            panic(err)
        }
        client := redis.NewClient(opts)
        result, err := client.FunctionLoad(context.Background(), "function-code").Result()
        if err != nil {
            panic(err)
        }
        fmt.Println(result)
    }
    ```
  </Accordion>

  <Accordion title="jedis" icon="java" iconType="brands">
    ```java theme={"system"}
    import java.net.URI;

    import redis.clients.jedis.Jedis;

    try (Jedis jedis = new Jedis(new URI(System.getenv("REDIS_URL")))) {
      Object result = jedis.functionLoad("function-code");
      System.out.println(result);
    }
    ```
  </Accordion>

  <Accordion title="redis-rs" icon="rust" iconType="brands">
    ```rust theme={"system"}
    fn main() -> redis::RedisResult<()> {
        let url = std::env::var("REDIS_URL").expect("REDIS_URL is not set");
        let client = redis::Client::open(url)?;
        let mut connection = client.get_connection()?;

        let mut command = redis::cmd("FUNCTION");
        command.arg("LOAD");
        command.arg("function-code");
        let result: redis::Value = command.query(&mut connection)?;
        println!("{result:?}");
        Ok(())
    }
    ```
  </Accordion>
</AccordionGroup>


## Related topics

- [FUNCTION LOAD](/docs/redis/sdks/ts/commands/functions/load.md)
- [Overview](/docs/redis/sdks/ts/commands/overview.md)
- [FCALL](/docs/redis/commands/functions/fcall.md)
- [Key-Based Locking](/docs/redis/features/key-locking.md)
- [Changelog](/docs/redis/overall/changelog.md)
