Introducing a new way to review your PRs.

Read the announcement

reflex-dev / reflex

🕸️ Web apps in pure Python 🐍

View on GitHub

30 documents · Updated Nov 23, 2026

docs / runtime-foundations

Runtime foundations

The reflex-base package provides the shared rules that let a Reflex application load configuration, describe browser work, register its state and event types, and process client work in a safe order. It forms the lower runtime layer used by application assembly, state exchange, compilation, and page routing. See Application runtime for the larger system view.

Foundation boundary

Package role

The reflex-base package is the common runtime layer for framework packages. Its public concepts describe configuration, events, execution context, registration, serialization, and extension hooks without owning a complete application. Frontend compilation and routing and page registration consume these shared contracts when they build browser output and page identity.

These concepts create contracts between the Python backend and the generated browser code:

  • Configuration gives both sides the same service addresses and runtime choices.
  • Registration gives event names and state classes a stable identity.
  • Events carry a handler name, route data, and user data across the client boundary.
  • Contexts carry the client and transaction data needed while work runs.
  • Processors turn events into ordered handler work and state updates.

References: packages/…/pyproject.toml• L1-23 packages/…/__init__.py• L92-167 packages/…/registry.py• L40-88

Contextual runtime state

BaseContext provides task-local context. A task-local context is a value that follows the current execution task without becoming a global value shared by unrelated requests. RegistrationContext uses this model for state and event registrations. EventContext uses it for the client session and the event being processed.

This separation lets concurrent applications, compile runs, and event tasks keep their own active state. Code that needs the current registration or event must run inside the matching context; a missing or inactive context is a runtime error rather than an implicit fallback.

References: packages/…/base.py• L10-128 packages/…/registry.py• L48-60 packages/…/context.py• L86-120

Configuration contract

Application configuration

packages/…/config.py defines the application configuration contract. It collects the values that affect backend and frontend coordination, then validates and normalizes them before the application uses them. The same contract also controls transport choice, state storage, build output, proxy trust, and runtime diagnostics.

The contract groups settings by their effect on the running system:

Setting groupRuntime effect
Application identitySelects the app module and project context.
Service addresses and pathsConnects browser routes, backend endpoints, deployment origins, and trusted proxy data.
State and transportSelects how client state is kept and how events reach the backend.
Frontend and pluginsAdds browser packages, build behavior, lazy library loading, and extension hooks.
Rendering and compilerSelects page memoization, React Compiler use, and asset compression.
Runtime limitsBounds locks, page generation, event-loop warnings, and asset output.

The configuration normalizes URL prefixes and validates values such as plugin entries, compression formats, proxy counts, frontend path segments, event-loop thresholds, and Redis requirements. The api_url, frontend_path, and backend_path values form one deployment contract rather than independent options. react_compiler is experimental, while auto_memoize controls the normal optimization path for stateful pages. Plugin declarations from application configuration are required, while optional extra plugin declarations from the environment can be skipped with a warning. Application lifecycle and configuration covers how the application loads and applies this contract.

Configuration is loaded from rxconfig.py into the active registration context. A context caches its configuration, while a reload replaces that context's value. The loader isolates project-local imports when the project changes and serializes concurrent loads, so separate application loads do not reuse stale project modules.

References: packages/…/config.py• L154-298 packages/…/config.py• L397-485 packages/…/config.py• L500-681 packages/…/config.py• L1022-1153 packages/…/installer.py• L118-169

Environment values

The environment layer turns process values into typed configuration values. An EnvVar is a named value with a default and a type rule. It supports common scalar values, durations, paths, lists, enums, and plugin references, then reports invalid input as a framework configuration error.

Application fields use the REFLEX_ prefix for environment overrides. Config reads these values after loading an optional env file, so deployment can change a setting without changing the Python config. Sensitive connection values are not written to debug logs. Application lifecycle and configuration describes the developer-facing configuration flow.

References: packages/…/environment.py• L329-446 packages/…/environment.py• L490-625 packages/…/config.py• L807-854

Registration context

RegistrationContext is the runtime registry for the definitions needed by compilation and event dispatch. It links full event names to handlers, links state names to state classes and substates, and holds the active app configuration.

The registry can be forked for an independent application context while preserving existing registrations. This supports isolated app loads without confusing classes or handlers from one project with another. Compile-only caches can be cleared without losing the registered application model.

References: packages/…/registry.py• L40-95 packages/…/registry.py• L96-175 packages/…/registry.py• L193-289

Event processing

Event contract

An Event is the transport form of a user or system action. It names a registered handler and carries a payload plus the route data that describes where the action occurred. An EventSpec describes that work during compilation, and an EventHandler turns a state method into a typed event source.

EventHandler is also awaitable. An awaited backend handler runs inline when the current task holds the state lock and returns its backend result; otherwise the runtime queues it and waits for its future. Returned events still form a chain, while a plain returned value remains backend-only. A background handler must be yielded or returned as an event instead of being called directly. Handler access keeps a state-bound method callable through an instance and keeps stored handlers visible to type checkers.

The runtime checks callback arguments before it creates the payload. It supports event callback signatures with several positional values and accepts generated JavaScript function vars as complete event-chain handlers. Mutable values are detached from state-bound proxies before a chained event carries them. Handler annotations are retained when the handler is registered so event arguments can be checked and converted against the intended signature.

The runtime keeps browser-only actions separate from backend handlers. Names that start with _ are sent to the browser. Other names are looked up in the registration context and enter the backend processor. State management and event processing explains how these events change state.

References: packages/…/__init__.py• L92-287 packages/…/__init__.py• L558-911 packages/…/__init__.py• L914-1030 packages/…/__init__.py• L1122-1248 packages/…/format.py• L438-511 packages/…/function.py• L287-331

Event context

EventContext carries the session data needed by one event chain. It includes the client token, the state manager, enqueue and emit actions, a transaction ID, parent transaction information, route data, and optional trace context.

Handlers use the context to enqueue more backend events, emit browser events, or send a state delta. A fork keeps the client and route view while recording the parent transaction. This lets chained work use the same session and lets the runtime trace or cancel the full chain as one unit. The context also records the state tree held by the current task, so inline work cannot outlive the lock that protects it.

References: packages/…/context.py• L43-172 packages/…/context.py• L180-254

Event queue

EventProcessor turns accepted events into asynchronous handler work. It owns the queue, the active tasks, and an EventFuture for each event chain. A future tracks child events so a caller can wait for the whole chain, and cancellation can stop its descendants.

The processor applies two ordering rules. Foreground events for one client run in order. Background events can run without waiting on that client queue. Handlers marked as superseding use latest-wins behavior: a newer root action cancels older unfinished work, while events from the same chain remain linked. An older chain that arrives after a newer chain is dropped instead of canceling the newer work. Cancellation is cooperative, so work must yield to the event loop for cancellation to take effect.

The processor also owns its lifecycle. It must be configured before it starts, and shutdown can drain pending work for a shared time limit before it cancels the remaining tasks. It can stream the state deltas from one event chain to its caller; ending that stream early cancels the unfinished chain. Application lifecycle and configuration describes where this lifecycle joins the application server.

The following flow shows how a client event becomes ordered handler work and returns a result or update.

flowchart LR
    Client[Client action] --> Event[Event]
    Event --> Queue[Event processor queue]
    Queue --> Order[Per-client ordering]
    Order --> Handler[Event handler]
    Handler --> Chain[Event chain]
    Chain --> Update[State delta or browser event]
    Update --> Client

References: packages/…/event_processor.py• L89-268 packages/…/event_processor.py• L306-409 packages/…/event_processor.py• L411-595 packages/…/event_processor.py• L636-736 packages/…/event_processor.py• L843-1052 packages/…/future.py• L10-140

State-aware execution

BaseStateEventProcessor adds state work to the general event queue. It obtains the client state under the state manager, merges current route data, runs middleware, invokes the handler, and sends changed values back to the client. It also restores state for a new client session before page-load work and cancels that work when the client disconnects.

The processor treats foreground and background handlers differently because they have different ownership of the state lock. Foreground work can emit a delta while it holds the lock. Background work uses a state proxy and flushes its changes through a later locked operation. This prevents one event from clearing changes made by another event.

Awaited handlers use the same middleware and state rules as queued handlers. A middleware block returns None to the awaiting caller and prevents the handler from running. A handler awaited without a locked state runs through the queue. A handler awaited while its caller holds the lock runs inline only when it is a foreground handler. Background work cannot be awaited in that situation because it would wait for the lock held by its caller.

If a foreground handler raises or is canceled after its last update, the processor flushes its pending state changes before the error continues. Background writes are emitted through a locked flush when the handler does not manage its own state context. This keeps writes visible even when the handler does not reach another yield.

Handler results can contain more backend events or browser-only events. Typed handler arguments are converted before invocation. Hydration and page-load work are tied to the client lifecycle, so a disconnect can cancel work that is no longer useful. State management and event processing covers the state tree and its storage backends in detail.

References: packages/…/base_state_processor.py• L268-372 packages/…/base_state_processor.py• L423-577 packages/…/base_state_processor.py• L580-754 packages/…/base_state_processor.py• L757-899 packages/…/base_state_processor.py• L901-1037

Runtime support

Browser event runtime

The generated browser runtime holds the client session token, event queue, socket connection, browser-only actions, and incoming state updates. It applies state deltas with structural sharing, so unchanged data keeps its identity and memoized UI can avoid work.

The browser sends backend events over the configured transport and processes frontend events locally. It also carries route data with outgoing events, handles reconnect hydration, and reports frontend state mismatches or update errors back to the backend. Application lifecycle describes when this runtime connects, while State and events explains the state data it exchanges.

References: packages/…/state.js• L25-115 packages/…/state.js• L298-445 packages/…/state.js• L577-782 packages/…/state.js• L877-925 packages/…/state.js• L1015-1325

Client-side state

Client-side state is a browser value with a React component scope. An unnamed value belongs to the component tree that creates it. A named value is global within the app and can be read or changed by backend events and JavaScript outside a component.

The same contract exposes reactive component access, event-trigger setters, backend retrieve and push actions, and non-reactive global accessors. The browser store is also reachable through the runtime reference used by evaluated scripts. This lets client-only values remain on the browser while still crossing the event boundary when an app needs them.

References: packages/…/client_state.py• L125-169 packages/…/client_state.py• L199-349 packages/…/client_state.py• L351-536 packages/…/state.js• L79-84 packages/…/state.js• L707-730

Component and expression model

Components form the typed tree that becomes browser UI. Their fields describe props and children, while event triggers, hooks, imports, refs, and app-level wrappers carry the extra runtime needs of that tree.

Var is an immutable JavaScript expression rather than a Python value. Its metadata records every state field it reads, plus dependencies, imports, hooks, embedded components, and required providers. A composed expression merges the field dependencies of all its inputs. This allows generated code to track every state value that can make the expression stale and to include the browser resources needed to evaluate it.

The expression model keeps Python types connected to browser types. Literal values become typed expressions, operations preserve or infer their result type, and registered Var subclasses provide the conversions used when an expression changes shape. Function expressions represent browser callbacks or calls without running them on the server. Reactive vars explains how these expressions participate in state-driven rendering.

References: packages/…/__init__.py• L1-81 packages/…/base.py• L118-256 packages/…/base.py• L328-541 packages/…/base.py• L723-907 packages/…/base.py• L1071-1328 packages/…/function.py• L126-416 packages/…/component.py• L337-380 packages/…/component.py• L735-826

Memoization and iteration

Memoization keeps state-dependent work near the component that owns it. User memos describe reusable value or component functions. Automatic memoization wraps suitable stateful subtrees and stabilizes event callbacks so unrelated page updates do not rebuild the whole subtree.

Iteration gives each rendered item its own expression scope and key. Hooks inside a loop therefore belong to each item rather than to the list as a whole. The compiler chooses a passthrough or snapshot boundary for a memoized subtree, so loop structure and state-dependent rendering stay in the correct scope.

When enabled, the experimental React Compiler also optimizes generated components. The generated code provides compiler knowledge for immutable elements and removes unused dependencies from generated event callbacks; configuration logs a warning because unsupported generated code may remain unoptimized. Frontend compilation covers the wider build pipeline.

References: packages/…/memo.py• L64-79 packages/…/memo.py• L391-405 packages/…/memoize_helpers.py• L1-17 packages/…/memoize_helpers.py• L92-157 packages/…/memoize_helpers.py• L319-331 packages/…/iter_tag.py• L20-33 packages/…/iter_tag.py• L90-136 packages/…/vite-plugin-react-compiler.js• L40-163 packages/…/config.py• L403-421

Extension hooks

The Plugin contract lets an extension add framework behavior at defined points without changing the event or configuration boundary. Plugins can contribute frontend dependencies and assets, add pages, observe compilation, and post-process a production build. Their page contributions join the route contract described in routing and page registration, while their compile hooks join the pipeline in frontend compilation.

Configuration resolves plugin declarations before the application starts. An explicit invalid plugin is a configuration error. Optional environment-supplied additions can be ignored with a warning. This difference keeps required application behavior strict while allowing optional integrations to fail without stopping the app.

References: packages/…/base.py• L121-248 packages/…/config.py• L500-634 packages/…/config.py• L686-703 packages/…/environment.py• L205-292

Serialization boundary

The serializer layer defines how Python values cross the JSON boundary used by configuration, state, and event data. Built-in conversions cover common date, time, UUID, collection, and structured values. Optional integrations are resolved only when their types are used, and the registry lets framework and application code add a serializer for a new type.

SQLAlchemy declarative models have a default wire form that includes loaded fields and relationships without forcing unloaded values to load. Relationship cycles use primary-key references, and synonym attributes keep the type of the attribute they name. Event arguments use matching deserializers when they enter a typed handler.

Serialization is part of the data contract, not only a utility. A value must have a stable wire form that the receiving side can read, and event arguments must be transformed back to the handler's declared types when they enter the backend.

References: packages/…/serializers.py• L31-57 packages/…/serializers.py• L94-235 packages/…/serializers.py• L532-642 packages/…/serializers.py• L660-837 packages/…/_serializer_types.py• L1-41 packages/…/types.py• L1030-1150 packages/…/base_state_processor.py• L268-372

Observability hooks

The optional OpenTelemetry layer adds trace and metric points at runtime boundaries. When it is disabled, event processing does not create spans or import the optional tracing package. When enabled, it can measure event duration, state acquisition, socket message size, and open socket count.

Event and context data carry transaction links so traces can follow a handler and its chained work. Development also has a separate event-loop monitor that warns when handler work blocks the asynchronous loop for longer than the configured threshold. The monitor identifies the app location when possible and gives different advice for app code, imports, and installed packages.

References: packages/…/otel.py• L1-13 packages/…/otel.py• L43-66 packages/…/otel.py• L98-220 packages/…/blocking.py• L78-205 packages/…/event_processor.py• L245-268 packages/…/config.py• L297

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to configuration fields must keep their defaults, REFLEX_ parsing rules, path normalization, serialized config form, and generated frontend choices aligned.
  • Changes to endpoint or socket event names must keep the backend constants aligned with the generated browser event contract.
  • Changes to EventContext fields must preserve inheritance of the client token, route data, transaction parent, and trace context across chained events.
  • Changes to queue ordering or supersession must preserve EventFuture parent-child cleanup, same-chain behavior, stale-chain dropping, and cancellation behavior.
  • Changes to inline awaiting must keep middleware checks, lock ownership, returned values, and returned event chains distinct.
  • Changes to state-aware execution must keep failed-handler flushes, background proxy flushes, hydration, and emitted deltas in the same order.
  • Changes to serializers or event argument conversion must keep the outbound wire form and inbound handler types compatible, including optional ORM types.
  • Changes to client-state scope must keep named global values separate from tree-scoped values across hooks, browser accessors, and backend bridge events.
  • Changes to VarData or Var subclass registration must preserve merged field dependencies, imports, hooks, app wrappers, and type conversion lookup.
  • Changes to function expressions must keep callback arguments, optional calls, return types, and event-chain conversion aligned with generated JavaScript.
  • Changes to number, sequence, or set expressions must keep their declared types aligned with the generated browser expression and with JSON transport, especially when sets are viewed as arrays.
  • Changes to memoization or loop scopes must preserve per-item hooks, callback dependencies, and the boundary between page code and generated memo modules.
  • Changes to plugin loading must preserve the difference between required config plugins and optional environment-supplied plugins.

Important failure modes

TriggerConsequenceGuard
A REFLEX_ value cannot be converted to the declared typeConfig loading stops before the app can use the invalid valueUse the type accepted by the environment contract and fail fast on the environment conversion error
A frontend path contains an empty segment, trailing dot or space, backslash, or drive markerThe configured build path is rejected because it is not a safe directory pathUse plain directory segments for frontend_path
Code reads RegistrationContext or EventContext outside an active contextThe runtime cannot identify the app, handler registry, client, or event chainEnter the matching context before calling context-dependent code
An event processor is used before configuration or startEvent enqueue or processing raises a runtime errorConfigure it with a state manager, then start it with the application lifecycle
An event name has no registered handlerThe queue cannot dispatch the eventRegister the handler in the active registration context and keep the generated event name stable
A background handler is awaited while the state lock is heldThe handler can deadlock while waiting for the lock it needsYield the background event, or await only a non-background handler outside that lock
A superseding event arrives from an older chain after a newer chainThe stale invocation is dropped rather than changing the newer resultUse supersession only for work that can safely be replaced
A foreground handler fails after its last state updateIts pending state changes can be lost before the next handler reads stateLet the state processor flush dirty state before it propagates the failure
Background work changes state without its state contextThe change cannot be safely flushed and may raise an immutable-state errorUse the background state proxy and enter its async state context for writes
A foreground handler blocks the event loopOther client events and runtime tasks stop respondingUse non-blocking async work or move blocking I/O to a thread pool
A component in a loop captures a loop value without the loop dependency metadataGenerated callbacks or memo boundaries can use the wrong scopeBuild loop expressions through the iteration primitives
A set is used as an array without an explicit array viewThe result can use deprecated behavior or fail the intended type contractUse .to_array() before array operations or iteration
A value has no JSON serializerState, config, or event transport cannot represent the valueRegister a serializer and keep its output readable by the receiving side
A browser bundle and backend use different state schemasUpdates can target missing dispatch functions or fail during hydrationRebuild and reconnect matching frontend and backend versions

Key files

FileWhy to read it
packages/…/pyproject.tomlDefines the package boundary and its role as the framework's core type layer.
packages/…/config.pyDefines shared application settings, environment overrides, project-local config loading, compiler choices, and plugin policy.
packages/…/environment.pyDefines typed environment values and the conversion rules used by configuration.
packages/…/registry.pyDefines the contextual registry for state classes, event handlers, app configuration, and compile data.
packages/…/base.pyDefines task-local context behavior used by the registry and event runtime.
packages/…/__init__.pyDefines events, handler contracts, event chains, payload boundaries, and the backend/browser event split.
packages/…/context.pyDefines the client, lock, route, and transaction context passed through event chains.
packages/…/event_processor.pyDefines event queueing, per-client ordering, chaining, supersession, streaming, errors, and shutdown.
packages/…/future.pyDefines the parent-child future tree used to wait for or cancel complete event chains.
packages/…/base_state_processor.pyShows how event dispatch joins state locks, middleware, hydration, failed-handler flushes, and state deltas.
packages/…/blocking.pyDefines development warnings for work that blocks the event loop.
packages/…/state.jsDefines the browser event queue, socket session, reconnect path, delta application, and browser-side event actions.
packages/…/client_state.pyDefines scoped and global browser state and its backend event bridge.
packages/…/component.pyDefines the typed component tree and the props, triggers, hooks, refs, and wrappers it exposes to the compiler.
packages/…/base.pyDefines immutable JavaScript expressions, field dependency metadata, and the type conversion model used by the compiler.
packages/…/function.pyDefines browser function values, calls, partial application, optional calls, and generated callbacks.
packages/…/memo.pyDefines reusable memo functions and component memo boundaries.
packages/…/memoize_helpers.pyDefines callback stabilization and automatic memoization render strategies.
packages/…/iter_tag.pyDefines loop-item variables, keys, and component rendering for iteration.
packages/…/serializers.pyDefines the JSON value boundary, optional model support, and custom serializer registry.
packages/…/format.pyDefines stable event names, generated event callbacks, refs, and JSON formatting.
packages/…/vite-plugin-react-compiler.jsDefines the optional React Compiler pass for generated browser components.
packages/…/base.pyDefines the extension hooks shared by app and compiler plugins.
packages/…/otel.pyDefines optional tracing and metric hooks at runtime boundaries.