Usage
Parameters
The name of the function to call. The function must be loaded on the server.
Array of key names that the function will access. These are available in the function as
KEYS[1], KEYS[2], etc.Array of arguments to pass to the function. These are available in the function as
ARGV[1], ARGV[2], etc.Response
The value returned by the Redis function. The type depends on what the function returns.
Examples
Calling a Simple Function
Counter Function
Working with Multiple Keys
Passing Arguments
No Keys or Arguments
FCALL vs FCALL_RO
FCALL
Thefcall command can execute functions that modify data:
FCALL_RO (Read-Only)
UsefcallRo for read-only functions that don’t modify data:
- Can be executed on read replicas
- Are optimized for read-heavy workloads
- Will error if they attempt to modify data
- Provide better performance in distributed setups
Example: Choosing the Right Command
Redis Functions vs Lua Scripts
Functions (FCALL)
Advantages:- Named and organized: Functions have names and can be grouped into libraries
- Persistent: Functions survive server restarts (stored in RDB/AOF)
- Versioned: Can replace functions without affecting running code
- Better management: Use
FUNCTION LIST,FUNCTION DELETE, etc.
Scripts (EVAL/EVALSHA)
Advantages:- Simpler: No need to manage function libraries
- More widely supported: Available in older Redis versions
- Ad-hoc execution: Good for one-off scripts
When to Use FCALL
Use FCALL when:- You have reusable logic used across your application
- You want functions to persist across server restarts
- You need better organization and management of server-side code
- You’re building a complex application with many server-side operations
When to Use EVAL
Use EVAL when:- You need a one-off script
- You’re working with older Redis versions
- You want simpler deployment (no function management)
- You’re prototyping or testing
Loading Functions
Before calling a function, it must be loaded on the server. Here’s an example using the Redis CLI:Error Handling
Best Practices
- Use descriptive function names:
increment_user_counterinstead ofinc - Load functions at startup: Ensure all required functions are loaded when your application starts
- Use FCALL_RO for reads: Take advantage of read replicas for better performance
- Handle errors gracefully: Check if functions are loaded before calling them
- Document your functions: Keep documentation of what each function does and its parameters
- Version your functions: When updating functions, consider versioning strategies