Skip to content

Commit f746f8e

Browse files
authored
fix(CubeProxy): initialize random seed in worker phase (#138)
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 <heqianfly@gmail.com>
1 parent 09101b2 commit f746f8e

1 file changed

Lines changed: 7 additions & 0 deletions

File tree

CubeProxy/lua/init_worker_phase.lua

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
-- In OpenResty, math.randomseed should be called in the init_worker phase.
2+
-- Without this, all worker processes would start with the same seed (typically 1),
3+
-- causing math.random() to return the same sequence of values across all workers.
4+
-- This is critical for cache TTL jitter and other randomized behaviors to ensure
5+
-- they are truly distributed and don't lead to synchronized stampedes.
6+
math.randomseed(ngx.now() * 1000 + ngx.worker.id())
7+
18
local function monitor_cache_usage()
29
local cache_free_space = ngx.shared.local_cache:free_space()
310
ngx.shared.local_cache:set("cache_free_space", cache_free_space)

0 commit comments

Comments
 (0)