worker_processes auto;
events { worker_connections 1024; }
http {
lua_shared_dict locks 50m; # for lua-resty-lock
lua_shared_dict redis_l1 100m; # optional L1 cache in memory
# Redis connection info (env or lua)
lua_package_path "/path/to/lua/?.lua;;";
# Fallback file cache config
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=news_cache:200m
inactive=10m use_temp_path=off;
proxy_cache_valid 200 10m;
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504
updating invalid_header http_404;
upstream origin_backend {
server origin.example.com;
keepalive 16;
}
server {
listen 80;
server_name news.example.com;
location / {
# Primary Lua handler
content_by_lua_block {
local redis = require "resty.redis"
local lock = require "resty.lock"
-- Key building
local uri = ngx.var.uri
local redis_key = "news:article:" .. uri
-- Config for TTLs
local ttl = 60 -- 60s fresh window
local stale_ttl = 300 -- 5m stale window beyond TTL
-- 1) Get from Redis
local function fetch_from_redis()
local r = redis:new()
r:set_timeout(50) -- ms
local ok, err = r:connect("127.0.0.1", 6379)
if not ok then
return nil, "redis_connect_error"
end
local res, err = r:get(redis_key)
if not res or res == ngx.null then
return nil, "not_found"
end
-- You can store metadata in JSON for TTL; for simplicity, assume:
-- res = "<timestamp>|<ttl>|<payload>"
local sep1 = string.find(res, "|")
local sep2 = string.find(res, "|", sep1+1)
if not sep1 or not sep2 then
return nil, "bad_format"
end
local ts = tonumber(string.sub(res, 1, sep1-1))
local item_ttl = tonumber(string.sub(res, sep1+1, sep2-1))
local payload = string.sub(res, sep2+1)
return {
ts = ts,
ttl = item_ttl,
payload = payload
}, nil
end
local cache_obj, err = fetch_from_redis()
-- 2) If Redis fetch fails, use fallback file cache via proxy_pass
if not cache_obj then
-- If Redis is down or key missing
ngx.log(ngx.WARN, "Redis error or miss: ", err, " => fallback to file cache")
-- Let NGINX proxy to origin with disk cache; `proxy_pass` in same location
return ngx.exec("@fetch_from_origin")
end
-- 3) Determine freshness
local now = ngx.time()
local age = now - cache_obj.ts
if age < cache_obj.ttl then
-- FRESH
ngx.header["X-Cache-Status"] = "HIT"
ngx.say(cache_obj.payload)
return
end
-- STALE window
if age < (cache_obj.ttl + stale_ttl) then
ngx.header["X-Cache-Status"] = "STALE"
ngx.say(cache_obj.payload)
-- Background refresh attempt with lock
local lock_key = "lock:" .. redis_key
local l = lock:new("locks", {timeout=0, exptime=5})
local elapsed, err = l:lock(lock_key)
if elapsed then
-- Refresh from origin in a subrequest
local res = ngx.location.capture("/_refresh_article", {
vars = { target = uri }
})
if res.status == 200 then
-- Update Redis
local r2 = redis:new()
r2:connect("127.0.0.1", 6379)
local new_ttl = ttl -- you can recalc based on headers
local val = now .. "|" .. new_ttl .. "|" .. res.body
r2:set(redis_key, val)
r2:expire(redis_key, ttl + stale_ttl)
end
l:unlock()
end
return
end
-- 4) Fully expired => fallback to file cache/origin to re-cache
ngx.log(ngx.WARN, "Cache fully expired for ", uri, "; fallback to origin")
return ngx.exec("@fetch_from_origin")
}
}
# Upstream fetch path (also writes to file cache)
location @fetch_from_origin {
proxy_set_header Host $host;
proxy_pass http://origin_backend;
proxy_cache news_cache;
proxy_cache_valid 200 10m;
proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504 updating;
}
# Background refresh location: captures from content_by_lua
location /_refresh_article {
internal;
proxy_set_header Host $host;
proxy_pass http://origin_backend;
}
}
}