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 / application-runtime

Application runtime

A Reflex application turns Python page and state declarations into a web system with two cooperating parts. The Python backend serves requests and manages server-side state. The generated frontend renders pages in the browser and sends events back to the backend. The runtime joins these parts through shared configuration, routes, generated code, and a client connection.

Runtime boundary

The runtime boundary defines what an application is and how its Python definition becomes a running service. It also provides the contracts that the generated frontend and backend must share. Runtime foundations describes the shared services below this boundary.

Application assembly

The App in reflex/app.py is the main assembly point for a Reflex application. It brings together pages, global presentation settings, optional state support, application wrappers, hydration fallback content, head content, middleware, and backend extensions. Page declarations are validated when they are registered and evaluated during compilation so the runtime can discover state and frontend needs from the complete application.

Application-wide wrappers are combined by priority to form the frontend root. A wrapper that does not render its children can hide lower-priority wrappers, so the built-in sticky badge is placed in a child-preserving fragment. This keeps other global elements such as portals in the rendered page.

The application starts with a backend API and adds the services needed by the selected features. State support adds a state manager, an event namespace, and an event processor. The assembled service is exposed as an ASGI application. ASGI is the server interface used for HTTP, WebSocket, and lifespan traffic. This boundary lets the same application serve backend endpoints and optionally serve the compiled frontend.

References: reflex/app.py• L350-409 reflex/app.py• L513-704 reflex/app.py• L723-824 reflex/app.py• L1650-1681 reflex/app.py• L1760-1802

Configuration contract

The application configuration is the shared contract for startup and serving. packages/…/config.py loads rxconfig.py, applies REFLEX_ environment overrides, and normalizes values before the app uses them. The contract covers the app module, frontend and backend addresses, URL prefixes, client transport, state manager, frontend packages, plugins, and deployment behavior.

Frontend and backend paths are not independent labels. The backend prefix affects event and API URLs, while the frontend prefix affects browser routes and static file serving. A deployment must therefore use matching values when the frontend and backend run as separate services.

References: packages/…/config.py• L152-193 packages/…/config.py• L289-415 packages/…/config.py• L647-681

Frontend and backend surfaces

The runtime presents one application to the user but serves two different surfaces. The frontend handles browser rendering. The backend handles application work and communication with server resources.

Generated frontend

The compiler turns pages and application-wide declarations into a frontend project. It produces page modules, the document root, the app wrapper, state and browser contexts, styles, assets, and supporting modules. The generated context also carries initial state and client-side storage declarations. A bundled-library registry records frontend packages discovered while compiling the application. An optional hydration fallback gives the browser a defined component to show while the generated page connects to its live runtime. Frontend runtime packaging describes the browser package and its runtime contract.

Initial state is resolved before it is written to the frontend. The backend caches the same resolved snapshot and compares it with hashes from the browser during the first hydrate, so it sends only values that differ from the compiled defaults. At connection time, the backend also compares the frontend state schema with its own schema and asks a stale frontend to reload before hydration continues. Client storage settings are collected across the state tree, including factory-backed storage fields, so browser storage can follow the state declaration. When several local-storage fields use one name, a write also updates the other synced fields on the server before the delta is sent, so the writing tab reaches the same value without waiting for a browser storage event.

The compiler isolates reactive component subtrees with generated memo wrappers when automatic memoization is enabled. This keeps state reads, event callbacks, and instance hooks in the render scope that owns them. In a loop, an item with lifecycle hooks or other instance hooks must use a stable key; otherwise the runtime warns that the hooks can follow the item position instead of the item.

The compiler also tracks generated memo modules and application assets between runs. A manifest records files emitted by the memo pipeline, and the next compile removes only stale files that the prior manifest names. A separate asset manifest removes app assets that no longer exist while preserving files produced by plugins or other frontend steps. This prevents old generated modules and assets from remaining in the frontend while avoiding removal of unrelated files. Frontend compilation follows this transformation from application declarations to browser output.

References: reflex/app.py• L1500-1532 reflex/app.py• L1683-1718 reflex/app.py• L1760-1802 reflex/app.py• L1879-1972 reflex/app.py• L2372-2400 reflex/…/compiler.py• L1232-1429 reflex/…/compiler.py• L1447-1517 reflex/…/memoize.py• L267-351 reflex/…/memoize.py• L354-588 reflex/…/utils.py• L231-364 reflex/…/utils.py• L1160-1360 reflex/state.py• L2160-2174 reflex/state.py• L2403-2504 reflex/state.py• L2630-2721

ASGI backend

The backend starts as a Starlette ASGI application. It provides health and ping endpoints, optional upload routes, and the event endpoint used when state is enabled. CORS rules define which browser origins can use the backend. In development the default policy remains open. In production an explicit policy is honored; otherwise a configured deployment origin is used, or same-origin access is kept when the frontend is served by the backend.

When the application is called, it prepares the current Python definition for serving. It may compile the frontend, rebuild the mounted frontend in preview mode after a hot reload, run post-compile plugin hooks, and mount the prepared frontend when one service serves both surfaces. API transformers can then mount or wrap the backend before request context and lifespan handling are added. The outer ASGI boundary also coordinates the lifespans of transformer applications, so their startup and shutdown work follows the server lifecycle.

The event transport rejects oversized polling requests after reading their body and closes the affected session. This prevents a rejected client request from remaining open while the server waits for another poll.

References: reflex/app.py• L412-460 reflex/app.py• L484-510 reflex/app.py• L679-824 reflex/app.py• L909-1011 reflex/app.py• L1013-1095 reflex/app.py• L1176-1244

Runtime coordination

The frontend and backend coordinate through page identity and client events. The browser chooses a page route for rendering, then uses the backend connection to request state work and receive the resulting changes.

Event and state exchange

The event transport carries user actions from the browser to the backend. The backend links each connection to a client token, captures connection data such as headers and client identity, and queues each event for processing. State handling produces an update for that client, and the event namespace sends the update back over the same connection. A state change made outside an event follows the same return path so the browser can stay in sync. If an update names a frontend substate that the browser does not know, the browser skips that substate and reports the mismatch through a fixed client-error signal instead of stopping the whole update.

Hydration takes browser storage values and the initial snapshot under one state lock. The backend compares the browser's per-state hashes with the compiled defaults, sends only needed values, then sends corrections from storage overrides. This keeps computed values and storage-dependent state aligned without repeating storage side effects.

Connection data that does not change during a session is captured when the client connects. Each event then combines that data with event-specific route data before processing. The state keeps session and header data separate from navigation data, so a navigation update does not resend unchanged connection data. Repeated request headers remain available in order: cookie fields use cookie separators, while other repeated fields use header separators. This keeps request context available to state handlers without repeating connection work for every event.

Router data exposes session details, request headers, the matched route, and the current URL to backend state logic. The frontend receives a safe router view: cookies and credential-bearing headers remain server-side, while deprecated frontend cookie reads resolve to an empty value. Applications that need browser cookie state use client-side cookie support instead.

The same connection can report frontend failures through a fixed client-error signal. This keeps state-contract failures visible even when the generated frontend cannot resolve a state event handler. The backend passes these reports to the configured frontend exception handler and limits them per session and across a time window so client reports cannot flood the logs. When a connection closes, the runtime also tells event processing to stop work tied to that client before it removes the token link.

The following flow shows the main path for a state-changing browser action.

flowchart LR
    Browser[Browser UI] -->|event| Transport[Event transport]
    Transport --> Backend[ASGI backend]
    Backend --> Namespace[Event namespace]
    Namespace --> Processor[Event processor]
    Processor --> State[Client state manager]
    State -->|state update| Namespace
    Namespace -->|update| Transport
    Transport --> Browser

State management and event processing explains state trees, event handlers, hydration, and the state backends in detail.

References: reflex/app.py• L2269-2294 reflex/app.py• L2297-2511 reflex/app.py• L2513-2624 reflex/app.py• L2635-2713 reflex/…/data.py• L93-142 reflex/…/data.py• L450-706 reflex/state.py• L1557-1634 reflex/state.py• L2403-2504 reflex/state.py• L2630-2721

State storage

The state manager stores the state tree for each client token and protects updates while an event changes that tree. The application selects a memory, disk, or Redis manager from configuration. All three provide the same event-facing state contract, but their lifetime and process-sharing behavior differ.

ManagerRuntime role
MemoryKeeps active client state in the worker and removes inactive entries after expiration. It suits a single process where state loss on restart is acceptable.
DiskKeeps a local copy of client state and writes changes in the background. It flushes pending writes when the worker closes.
RedisShares client state and update locks through Redis. It supports coordinated access across workers and uses lock and lease limits to bound long-running work.

The choice is part of the deployment contract. A manager that is local to one worker cannot provide the same cross-worker continuity as Redis, while a Redis manager also depends on a reachable Redis service and valid lock settings.

References: reflex/…/__init__.py• L34-95 reflex/…/memory.py• L21-46 reflex/…/memory.py• L128-161 reflex/…/disk.py• L65-116 reflex/…/disk.py• L312-421 reflex/…/disk.py• L450-457 reflex/…/redis.py• L131-225 reflex/…/redis.py• L392-431 reflex/…/redis.py• L575-595

Lifespan coordination

The ASGI lifespan keeps long-running runtime services aligned with the server process. Startup creates a fresh event processor for the worker and activates its state and event links. Registered lifespan tasks can run as functions, coroutines, or async context managers. API transformer applications that expose a lifespan also receive startup and shutdown signals in the runtime's transformer order. Shutdown cancels running tasks and closes client-token and state-manager resources.

Request context middleware restores the registration and event context needed for state and event work. This matters because an ASGI server can give each request a fresh context scope. Lifespan state from transformer applications is shared with requests, so startup resources can reach request handlers through the normal ASGI request context.

References: reflex/app.py• L350-409 reflex/app.py• L825-899 reflex/app.py• L965-1008 reflex/app.py• L1232-1244 reflex/…/lifespan.py• L43-148

Route identity

A route is the normalized identity that connects a Python page declaration to a browser URL and its generated frontend page. Registration validates static, dynamic, optional, and catch-all route forms. The runtime rejects conflicting routes and keeps dynamic argument names consistent across the route tree.

Plugin route contributions are staged before they become part of the application. The runtime checks all plugin contributions against app routes and other plugins first, then commits the valid set. This keeps a failed plugin hook from leaving partial routes or dynamic route variables behind.

At event time, the router maps the browser path back to the registered route. This mapping selects page-load events and supplies route data to state processing. Routing and page registration covers this contract in detail.

References: reflex/app.py• L1127-1647 reflex/app.py• L2545-2620 reflex/state.py• L1439-1512 reflex/state.py• L1557-1634

Serving modes

The runtime changes its compile and serve behavior by environment. Development favors fast rebuilds and reloads. Production serves a prepared frontend and starts the backend without repeating the full frontend compile.

Development serving

The development workflow starts a reload-capable backend and a frontend development server. The backend app factory can compile the current Python definition, while the frontend process watches the generated project and refreshes the browser. Compile markers and reload triggers prevent an ordinary backend worker restart from doing unnecessary frontend work.

The application compile step also records which pages create dynamic state. It writes that information through an atomic file swap so backend workers do not read a partial marker. Page evaluation is tracked within a process because evaluating a page can create global state definitions more than once. Backend-only evaluation can skip initial-state serialization when a caller only needs page side effects, such as database setup.

This split lets Python changes rebuild the generated frontend and lets frontend changes refresh without changing the backend contract. Application lifecycle and configuration describes the developer-facing startup path.

References: reflex/…/exec.py• L38-77 reflex/…/exec.py• L312-355 reflex/…/exec.py• L646-668 reflex/…/exec.py• L706-862 reflex/app.py• L1769-1802 reflex/app.py• L2100-2214 reflex/…/compiler.py• L1210-1303

Production serving

Production first creates the frontend artifacts and installs the libraries required by the generated project. The compile also persists the route table for a standalone static server, so known single-page application routes can return the frontend while unknown routes can return 404. The backend is then started with compilation disabled because it uses those prepared outputs. The frontend can run as a separate static service or be mounted into the backend ASGI application.

Static serving honors the frontend path and configured pre-compressed asset formats. The backend and frontend may use separate worker processes, but they must use the same generated frontend contract and compatible configuration.

References: reflex/…/compiler.py• L1507-1583 reflex/…/exec.py• L343-402 reflex/…/exec.py• L865-983 reflex/app.py• L926-1011

Runtime extension points

Plugins and middleware extend the runtime without changing the main application boundary. Plugins can add routes, frontend dependencies, generated files, and compile hooks. Middleware can stop or change event processing before a handler runs, then change the resulting state update afterward. API transformers can mount or wrap the backend ASGI app.

These extension points connect Python startup, frontend generation, and request handling. A change to one stage can affect the contract used by the next stage.

References: packages/…/config.py• L425-559 reflex/…/compiler.py• L1196-1207 reflex/…/compiler.py• L1455-1492 reflex/…/memoize.py• L354-375 reflex/…/middleware.py• L16-85 reflex/app.py• L1341-1498 reflex/app.py• L965-1008

Change checklist

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

  • Changes to frontend_path, backend_path, or api_url must stay aligned across generated browser URLs, route matching, event transport, static mounts, and the browser-visible router URL.
  • Changes to state enablement, transport, or state-manager selection must keep generated contexts, the event endpoint, client tokens, and the selected state backend compatible.
  • Changes to compiler outputs or templates must also update the production static mount, the route manifest, the bundled-library registry, and memo and asset cleanup rules that remove stale generated files.
  • Changes to initial-state resolution, serialization, or hydrate hashes must keep the compiled frontend snapshot aligned with the backend snapshot used for first hydration.
  • Changes to client-storage field detection must preserve storage options for declared fields and factory-backed storage defaults across the full state tree.
  • Changes to shared local-storage names must preserve server fan-out for synced fields and must not replace values written by the same event.
  • New plugin routes must preserve staged route ownership, dynamic argument names, and dynamic argument types across app and plugin pages.
  • Production compile behavior must preserve the contract that backend workers can skip compilation while still loading the generated frontend and state markers.
  • Backend-only page evaluation must keep initial-state serialization disabled for callers that only need page registration side effects.
  • Changes to automatic memoization must preserve hook scope, loop-variable access, app-wrapper discovery, and stable-key warnings for hook-bearing loop items.
  • Changes to frontend mismatch handling must keep schema checks and unknown substates skippable and the fixed client-error signal usable when generated state definitions do not match the backend.
  • Changes to router serialization must keep the backend router shape and frontend RouterDataVar shape aligned while excluding cookies and credential-bearing headers from browser data.
  • Changes to repeated ASGI header handling must preserve all values and the separator rules used by cookies and other headers before router data reaches state logic.
  • Changes to app-wrapper priority or child rendering must preserve the visibility of lower-priority portals and other global frontend elements.
  • Changes to hydration fallback resolution must preserve the difference between explicit app configuration and ambient environment configuration.
  • Changes to application initialization must keep the event processor tied to ASGI lifespan startup and shutdown.
  • Changes to state-manager expiration, deferred writes, or distributed locks must preserve state visibility after idle periods, worker shutdown, and concurrent event processing.
  • Changes to default or explicit CORS settings must keep the browser origin policy consistent between the HTTP backend and the event transport, especially when the frontend uses a separate deployment origin.
  • Changes to API transformer order or lifecycle handling must keep transformer startup, shutdown, and request-visible lifespan state aligned.
  • Changes to event buffer limits must preserve the rejection and session-close path for oversized polling requests so the client does not remain blocked.
  • Changes to disconnect handling must keep client-token cleanup and cancellation of client-bound event work in the same lifecycle.

Important failure modes

TriggerConsequenceGuard
Frontend and backend use different generated state definitionsUnknown substates are skipped and the affected part of the update does not reach the browser; the mismatch is reported to the backendRebuild the frontend and point api_url to the matching backend
Router serialization sends cookies or credential-bearing headersBrowser state or event data exposes request credentialsKeep private headers out of the serialized router view and use client-side cookie support for browser cookies
Repeated ASGI headers are collapsed or joined with the wrong separatorState handlers receive incomplete cookies or incorrect request metadata such as forwarded client address dataPreserve repeated values in order and join cookies separately from other headers
A partial navigation payload clears session or header dataLater state work loses connection context or builds an incomplete URLMerge new router data with the prior connection data before updating per-field router state
A client sends repeated frontend error reportsBackend logs can be flooded or hide useful errorsAccept reports only from linked sessions and enforce per-session and process-wide rate limits
A route conflicts with an existing route or reuses a dynamic name with another typeCompilation or route registration stops with a route errorUse unique normalized routes and keep each dynamic argument type consistent
Production starts with missing or stale frontend output, route manifest, or app asset copiesThe backend can run while browser pages, static assets, or routable SPA paths are missing or out of dateRun the frontend compile before starting the backend and let the owned-file manifests prune only prior generated outputs
A page uses state while the app has no state classCompilation fails because generated frontend code needs a state providerDefine an rx.State subclass or remove state access from the page
Redis state mode has no Redis URLConfiguration fails before the app can startSet the Redis connection value when selecting the Redis state manager
Redis event work exceeds the lock lifetimeThe state write fails because the worker no longer owns the update lockIncrease the lock limit or use a background event for long-running work
Disk state is still queued when a worker stops unexpectedlyRecent client state changes may not reach diskAllow normal manager shutdown to flush pending writes and choose a suitable write debounce
Frontend and backend paths do not match the deployment layoutBrowser requests reach the wrong route or event endpointSet the path prefixes and backend URL from the actual service layout
A lower-priority portal is nested under an app wrapper that drops childrenThe portal is absent from the DOM and its browser feature cannot openKeep non-child-rendering wrappers inside a child-preserving fragment
A page is evaluated more than once in one processDynamic state classes can be registered more than once and produce an invalid app contractKeep page evaluation idempotent through the app's evaluated-page tracking
A configured hydration fallback cannot be loadedThe fallback is absent, so the browser uses the default hydration behaviorUse a valid component callable or import path and review the startup log
A memo module or app asset is removed from the current source but remains on diskThe frontend can load stale generated code or an outdated assetLet the owned-file manifest cleanup run after compile output and asset scans are determined
An automatic memo wrapper captures a loop item without a stable keyLifecycle hooks can run for the item now at another position after a removal or moveGive hook-bearing loop items a stable key and heed the compile warning
Production uses the default open CORS policy with a separate frontend originAn unrelated site can attempt cross-origin requests to the backendSet deploy_url to the frontend origin or configure cors_allowed_origins explicitly
Production has no deploy_url while the frontend is served by the backendAn unnecessary cross-origin policy can block or weaken the same-origin deployment contractLeave CORS unconfigured for the same-origin mode or set the actual deployment origin for a split service
A Starlette transformer lifespan is also registered as a Reflex lifespan taskThe same startup and shutdown work runs twiceLet the transformer own its lifespan or register the task once, not both ways
An oversized polling POST reaches the event server without being drainedThe client can wait for a response while the event session remains stuckRead and reject the body through the runtime guard, then close the session
A socket disconnects while client-bound page-load work is activeWork can continue after the browser is gone and produce stale updatesNotify the event processor during disconnect before removing the token link
A request header contains bytes that are not valid UTF-8Building router data can fail before the event reaches state processingDecode invalid header values with the runtime's Latin-1 fallback
A backend-only page evaluation serializes initial state without a frontend compileA serializer can require frontend libraries that the compile did not registerDisable initial-state serialization for page-evaluation-only commands
Two synced local-storage fields share a name but the backend does not fan out a writeThe writing tab keeps related state fields out of sync until another browser eventGroup storage fields by name and update only fields not written by the event

Key files

FileWhy to read it
reflex/app.pyDefines the application boundary. It assembles the backend, pages, state services, event namespace, wrappers, compilation step, ASGI lifecycle, and final ASGI app.
packages/…/config.pyDefines how app settings are loaded, overridden, normalized, and exposed to both runtime sides.
reflex/…/compiler.pyShows the high-level conversion from app definitions to generated frontend files, production artifacts, and backend-only evaluation paths.
reflex/…/memoize.pyShows how reactive subtrees and hook-bearing loop items are scoped during frontend generation.
reflex/…/utils.pyShows how initial state, client-side storage, frontend library discovery, generated memo files, and app assets become compile outputs.
reflex/…/data.pyDefines the router data contract shared by backend state and the generated frontend, including URL parsing and safe header serialization.
reflex/state.pyDefines state classes, router state updates, dynamic route argument access, hydration snapshots, frontend schema checks, and shared browser-storage updates.
reflex/…/__init__.pyDefines the state-manager contract and selects the storage model used by the running app.
reflex/…/memory.pyIllustrates local in-process state lifetime and expiration.
reflex/…/disk.pyIllustrates local state persistence, deferred writes, expiration, and shutdown flushing.
reflex/…/redis.pyIllustrates shared state access and lock coordination across workers.
reflex/…/exec.pyShows how development and production frontend and backend processes are started and how compile skipping is coordinated.
reflex/route.pyDefines the route forms and the mapping from browser paths to registered application routes.
reflex/…/lifespan.pyDefines startup and shutdown coordination for long-running app services.
reflex/…/middleware.pyDefines the event interception points used by runtime middleware.