Skip to main content

What are Context Variables?

Context variables are a feature in some languages and runtimes, unrelated to abxbus, that let you set ambient “thread-local variables” that may be needed by many functions without passing them manually. Context variables are mostly used for repetitive arguments that would clutter function signatures if they had to be passed through every layer, such as request IDs, trace and span IDs, user IDs, database transaction IDs, and connection handles. They are especially common in FastAPI, Fastify, Express/Nest, and OpenTelemetry.

How abxbus works in each runtime

abxbus generally snapshots context variables at emit time and provides the snapshot to each event handler when it executes. For async or queued events, this gives handlers a consistent view of history that matches event dispatch order. This matters because dispatch order is the only strict order that exists when using any of the parallel event_concurrency or event_handler_concurrency modes. Event execution order is only statically guaranteed with:
These are the fully predictable modes, similar to a database’s STRICT SERIALIZABLE mode, but they can be impractically slow when processing more than a few thousand events in a complex system. More parallel modes are typically used for performance.

Why this matters

Without propagation, event-based code would be difficult to integrate gradually into larger existing systems. With propagation, event handlers can log/trace normally like any other request handler or method an existing backend or framework.

Web server style examples

These patterns are typical in frameworks where each incoming request gets a request-local context object.

Browser runtime note

AsyncLocalStorage is a Node/Bun API and is not available in browser runtimes. In browsers:
  • AbxBus still works normally for events.
  • ambient async context propagation via AsyncLocalStorage is not available.
  • pass correlation/tracing fields explicitly in event payloads when you need that metadata.
See Supported Runtimes for runtime compatibility details.

Golang runtime note

Go does not have ambient AsyncLocalStorage/ContextVar state; pass the request context at emit time with bus.EmitWithContext(...) or event.EmitWithContext(...) and AbxBus propagates that context.Context into handlers and awaited child events.