Lua Academy · Lesson

Shared Memory Dictionaries

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

Lesson 4 of 413 steps

Shared Memory Dictionaries is a free Lua Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

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.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Shared Memory Dictionaries” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Shared Memory Dictionaries”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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