Skip to content

fix(custom_mappings): cache compiled template to prevent sandbox OOM under load - #5372

Closed
shekhar-rudder wants to merge 1 commit into
developfrom
feature/int-6832-isolate-vm-errors-for-http-destination
Closed

shekhar-rudder wants to merge 1 commit into
developfrom
feature/int-6832-isolate-vm-errors-for-http-destination

Conversation

@shekhar-rudder

@shekhar-rudder shekhar-rudder commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

What

Custom-mapping evaluation runs inside a per-workspace isolated-vm sandbox. Today it recompiles the JsonTemplateEngine template from scratch on every event (createAsSync(mappings).evaluate(event)), even though the mapping is fixed per destination and only the event varies. This change memoizes the compiled engine per template and only runs evaluate() per event.

Why

Compilation (parse + codegen) is the dominant per-eval cost. A single isolated-vm isolate serializes execution, so its throughput is a hard ceiling. When a workspace bursts past that ceiling, evals back up on the one shared 16 MB isolate, live argument copies accumulate, and V8 disposes the whole isolate on the memory limit — the one eval that tips it logs the genuine OOM while every other in-flight eval fails at once with "Isolate is disposed" (the amplified ivm-platform-error alerts).

Caching the compiled engine removes the dominant per-call cost, so each eval only runs evaluate(). That lifts the single-isolate throughput ceiling and lowers per-eval heap, so a workspace can sustain a much higher arrival rate before its isolate backs up.

Load test results

Both variants driven through the real isolated-vm path (16 MB limit, 500 ms timeout, copy:true args — identical to scriptRunner.ts).

CPU / throughput (single warm isolate, sequential evals):

Mapping metric uncached cached speedup
Simple (32 fields) per-eval latency 0.387 ms 0.060 ms 6.5×
Simple throughput 2,583 evals/s 16,674 evals/s 6.5×
Complex (40 expression fields) per-eval latency 1.785 ms 0.210 ms 8.5×
Complex throughput 560 evals/s 4,768 evals/s 8.5×

Peak heap under a concurrent burst (complex mapping, fresh 16 MB isolate):

Concurrency K uncached peak heap cached peak heap reduction
100 5.87 MB 3.36 MB 43%
400 9.70 MB 7.22 MB 26%
600 12.30 MB 9.00 MB 27%

Scope of the benefit (measured, not assumed)

  • The win is throughput / sustained arrival rate (6.5–8.5×) and lower heap at operating concurrency (25–43%).
  • A synthetic burst of K evals pre-queued all at once OOMs at roughly the same K for both variants (~1600 in this harness). At that extreme, the structured-clone of K argument-sets dominates the heap — a factor caching does not touch. Real load arrives over time against a serialized isolate, where the throughput ceiling is what governs OOM onset; this change lifts that ceiling.

Notes for reviewers

  • Cache key is content, not reference. Args cross the isolate boundary via structured clone, so mappings is a fresh copy each call — identity caching would never hit. Keyed by JSON.stringify(mappings), whose cost is far below parse + codegen.
  • Bounded cache. Compiled engines are retained in the same 16 MB heap, so the cache is capped (FIFO) to avoid trading a transient-allocation OOM for a retained-memory one. A workspace realistically has a handful of distinct templates, so the cap rarely bites.
  • No locking needed. The isolate holds a single-execution lock and the cache read/compile/write path is synchronous, so concurrent evals can't race on the map.
  • Reuse-safety. Two new tests assert that reusing a compiled engine across different events yields independent results, and that distinct templates on the same isolate don't collide on the cache.

Testing

  • customMappings unit tests: 8/8 pass (incl. two new reuse-safety guards)
  • http component tests: 33/33 pass
  • ga4_v2 component tests: 23/23 pass
  • lint clean

🤖 Generated with Claude Code

@shekhar-rudder
shekhar-rudder requested review from a team as code owners July 17, 2026 10:27
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key: "auto_resolve_threads"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Walkthrough

The sandbox now caches up to 100 compiled custom-mapping engines by serialized mappings, evicts the oldest entries when full, and evaluates events through cached engines. Tests cover event-state isolation and separation between distinct templates.

Changes

Sandbox engine caching

Layer / File(s) Summary
Bounded engine cache
src/util/customMappings/mappingsSandbox.ts
Compiled JsonTemplateEngine instances are cached by JSON.stringify(mappings), with FIFO eviction at 100 entries before event evaluation.
Cache isolation tests
src/util/customMappings/sandboxClient.test.ts
Tests verify independent outputs across events and correct results for distinct templates sharing one workspace isolate.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: saikumarrs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes caching compiled templates to reduce sandbox OOM risk.
Description check ✅ Passed The description is mostly complete, with clear what/why, results, notes, and testing; only the Linear task placeholder is missing.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/int-6832-isolate-vm-errors-for-http-destination

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.87%. Comparing base (15ed184) to head (3d5b5c4).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #5372   +/-   ##
========================================
  Coverage    92.87%   92.87%           
========================================
  Files          706      706           
  Lines        38372    38372           
  Branches      9005     9001    -4     
========================================
  Hits         35638    35638           
  Misses        2508     2508           
  Partials       226      226           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…heap under load

Custom-mapping evaluation recompiled the JsonTemplateEngine template on every
event inside the per-workspace isolate, even though the template is fixed per
destination and only the event varies. Compilation (parse + codegen) is the
dominant per-eval cost, so it both burned CPU and inflated per-eval heap in the
shared 16 MB isolate. A single isolate serializes execution, so its throughput
is a hard ceiling; a workspace bursting past that ceiling backs up, live
argument copies accumulate, and the isolate is disposed on the memory limit —
cascading into collateral "Isolate is disposed" failures (the ivm-platform-error
OOM alerts).

Memoize the compiled engine per template (keyed by content, since args cross the
isolate boundary via structured clone so reference identity never hits) and only
run evaluate() per event. Measured on the real isolated-vm path (16 MB, 500 ms
timeout): per-eval latency drops 6.5-8.5x (throughput 2.6k->16.7k evals/s for a
simple mapping, 560->4.8k for a complex one) and peak heap at operating
concurrency drops ~25-40%, lifting the arrival rate a single isolate sustains
before it backs up and OOMs. The cache is bounded so a workspace with many
distinct templates cannot itself grow the isolate heap into the same OOM.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@shekhar-rudder
shekhar-rudder force-pushed the feature/int-6832-isolate-vm-errors-for-http-destination branch from 3e026fa to 3d5b5c4 Compare July 17, 2026 11:04
@sonarqubecloud

Copy link
Copy Markdown

shekhar-rudder added a commit that referenced this pull request Jul 21, 2026
Drops the default queue bound so excess evaluations wait rather than shed:
the concurrency cap alone is what protects the isolate heap, and a
single-threaded isolate drains its queue at the same rate either way, so
shedding only bought a worse failure mode. Still configurable via
CUSTOM_MAPPINGS_IVM_MAX_QUEUED_EXECUTIONS for anyone who wants
backpressure instead of latency.

Also documents where the concurrency cap of 100 comes from, measured on
enterprise-eu / rudder-eu-central-1b (the busiest namespace for this pool,
~380x eu-central-1a): peak single-pod eval rate ~13.8k/s implies a
sub-100us evaluation and therefore a steady-state in-flight depth near 1,
so 100 sits ~100x above normal traffic and ~16x below the ~1600
OOM onset measured in #5372.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
shekhar-rudder added a commit that referenced this pull request Jul 28, 2026
…#5385)

## What are the changes introduced in this PR?

Caps how many custom-mapping evaluations run concurrently on a single
`isolated-vm` isolate and queues the excess.

`IvmScriptRunner` gains one optional knob — `maxConcurrentExecutions`.
It defaults to unlimited, so `custom_audience` and every other consumer
keep today's behaviour; only the `custom_mappings_ivm` pool 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`), and `ga4_v2`
`Promise.all`s 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_ivm` pool 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):

| Env var | Default | Rationale |
|---|---|---|
| `CUSTOM_MAPPINGS_IVM_MAX_CONCURRENT_EXECUTIONS` | 100 | Sized from
prod — see below. |

The 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 (~380x `eu-central-1a`):

| Observation (7d) | Value |
|---|---|
| Peak single-pod eval rate | ~13.8k/s |
| Warm isolates per pod | 18 (cache max 20) |
| Observed heap per isolate | ~5.6 MB baseline |
| `ivm_platform_error`, `custom_mappings_ivm` | 879, **all in one hour,
all one workspace** |

That 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 `http` destination 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**.

| offered concurrency | evals/s | queued/s | mean wait | in-flight depth
|
|---|---|---|---|---|
| 1 | 6,900 | 0 | — | 0.39 |
| 4 | 14,803 | 0 | — | 0.84 |
| 8 | 16,518 | 0 | — | 0.94 |
| 16 | 17,003 | 0 | — | 0.97 |
| 32 | 17,551 | 13,553 | 0.39ms | **7.84** |
| 64 | 17,509 | 17,651 | 1.11ms | **20.43** |

Three things the run confirms:

- **Throughput is flat from concurrency 8 onward** (~17.5k evals/s)
while offered load grows 8x. Extra concurrency bought zero throughput
and became queue depth — the premise of the PR, measured. The implied
~57µs service time is consistent with the sub-100µs figure inferred from
prod.
- **The gate is silent until it is genuinely saturated.**
`ivm_execution_queued` stayed at exactly 0 through four phases of rising
load. Past the cap, 312,295 evaluations queued and
`ivm_execution_queue_wait_count` equalled that number exactly — every
queued call was admitted, nothing lost or double-counted, and
`ivm_platform_error` stayed at 0 across all 542k evaluations.
- **In-flight depth crosses the cap where queueing starts.** Depth above
is Little's Law (throughput x residence), derived independently of the
gate's own counters, and it crosses 8 at precisely the phase where the
counter switches on.

### 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 by `custom_mappings` and `custom_audience`)
gains the option above, opt-in per consumer.

`prometheus.js` gains a static registration for
`ivm_execution_queue_wait` with explicit buckets — see the metrics
bullet below for why.

### Any technical or performance related pointers to consider with the
change?

- **Slot handoff, not free-and-wake.** `release()` hands its slot
directly to the next waiter and leaves `slotsInUse` untouched.
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.
- **Waiters are FIFO.** `pop()` would be marginally cheaper, but it
starves the oldest waiter under sustained saturation, and nothing bounds
queue time here (`execTimeoutMs` covers 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.
- **Gates are per isolate** (keyed like the isolate cache, i.e. per
workspace) and dropped once fully idle, so the map stays bounded by the
live isolate set rather than every workspace ever seen. A queued caller
resolves with its own release closure and its own `cacheKey`, so it can
never bind to another tenant's isolate.
- **New metrics:** `ivm_execution_queued` (counter) and
`ivm_execution_queue_wait` (timer), both carrying the full
`(workspaceId, functionName, cache)` label set that `ivm_platform_error`
already 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_queued` is 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_queued` is 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; `functionName`
is 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_wait` is declared statically with explicit
buckets.** Left to `prometheus.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.
- **Metric emission ordering.** `ivm_execution_queued` is emitted before
the waiter promise is constructed, and the wait timer after `resolve()`,
so a throwing metric client can never strand a waiter in the queue
holding a slot that was handed to it and never released.
- **Out of scope, deliberately:** the code default for
`CUSTOM_MAPPINGS_IVM_MEMORY_MB` is still 16 while prod is overridden to
32 via helm — separate concern, prod already carries the bump.
`custom_audience` stays ungated; enabling it there is a one-line config
change if wanted.

@coderabbitai review

<hr>

### Developer checklist

- [x] My code follows the style guidelines of this project

- [x] **No breaking changes are being introduced.**

- [x] All related docs linked with the PR?

- [x] All changes manually tested?

- [ ] Any documentation changes needed with this change?

- [x] Is the PR limited to 10 file changes?

- [x] Is the PR limited to one linear task?

- [x] 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.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@github-actions
github-actions Bot deleted the feature/int-6832-isolate-vm-errors-for-http-destination branch October 18, 2026 01:19
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.

1 participant