Why can a counter defined only once in a Lua module return 1 several times in a row? After you change a Lua file and reload, why can an unfinished request still return the old version? And if you configure eight workers, how many copies of your in-process caches and connection pools exist?

All of these behaviors come from the Nginx multi-process model that OpenResty inherits. To write correct OpenResty applications, you do not need to study every Nginx internal first, but you do need to know which worker a piece of Lua state belongs to, when it is created, and when it disappears.

This article starts with a diagnostic endpoint you can run right away and builds the small gateway that later articles in this series will keep using. We first work out which process your Lua code runs in; the next article covers which *_by_lua execution phase it belongs in.

Quick Answer

The OpenResty master process reads the configuration and manages workers; ordinary HTTP requests are handled by workers. In the default lua_code_cache on mode, every HTTP worker holds its own long-lived Lua VM. Requests in the same worker share the Lua modules already loaded, but the Lua VMs and module state of different workers are isolated from each other.

On a reload, OpenResty does not clear the Lua VM inside an existing worker and swap in new code in place. Instead, it creates workers that use the new configuration and new Lua VMs, then lets the old workers finish their existing requests and exit. During the handover, two generations of code and in-process state can therefore coexist.

Start with the Symptom: Why Does the Counter Start at 1 More Than Once?

First, create the gateway’s directory layout. Request handling, Redis, shared state, caching, and rate limiting in later articles will all build on this project, instead of starting an unrelated example from scratch each time.

mkdir -p gateway/conf gateway/logs gateway/lua/gateway
cd gateway

Create lua/gateway/state.lua:

local _M = {}

local requests = 0
local version = "v1"

function _M.next_request()
    requests = requests + 1
    return requests
end

function _M.version()
    return version
end

return _M

Here requests is a module-level local variable; for how to write modules, see How to Write Lua Modules in OpenResty: A Step-by-Step Example. Every call to next_request() increments it by one.

Next, create conf/nginx.conf:

worker_processes 4;
error_log logs/error.log notice;
pid logs/nginx.pid;

events {
    worker_connections 1024;
}

http {
    lua_package_path "$prefix/lua/?.lua;;";

    init_by_lua_block {
        require "gateway.state"
    }

    init_worker_by_lua_block {
        ngx.log(
            ngx.NOTICE,
            "gateway worker started: pid=", ngx.worker.pid(),
            " worker_id=", ngx.worker.id()
        )
    }

    server {
        listen 127.0.0.1:8080;

        location = /_debug/worker {
            default_type text/plain;

            content_by_lua_block {
                local state = require "gateway.state"

                ngx.say(
                    "pid=", ngx.worker.pid(),
                    " worker_id=", ngx.worker.id(),
                    " version=", state.version(),
                    " count=", state.next_request()
                )
            }
        }
    }
}

error_log is set to the notice level so that the diagnostic messages we log later with ngx.NOTICE are written to logs/error.log; at the default error level, they would be filtered out.

Check the configuration first, then start the instance:

openresty -p "$PWD/" -c conf/nginx.conf -t
openresty -p "$PWD/" -c conf/nginx.conf

Send a series of requests:

for i in $(seq 1 12); do
    curl -s http://127.0.0.1:8080/_debug/worker
done

The actual PIDs and the order in which requests are distributed vary by machine, but the output will look something like this:

pid=32101 worker_id=0 version=v1 count=1
pid=32102 worker_id=1 version=v1 count=1
pid=32101 worker_id=0 version=v1 count=2
pid=32103 worker_id=2 version=v1 count=1
pid=32102 worker_id=1 version=v1 count=2

The counter did not go backward; the requests landed on different workers. The worker with PID 32101 has its own requests, and the one with PID 32102 has another. Each counter records only the requests handled by its own worker.

If you see only one PID at first, just send more requests. Neither the operating system nor Nginx guarantees that connections are spread evenly across workers in round-robin order.

How Do Requests, Workers, and Lua VMs Relate?

Let’s first boil the full implementation down to a mental model that is good enough for practical work:

There are four key points:

  1. The master does not handle ordinary HTTP requests. It reads the configuration, creates and manages workers, and responds to control signals such as reload and quit.
  2. Workers are isolated operating system processes. Each process has its own address space, so an ordinary Lua table in one worker does not automatically appear in another.
  3. Requests in the same worker share a Lua VM. Modules loaded with require are cached in that VM’s package.loaded, so later requests that land on the worker reuse the same module code and module-level state.
  4. Each request runs in its own Lua coroutine. A worker can have many requests suspended while they wait on network I/O, but it runs only one piece of Lua code at a time, on a single CPU thread. Blocking calls, or computations that run for a long time without yielding, will stall the other requests on that worker.

So the basic production model is not “one Lua VM per request” but “one long-lived Lua VM per worker, and one coroutine per request.” lua_code_cache off is a special mode meant only for local development: it uses a separate VM for requests and reloads the code, and neither its performance nor its behavior is suitable for production. For details, see How to Run Lua Scripts in Nginx with OpenResty: Configuration, Common Uses, and Pitfalls.

There is one more boundary you are likely to run into later: the HTTP and Stream subsystems each use their own Lua VM. The gateway in this article enables only HTTP, so we can simplify the model to “one Lua VM per worker”; a later article on the Stream subsystem will cover how the two subsystems differ. For how LuaJIT itself interprets and compiles code, see LuaJIT in OpenResty: How It Works and How luajit2 Differs.

Who Does Lua State Actually Belong To?

Back to the gateway.state module from the beginning. It is preloaded in init_by_lua_block, and the workers are then forked from the master. Every worker initially sees requests = 0, but once they start handling requests, the changes happen in each worker’s own process address space, and the counts are never synchronized with each other.

When writing gateway code, you can use the following table to decide where a piece of state should live:

State locationVisible toDisappears whenTypical use
local variable in a functionThe current function callThe function call endsIntermediate results
ngx.ctxThe current requestThe request endsPassing values between phases of the same request
Lua module variable or upvalueRequests in the current workerThe worker exitsRead-only configuration, per-worker caches
lua_shared_dictAll workers in the same OpenResty instanceThe instance exits; retained across a reload if its name and size stay unchangedCounters, rate-limit state, shared flags
External storage such as RedisMultiple processes and nodesDetermined by the external systemCross-node state, persistent data

If you draw out these visibility scopes, they nest inside one another: the further out you go, the more requests and processes can see the state, and the longer it lives.

This gives us a few rules you can apply directly:

  • Request-level data such as user IDs and request parameters belongs in function-local variables or ngx.ctx, never in module variables.
  • A module-level table can cache data the current worker reuses, but do not mistake it for a single table shared by the whole service.
  • Instance-wide counters and rate-limit state cannot rely on Lua module variables alone.
  • Cross-node state requires an external system such as Redis; lua_shared_dict covers only the current OpenResty instance.

Ordinary Lua global variables are not a shortcut for sharing either. A global variable written in request-handling code is not isolated per request: it stays in the current worker’s Lua VM and is visible to later requests handled by that worker, and ngx_lua only logs a writing a global Lua variable warning in error.log. Other workers never see it. Relying on implicit globals invites typos and name pollution, and it blurs the boundaries of your state. Real code should still use local by default and expose state through an explicit module interface when it needs to be shared. For the basic rules of Lua variables and error handling, see Lua for OpenResty: Essential Syntax, Error Handling, and I/O Pitfalls.

How to Share Data Between Requests in OpenResty already showed the basic difference between module variables and lua_shared_dict. A later article on shared dicts will go further into atomic operations, capacity, expiration, and eviction; for this article, you only need to remember the process boundary.

Worker Count Also Multiplies Caches, Memory, and Connections

“One copy per worker” affects more than counters; it also affects your production resource budget. Suppose a gateway is configured with eight workers:

  • A module-local LRU cache with a capacity of 10,000 entries may hold up to about 80,000 entries across the machine, not 10,000;
  • For a parsed Lua routing table that takes 20 MB, even if business code never modifies it, Lua garbage collection rewrites the marks on objects as it scans them, so the memory pages are gradually copied into each worker; budget roughly 8 × 20 MB for it;
  • The cosocket connection pool is also managed per worker: if you set the Redis connection pool limit to 100 (the default is 30), eight workers may end up holding about 800 idle connections;
  • With more workers, each process receives fewer requests, so a single worker’s local cache may have a harder time warming up to a high hit rate.

So do not mechanically read worker_processes as “always set it to the number of CPU cores.” worker_processes auto; is a common starting point, but validate the final value against container CPU quotas, memory limits, traffic patterns, and backend connection budgets. This article uses a fixed four workers to make state isolation easy to observe; this is not a recommended value for every production environment.

How to size connection pools will be covered in a later article on connection pools and timeouts; how to combine in-process caches with shared dicts is left for a later article on caching.

What Do init_by_lua and init_worker_by_lua Each Initialize?

The configuration at the start uses two initialization hooks:

init_by_lua_block {
    require "gateway.state"
}

init_worker_by_lua_block {
    ngx.log(
        ngx.NOTICE,
        "gateway worker started: pid=", ngx.worker.pid(),
        " worker_id=", ngx.worker.id()
    )
}

The names are similar, but they run in different places.

init_by_lua*: Load Before Workers Are Created

init_by_lua* runs while Nginx loads its configuration, before a new generation of workers is created. A common use is preloading Lua modules:

  • A missing module or an error in top-level code is caught early, during startup or reload (openresty -t does not run init_by_lua*, so it cannot catch these errors);
  • The first real request no longer has to pay the cost of loading the module for the first time;
  • Workers inherit the already-loaded memory pages through fork, so early on they can share physical memory through the operating system’s copy-on-write.

Copy-on-write does not mean “all workers keep sharing the same Lua table.” Once a worker modifies memory, it sees its own copy, and the other workers do not change along with it. Moreover, Lua garbage collection rewrites the marks on objects, so even read-only data is gradually copied page by page as the workers run; do not count on copy-on-write for long-term memory savings.

Only a limited set of ngx.* APIs is available in this phase, and there is no ordinary request context. Do not try to connect to Redis with a cosocket here; connections to external systems should be made in contexts that allow non-blocking I/O, which a later article on cosockets will demonstrate in full.

init_worker_by_lua*: Runs Once in Every Worker

init_worker_by_lua* runs when each worker starts. With four workers configured, the startup log normally contains four gateway worker started entries with different PIDs; when a reload creates a new generation of workers, the hook runs again in every new worker.

It is a good place to set up per-worker initial state and is also commonly used to start timers. But note: do not run long CPU computations or synchronously load huge datasets here. The slower a new worker initializes, the later it starts handling events normally, and the more likely you are to see latency jitter during a reload. How to start timers, and how to handle premature when a worker exits, will be covered in a later article on timers.

A Reload Does Not Replace Code Inside Existing Workers

After you edit state.lua, a reload looks like a single command:

openresty -p "$PWD/" -c conf/nginx.conf -t
openresty -p "$PWD/" -c conf/nginx.conf -s reload

But inside, the processes go through a generational handover:

Here is what happens:

  1. The master receives the HUP/reload signal;
  2. The master reads and tries to apply the new configuration, including opening the files and listening addresses it references;
  3. If loading fails, the new configuration is discarded and the existing workers keep serving;
  4. If loading succeeds, the master creates new workers, which use the new configuration and new Lua VMs;
  5. The old workers close their listening sockets and stop accepting new connections, but keep serving existing clients;
  6. Only after their requests and connections finish do the old workers exit.

A failure in step 3 does not show up in the reload command: the command returns as usual and the error goes only to error.log. -t does not run init_by_lua* either, so Lua errors such as a missing module first appear at this step. After a reload, check error.log or use ps to confirm that the worker PIDs have changed before you assume the new code is live.

So a reload does not “clear package.loaded in the existing VM and reload the files.” New workers build their own package.loaded, module variables, and in-process caches; old workers keep the old VM until they actually exit.

Hands-On: Watch Old and New Lua Code Run at the Same Time

You can add a slow request to the gateway purely for this experiment. Add the following inside server {}:

location = /_debug/hold {
    default_type text/plain;

    content_by_lua_block {
        local state = require "gateway.state"
        local pid = ngx.worker.pid()
        local version = state.version()

        ngx.sleep(10)
        ngx.say("pid=", pid, " version=", version)
    }
}

This first saves the PID and version in local variables, then uses the non-blocking ngx.sleep(10) to make the request wait 10 seconds. ngx.sleep suspends the current request’s coroutine; unlike the operating system’s sleep command, it does not block the whole worker.

Check the configuration and reload once to activate this location:

openresty -p "$PWD/" -c conf/nginx.conf -t
openresty -p "$PWD/" -c conf/nginx.conf -s reload

In terminal A, send the slow request:

curl http://127.0.0.1:8080/_debug/hold

While it is still waiting, change the version in lua/gateway/state.lua to:

local version = "v2"

Then check the configuration and reload in terminal B:

openresty -p "$PWD/" -c conf/nginx.conf -t
openresty -p "$PWD/" -c conf/nginx.conf -s reload
curl http://127.0.0.1:8080/_debug/worker

The new request is handled by a new worker and returns version=v2 with a new PID. When the old request in terminal A finishes, it still returns something like:

pid=32101 version=v1

This experiment shows that two generations of code can coexist during a reload handover: existing requests keep running v1 in the old worker, while new requests are already running v2 in new workers. When deploying, do not assume the whole machine switches versions atomically at a single instant.

When you are done testing, stop the example instance:

openresty -p "$PWD/" -c conf/nginx.conf -s stop

What Survives a Reload, and What Starts Over?

ItemAfter a HUP reloadWhy
Master PIDUsually unchangedThe reload is managed by the existing master
Worker PIDsReplaced by a new generationThe master created new processes
package.loadedRebuilt in the new workersIt belongs to the Lua VM
Lua module variablesReinitializedNew workers use new in-process state
Per-worker LRU cachesStart coldOld caches are not migrated to the new processes
Cosocket connection poolsRebuilt by the new workersConnection pools belong to workers
lua_shared_dict dataRetained if name and size stay unchangedThe data lives in an Nginx shared memory zone
Data in RedisRetainedThe data lives in an external process
Old requests already in progressUsually keep running the old codeThe old workers finish them

A reload is also not the same as a restart. A restart makes the whole process tree exit and start again, so you cannot expect in-process state or Nginx shared memory state to survive; a reload, by contrast, has the existing master coordinate the handover between old and new workers.

A “graceful handover” is not invisible to users in every scenario, either. In production, pay particular attention to four things:

  1. Cold caches: The new workers’ local caches are empty, so for a short while they may send more requests through to the backend;
  2. Slow initialization: Parsing a huge configuration or running CPU-intensive tasks slows down how quickly new workers become ready;
  3. Lingering old workers: Long requests, streaming responses, WebSockets, and similar connections extend the time it takes old workers to exit;
  4. Version compatibility window: Old and new code may access the shared dict or external storage at the same time, so your data structures must not be readable by only one version.

If routes, upstreams, or certificates change frequently, you should usually design them as data that can be updated at runtime, rather than creating a new generation of workers for every change. As the number of nodes grows and you need centralized configuration distribution, versioning, and rollback, you can use OpenResty Edge to manage gateway policies and sync changes to multiple nodes without relying on frequent Nginx reloads.

What This Article Leaves the Gateway

At this point, the gateway has three foundations that later articles will keep building on:

  • The directory layout for the gateway.* Lua modules;
  • A diagnostic endpoint for observing the PID, worker ID, code version, and module state;
  • A working model of the worker lifecycle and the reload handover.

Before moving on, use these four questions to check whether you have this model down:

  1. Is the counter in gateway.state one per service or one per worker?
  2. With eight workers and a Redis connection pool limit of 100, at most how many idle connections might the machine keep?
  3. Why can a request that has not yet finished still run old code after a reload?
  4. Why can a global rate-limit count not live only in a Lua module’s table?

The answers: one per worker; about 800; old requests are still finished by the old workers; and a module table cannot be shared across processes.

We now know which process Lua code runs in and who its state belongs to. The next article, OpenResty Execution Phases: Lua Execution Order and Choosing *_by_lua, keeps using this gateway to answer the next question: as a request passes through Nginx, which phase should authentication, rewriting, response generation, and logging each run in? For the full learning path, see the OpenResty tutorial series.

About The Author

Yichun Zhang (Github handle: agentzh), is the original creator of the OpenResty® open-source project and the CEO of OpenResty Inc..

Yichun is one of the earliest advocates and leaders of “open-source technology”. He worked at many internationally renowned tech companies, such as Cloudflare, Yahoo!. He is a pioneer of “edge computing”, “dynamic tracing” and “machine coding”, with over 22 years of programming and 16 years of open source experience. Yichun is well-known in the open-source space as the project leader of OpenResty®, adopted by more than 40 million global website domains.

OpenResty Inc., the enterprise software start-up founded by Yichun in 2017, has customers from some of the biggest companies in the world. Its flagship product, OpenResty XRay, is a non-invasive profiling and troubleshooting tool that significantly enhances and utilizes dynamic tracing technology. And its OpenResty Edge product is a powerful distributed traffic management and private CDN software product.

As an avid open-source contributor, Yichun has contributed more than a million lines of code to numerous open-source projects, including Linux kernel, Nginx, LuaJIT, GDB, SystemTap, LLVM, Perl, etc. He has also authored more than 60 open-source software libraries.