A user of Corvus, my open-source gateway on top of
OpenResty, opened a short issue: "This community blocklist is 50 MB and fails to download (limit
is 5 MB). Please support larger blocklists."
Raising the limit would have taken one line. It would also have been a bad idea, and fixing it
properly turned into one of the more satisfying pieces of work on the project. This post is about
that fix, because the technique works for any nginx/OpenResty setup that needs to check client
addresses against a big list.
Why raising the limit wasn't enough
The list in question has about 3.9 million IPv4 addresses and networks, one per line. At the
time, Corvus handled IP lists the obvious way: the control plane stored the entries, wrote them into
the gateway's rule file, and every nginx worker loaded them into a Lua table when the configuration
loaded.
That's fine for a few thousand entries. For 3.9 million:
- a Lua table of that size costs over 200 MB per worker, and nginx runs one worker per CPU core;
- every reload rebuilds all of it, which takes several seconds;
- the settings database and the rule file grow by the same amount.
So the real question was: how do you check an address against millions of networks, in every
worker, without each worker holding its own copy?
The idea in three steps
-
Turn the list into sorted, non-overlapping ranges.
10.0.0.0/24is just the range10.0.0.0 – 10.0.0.255. Overlapping and adjacent entries merge into one range. An IPv4 range is two 32-bit numbers: 8 bytes. - Write the ranges to a flat binary file and map it into memory once, read-only, in the nginx master before it starts the workers. Every worker inherits the mapping, and the kernel shares the pages through the page cache.
- Look an address up with a binary search over the ranges. No allocation, no hashing, about 22 steps for 4 million ranges.
Nothing here is new. Routing tables and GeoIP databases have worked like this for decades. The
interesting parts are in the details.
Step 1: building the ranges without using lots of memory
The control plane (Go) downloads the list and parses it while it downloads, without allocating
a string per line for IPv4. Each entry becomes a range, and the ranges go into fixed-size chunks of
512 KiB. Chunks never get copied when they grow, unlike one big slice that doubles.
When the download is done, each chunk is sorted on its own, and a k-way merge (a small heap over
the chunks) produces the ranges in order. Merging overlapping and adjacent neighbours happens on the
fly while the result streams straight into the file, and the chunks are released as they're used up:
// merging while streaming: r arrives in sorted order
if have && (cur.Last == ^uint32(0) || r.First <= cur.Last+1) {
cur.Last = max(cur.Last, r.Last) // overlaps or touches: extend
} else {
if have { write(cur) }
cur, have = r, true
}
(The ^uint32(0) check stops 255.255.255.255 + 1 from wrapping around to 0. I found that one
with a test, fortunately.)
Result for the 3.9 million entry list (a 56 MB download): 3.55 million ranges, a 28.5 MB file,
about 1 second and about 35 MB of peak heap, which is given back afterwards.
The file format
It's deliberately boring, so that Lua can read it with pointer casts:
| Offset | Content |
|---|---|
| 0 | magic CVIPSET\0, version (u32), reserved (u32) |
| 16 | number of IPv4 ranges (u64), number of IPv6 ranges (u64) |
| 32 | SHA-256 of the payload |
| 64 | IPv4 ranges: {u32 first, u32 last} × n4 |
| … | IPv6 ranges: {u64 first_hi, first_lo, last_hi, last_lo} × n6 |
Little-endian, so x86-64 and arm64 read it natively. An IPv6 address is split into two 64-bit
halves, compared high half first.
Files are content-addressed: the name is the SHA-256 of the file (<sha256>.bin), and they're
written to a temporary name and renamed into place. That matters a lot for mmap. More on that below.
Step 2: mapping the file from Lua
OpenResty's init_by_lua runs in the nginx master, before the workers are forked. If you
mmap a file there with MAP_SHARED and PROT_READ, every worker gets the same physical pages.
LuaJIT's FFI makes this short:
local ffi = require "ffi"
ffi.cdef[[
int open(const char *path, int flags, ...);
int close(int fd);
int64_t lseek(int fd, int64_t offset, int whence);
void *mmap(void *addr, size_t length, int prot, int flags, int fd, int64_t offset);
int munmap(void *addr, size_t length);
]]
local C = ffi.C
local O_RDONLY, O_CLOEXEC = 0, 0x80000 -- Linux x86-64 / arm64
local PROT_READ, MAP_SHARED, SEEK_END = 1, 1, 2
local fd = C.open(path, O_RDONLY + O_CLOEXEC)
local size = tonumber(C.lseek(fd, 0, SEEK_END))
local m = C.mmap(nil, size, PROT_READ, MAP_SHARED, fd, 0)
C.close(fd) -- the mapping stays valid without the descriptor
-- unmap when this Lua VM is collected (more on reloads below)
local base = ffi.gc(ffi.cast("const uint8_t *", m),
function(p) C.munmap(ffi.cast("void *", p), size) end)
local h = ffi.cast("const uint64_t *", base + 16)
local n4 = tonumber(h[0])
local v4 = ffi.cast("const uint32_t *", base + 64) -- {first, last} pairs
Before the gateway uses a file it checks it: magic and version, that the size matches the header,
the SHA-256 of the whole file against the hash in the configuration, and that the ranges really are
sorted and disjoint (the binary search silently gives wrong answers otherwise). If anything is off,
the configuration is rejected: openresty -t fails and a reload keeps the running config. For the
28.5 MB file, all of that takes about 80 ms, once per configuration load, not per worker.
Step 3: the lookup
ngx.var.binary_remote_addr gives the client address as 4 (or 16) raw bytes. For IPv4, turn it into
a number and find the last range whose start is ≤ the address:
local function has4(l, bin)
local n = l.n4
if n == 0 then return false end
local b1, b2, b3, b4 = string.byte(bin, 1, 4)
local x = ((b1 * 256 + b2) * 256 + b3) * 256 + b4
local a = l.v4
if a[0] > x then return false end
local lo, hi = 0, n - 1
while lo < hi do
local mid = bit.rshift(lo + hi + 1, 1)
if a[mid * 2] <= x then lo = mid else hi = mid - 1 end
end
return x <= a[lo * 2 + 1]
end
The IPv6 version is the same with two 64-bit halves (bit.bswap on the raw bytes, then compare
hi first). LuaJIT compiles this loop into tight machine code: about 1.9 million lookups per
second per CPU core against 4 million ranges, with no garbage created per request.
The parts that can bite you
Reloads. On nginx -s reload the master loads the new configuration in a fresh Lua VM, and the
old VM is closed. Because the pointer was wrapped in ffi.gc, closing the old VM unmaps the old
files in the master. The old workers still have their own inherited mappings and keep them until
they exit, so a request that's in flight never sees its list disappear.
Never modify a mapped file in place. If you truncate or rewrite a file that a process has
mapped, the next access to a page that no longer exists is a SIGBUS, which kills the worker. This is
why the files are content-addressed and written by rename: a changed list is a new file with a new
name, and the old one is only deleted when no configuration uses it any more (with a 10-minute
grace period). Deleting a mapped file is harmless; the pages stay until the last mapping goes.
Container memory. Page cache for a mapped file counts towards the container's memory cgroup, but
only once, not per worker. In the integration test, a 1.2-million-entry list made the whole
container grow by 17 MiB.
Platform assumptions. O_CLOEXEC = 0x80000 is the value on Linux x86-64 and arm64, not
everywhere. The loader refuses to run on big-endian systems rather than guessing.
Why not something else?
-
lua_shared_dictis shared between workers too, but it's a key-value store. Range lookups would mean one key per address or one per prefix length, and filling it at every reload is slow. -
ipset/nftables in the kernel is excellent for pure blocking. But it needs
NET_ADMINin the container, sits outside the proxy, and can't be one condition among others in a WAF rule ("block if the address is in this list and the path is/admin"). - A Lua table per worker is what I had. See the 200 MB above.
Numbers
Measured with the 3.9 million entry list:
| Stored file | 3.55 million ranges, 28.5 MB |
| Download and conversion | about 1 s, about 35 MB peak memory, given back afterwards |
| Gateway memory | the file once, shared by all workers |
| File check at configuration load | about 80 ms |
| Lookups | about 1.9 million per second per CPU core |
| Before | over 200 MB per worker, several seconds per reload |
Try it
The code is short enough to read in one sitting:
gateway/lua/corvus/iplist.lua
(the mapping and the lookup, ~170 lines) and
control/internal/ipset
(the Go builder and file format). A golden test file is shared between the Go and Lua tests, so both
sides agree on the format byte for byte.
If you've solved this differently, for example with a radix tree in shared memory or something
eBPF-based, I'd love to hear how it compares.
About Corvus
Corvus is an Apache-2.0 reverse proxy with a built-in
WAF, one container with a web console in the style of Nginx Proxy Manager. In the console, an IP list
can now be a URL to a blocklist of millions of entries; the list page shows the counts, a preview
and a "check an IP address" box instead of loading the whole thing. The user who opened the issue
got their 50 MB list, and I got an excuse to write mmap from Lua.
Top comments (0)