Skip to content

feat(rum): add web worker profiling support as opt-in subpath plugin - #5369

Draft
thomasbertet wants to merge 10 commits into
mainfrom
feat/web-worker-profiling-plugin
Draft

thomasbertet wants to merge 10 commits into
mainfrom
feat/web-worker-profiling-plugin

Conversation

@thomasbertet

@thomasbertet thomasbertet commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

RUM Profiling shows what code runs in the browser. It samples the running functions at regular intervals. Today it only records the main thread.

Many apps do heavy work in Web Workers. Workers run on separate threads. The profiler does not see that work today.

This PR adds profiling for regular Web Workers (created with new Worker(...)).

  • It is opt-in. Apps that do not use it are not affected.
  • It only changes @datadog/browser-rum. It does not change @datadog/browser-core or @datadog/browser-rum-slim.
  • Shared workers and service workers are not supported.

It is an alternative to #5368. #5368 puts the feature on the RUM public API. This PR moves it into separate import paths. This keeps the main bundle smaller.

Refs: PROF-15093

Browser support (read before testing)

The browser support is narrow. This comes from the browser API, not from this PR.

  • Only Chromium supports profiling inside workers. The API is self.Profiler in the worker.
  • The API is experimental. Start Chrome with --enable-blink-features=DocumentPolicyInDedicatedWorker,ProfilerAPIForDedicatedWorker.
  • The server must send Document-Policy: js-profiling on the worker script response.
  • Safari and Firefox do not support the API. The SDK detects this and stays silent.

How to use it (npm)

  1. Turn on profiling in the init:
datadogRum.init({
  // ...
  profilingSampleRate: 100,
})
  1. Attach the worker from the page:
import { profileWorker } from '@datadog/browser-rum/worker-profiling'

const worker = new Worker('/my-worker.js')
profileWorker(worker)
  1. Start profiling inside the worker script. Call it before any onmessage handler:
import { startWorkerProfiling } from '@datadog/browser-rum/worker-profiling/worker'

startWorkerProfiling()

Each worker sends its own profile events. Tags link them to the page: thread_type:worker, thread_id, main_thread_id, parent_thread_id, worker_name. A worker created inside a worker also works. The inner worker reports directly to the page.

CDN users load two extra script tags and call DD_RUM_WORKER_PROFILING.profileWorker(worker) on the page, and self.DD_RUM_WORKER_PROFILING.startWorkerProfiling() in the worker. The README has the full example.

Changes

How the pieces connect. White dashed nodes are the customer's code. Everything else is the SDK. The thick arrow is the only new thing crossing between page and worker:

%%{init: { "theme": "base", "themeVariables": { "fontSize": "14px", "lineColor": "#94a3b8" } } }%%
flowchart LR
    subgraph PAGE["🖥  Page — main thread"]
        direction TB
        APP1("🧑 your page code")
        INIT["datadogRum.init()"]
        PW("profileWorker(worker)")
        HOOK["plugin hook<br>registerProfilerExtension"]
        COORD["worker profiler coordinator<br>thread tags · clock shift"]
        PIPE["profile pipeline<br>same as main-thread profiles"]

        APP1 --> INIT
        APP1 --> PW
        INIT --> HOOK
        PW -.->|"registers itself"| HOOK
        HOOK --> COORD
        COORD --> PIPE
    end

    subgraph WORKER["⚙  Worker — new Worker()"]
        direction TB
        APP2("🧑 your worker code")
        START["startWorkerProfiling()"]
        PROF["self.Profiler<br>10 ms samples"]

        APP2 --> START
        START --> PROF
    end

    PW ==>|"handshake + MessagePort"| START
    START <-->|"profiling data over the port"| COORD

    classDef app fill:#ffffff,stroke:#64748b,stroke-dasharray:5 5,color:#334155
    classDef existing fill:#f1f5f9,stroke:#94a3b8,color:#334155
    classDef new fill:#eff6ff,stroke:#60a5fa,color:#1e3a8a
    classDef optin fill:#fffbeb,stroke:#f59e0b,color:#92400e
    class APP1,APP2 app
    class INIT,PIPE existing
    class HOOK,COORD,START,PROF new
    class PW optin
    style PAGE fill:#f8fafc,stroke:#cbd5e1,color:#334155
    style WORKER fill:#f0fdf4,stroke:#86efac,color:#14532d
Loading

New import paths (opt-in)

  • @datadog/browser-rum/worker-profiling exports profileWorker, createWorkerProfilingPort and workerProfilingPlugin. It runs on the page.
  • @datadog/browser-rum/worker-profiling/worker exports startWorkerProfiling. It runs inside the worker. It has zero runtime dependencies.
  • Two new CDN bundles: datadog-rum-worker-profiling.js (9.8 KB, 4.0 KB gzipped) and datadog-rum-worker-profiling-worker.js (6.2 KB, 2.3 KB gzipped). They expose the DD_RUM_WORKER_PROFILING global.

How it plugs into RUM

  • RUM now accepts a profiler "extension" at startup. The hook is registerProfilerExtension in packages/browser-rum-core/src/domain/plugins.ts (plus startRum.ts, preStartRum.ts, rumPublicApi.ts). The hook is optional and marked @internal. browser-rum-slim does not get it.
  • The plugin registers itself when datadogRum.init() runs, or when the app calls profileWorker().
  • The profiler notifies the extension on start, stop and flush (beforeunload). Worker traces go through the existing profile pipeline. So worker profiles reuse RUM's session, views, transport and compression.

What the worker side does

  • It starts profiling immediately at load. It buffers up to 2 traces while the page has not decided yet. If the page never decides, it stops after 30 s and drops the data.
  • It collects a trace every 60 s. It also sends early when the sample buffer is full.
  • It never pauses when the tab is hidden.
  • The page can stop or terminate a worker. The SDK flushes the data before the worker dies. It also cleans up when the app calls worker.terminate() directly.
  • Timestamps are shifted onto the page clock. All numbers stay positive. Existing RUM events are not changed.

What we do not do

  • We do not replace or wrap any browser function. Worker, terminate, close and onmessage stay untouched.
  • We do not add anything to the main bundles for apps that do not import the new paths.

Bundle size (measured against #5368, before the merge of main)

  • datadog-rum.js: -1,078 B raw / -408 B gzipped
  • datadog-rum-slim.js: -327 B raw / -98 B gzipped
  • chunks/datadogProfiler-*.js: -4,322 B raw / -1,388 B gzipped (-32%)

Merge of main

main refactored the profiler lifecycle in #5364. This branch now builds on that structure. The extension hook sits on the new start/stop/flush flow.

Known limitation

On Safari 14 the final worker trace can be lost when the app closes the worker with workerProfiler.close(). Safari 14 drops queued port messages when a port closes. The SDK skips all profiling tests on Safari. Follow-up: keep the port open one tick longer before closing.

Test instructions

Automated:

yarn typecheck
yarn test:unit packages/browser-rum packages/browser-rum-core
yarn test:e2e -g "profiling"

The last command runs 9 E2E tests. Four of them are new:

  • worker loaded from a network URL,
  • worker created from a Blob URL,
  • worker created inside a worker,
  • warning when the server does not send the header.

They run real Chromium with the two flags above.

Manual (optional, to see it yourself):

  1. Run yarn test:e2e --ui -g "worker profiling".
  2. Watch the profile requests in the test's intake log. Each request contains a wall-time.json trace and the thread_type tags.

Checklist

  • Tested locally
  • Tested on staging
  • Added unit tests for this change.
  • Added e2e/integration tests for this change.
  • Updated documentation and/or relevant AGENTS.md file

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Bundles Sizes Evolution

📦 Bundle Name Base Size Local Size 𝚫 𝚫% Status
Rum Salesforce 195.92 KiB 196.54 KiB +642 B +0.32% ✅
Rum Worker Profiling Worker N/A 6.15 KiB N/A N/A N/A
Rum Worker Profiling N/A 9.79 KiB N/A N/A N/A
Rum 195.89 KiB 196.52 KiB +642 B +0.32% ✅
Rum Salesforce Profiler 7.81 KiB 8.81 KiB +1016 B +12.70% ⚠️
Rum Profiler 7.81 KiB 8.81 KiB +1016 B +12.70% ⚠️
Rum Salesforce Recorder 32.80 KiB 32.80 KiB 0 B 0.00% ✅
Rum Recorder 32.80 KiB 32.80 KiB 0 B 0.00% ✅
Logs 60.43 KiB 60.43 KiB 0 B 0.00% ✅
Rum Slim 151.28 KiB 151.50 KiB +220 B +0.14% ✅
Worker 24.23 KiB 24.23 KiB 0 B 0.00% ✅
Rum Shopify 227.44 KiB 228.07 KiB +642 B +0.28% ✅
Rum Shopify Profiler 7.81 KiB 8.81 KiB +1016 B +12.70% ⚠️
Rum Shopify Recorder 4.85 KiB 4.85 KiB 0 B 0.00% ✅
Early Collection 309 B 309 B 0 B 0.00% ✅

⚠️ The increase is particularly high and exceeds 5.00%. Please check the changes.

@datadog-prod-us1-4

datadog-prod-us1-4 Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 74.80%
• Overall Coverage: 77.90% (-0.21%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: a732bc7 | Docs | View more details | Give us feedback!

…CDN bundles

Build the worker-profiling subpath entries as standalone CDN bundles
(datadog-rum-worker-profiling.js and datadog-rum-worker-profiling-worker.js)
exposing a DD_RUM_WORKER_PROFILING global, since webpack drops exports from
bundles without a library config and re-export-only entries built empty.

- Main bundle exposes profileWorker, createWorkerProfilingPort and
  workerProfilingPlugin (auto-registering with DD_RUM on first use)
- Worker bundle exposes startWorkerProfiling and stays dependency-free
  (no @datadog/js-core / @datadog/browser-core runtime imports)
- Document the CDN usage in the README
Cover the full worker profiling matrix against real Chromium (M154+):

- network-loaded dedicated worker: main + worker profile events with
  thread_type/thread_id/main_thread_id/parent_thread_id/worker_name tags,
  page-clock-aligned timestamps, no main-thread long tasks in worker traces
- blob: worker inheriting the page Document-Policy
- nested dedicated workers via workerProfiler.profileWorker()
- console warning + no worker events when the worker script misses the
  Document-Policy header

Infra: enable DocumentPolicyInDedicatedWorker,ProfilerAPIForDedicatedWorker
on the chromium project, serve the two new worker-profiling bundles from the
dev server and mock server, support createWorker({ dedicated, profiling,
documentPolicy }), and set Document-Policy: js-profiling on /sw.js.

Note: on current Chromium, classic workers honor the Document-Policy header
on the worker script response but module workers do not (fixed upstream by
CL 8804097, not yet in Chrome for Testing 159), so profiling workers are
served as classic workers.

Also fix the pre-existing main-thread profiling assertion that this branch
broke by adding thread tags to main-thread profile events.
Add the datadog-rum-worker-profiling[-worker] bundles to the expected
rename, upload and CloudFront invalidation commands in the deploy and
upload-source-maps specs.
Safari 14 (the BrowserStack unit matrix) empties the peer port's message
queue when a MessagePort closes, so the final 'trace' and 'closed'
messages posted by workerProfiler.close() right before closePort() are
dropped and the test times out. Modern engines deliver queued messages
even after the sender closes. Skip the test on Safari < 15 for now;
keeping the port open for one macrotask before closing is a follow-up
option to preserve the final trace on Safari 14.
Safari does not support the JS Self-Profiling API, and the profiler never
activates there at runtime, so the profiling suites cannot exercise
production behavior on Safari and only risk engine-specific flakes (e.g.
Safari 14 dropping queued MessagePort messages on close).

Wrap the top-level describes of all profiling specs (main thread, worker
profiling, early collection) in a describeUnlessSafari helper so they run
on Chromium and are reported as skipped on Safari/WebKit. E2E profiling
scenarios already skip on non-chromium browsers.
Reconcile the Web Worker Profiling extension seam with the profiling state
and lifecycle refactor from #5364:

- keep main's simplified start/stop lifecycle (cleanupTasks, QuotaResult,
  no stateReason)
- re-add the ProfilerExtension/ProfilerHost seam: mainThreadId shared with
  profileAssembly, attachExtension, onStart/onStop/onFlush hooks, and the
  stoppedByUser distinction for closePorts
- stopProfiling() semantics: quota_ko discards extensions, stopped-by-user
  closes their ports, session expiry keeps them open for renewal

This branch has not been deployed

No deployments
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