Skip to content

CONCEPT Cited by 1 source

Zone.js monkey-patching

Definition

Zone.js (npm: zone.js) is a library originally built for Angular that provides asynchronous execution contexts ("zones") in JavaScript by monkey-patching all global async primitives — setTimeout, setInterval, Promise, XMLHttpRequest, addEventListener, and so on — so that each async continuation can carry a contextual tag back to the zone that scheduled it.

In the browser observability context, Zone.js is the only available path for automatic async-context propagation because the browser has no native primitive equivalent to Node's AsyncLocalStorage (the TC39 AsyncContext proposal is still in progress).

Why it works

By wrapping every global async primitive, Zone.js intercepts scheduling events and attaches the current zone to the continuation. When the continuation runs, it runs inside that zone and can access any per-zone state (like the current OTel span). This provides "automatic" context propagation without requiring the application programmer to pass context parameters through callbacks.

Why Zalando rejected it

The Zalando engineering team "are not big fans of this, especially when done in the customer's browser" (Source: sources/2024-07-28-zalando-opentelemetry-for-javascript-observability-at-zalando). Reasons (inferable / implied):

  • Global scope mutation — every page that imports the SDK silently rewrites JS builtins in the customer's browser. Third-party scripts on the same page that expect unmodified Promise / setTimeout may behave subtly differently.
  • Bundle-size cost — Zone.js is substantial; Zalando already trimmed their SDK to ~30 KB (concepts/cherry-picked-instrumentation-payload), adding Zone.js would have blown the budget.
  • Debugging opacity — when a patched Promise behaves unexpectedly, the root cause is several layers below the application code.
  • Interaction risk with frameworks / libraries — Zone.js is known to interact badly with some ESM toolchains and with certain promise implementations.

Alternative chosen

Zalando opted out of context propagation entirely in the browser SDK and fell back to manual span-passing through function parameters (patterns/manual-span-passing-over-async-context).

Seen in

Last updated · 501 distilled / 1,218 read