Skip to content

Lesson 7 of 9 · 28m

OpenResty and the nginx Request Lifecycle

Place Lua in the correct nginx phase, use cosockets without blocking workers, and avoid the configuration mistakes that make OpenResty unreliable.

OpenResty feels magical the first time a ten-line Lua block replaces an awkward chain of proxy rules. The magic ends when someone puts a blocking HTTP client in access_by_lua_block and one slow upstream takes down every nginx worker. OpenResty is not a normal application server embedded in nginx. It is Lua glued directly into nginx phases and its event loop. If you do not know which phase you are in, you do not know what your code is allowed to do.

nginx phases are the programming model

http {
    lua_shared_dict rate_limits 10m;
    server {
        listen 8080;
        location /api/ {
            access_by_lua_block {
                if not ngx.var.http_authorization then
                    return ngx.exit(ngx.HTTP_UNAUTHORIZED)
                end
            }
            content_by_lua_block {
                ngx.header.content_type = "application/json"
                ngx.say('{"ok":true}')
            }
        }
    }
}

The important question is when does this run? Access code runs during access control, content code generates the response, filters transform proxied responses, and log_by_lua_block must remain cheap.

Use the right phase for the right decision

Authentication belongs in access logic; response mutation belongs in filters; initialization belongs in init_worker_by_lua_block. lua_shared_dict is cross-worker but bounded memory:

local limits = ngx.shared.rate_limits
local n, err = limits:incr(ngx.var.binary_remote_addr, 1, 0, 60)
if n and n > 120 then return ngx.exit(ngx.HTTP_TOO_MANY_REQUESTS) end

It is ephemeral and eviction-prone, not a database or authorization system.

Blocking calls poison the event loop

OpenResty cosockets yield cooperatively; blocking sockets, subprocesses, and synchronous file reads do not. Use cosocket-aware libraries and timeouts:

local http = require("resty.http")
local httpc = http.new()
httpc:set_timeout(500)
local res, err = httpc:request_uri("http://127.0.0.1:9001/authorize", {
    method = "POST", headers = { ["Content-Type"] = "application/json" },
})

A dependency without a timeout is a queue of workers waiting to die together.

Respect worker-local state

OpenResty runs multiple workers. A Lua table inside a module is per worker, not global. Counters, caches, and connection pools are duplicated. This is often desirable for locality, but it changes semantics. If exact global coordination matters, use shared dictionaries, external stores, or accept approximation deliberately.

Field notes

  • ngx.exit is control flow, not just response formatting; understand what phases it terminates.
  • ngx.var values are strings or nil, never trust their shape without validation.
  • Shared dictionaries evict entries under memory pressure; design counters and locks accordingly.
  • Do not perform heavy work in log_by_lua_block; logging is on the critical path of completion.

Was this lesson helpful?

Sign in to rate