I am working with NGINX server and I need to make sure all workers
are dynamically sharing in-memory data. When data is updated, all
workers should be up-to-date.
Reading the docs ngx.shared.DICT can be used for sharing data among workers. So i put that to the test, and it doesn't work.
It seems ngx.shared created copy data for each worker, instead of having one data for all workers.
Here is my simple test code.
nginx.conf
conf
worker_processes 4;
events {
worker_connections 5;
}
http{
lua_shared_dict metadata 10m;
init_by_lua_file lua/init.lua;
server{
listen 80 reuseport;
location / {
return 200 "Hello";
}
location =/worker {
content_by_lua '
ngx.say("worker id: " .. ngx.var.pid)
ngx.say("worker count: " .. ngx.worker.count())
local metadata = ngx.shared.metadata;
ngx.say("shared data: " .. metadata["last"])
';
}
location =/change{
content_by_lua '
local metadata = ngx.shared.metadata;
local t = metadata["last"];
metadata["last"] = t + 1;
';
}
}
}
init.lua
ngx.shared.metadata["last"] = 1;
On initialization a shared value last
is declared with value 1
.
After I make /change
request and increment the value +1,
only 1/4 workers will have shared value updated, while the others are
going to keep using the old value. Probably because that is the worker
that caught the request.
I am curling the server in a loop to see the results updated. And in
the printout i can see that exactly which worker has newer version
worker id: 10
worker count: 4
shared data: 1
----
worker id: 9
worker count: 4
shared data: 2
I am using dockerized NGINX with open resty Lua module. And also activated the reuseport
directive which forces nginx to loadbalance to all workers (just for developing).
How do I make all nginx workers share the date from shared dict dynamically? Is there a system in nginx that can?
Can someone please help,
Thank you