Skip to content

perf(3scale_batcher): filter by keys to avoid expensive shared dict read - #1615

Open
tkan145 wants to merge 1 commit into
3scale:masterfrom
tkan145:THREESCALE-16640-part-2
Open

tkan145 wants to merge 1 commit into
3scale:masterfrom
tkan145:THREESCALE-16640-part-2

Conversation

@tkan145

@tkan145 tkan145 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

What

Previously, we need to fetches all keys from the shared dict, then loop through each key and retrieve each key from the shared_dict and discard all keys that does not match service_id. This PR will filter by keys to avoid expensive shared dict read.

Benchmark

Benchmark script

Details
local root = require('pl.path').currentdir()
package.path = root .. '/?.lua;' ..
               root .. '/gateway/src/?.lua;' ..
               root .. '/gateway/src/apicast/policy/3scale_batcher/?.lua;' ..
               package.path

local monotonic_msec = require("resty.core.time").monotonic_msec
local update_time = ngx.update_time
local print = print
local Usage = require('apicast.usage')
local s, e
---------------------------------------------------------------------------
-- Benchmark: reports_batcher add/get_all, scaled by number of services
-- sharing the 'batched_reports' shdict.
--
-- This isolates the Lua-level cost of ReportsBatcher:get_all() from
-- end-to-end request latency (dominated by the backend auth round trip,
-- which swamps anything measurable here). It shows how get_all()'s cost for
-- ONE service grows as OTHER services accumulate keys in the same shared
-- dict, since storage:get_keys() has no way to filter by prefix and returns
-- every key in the dict regardless of which service is being flushed.
---------------------------------------------------------------------------
print('\n--- reports_batcher add/get_all (shared dict scan cost) ---')

local ReportsBatcher = require('apicast.policy.3scale_batcher.reports_batcher')
local Transaction = require('apicast.policy.3scale_batcher.transaction')

local GET_ALL_ITERATIONS = 1000
local CREDS_PER_SERVICE = 50
local METRICS_PER_CRED = 3

local function add_reports_for(reports_batcher, service_id, creds_per_service, metrics_per_cred)
  for c = 1, creds_per_service do
    local creds = { user_key = 'user_' .. service_id .. '_' .. c }
    local usage = Usage.new()
    for m = 1, metrics_per_cred do
      usage:add('metric_' .. m, 1)
    end
    reports_batcher:add(Transaction.new(service_id, creds, usage))
  end
end

local function bench_get_all(num_other_services)
  ngx.shared.batched_reports:flush_all()
  ngx.shared.batched_reports:flush_expired()

  local reports_batcher = ReportsBatcher.new(
    ngx.shared.batched_reports, 'batched_reports_locks')

  local target_service = 'svc_target'

  -- Other services' pending reports that get_all(target_service) has to
  -- scan past and discard on every call.
  for s = 1, num_other_services do
    add_reports_for(reports_batcher, 'svc_other_' .. s, CREDS_PER_SERVICE, METRICS_PER_CRED)
  end

  update_time()
  s = monotonic_msec()
  for _ = 1, GET_ALL_ITERATIONS do
    -- get_all() deletes the target service's keys as it collects them, so
    -- repopulate before each call to keep the scan size constant.
    add_reports_for(reports_batcher, target_service, CREDS_PER_SERVICE, METRICS_PER_CRED)
    reports_batcher:get_all(target_service)
  end
  update_time()
  e = monotonic_msec()

  print(string.format(
    '  get_all (own creds=%d, other services=%d, total keys~=%d): ',
    CREDS_PER_SERVICE, num_other_services,
    CREDS_PER_SERVICE * METRICS_PER_CRED * (num_other_services + 1)),
    e - s, ' ms for ', GET_ALL_ITERATIONS, ' calls')
end

bench_get_all(0)
bench_get_all(10)
bench_get_all(50)
bench_get_all(200)

Run with

resty --shdict 'batched_reports 50m' --shdict 'batched_reports_locks 1m' benchmark/3scale_batcher.lua

Results

Before

--- reports_batcher add/get_all (shared dict scan cost) ---
  get_all (own creds=50, other services=0, total keys~=150): 285 ms for 1000 calls
  get_all (own creds=50, other services=10, total keys~=1650): 1104 ms for 1000 calls
  get_all (own creds=50, other services=50, total keys~=7650): 1284 ms for 1000 calls
  get_all (own creds=50, other services=200, total keys~=30150): 1476 ms for 1000 calls

After

--- reports_batcher add/get_all (shared dict scan cost) ---
  get_all (own creds=50, other services=0, total keys~=150): 297 ms for 1000 calls
  get_all (own creds=50, other services=10, total keys~=1650): 220 ms for 1000 calls
  get_all (own creds=50, other services=50, total keys~=7650): 223 ms for 1000 calls
  get_all (own creds=50, other services=200, total keys~=30150): 226 ms for 1000 calls

@tkan145
tkan145 requested a review from a team as a code owner November 27, 2026 07:09
@tkan145
tkan145 force-pushed the THREESCALE-16640-part-2 branch from df698c7 to 7c46e69 Compare November 30, 2026 04:12
@akostadinov

Copy link
Copy Markdown

Sorry for the low-effort review, I just lack the time to get enough into the project to have a strong opinion. But this is what Bob said about it. I trust your judgment whether these make sense or not:

Review of #1615: filter by keys to avoid expensive shared dict read

Summary: the change preserves behavior for the target service, but it makes an existing get_keys() 1024-key limit worse. The benchmark also doesn't measure what it claims for the larger cases. I'd hold off merging until that's addressed.

I read the diff and the surrounding code, and checked lua-nginx-module's ngx_http_lua_shdict.c for how get_keys and get behave. I did not run the specs or the benchmark, because resty isn't available in my environment.

What the code change does

The PR touches only reports_batcher.lua (get_all) and the CHANGELOG.

In get_all(service_id):

  1. It takes the per-service lock, then calls storage:get_keys() as before.
  2. New: it builds service_prefix = "service_id:" .. service_id .. "," once.
  3. New: each key goes through key:find(service_prefix, 1, true) == 1, a plain-text start-of-string check.
  4. Only keys that pass get the old processing: storage:get(key), then report_from_key_batched_report (a ngx_re.match), then the report.service_id == service_id and value > 0 checks, then insert and delete.

Everything else is only re-indented.

Before, every key in the batched_reports dict, including other services' keys, got a shared-dict get (which takes the shpool mutex) and a regex match. Then report.service_id == service_id discarded it. Now other services' keys cost only a find.

Does it preserve behavior?

For normal cases, yes.

  • The filter is only a pre-filter. The original report.service_id == service_id check is still there, so the pre-filter can only skip keys, never accept extra ones.
  • No false negatives for valid ids. Keys are built only by key_for_batched_report as service_id:%s,<creds>,metric:%s, so every key for a service starts with exactly that prefix. The trailing comma stops service 1 from matching 12. The regex's [\w-]+ can't contain a comma, so the old and new matches agree.
  • Locking and nil handling are unchanged. The earlier fix (79f35ae) that reads keys under the lock is kept. Skipping foreign keys also removes the race where another service's timer deletes a key between get_keys and get.
  • Existing specs should still pass. The spec keys all begin with service_id:1,.

Small differences:

  • The WARN failed to get report for key ... log now fires only for the service's own malformed keys. Before, it fired for every unparseable key in the dict, from every service's timer. This is arguably better.
  • If a service id contains characters outside [\w-], or a credential contains the text service_id:, the old unanchored regex could attribute a key to the wrong service. The new prefix check avoids that. Real 3scale ids are numeric, so this is theoretical.
  • get refreshes a key's LRU position (ngx_queue_insert_head in ngx_http_lua_shdict_lookup), and foreign keys are no longer refreshed. This is the root of the issuebelow.
  • The PR adds no test for the new filtering.
  • The CHANGELOG entry is labelled PR #1618 but links to /pull/1608. The PR number is 1615.

A hidden problem: the 1024-key limit

self.storage:get_keys() is called with no argument. In shdict.c, the default is attempts = 1024. The keys returned are the 1024 least-recently-used ones, because iteration starts at ngx_queue_last (the LRU tail). Both get and incr move a key to the head. This limit was already there; the PR changes how it plays out.

  • Before: get on each of the 1024 returned keys moved them to the head. The next get_keys call therefore returned a different slice, so across calls the dict was effectively scanned in rotation. This was accidental, but it kept things fair.
  • After: foreign keys are never touched, so the same 1024 oldest keys stay at the tail. Fresh keys for an active service sit at the head and fall outside the window.

Once the dict holds more than 1024 live keys, get_all(svc) can return nothing for a busy service. Its reports wait until the owners of the older keys flush them and shrink the window. That delays reporting and can leave a lot of data pending in the dict. In the worst case it hits the 'no memory' path in add, which silently loses reports.

The benchmark seems to show this. With 0 other services (150 keys), get_all does real work and takes 297 ms. With 10, 50 or 200 other services (1650+ keys), it takes about 220 ms, which is less than the 0-other-services run even though there are far more keys. That fits get_all finding none of the target's keys and doing no regex, delete or insert work. So the "after" numbers for the larger cases measure the scan-and-skip cost, not a faster flush. The "before" plateau at about 1.1–1.5 s fits the 1024 cap as well.

Performance impact

  • Single service, under 1024 keys: about the same. The extra plain find per key is tens of nanoseconds. The 285 → 297 ms is noise-level.
  • Many services sharing the dict: the CPU saving per call is real. It removes up to 1024 get calls and regex matches, and each get takes the shdict mutex that request-path add/incr also use. That should reduce mutex contention and Lua allocations.
  • Unchanged cost: get_keys still builds a table of up to 1024 strings while holding the shdict mutex, and it still scans from the LRU tail. The PR doesn't change that.
  • The cost is correctness: the new tail-pinned behavior described above.

Recommendations

  1. Don't merge until the starvation case is addressed. The simplest option is get_keys(0), but it holds the mutex for O(n) and that is costly, so I wouldn't use it as-is. Better options are a per-service key index or a per-service dict. A cheaper fix is a bounded max_count combined with an LRU "touch" for skipped keys, but that gives back part of the savings.
  2. Fix the benchmark so each iteration checks that #get_all(target) == CREDS_PER_SERVICE * METRICS_PER_CRED. Otherwise it can pass while doing no work.
  3. Add specs for these cases:
    • mixed-service keys, where only the target service's keys are returned and deleted;
    • prefix collisions such as 1 vs 12;
    • more than 1024 keys, if an integration test in t/ can cover it.
  4. Fix the CHANGELOG PR number and link.

@borisurbanik

borisurbanik commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

I was familiar with this file already so I took a look as well - the PRs change is very minimal and a performance improvement.

The LRU dict updates from @akostadinov comment are a real hidden change that is reproducible (see below). This could be an impossible edge case that might require re-configuration, or timer tasks crashing for some reason.

OTOH the effect is bad enough we might want to address this - @tkan145 is the best person to decide if it's something to worry about. Besides this just the changelog entry needs a correction.

To reproduce I've run the slightly modified benchmark with rover exec resty --shdict 'batched_reports 50m' --shdict 'batched_reports_locks 1m' benchmark/3scale_batcher.lua. It populates the dict once, doesn't touch the entries afterwards, and counts how many get_all(target) calls are needed before the target service's entries are returned:

entries master this PR
1,500 (10 services) call 2 not collected in 9 calls
7,500 (50 services) call 8 not collected in 21 calls
30,000 (200 services) call 30 not collected in 65 calls

Conditions for the edge case:

  • there is a service (or more) that produced 1024 entries in the cache
  • these records are no longer getting updates from the requests
  • the timer task(s) are not collecting the records (crashed / failed to start)
Script
local root = require('pl.path').currentdir()
package.path = root .. '/?.lua;' ..
               root .. '/gateway/src/?.lua;' ..
               root .. '/gateway/src/apicast/policy/3scale_batcher/?.lua;' ..
               package.path

local monotonic_msec = require("resty.core.time").monotonic_msec
local update_time = ngx.update_time
local print = print
local Usage = require('apicast.usage')
local s, e
---------------------------------------------------------------------------
-- Benchmark: reports_batcher add/get_all, scaled by number of services
-- sharing the 'batched_reports' shdict.
--
-- This isolates the Lua-level cost of ReportsBatcher:get_all() from
-- end-to-end request latency (dominated by the backend auth round trip,
-- which swamps anything measurable here). It shows how get_all()'s cost for
-- ONE service grows as OTHER services accumulate keys in the same shared
-- dict, since storage:get_keys() has no way to filter by prefix and returns
-- every key in the dict regardless of which service is being flushed.
---------------------------------------------------------------------------
print('\n--- reports_batcher add/get_all (shared dict scan cost) ---')

local ReportsBatcher = require('apicast.policy.3scale_batcher.reports_batcher')
local Transaction = require('apicast.policy.3scale_batcher.transaction')

local GET_ALL_ITERATIONS = 1000
local CREDS_PER_SERVICE = 50
local METRICS_PER_CRED = 3

local function add_reports_for(reports_batcher, service_id, creds_per_service, metrics_per_cred)
  for c = 1, creds_per_service do
    local creds = { user_key = 'user_' .. service_id .. '_' .. c }
    local usage = Usage.new()
    for m = 1, metrics_per_cred do
      usage:add('metric_' .. m, 1)
    end
    reports_batcher:add(Transaction.new(service_id, creds, usage))
  end
end

local function print_histogram(histogram)
  local returned_counts = {}
  for returned in pairs(histogram) do
    returned_counts[#returned_counts + 1] = returned
  end
  table.sort(returned_counts)

  print(string.format('    reports returned per call (expected %d):',
    CREDS_PER_SERVICE * METRICS_PER_CRED))
  for _, returned in ipairs(returned_counts) do
    print(string.format('      %4d reports: %4d calls', returned, histogram[returned]))
  end
end

local function bench_get_all(num_other_services)
  ngx.shared.batched_reports:flush_all()
  ngx.shared.batched_reports:flush_expired()

  local reports_batcher = ReportsBatcher.new(
    ngx.shared.batched_reports, 'batched_reports_locks')

  local target_service = 'svc_target'

  -- Other services' pending reports that get_all(target_service) has to
  -- scan past and discard on every call.
  for s = 1, num_other_services do
    add_reports_for(reports_batcher, 'svc_other_' .. s, CREDS_PER_SERVICE, METRICS_PER_CRED)
  end

  -- histogram[number of reports returned by get_all] = number of calls
  local histogram = {}

  update_time()
  s = monotonic_msec()
  for _ = 1, GET_ALL_ITERATIONS do
    -- get_all() deletes the target service's keys as it collects them, so
    -- repopulate before each call to keep the scan size constant.
    add_reports_for(reports_batcher, target_service, CREDS_PER_SERVICE, METRICS_PER_CRED)
    local returned = #reports_batcher:get_all(target_service)
    histogram[returned] = (histogram[returned] or 0) + 1
  end
  update_time()
  e = monotonic_msec()

  print(string.format(
    '  get_all (own creds=%d, other services=%d, total keys~=%d): ',
    CREDS_PER_SERVICE, num_other_services,
    CREDS_PER_SERVICE * METRICS_PER_CRED * (num_other_services + 1)),
    e - s, ' ms for ', GET_ALL_ITERATIONS, ' calls')

  print_histogram(histogram)
end

---------------------------------------------------------------------------
-- Window rotation: does get_all(target) ever reach the target's keys when
-- other services' keys fill the get_keys() window?
--
-- Unlike bench_get_all, every key is added ONCE and never touched by the
-- benchmark again, so the only thing that can change the LRU order between
-- calls is get_all() itself (the per-key storage:get() moves the key to the
-- head of the LRU). The other services have no timer here, so nothing
-- collects their keys.
--
-- get_keys() returns at most GET_KEYS_WINDOW keys, so a get_all() that moves
-- the keys it scans to the LRU head needs about foreign_keys / window calls
-- to reach the target. The loop stops at the first call that returns
-- reports, or after twice that many calls (plus a margin) if none does.
---------------------------------------------------------------------------
local GET_KEYS_WINDOW = 1024

local function bench_rotation(num_other_services)
  ngx.shared.batched_reports:flush_all()
  ngx.shared.batched_reports:flush_expired()

  local reports_batcher = ReportsBatcher.new(
    ngx.shared.batched_reports, 'batched_reports_locks')

  local target_service = 'svc_target'

  for o = 1, num_other_services do
    add_reports_for(reports_batcher, 'svc_other_' .. o, CREDS_PER_SERVICE, METRICS_PER_CRED)
  end
  -- Added last, so the target's keys start at the head of the LRU (the last
  -- ones get_keys() returns).
  add_reports_for(reports_batcher, target_service, CREDS_PER_SERVICE, METRICS_PER_CRED)

  local foreign_keys = CREDS_PER_SERVICE * METRICS_PER_CRED * num_other_services
  local max_calls = 2 * math.ceil(foreign_keys / GET_KEYS_WINDOW) + 5
  local first_hit

  for call = 1, max_calls do
    if #reports_batcher:get_all(target_service) > 0 then
      first_hit = call
      break
    end
  end

  print(string.format(
    '  rotation (other services=%d, total keys~=%d): target %s',
    num_other_services,
    CREDS_PER_SERVICE * METRICS_PER_CRED * (num_other_services + 1),
    first_hit and ('first collected on call ' .. first_hit)
               or ('NOT collected in ' .. max_calls .. ' calls')))
end

bench_get_all(0)
bench_get_all(10)
bench_get_all(50)
bench_get_all(200)

print('\n--- window rotation (keys added once, get_all called repeatedly) ---')
bench_rotation(10)
bench_rotation(50)
bench_rotation(200)

master
--- reports_batcher add/get_all (shared dict scan cost) ---
  get_all (own creds=50, other services=0, total keys~=150): 311 ms for 1000 calls
    reports returned per call (expected 150):
       150 reports: 1000 calls
  get_all (own creds=50, other services=10, total keys~=1650): 999 ms for 1000 calls
    reports returned per call (expected 150):
         0 reports: 1000 calls
  get_all (own creds=50, other services=50, total keys~=7650): 1047 ms for 1000 calls
    reports returned per call (expected 150):
         0 reports: 1000 calls
  get_all (own creds=50, other services=200, total keys~=30150): 1082 ms for 1000 calls
    reports returned per call (expected 150):
         0 reports: 1000 calls

--- window rotation (keys added once, get_all called repeatedly) ---
  rotation (other services=10, total keys~=1650): target first collected on call 2
  rotation (other services=50, total keys~=7650): target first collected on call 8
  rotation (other services=200, total keys~=30150): target first collected on call 30
this PR
--- reports_batcher add/get_all (shared dict scan cost) ---
  get_all (own creds=50, other services=0, total keys~=150): 304 ms for 1000 calls
    reports returned per call (expected 150):
       150 reports: 1000 calls
  get_all (own creds=50, other services=10, total keys~=1650): 242 ms for 1000 calls
    reports returned per call (expected 150):
         0 reports: 1000 calls
  get_all (own creds=50, other services=50, total keys~=7650): 238 ms for 1000 calls
    reports returned per call (expected 150):
         0 reports: 1000 calls
  get_all (own creds=50, other services=200, total keys~=30150): 241 ms for 1000 calls
    reports returned per call (expected 150):
         0 reports: 1000 calls

--- window rotation (keys added once, get_all called repeatedly) ---
  rotation (other services=10, total keys~=1650): target NOT collected in 9 calls
  rotation (other services=50, total keys~=7650): target NOT collected in 21 calls
  rotation (other services=200, total keys~=30150): target NOT collected in 65 calls

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants