From 0b5f058ff878288b91ca7111644c77a300939f6b Mon Sep 17 00:00:00 2001 From: novahe Date: Mon, 4 May 2026 19:21:35 +0800 Subject: [PATCH] fix(CubeProxy): initialize random seed in worker phase In OpenResty, all worker processes inherit the same state from the master process. Without explicitly seeding the random number generator in the init_worker phase, each worker starts with the same default seed. This results in math.random() producing the exact same sequence of numbers across all workers. Seeding with (ngx.now() * 1000 + ngx.worker.id()) ensures that each worker has a unique, time-varying seed. This is essential for features like cache TTL jitter to work as intended and avoid synchronized cache expiration stampedes. Signed-off-by: novahe --- CubeProxy/lua/init_worker_phase.lua | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CubeProxy/lua/init_worker_phase.lua b/CubeProxy/lua/init_worker_phase.lua index 83392f6e..1eb3170f 100644 --- a/CubeProxy/lua/init_worker_phase.lua +++ b/CubeProxy/lua/init_worker_phase.lua @@ -1,3 +1,10 @@ +-- In OpenResty, math.randomseed should be called in the init_worker phase. +-- Without this, all worker processes would start with the same seed (typically 1), +-- causing math.random() to return the same sequence of values across all workers. +-- This is critical for cache TTL jitter and other randomized behaviors to ensure +-- they are truly distributed and don't lead to synchronized stampedes. +math.randomseed(ngx.now() * 1000 + ngx.worker.id()) + local function monitor_cache_usage() local cache_free_space = ngx.shared.local_cache:free_space() ngx.shared.local_cache:set("cache_free_space", cache_free_space)