lua-resty-redis-fast

Asynchronous Redis client for OpenResty: Lua API changes, shared connections, TLS, pipelines, and performance compared with lua-resty-redis.

Name

lua-resty-redis-fast - asynchronous standalone Redis client for OpenResty

Table of Contents

Status

The legacy implementation is considered production ready. This manual also documents the new standalone implementation targeting Nginx 1.31.8, with differences marked below.

Description

The new implementation provides asynchronous standalone Redis access through require "resty.redis.fast" and ngx_redis_fast_module.so. It targets Nginx 1.31.8, bundled with OpenResty 1.31.8.x. Common command and pipeline methods follow lua-resty-redis, but connection ownership, pooling, TLS verification, and session operations differ as described below. See the installation and usage guide for package configuration and legacy instructions.

The description and older minimum versions below apply to the legacy implementation.

This Lua library is a Redis client driver for the ngx_lua nginx module:

https://github.com/openresty/lua-nginx-module/#readme

This Lua library takes advantage of ngx_lua’s cosocket API, which ensures 100% nonblocking behavior.

Note that at least ngx_lua 0.5.14 or OpenResty 1.2.1.14 is required.

Lua API Changes

The Lua entry point remains resty.redis.fast. Review the following changes when upgrading from the legacy fast client or replacing the open-source client:

InterfaceNew behavior
connect(..., options)Adds shared-connection controls max_connections (default 3) and pending_threshold (default 32), plus database, authentication, and TLS options.
db and select(db)Database binding belongs to the Lua instance. Different instances can share transports without changing each other’s selected database.
set_keepalive(timeout, size)Uses both arguments to update idle policy and release the logical client. Defaults are 60000 milliseconds and 128 idle connections.
close()Releases the logical client. Clean ordinary transports can remain cached; private or modified session transports close.
get_reused_times()Describes the last borrowed transport; returns 0 while closed. Later operations may use another transport.
WAIT and WAITAOFRequire exclusive = true in connect() before the writes to be acknowledged.
TLSCertificate chain verification defaults to enabled. Use ssl_ca_cert and, for certificate identity checks, ssl_verify_name; SNI alone is insufficient.
Command errorsRedis errors remain false, err; transport failures are nil, err. A successful RESP3 boolean can be false, nil, so check the error value.

Ordinary operations share physical connections while retaining separate replies and timeouts. Transactions, WATCH, subscriptions, blocking commands, and session-changing commands use exclusive connections. Do not use one Lua instance concurrently. After release, commands return nil, "closed" until a successful reconnect.

Performance relative to the open-source client

In a typical concurrent-read application scenario, lua-resty-redis-fast achieved 3.47 times the throughput of open-source lua-resty-redis v0.34, a 246.9% increase.

Metriclua-resty-redis-fastlua-resty-redis v0.34
Median GET throughput214,314 commands/s61,778 commands/s
Median GET p99 latency0.785 ms1.793 ms

The comparison uses shared mode at equal Lua concurrency with different physical connection counts. The Fast connection limit was 6 for the test; the current default is 3. Actual gains depend on workload, connection settings, and deployment.

Synopsis

For the new implementation, load the following module in the main context of nginx.conf:

load_module /usr/local/openresty/nginx/modules/ngx_redis_fast_module.so;

Use the actual module path for a custom installation. The new implementation does not require coro_preload or coro_stack_size. RPM and DEB packages use the same configuration and install Lua bytecode under /usr/local/openresty/site/lualib. Preserve default Lua search paths with ;;, or include /usr/local/openresty/site/lualib/?.ljbc. See the installation and usage guide for the new Lua example’s connection and release calls.

The following complete example is retained for the legacy implementation. Its coro module loading and preload directives describe that implementation.

    # you need to load the corresponding dynamic modules
    load_module "/usr/local/openresty-coro-nginx-module/lib/ngx_http_coro_module.so";
    load_module "/usr/local/openresty-coro-nginx-module/lib/ngx_http_coro_hiredis_module.so";

    http {
        # you do not need the following line if you are using
        # the OpenResty bundle:
        lua_package_path "/usr/local/openresty/site/lualib/?.lua;;";

        # specify the location of the hiredis
        coro_preload /usr/local/openresty-plus/hiredis/lib/libhiredis.so;
        coro_stack_size  32768;

        server {
            location /test {
                # need to specify the resolver to resolve the hostname
                resolver 8.8.8.8;

                content_by_lua_block {
                    local redis = require "resty.redis.fast"
                    local red = redis:new()

                    red:set_timeout(1000) -- 1 sec

                    local ok, err = red:connect("127.0.0.1", $TEST_NGINX_REDIS_PORT)
                    if not ok then
                        ngx.say("failed to connect: ", err)
                        return
                    end

                    ok, err = red:select(1)
                    if not ok then
                        ngx.say("failed to select: ", err)
                        return
                    end

                    local res, err = red:set("dog", "an animal")
                    if not res then
                        ngx.say("failed to set dog: ", err)
                        return
                    end

                    local ok, err = red:set_keepalive()
                    if not ok then
                        ngx.say("failed to set keepalive: ", err)
                        return
                    end
                }
            }
        }
    }

Back to TOC

Methods

The reference below covers common methods and marks differences between the new standalone and legacy implementations. Redis command names accept lowercase, uppercase, or mixed case in the new implementation. Use lowercase names for Lua helpers and the hmset/hmget table overloads.

All of the Redis commands have their own methods with the same name except all in lower case.

You can find the complete list of Redis commands here:

http://redis.io/commands

You need to check out this Redis command reference to see what Redis command accepts what arguments.

The Redis command arguments can be directly fed into the corresponding method call. For example, the “GET” redis command accepts a single key argument, then you can just call the “get” method like this:

    local res, err = red:get("key")

Similarly, the “LRANGE” redis command accepts three arguments, then you should call the “lrange” method like this:

    local res, err = red:lrange("nokey", 0, 1)

For example, “SET”, “GET”, “LRANGE”, and “BLPOP” commands correspond to the methods “set”, “get”, “lrange”, and “blpop”.

Here are some more examples:

    -- HMGET myhash field1 field2 nofield
    local res, err = red:hmget("myhash", "field1", "field2", "nofield")
    -- HMSET myhash field1 "Hello" field2 "World"
    local res, err = red:hmset("myhash", "field1", "Hello", "field2", "World")

Command methods return the Redis reply on success. Redis errors return false, err; connection and transport failures return nil, err. With RESP3, false, nil can be a successful boolean reply; check err ~= nil to detect failure and handle ngx.null for missing values separately.

A Redis “status reply” results in a string typed return value with the “+” prefix stripped.

A Redis “integer reply” results in a Lua number typed return value.

A Redis “error reply” results in a false value and a string describing the error.

A non-nil Redis “bulk reply” results in a Lua string as the return value. A nil bulk reply results in a ngx.null return value.

A non-nil Redis “multi-bulk reply” results in a Lua table holding all the composing values (if any). If any of the composing value is a valid redis error value, then it will be a two element table {false, err}.

A nil multi-bulk reply returns in a ngx.null value.

In the new implementation, resp3 = true enables RESP3. Maps become Lua key/value tables, sets become arrays, and booleans become Lua booleans. Arguments are stringified and nil arguments are omitted, matching the former fast client. Use strings for integers that Lua numbers cannot represent exactly.

See http://redis.io/topics/protocol for details regarding various Redis reply types.

In addition to all those redis command methods, the following methods are also provided:

Back to TOC

new

syntax: red, err = redis:new()

Creates a redis object. In case of failures, returns nil and a string describing the error.

Back to TOC

connect

syntax: ok, err = red:connect(host, port, options_table?)

syntax: ok, err = red:connect("unix:/path/to/unix.sock", options_table?)

Attempts to connect to the remote host and port that the redis server is listening to or a local unix domain socket file listened by the redis server.

Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method.

In the new implementation, ports may be numbers or numeric strings. Hostnames use Nginx’s asynchronous resolver. Compatible clients may share an active physical connection. Reconnect releases the previous logical client and clears queued pipeline and subscription state; failed connection attempts leave it closed.

New implementation options:

OptionMeaning
dbDatabase number or numeric string; defaults to database 0. Authentication and initial database selection complete before connect() succeeds. Selection failures return nil, "failed to select database <db>: <err>".
max_connectionsPositive integer, default 3. Regular shared connection budget per worker, endpoint, and database, across custom pool names, credentials, and TLS/RESP identities. Each database has a separate budget. The first connection establishes the limit while its pools remain in use. Exclusive sessions are exempt.
pending_thresholdPositive integer, default 32. Soft expansion threshold for outstanding command replies per connection, including pipeline commands. Uses the least-loaded compatible connection and expands within the database budget when all reach the threshold.
poolOptional pool name. Endpoint, database, credentials, TLS settings, and RESP version remain isolation boundaries even with a custom name.
pool_sizeDefault 128 retained idle connections per pool identity. With backlog, also limits ordinary physical connections in that pool.
backlogMaximum queued connection requests when the pool creation limit is reached; waiting uses the connect timeout. Exclusive sessions bypass regular creation limits.
max_idle_timeoutIdle timeout in milliseconds, default 60000; 0 disables expiry. An idle Lua instance does not prevent physical idle expiry.
exclusiveSet to true for a private transport, including writes followed by WAIT/WAITAOF. Exempt from the regular shared connection limit.
username, passwordOptional Redis ACL credentials; an empty username selects the default user. Incorrect credentials fail connect().
resp3Set to true for RESP3; use_resp3 is also accepted. Supply credentials during connection to a protected server.
sslEnable TLS. Certificate, key, CA, and server-name options also enable TLS.
ssl_verifyCertificate chain verification, default true.
ssl_ca_certCA file; otherwise use OpenSSL’s trust store. Legacy alias: ca.
ssl_cert, ssl_keyClient certificate and private key for mutual TLS. Legacy aliases: cert, key.
ssl_server_nameSNI name; server_name and ssl_sni are aliases.
ssl_verify_nameExpected certificate DNS name or IP; requires verification. SNI alone does not enable identity checks.

Pool settings are established by the first connection for that pool. Compatible idle connections may move between pools when endpoint, authentication, TLS, and RESP settings agree. Each operation still borrows for its own logical database.

The following cosocket option descriptions apply to the legacy implementation:

The optional options_table argument is a Lua table holding the following keys:

  • ssl

    If set to true, then uses SSL to connect to redis (defaults to false).

  • ssl_verify

    If set to true, then verifies the validity of the server SSL certificate (defaults to false). Note that you need to configure the lua_ssl_trusted_certificate to specify the CA (or server) certificate used by your redis server. You may also need to configure lua_ssl_verify_depth accordingly.

  • server_name

    Specifies the server name for the new TLS extension Server Name Indication (SNI) when connecting over SSL.

  • pool

    Specifies a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template <host>:<port> or <unix-socket-path>.

  • pool_size

    Specifies the size of the connection pool. If omitted and no backlog option was provided, no pool will be created. If omitted but backlog was provided, the pool will be created with a default size equal to the value of the lua_socket_pool_size directive. The connection pool holds up to pool_size alive connections ready to be reused by subsequent calls to connect, but note that there is no upper limit to the total number of opened connections outside of the pool. If you need to restrict the total number of opened connections, specify the backlog option. When the connection pool would exceed its size limit, the least recently used (kept-alive) connection already in the pool will be closed to make room for the current connection. Note that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so the size limit specified here also applies to every single Nginx worker process. Also note that the size of the connection pool cannot be changed once it has been created. Note that at least ngx_lua 0.10.14 is required to use this options.

  • backlog

    If specified, this module will limit the total number of opened connections for this pool. No more connections than pool_size can be opened for this pool at any time. If the connection pool is full, subsequent connect operations will be queued into a queue equal to this option’s value (the “backlog” queue). If the number of queued connect operations is equal to backlog, subsequent connect operations will fail and return nil plus the error string "too many waiting connect operations". The queued connect operations will be resumed once the number of connections in the pool is less than pool_size. The queued connect operation will abort once they have been queued for more than connect_timeout, controlled by set_timeout, and will return nil plus the error string “timeout”. Note that at least ngx_lua 0.10.14 is required to use this options.

Back to TOC

select

syntax: ok, err = red:select(db)

In the new implementation, changes only this Lua instance’s database binding. It uses a compatible target connection or reuses an idle connection from the same endpoint, selecting the requested database when needed. Other instances retain their own bindings; a rejected SELECT leaves the previous binding usable.

SELECT is rejected during transactions, WATCH, subscriptions, or non-replayable state such as CLIENT SETNAME or SCRIPT DEBUG. In ordinary pipelines, SELECT splits execution into segments. A SELECT within MULTI or WATCH returns nil, "SELECT cannot switch connections in a transaction"; pipelines containing such a switch are rejected before any commands are sent. Redis RESET preserves script debugging: use SCRIPT DEBUG NO followed by RESET before changing databases, or close the instance.

Back to TOC

set_timeout

syntax: red:set_timeout(time)

Sets the timeout (in ms) protection for subsequent operations, including the connect method.

Prefer set_timeouts when different phases need different thresholds. The new implementation defaults all three thresholds to 60000 milliseconds; 0 disables the corresponding deadline. Values must be integer milliseconds from 0 through 2147483647; invalid values raise an argument error.

Back to TOC

set_timeouts

syntax: red:set_timeouts(connect_timeout, send_timeout, read_timeout)

Respectively sets the connect, send, and read timeout thresholds (in ms), for subsequent socket operations. Setting timeout thresholds with this method offers more granularity than set_timeout. As such, it is preferred to use set_timeouts over set_timeout.

In the new implementation, values must be integer milliseconds from 0 through 2147483647; invalid values raise an argument error. All three default to 60000; 0 disables the corresponding deadline. Success returns no values. Different Lua instances retain their own timeouts even when sharing a physical connection. Send errors report "send timed out", while read timeouts report "timeout".

Back to TOC

set_keepalive

syntax: ok, err = red:set_keepalive(max_idle_timeout, pool_size)

In the new implementation, returns 1, updates idle retention policy, and closes the calling logical client. Ordinary transports already return to the pool after each operation. The optional arguments default to 60000 milliseconds and 128 idle connections per pool identity; a zero idle timeout disables expiry. The corresponding connect() options are max_idle_timeout and pool_size.

WATCH, unfinished transactions, and subscriptions cannot be returned to the idle pool. Finish them or close the client. Modified session transports are discarded when released.

The legacy reference describes returning the current Redis connection to the ngx_lua cosocket connection pool. The new implementation uses its shared connection pool instead.

For the new implementation, the timeout and capacity control idle retention in the worker-local pool.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Only call this method in the place you would have called the close method instead. Calling this method will immediately turn the current redis object into the closed state. Any subsequent operations other than connect() on the current object will return the closed error.

Back to TOC

get_reused_times

syntax: times, err = red:get_reused_times()

In the new implementation, reports the last borrowed transport’s attachment reuse count, or 0 while closed. A later operation may borrow a different transport.

The following description applies to the legacy implementation: this method returns the reuse count for the current connection, or nil, err on failure.

If the current connection does not come from the built-in connection pool, then this method always returns 0, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.

Back to TOC

close

syntax: ok, err = red:close()

In the new implementation, releases the calling logical client and returns 1. Clean ordinary transports remain cached for reuse; private or dirty session transports close. It does not necessarily close a shared physical connection. Commands and read_reply() then return nil, "closed"; reconnect before using the client again. Garbage collection also releases an abandoned logical client.

The legacy implementation closes the current Redis connection and returns its status.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

init_pipeline

syntax: red:init_pipeline()

syntax: red:init_pipeline(n)

Enable the redis pipelining mode. All subsequent calls to Redis command methods will automatically get cached and will send to the server in one run when the commit_pipeline method is called or get cancelled by calling the cancel_pipeline method.

In the new implementation, a conflicting operation on the same Lua instance returns nil, "socket busy".

If the redis object is already in the Redis pipelining mode, then calling this method will discard existing cached Redis queries.

The optional n argument specifies the (approximate) number of commands that are going to add to this pipeline, which can make things a little faster.

Back to TOC

commit_pipeline

syntax: results, err = red:commit_pipeline()

Quits the pipelining mode by committing all the cached Redis queries to the remote server in a single run. All the replies for these queries will be collected automatically and are returned as if a big multi-bulk reply at the highest level.

This method returns nil and a Lua string describing the error upon failures. In the new implementation, an initialized empty pipeline returns an empty table; committing without initialization returns nil, "no pipeline". Replies retain command order, including {false, err} error entries. Pipelines support MULTI/EXEC and authentication. SELECT forms database-switch boundaries outside transactions; subscription commands and MONITOR cannot be queued.

Back to TOC

cancel_pipeline

syntax: red:cancel_pipeline()

Quits the pipelining mode by discarding all existing cached Redis commands since the last call to the init_pipeline method.

In the new implementation, a conflicting operation on the same Lua instance returns nil, "socket busy".

If the redis object is not in the Redis pipelining mode, then this method is a no-op.

Back to TOC

hmset

syntax: res, err = red:hmset(myhash, field1, value1, field2, value2, ...)

syntax: res, err = red:hmset(myhash, { field1 = value1, field2 = value2, ... })

Special wrapper for the Redis “hmset” command.

When there are only three arguments (including the “red” object itself), then the last argument must be a Lua table holding all the field/value pairs.

Back to TOC

hmget

syntax: res, err = red:hmget(myhash, field1, field2, ...)

syntax: res, err = red:hmget(myhash, { field1, field2, ... })

The new implementation accepts either a fields table or separate field arguments.

Back to TOC

array_to_hash

syntax: hash = red:array_to_hash(array)

Auxiliary function that converts an array-like Lua table into a hash-like table.

This method was first introduced in the v0.11 release.

Back to TOC

read_reply

syntax: res, err = red:read_reply()

Reads a reply, primarily for the Redis Pub/Sub API. In the new implementation, subscriptions use an exclusive connection; multi-channel operations return arrays of acknowledgements. Messages arriving while commands await acknowledgement remain available through read_reply(). Read timeouts preserve the subscription so the caller may retry reading. Unsubscribe before keepalive, or close the client. SELECT is rejected while subscribed.

RESP3 permits ordinary commands while subscribed. Sharded subscription methods require a Redis version supporting them. Pending subscription messages are bounded to 1024 replies and 8 MiB per connection; exceeding either limit closes the connection.

For example,

    local cjson = require "cjson"
    local redis = require "resty.redis.fast"

    local red = redis:new()
    local red2 = redis:new()

    red:set_timeouts(1000, 1000, 1000) -- 1 sec
    red2:set_timeouts(1000, 1000, 1000) -- 1 sec

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("1: failed to connect: ", err)
        return
    end

    ok, err = red2:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("2: failed to connect: ", err)
        return
    end

    local res, err = red:subscribe("dog")
    if not res then
        ngx.say("1: failed to subscribe: ", err)
        return
    end

    ngx.say("1: subscribe: ", cjson.encode(res))

    res, err = red2:publish("dog", "Hello")
    if not res then
        ngx.say("2: failed to publish: ", err)
        return
    end

    ngx.say("2: publish: ", cjson.encode(res))

    res, err = red:read_reply()
    if not res then
        ngx.say("1: failed to read reply: ", err)
        return
    end

    ngx.say("1: receive: ", cjson.encode(res))

    red:close()
    red2:close()

Running this example gives the output like this:

1: subscribe: ["subscribe","dog",1]
2: publish: 1
1: receive: ["message","dog","Hello"]

The following class methods are provided:

Back to TOC

add_commands

syntax: hash = redis.add_commands(cmd_name1, cmd_name2, ...)

WARNING this method is now deprecated since we already do automatic Lua method generation for any redis commands the user attempts to use and thus we no longer need this.

Adds new redis commands to the resty.redis class. Here is an example:

    local redis = require "resty.redis.fast"

    redis.add_commands("foo", "bar")

    local red = redis:new()

    red:set_timeouts(1000, 1000, 1000) -- 1 sec

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end

    local res, err = red:foo("a")
    if not res then
        ngx.say("failed to foo: ", err)
    end

    res, err = red:bar()
    if not res then
        ngx.say("failed to bar: ", err)
    end

Back to TOC

Redis Authentication

The new implementation accepts password and optional ACL username in connect() and authenticates before connection success. Incorrect credentials fail connect(). Without credentials, connect permits a NOAUTH response so callers may use auth(password) or auth(username, password). Redis authentication errors return false, err, leaving the connection usable.

Manual AUTH, HELLO, and RESET use exclusive connections. Successful authentication and protocol options are retained for later connection switches. AUTH and HELLO AUTH can also appear in pipelines and transactions in Redis’s order. To authenticate manually before RESP3, connect with default RESP2, authenticate, and then call hello(3).

Redis uses the AUTH command to do authentication: http://redis.io/commands/auth

There is nothing special for this command as compared to other Redis commands like GET and SET. So one can just invoke the auth method on your resty.redis instance. Here is an example:

    local redis = require "resty.redis.fast"
    local red = redis:new()

    red:set_timeouts(1000, 1000, 1000) -- 1 sec

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end

    local res, err = red:auth("foobared")
    if not res then
        ngx.say("failed to authenticate: ", err)
        return
    end

where we assume that the Redis server is configured with the password foobared in the redis.conf file:

requirepass foobared

If the password specified is wrong, then the sample above will output the following to the HTTP client:

failed to authenticate: ERR invalid password

Back to TOC

Redis Transactions

The new implementation acquires an exclusive connection for WATCH, MULTI/EXEC, subscriptions, blocking commands, and other session-sensitive operations. WATCH and unfinished transactions cannot enter the idle pool; finish with EXEC, DISCARD, or UNWATCH, or call close(). To use WAIT/WAITAOF, connect with {exclusive = true} before the writes. Shared clients reject them with nil, "WAIT requires an exclusive connection" or the corresponding WAITAOF error.

This library supports the Redis transactions. Here is an example:

    local cjson = require "cjson"
    local redis = require "resty.redis.fast"
    local red = redis:new()

    red:set_timeouts(1000, 1000, 1000) -- 1 sec

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end

    local ok, err = red:multi()
    if not ok then
        ngx.say("failed to run multi: ", err)
        return
    end
    ngx.say("multi ans: ", cjson.encode(ok))

    local ans, err = red:set("a", "abc")
    if not ans then
        ngx.say("failed to run sort: ", err)
        return
    end
    ngx.say("set ans: ", cjson.encode(ans))

    local ans, err = red:lpop("a")
    if not ans then
        ngx.say("failed to run sort: ", err)
        return
    end
    ngx.say("set ans: ", cjson.encode(ans))

    ans, err = red:exec()
    ngx.say("exec ans: ", cjson.encode(ans))

    red:close()

Then the output will be

multi ans: "OK"
set ans: "QUEUED"
set ans: "QUEUED"
exec ans: ["OK",[false,"ERR Operation against a key holding the wrong kind of value"]]

Back to TOC

Redis Module

This library supports the Redis module. Here is an example with RedisBloom module:

    local cjson = require "cjson"
    local redis = require "resty.redis.fast"
    -- register the module prefix "bf" for RedisBloom
    redis.register_module_prefix("bf")

    local red = redis:new()

    local ok, err = red:connect("127.0.0.1", 6379)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end

    -- call BF.ADD command with the prefix 'bf'
    res, err = red:bf():add("dog", 1)
    if not res then
        ngx.say(err)
        return
    end
    ngx.say("receive: ", cjson.encode(res))

    -- call BF.EXISTS command
    res, err = red:bf():exists("dog")
    if not res then
        ngx.say(err)
        return
    end
    ngx.say("receive: ", cjson.encode(res))

Load Balancing and Failover

You can trivially implement your own Redis load balancing logic yourself in Lua. Just keep a Lua table of all available Redis backend information (like host name and port numbers) and pick one server according to some rule (like round-robin or key-based hashing) from the Lua table at every request. You can keep track of the current rule state in your own Lua module’s data, see https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker

Similarly, you can implement automatic failover logic in Lua at great flexibility.

Back to TOC

Debugging

It is usually convenient to use the lua-cjson library to encode the return values of the redis command methods to JSON. For example,

    local cjson = require "cjson"
    ...
    local res, err = red:mget("h1234", "h5678")
    if res then
        print("res: ", cjson.encode(res))
    end

Back to TOC

Automatic Error Logging

For the new implementation, check returned errors and the Nginx error log. The following cosocket logging advice applies to the legacy implementation; lua_socket_log_errors does not control the new module’s own diagnostics.

By default the underlying ngx_lua module does error logging when socket errors happen. If you are already doing proper error handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off ngx_lua’s lua_socket_log_errors directive, that is,

    lua_socket_log_errors off;

Back to TOC

Check List for Issues

  1. For the new implementation, distinguish max_connections (regular shared connections per worker, endpoint, and database), pending_threshold (soft expansion trigger), and pool_size (idle retention and, with backlog, pool creation limit). The default regular budget is 3; exclusive sessions and separate databases add connections independently. Configure idle policy in connect() or set_keepalive().
  2. Ensure the backlog setting on the Redis side is large enough. For Redis 2.8+, you can directly tune the tcp-backlog parameter in the redis.conf file (and also tune the kernel parameter SOMAXCONN accordingly at least on Linux). You may also want to tune the maxclients parameter in redis.conf.
  3. Use appropriate timeouts. Ordinary read timeouts and cancellation discard late replies while preserving the transport and logical client. A state-changing request with an unconfirmed result requires RESET before further commands or keepalive. A timeout does not prove a write failed; retry only when safe.
  4. If your NGINX worker processes’ CPU usage is very high under load, then the NGINX event loop might be blocked by the CPU computation too much. Try sampling a C-land on-CPU Flame Graph and Lua-land on-CPU Flame Graph for a typical NGINX worker process. You can optimize the CPU-bound things according to these Flame Graphs.
  5. If your NGINX worker processes’ CPU usage is very low under load, then the NGINX event loop might be blocked by some blocking system calls (like file IO system calls). You can confirm the issue by running the epoll-loop-blocking-distr tool against a typical NGINX worker process. If it is indeed the case, then you can further sample a C-land off-CPU Flame Graph for a NGINX worker process to analyze the actual blockers.
  6. If your redis-server process is running near 100% CPU usage, then you should consider scale your Redis backend by multiple nodes or use the C-land on-CPU Flame Graph tool to analyze the internal bottlenecks within the Redis server process.

Back to TOC

Limitations

The new implementation supports the HTTP subsystem, including timers and light threads, but not stream. It does not perform Redis Cluster discovery, hash-slot routing, redirects, or cross-node command splitting. Use the Cluster client for those features. Do not use one Lua instance concurrently; conflicting operations return nil, "socket busy". Different instances may share physical connections.

  • This library cannot be used in code contexts like init_by_lua*, set_by_lua*, log_by_lua*, and header_filter_by_lua* where the ngx_lua cosocket API is not available.
  • The resty.redis object instance cannot be stored in a Lua variable at the Lua module level, because it will then be shared by all the concurrent requests handled by the same nginx worker process (see https://github.com/openresty/lua-nginx-module/#data-sharing-within-an-nginx-worker ) and result in bad race conditions when concurrent requests are trying to use the same resty.redis instance (you would see the “bad request” or “socket busy” error to be returned from the method calls). You should always initiate resty.redis objects in function local variables or in the ngx.ctx table. These places all have their own data copies for each request.

Back to TOC

Installation

Follow the private-library installation guide for the package matching your OpenResty version. For the new implementation, install both the Lua modules and ngx_redis_fast_module.so; changing only the Lua import is insufficient. RPM and DEB packages use the same Nginx and Lua configuration. Preserve the default Lua search path and ensure Nginx workers can read modules and required certificate/key files.

Installation - Build from source

The following commands install the open-source lua-resty-redis library, which provides resty.redis. They are retained as an upstream reference and do not install this private library or ngx_redis_fast_module.so.

# Clone latest release , assuming v0.29
wget https://github.com/openresty/lua-resty-redis/archive/refs/tags/v0.29.tar.gz

# Extract
tar -xvzf v0.29.tar.gz

# go into directory
cd lua-resty-redis-0.29

export LUA_LIB_DIR=/usr/local/openresty/site/lualib

# Compile and Install
make install

# Now compiled path will be outputted
# /usr/local/lib/lua/resty = lua_package_path in nginx conf

Installation Notes

These notes describe the open-source resty.redis library included in OpenResty. The private resty.redis.fast library and its required dynamic module must be installed separately as described in the private-library installation guide.

If you are using the OpenResty bundle (http://openresty.org ), then you do not need to do anything because it already includes and enables lua-resty-redis by default. And you can just use it in your Lua code, as in

    local redis = require "resty.redis"
    ...

If you are using your own nginx + ngx_lua build, then you need to configure the lua_package_path directive to add the path of your lua-resty-redis source tree to ngx_lua’s LUA_PATH search path, as in

    # nginx.conf
    http {
        lua_package_path "/path/to/lua-resty-redis/lib/?.lua;;";
        ...
    }

Ensure that the system account running your Nginx ‘‘worker’’ proceses have enough permission to read the .lua file.

Back to TOC

TODO

Back to TOC

Community

Back to TOC

English Mailing List

The openresty-en mailing list is for English speakers.

Back to TOC

Chinese Mailing List

The openresty mailing list is for Chinese speakers.

Back to TOC

Bugs and Patches

Please report bugs or submit patches by

  1. creating a ticket on the GitHub Issue Tracker,
  2. or posting to the OpenResty community.

Back to TOC

Author

Yichun “agentzh” Zhang (章亦春) agentzh@gmail.com, OpenResty Inc.

Back to TOC

This module is licensed under the BSD license.

Copyright (C) 2012-2017, by Yichun Zhang (agentzh) agentzh@gmail.com, OpenResty Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Back to TOC

See Also

Back to TOC