Repository navigation
fix(ivm): cap concurrent evaluations per isolate and queue the excess - #5385
Conversation
|
Warning Review limit reached
Next review available in: 55 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
Note
|
| Layer / File(s) | Summary |
|---|---|
Gate option and runner wiring src/util/ivm/scriptRunner.ts, src/util/customMappings/sandboxClient.ts |
Adds the optional concurrency limit, normalizes invalid values to ungated execution, and configures custom mappings with a default cap. |
Slot acquisition and queue metrics src/util/ivm/scriptRunner.ts, src/util/prometheus.js |
Adds FIFO per-isolate slot gates, queue wait handling, release behavior, unified metric tags, and the ivm_execution_queue_wait histogram. |
Concurrency and metrics validation src/util/ivm/scriptRunner.gate.test.ts |
Tests concurrency limits, queue draining, workspace isolation, failure release, gate cleanup, and queue metrics. |
Estimated code review effort: 4 (Complex) | ~45 minutes
Sequence Diagram(s)
sequenceDiagram
participant Client as sandboxClient
participant Runner as IvmScriptRunner
participant Gate as ExecutionGate
participant Isolate as isolated-vm
participant Metrics as Prometheus metrics
Client->>Runner: execute custom mapping
Runner->>Gate: acquireSlot(cacheKey, metricTags)
Gate->>Isolate: admit evaluation or queue caller
Isolate-->>Runner: result or error
Runner->>Gate: releaseSlot()
Gate->>Metrics: record queue count and wait duration
Possibly related PRs
- rudderlabs/rudder-transformer#5348: Adds the isolated-vm custom-mapping sandbox runner that this throttling builds on.
- rudderlabs/rudder-transformer#5373: Overlaps with the platform-error metric tagging changes in
IvmScriptRunner.execute().
Suggested reviewers: maheshkutty
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title accurately summarizes the core change: capping per-isolate concurrency and queueing overflow. |
| Description check | ✅ Passed | The description includes the required sections, Linear task, objectives, behavior changes, dependencies, and technical notes. |
| Docstring Coverage | ✅ Passed | No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✨ Finishing Touches
🧪 Generate unit tests (beta)
- Create PR with unit tests
- Commit unit tests in branch
fix/int-6832-ivm-concurrency-cap
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #5385 +/- ##
===========================================
+ Coverage 92.89% 92.93% +0.04%
===========================================
Files 709 709
Lines 38460 38817 +357
Branches 9021 9106 +85
===========================================
+ Hits 35726 36075 +349
- Misses 2508 2532 +24
+ Partials 226 210 -16 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
An isolate runs JS on one thread against one fixed heap, so extra concurrency on it buys no throughput — it only keeps more structured-clone argument copies and evaluation working sets alive on that heap at once. When the total breaches memoryLimit, V8 disposes the whole isolate, failing every in-flight evaluation rather than just the one that tipped it. That amplification is what surfaced as intermittent retryable 500s on custom-mapping evaluation: 879 ivm_platform_error in a single hour on one workspace, and zero across the rest of the week. Nothing bounded that fan-in: execute() coalesced isolate *creation* only, and a warm isolate accepted unlimited concurrent calls while callers actively fan out (the HTTP destination evaluates headers, query params and payload separately; ga4_v2 Promise.all's over its mappings). Gate admission per isolate: cap the calls in flight and queue the excess. The queue is unbounded — nothing is ever shed, so an overload costs latency rather than dropped events. Queued callers hold their args on the Node heap, where those args already were, so the queue costs the isolate nothing. release() hands its slot straight to the next waiter rather than freeing it and waking one, which would let the accounting drift and admit past the cap. Waiters are FIFO so the oldest cannot starve under sustained saturation, and a gate is dropped from the map once fully idle so it stays bounded by the live isolate set. Two new metrics carry the same (workspaceId, functionName, cache) labels as ivm_platform_error, so they join with it and with each other: ivm_execution_queued (counter, incremented at enqueue so a backlog is visible the moment it forms) and ivm_execution_queue_wait (timer, sampled on admission). The gate is per isolate, i.e. per workspace, so "which tenant is at its cap" is answerable from them. maxConcurrentExecutions defaults to unlimited, so custom_audience and every other consumer keep today's behaviour; only the custom_mappings_ivm pool opts in, at 100 via CUSTOM_MAPPINGS_IVM_MAX_CONCURRENT_EXECUTIONS. An absent or unparseable value leaves execution ungated rather than wedging the sandbox. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
beecac1 to
d1c248e
Compare
The metric was not in the static registry, so prometheus.js created it on first observation with no bucket argument and it fell back to prom-client's defaults, whose first boundary is 5ms. A gated isolate drains far faster than that. Measured on a local run (cap 8, one workspace, 542k evaluations): 310,578 of 312,295 observations — 99.45% — landed in that single first bucket, with the remaining 0.55% in the next and every higher bucket empty. histogram_quantile() on that series interpolates inside one bucket, so it cannot separate a healthy 0.4ms wait from a degraded 4ms one. The counter tells you queueing is happening; this histogram is meant to say how badly, and as registered it could not. Declaring it explicitly also pins the label set to (functionName, workspaceId, cache) rather than inferring it from the first call site. Re-measured with the new buckets under the same load: the distribution now spans five buckets (p50 ~3.8ms, p99 ~19ms) instead of collapsing into one. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/util/ivm/scriptRunner.ts (1)
183-284: 🩺 Stability & Availability | 🔵 TrivialSolid FIFO gate implementation — one operational note on unbounded queue wait.
Slot accounting, hand-off, and gate cleanup all check out against the test suite (cap enforcement, FIFO order, per-workspace isolation, failure release, idle cleanup). One thing worth keeping in mind operationally: a queued caller's wait has no timeout or cancellation hook —
execTimeoutMsonly bounds the isolate evaluation once admitted, not the time spent waiting ingate.waiters. If an isolate becomes permanently stuck (e.g., a hungevalClosurethat never resolves/rejects), every subsequently queued call for that workspace would wait forever with no way to bail out, even if the upstream HTTP request has already timed out and moved on.This looks like a deliberate, well-reasoned tradeoff given the inline comments and the load-test results cited in the PR description, so I'm not blocking on it — just flagging for awareness in case a max-queue-wait or abort-signal integration becomes worth adding later.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/util/ivm/scriptRunner.ts` around lines 183 - 284, Document the operational limitation of acquireSlot: queued callers have no timeout or cancellation while waiting in gate.waiters, and execTimeoutMs applies only after isolate admission. No code change is required; preserve the current unbounded FIFO queue behavior unless a future change explicitly adds max-wait or abort-signal support.src/util/prometheus.js (1)
983-994: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
ivm_execution_queuedcounter isn't explicitly registered here, unlike its sibling.
scriptRunner.ts'sacquireSlot()emitsstats.increment('ivm_execution_queued', metricTags)with the same label set asivm_execution_queue_wait, but only the histogram was added to thismetricsarray — the counter is missing. It still works today becausecounter()/increment()auto-creates unregistered metrics on first use, but that path also logs a warning on first increment and leaves the counter undocumented next to its carefully-tuned sibling.♻️ Proposed fix: register `ivm_execution_queued` alongside `ivm_execution_queue_wait`
{ name: 'ivm_execution_queue_wait', help: 'Time an evaluation waited for a free isolate concurrency slot (seconds)', type: 'histogram', labelNames: ['functionName', 'workspaceId', 'cache'], buckets: [0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1], }, + { + name: 'ivm_execution_queued', + help: 'Count of evaluations that had to queue for a free isolate concurrency slot', + type: 'counter', + labelNames: ['functionName', 'workspaceId', 'cache'], + },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/util/prometheus.js` around lines 983 - 994, Add an explicit counter metric definition for ivm_execution_queued alongside ivm_execution_queue_wait in the metrics array, using the same functionName, workspaceId, and cache labelNames. Keep the existing histogram configuration unchanged and ensure the counter is registered before scriptRunner.ts acquireSlot() increments it.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@src/util/ivm/scriptRunner.ts`:
- Around line 183-284: Document the operational limitation of acquireSlot:
queued callers have no timeout or cancellation while waiting in gate.waiters,
and execTimeoutMs applies only after isolate admission. No code change is
required; preserve the current unbounded FIFO queue behavior unless a future
change explicitly adds max-wait or abort-signal support.
In `@src/util/prometheus.js`:
- Around line 983-994: Add an explicit counter metric definition for
ivm_execution_queued alongside ivm_execution_queue_wait in the metrics array,
using the same functionName, workspaceId, and cache labelNames. Keep the
existing histogram configuration unchanged and ensure the counter is registered
before scriptRunner.ts acquireSlot() increments it.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a821aa37-6eda-4a7c-83bd-80bf9d9586ff
📒 Files selected for processing (4)
src/util/customMappings/sandboxClient.tssrc/util/ivm/scriptRunner.gate.test.tssrc/util/ivm/scriptRunner.tssrc/util/prometheus.js
histogram_quantile() clamps any quantile landing in the +Inf bucket to the highest finite boundary, so with buckets topping out at 1s a real backlog (queue depth growing behind timed-out executions) reports p99 as flatly 1 regardless of whether the true wait is 1.1s or 60s, and a p99 > 5s alert can never fire. Extends the range to 10s. Addresses review feedback: #5385 (comment)
9ef1bcb
histogram_quantile() clamps any quantile landing in the +Inf bucket to the highest finite boundary, so with buckets topping out at 1s a real backlog (queue depth growing behind timed-out executions) reports p99 as flatly 1 regardless of whether the true wait is 1.1s or 60s, and a p99 > 5s alert can never fire. Extends the range to 10s. Addresses review feedback from PR #5385, discussion r3658951219.
9ef1bcb to
3655fcb
Compare
|



What are the changes introduced in this PR?
Caps how many custom-mapping evaluations run concurrently on a single
isolated-vmisolate and queues the excess.IvmScriptRunnergains one optional knob —maxConcurrentExecutions. It defaults to unlimited, socustom_audienceand every other consumer keep today's behaviour; only thecustom_mappings_ivmpool opts in.What is the related Linear task?
Resolves INT-6832
Please explain the objectives of your changes below
An isolate runs JS on one thread against one fixed heap. Extra concurrency on it buys no throughput — it only keeps more structured-clone argument copies and evaluation working sets alive on that heap at the same time. When the total breaches
memoryLimit, V8 disposes the whole isolate, so every in-flight evaluation fails at once with a retryable 500, not just the one that tipped it. That amplification is what surfaced as the intermittent 500 spikes on Lovable's HTTP destination.Nothing bounded that fan-in before this.
execute()had promise-coalescing on isolate creation only; once an isolate was warm, unlimited calls could re-enter it. Callers actively fan out — the HTTP destination maps headers, query params and payload as three separate evaluations per event (procWorkflow.yaml:39,50,59), andga4_v2Promise.alls over its mapping list (customMappingsHandler.js:110).Bounding admission converts "the isolate dies and takes every in-flight event with it" into "the excess waits". Queued callers hold their args on the Node heap, where those args already were — the queue itself costs the isolate nothing.
This is follow-up #1 from the INT-6832 thread. Follow-up #2 (compile-caching the mapping template) is #5372; the two are independent and can merge in either order.
Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?
Only the
custom_mappings_ivmpool changes behaviour, and only past the cap. Nothing is ever shed — the queue is unbounded by construction, so an overload costs latency rather than dropped events.acquireSlot()cannot reject; it only ever admits or queues.One new tunable (falling back to unlimited — i.e. today's behaviour — if absent or unparseable, rather than wedging the sandbox):
CUSTOM_MAPPINGS_IVM_MAX_CONCURRENT_EXECUTIONSThe cap alone is what protects the isolate heap, and a single-threaded isolate drains its queue at its own throughput either way, so an explicit queue bound would only have bought a strictly worse failure mode (a dropped event instead of a slower one).
Where the cap of 100 comes from
Sized against
enterprise-eu/rudder-eu-central-1b, the busiest namespace for this pool by a wide margin (~380xeu-central-1a):ivm_platform_error,custom_mappings_ivmThat error profile is the whole argument for this PR: 879 failures inside a single hour and zero across the rest of the week is not a steady error rate, it is one isolate dying and taking every in-flight evaluation with it.
An isolate runs on one thread, so sustaining ~13.8k evals/s implies a sub-100µs evaluation, which by Little's Law puts steady-state in-flight depth near 1. Concurrency only builds when arrivals transiently outrun the isolate — exactly the OOM regime. So 100 sits ~100x above anything normal traffic reaches (it will not throttle the hot workspace) and ~16x below the ~1600-concurrency OOM onset measured in #5372. Memory agrees: ~5.9 MB of eval working set at concurrency 100, on top of the ~5.6 MB baseline, against the 32 MB prod limit.
Measured under load
Verified locally against the real
httpdestination path (single process, one workspace, 6s per phase). The cap was set to 8 rather than 100 for the run: by the Little's Law argument above, steady-state depth sits near 1, so a laptop cannot drive an isolate to depth 100 — lowering the cap exercises the identical code path at reachable load. 180,674 requests / 542,022 evaluations, all HTTP 200.Three things the run confirms:
ivm_execution_queuedstayed at exactly 0 through four phases of rising load. Past the cap, 312,295 evaluations queued andivm_execution_queue_wait_countequalled that number exactly — every queued call was admitted, nothing lost or double-counted, andivm_platform_errorstayed at 0 across all 542k evaluations.Any new dependencies introduced with this change?
N/A — no new packages; the gate is ~60 lines of plain promise plumbing.
Any new generic utility introduced or modified. Please explain the changes.
IvmScriptRunner(shared bycustom_mappingsandcustom_audience) gains the option above, opt-in per consumer.prometheus.jsgains a static registration forivm_execution_queue_waitwith explicit buckets — see the metrics bullet below for why.Any technical or performance related pointers to consider with the change?
release()hands its slot directly to the next waiter and leavesslotsInUseuntouched. Decrementing and waking a waiter would let the accounting drift and admit past the cap. There is a regression test for exactly that — it fails with peak 3 against a cap of 2 under the buggy variant. The counter is named for slots reserved, not work in progress: a slot in transit between a departing caller and a waiter stays counted across the microtask gap in which neither is executing.pop()would be marginally cheaper, but it starves the oldest waiter under sustained saturation, and nothing bounds queue time here (execTimeoutMscovers evaluation only, and the queue is unbounded). The O(n)shift()is a pointer memmove on a queue that Little's Law keeps near-empty in steady state — orders of magnitude below the ~100µs evaluation it gates.cacheKey, so it can never bind to another tenant's isolate.ivm_execution_queued(counter) andivm_execution_queue_wait(timer), both carrying the full(workspaceId, functionName, cache)label set thativm_platform_erroralready uses, so all three join on the same series. The gate is per isolate — i.e. per workspace — and these two are the only overload signal there is, so "which tenant is at its cap" has to be answerable from them.ivm_execution_queuedis incremented at enqueue, so a backlog shows up the moment it forms; the wait timer only samples on admission and so lags a burst by however long the queue takes to drain.ivm_execution_queuedis the one to alert on. Cardinality is bounded by the workspaces that actually reach the cap — rare by design, since the cap sits far above normal traffic — not by call volume;functionNameis a hardcoded expression literal per call site (three exist repo-wide, only one on a gated pool), so it adds no fan-out.ivm_execution_queue_waitis declared statically with explicit buckets. Left toprometheus.js's dynamic path it inherits prom-client's default buckets, whose first boundary is 5ms — and a gated isolate drains far faster than that. In the load run above, 99.45% of 312k observations (310,578) landed in that single first bucket, with the remaining 0.55% in the next and every higher bucket empty;histogram_quantile()on that series interpolates inside one bucket and cannot separate a healthy 0.4ms wait from a degraded 4ms one. The declared buckets start at 0.5ms and run to 1s; re-measured under the same load the distribution spans five buckets (p50 ~3.8ms, p99 ~19ms). Declaring it also pins the label set rather than inferring it from whichever call site observes first.ivm_execution_queuedis emitted before the waiter promise is constructed, and the wait timer afterresolve(), so a throwing metric client can never strand a waiter in the queue holding a slot that was handed to it and never released.CUSTOM_MAPPINGS_IVM_MEMORY_MBis still 16 while prod is overridden to 32 via helm — separate concern, prod already carries the bump.custom_audiencestays ungated; enabling it there is a one-line config change if wanted.@coderabbitai review
Developer checklist
My code follows the style guidelines of this project
No breaking changes are being introduced.
All related docs linked with the PR?
All changes manually tested?
Any documentation changes needed with this change?
Is the PR limited to 10 file changes?
Is the PR limited to one linear task?
Are relevant unit and component test-cases added in new readability format?
Reviewer checklist
Is the type of change in the PR title appropriate as per the changes?
Verified that there are no credentials or confidential data exposed with the changes.