Table of contents
1.
Introduction
2.
Scripting Properties 
3.
Example
4.
Interacting with Redis Using Script
5.
Script cache
6.
Script Command
7.
Frequently Asked Questions
7.1.
What is Redis scripting?
7.2.
What is the Redis pipeline?
7.3.
What is Redis EVALSHA?
7.4.
What are the benefits of Redis?
7.5.
What data is stored in Redis?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Scripting with Lua In Redis

Author yuvatimankar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Redis stands for Remote Dictionary Server. It is an in-memory database that is used as a cache on top of other databases to improve the application performance; however, Redis is a fully-fledged primary Database that can store and persist multiple data formats for complex applications. The purpose of redis scripting is to evaluate scripts using the Lua interpreter.

Source:micro.medium 

Redis allows users to upload and execute Lua Scripts on the server. Redis Scripts can use programmatic control structures and use many of the commands while executing to access the database. Because Redis scripts are carried out on the server, reading and writing data from the server is very efficient. Redis script ensures atomic execution, which means while executing the redis script, the entire server activities are blocked during its whole runtime. 

The scripts could be a prominent choice for creating a simulation before the implementation and experimentation because it is quite flexible and is way faster.

Scripting Properties 

Redis Scripting offers various properties that can be invaluable in many cases. Properties are:

  • Redis scripts are providing locality by executing logic where data lives. This locality of data reduces overall delay and saves networking resources.
  • Redis script blocks the semantics that ensures the script's atomic execution.
  • Redis script enables the composition of simple capabilities that are either missing from Redis or are too the alcove to a part of it.

 

Lua enables you to run part of your application logic inside Redis Scripts. These types of Redis scripts can perform conditional updates across multiple keys, possibly combining multiple different data types.

Example

We will start Script by using the EVAL command.

> EVAL “return ‘Hello, Ninja! ‘ “ 0
   “Hello, Ninja!”

 

In the above example, EVAL has taken two arguments; the first argument is a string with redis script’s Lua source code. The Redis script doesn't need to include any definitions of the Lua function. Just a Lua program will run in the Redis engine’s context. The second argument is the number of arguments that follow the redis script’s body; in the above example, we have used the value 0 because we didn’t provide the script with any argument.

Interacting with Redis Using Script

We can call Redis  commands from a Lua script either via Redis.call() or Redis.pcall(). The two are nearly the same. Both carry out a Redis command and its provided arguments if these represent a well-formed command. The difference between the two functions lies in how runtime errors are handled. From calling redis.call(), raised errors are returned directly to the client who had executed it. On the contrary, errors were encountered when calling the redis.pcall() functions are returned to the script’s execution context instead for possible handling.

For example,

> EVAL “return redis.call(‘SET’ , KEYS [1], ARGV [1] )” 1 foo bar
   OK

 

The Lua script in Redis accepts one key name and one value as its input argument in the example. When executed, the script calls the SET command to set the input key, foo, with the string value “bar.”

Script cache

Until now, we have used the EVAL command to script run redis. Whenever we call EVAL, we add the lua script’s source code with the request. Calling EVAL, again and again, to execute the same set of parameterized scripts wastes both network bandwidth and has some Redis script overheads.


source: medium

Redis Script that we execute with EVAL is stored in a dedicated cache that the server keeps. The script's SHA1 digest sums organize the content of the cache; thus, the SHA1 digest sum of a script uniquely identifies it in the cache. You can verify this activity by running EVAl and calling INFO after that. You will see that the used_memory_scripts_eval and number_of_cached_scripts metrics grow with every new script executed. Dynamically generated scripts are an anti-pattern. During the applications runtime generating redis scripts may exhaust the host’s memory resources for caching them. Rather, scripts should be as generic as possible and provide customized execution via argument. 

A Redis script is loaded to the server’s cache and provides its source code by calling the SCRIPT LOAD command. The server does not execute the script, instead, it just compiles and loads it to the server’s cache. Once it is loaded, you can execute the cached redis script with the SHA1 digest returned from the server.

Example,

redis> SCRIPT LOAD "return 'Immabe a cached script'"
"c664a3bf70bd1d45c4284ffebb65a6f2299bfc9f"
redis> EVALSHA c664a3bf70bd1d45c4284ffebb65a6f2299bfc9f 0
"Immabe a cached script"

 

Cache volatility

The Redis script cache is volatile always. It is not persisted and isn't considered as a part of the database. Applications that use redis scripts should always call EVALSHA to execute them.

redis> EVALSA fffffffffffffffffffffffffffffffffffff 0
(error) NOSCRIPT No matching script

Script Command

A few of the redis scripting command is mentioned below:

  • SCRIPT FLUSH: This command is the only method to force the script to flush the redis script's cache. It is useful in environments where the same Redis instance is assigned to different uses. 
  • SCRIPT EXISTS: This command returns an array of 0’s and 1’s when given one or more SHA1 digest as an argument. 1 means SHA1 is perceived as a redis script already present in the scripting cache, and 0 means a script with this SHA1 was not loaded before.
  • SCRIPT LOAD script: This command registers the specific script in the Redis script cache.
  • SCRIPT DEBUG: It controls the use of the built-in Redis Lua scripts debugger.

Frequently Asked Questions

What is Redis scripting?

Redis scripting is scripting that is used to evaluate scripts using a Lua interpreter. EVAL command is used for scripting.

What is the Redis pipeline?

It is a technique for improving performance by issuing several commands at once without waiting for the response to each command.

What is Redis EVALSHA?

It is a command that evaluates a script cached on the server-side by its SHA1 digest. Using SCRIPT LOAD command scripts are cached on the server-side; otherwise, the command is identical to EVAL.

What are the benefits of Redis?

Some of the benefits of Redis are caching, session management, leaderboards, media streaming, real-time analytics, gaming, etc.

What data is stored in Redis?

Redis can store any type of data like text, float, integer, images, float, or audio files. We can store up to 512 megabytes in a Redis string.

Conclusion

In this article, we have extensively discussed Redis's properties of scripting and its example and how to interact with Redis using the script, redis script cache, and script command. 

After reading this article are you not feeling excited to read/explore more articles on this topic? Don't worry Coding Ninjas Has you covered. To learn more about such topics, you can visit the code studio and also see topics related to Redis.

Refer to our guided path on Coding Ninjas Studio to upskill yourself in Data structure and algorithmsCompetitive Programming, JavascriptSystem Design, and many more if you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others.

Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Live masterclass