0Pricing
Lua Academy · Lesson

Shared Memory Dictionaries

Cache data across workers with ngx.shared.DICT for low-latency lookups.

Shared Memory Dictionaries is a free Lua Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is ngx.shared.DICT?

ngx.shared.DICT is a shared memory zone accessible by all Nginx worker processes. It provides O(1) get/set/incr operations for caching and coordination.

Declaring Shared Memory in nginx.conf

Allocate shared dictionaries with a name and size in the http block.

# nginx.conf
http {
  lua_shared_dict rate_limit 10m;
  lua_shared_dict cache      50m;
  lua_shared_dict locks      1m;
}

Basic Get and Set

Store and retrieve values with an optional TTL (time-to-live in seconds).

-- content_by_lua_block
local cache = ngx.shared.cache
cache:set("greeting", "Hello, World!", 60)  -- expires in 60s
local val = cache:get("greeting")
ngx.say(val)  -- Hello, World!

Atomic Increment

dict:incr(key, delta, init, expiry) atomically increments a counter. Initializes to init if the key does not exist.

local rl = ngx.shared.rate_limit
local count = rl:incr("req:" .. ngx.var.remote_addr, 1, 0, 60)
if count > 100 then
  ngx.exit(429)  -- Too Many Requests
end

Rate Limiting with Shared Memory

The incr pattern implements a simple sliding window rate limiter — one of the most common OpenResty patterns.

delete and flush

dict:delete(key) removes a single key. dict:flush_all() marks all keys as expired (lazy deletion). dict:flush_expired(n) actively removes expired keys.

Atomic Add

dict:add(key, val, expiry) sets a key only if it does not already exist — useful for distributed locking.

local locks = ngx.shared.locks
local ok, err = locks:add("my_lock", true, 5)  -- 5s lock
if not ok then
  ngx.say("Lock held, try later")
  return
end
-- critical section
-- locks:delete("my_lock")  -- release

Shared Memory Size Planning

Each key-value pair has overhead (~100 bytes). Estimate: size_mb * 1024^2 / avg_entry_size = max entries. Monitor with dict:capacity() and dict:free_space().

Memory Eviction

When the dictionary is full, OpenResty evicts the oldest entries to make room. Set appropriate TTLs to control eviction behavior.

Cross-Worker Coordination

Since all workers share the same dictionary, use :add for leader election and :incr for global counters across all worker processes.

Limitations

Shared dictionaries only support scalar values (string, number, boolean). Store tables by serializing to JSON with cjson.

Shared Memory Question

What does dict:incr(key, 1, 0, 60) do?

Recap: Shared Memory Dictionaries

ngx.shared.DICT provides O(1) atomic get/set/incr across all workers. Use for rate limiting, caching, distributed locking. Set TTLs to control eviction. Serialize tables to JSON for complex values.

Frequently asked questions

Is the “Shared Memory Dictionaries” lesson free?

Yes — the full text of “Shared Memory Dictionaries” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Shared Memory Dictionaries”?

Cache data across workers with ngx.shared.DICT for low-latency lookups. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Shared Memory Dictionaries” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. OpenResty Architecture
  2. Handling HTTP Requests in Lua
  3. Cosockets and Non-Blocking TCP
  4. Shared Memory Dictionaries
← Back to Lua Academy