Application lifecycle and configuration
The Reflex application lifecycle turns an app definition into a configured, compiled, and running full-stack service. An App joins page registration, optional state and event support, HTTP routes, frontend output, and server lifetime management. Its cross-origin policy also changes with explicit configuration and the selected run mode. This page gives the startup model that connects application runtime with state and events, frontend compilation, frontend runtime package, routing and pages, and runtime foundations.
Application model
App construction
The App is the top-level application object. A developer creates it in the app module and can give it global visual settings, page metadata, middleware, plugins, exception handlers, and API transforms. Construction binds the app to its registration context, reloads project configuration, validates the base state shape, creates the backend API, and installs the common service layers used by the rest of the lifecycle (reflex/app.py• L881-1037, reflex/app.py• L1048-1087). The same construction step applies the CORS policy that the backend will use for HTTP and websocket traffic (reflex/app.py• L504-542, reflex/app.py• L1438-1465).
An app can run with state enabled or disabled. With state enabled, construction prepares a state manager and a client event channel. It also makes the event namespace available to the runtime so client events can reach state handlers and state updates can return to the right client (reflex/app.py• L1089-1185). The event processor starts with the server lifespan. This gives each worker a fresh processing context (reflex/app.py• L1193-1269).
Custom frontend and backend exception handlers are checked during initialization. They must be named callables with the expected exception argument. A backend handler must return an event specification or no result (reflex/app.py• L2430-2520).
References: reflex/app.py• L881-1037 reflex/app.py• L1048-1087 reflex/app.py• L1089-1185 reflex/app.py• L1193-1269 reflex/app.py• L504-542 reflex/app.py• L1438-1465 reflex/app.py• L2430-2520
Application composition
The app combines user pages with shared app-level behavior. Default wrappers provide error handling and connection feedback. Plugins can add pages and other compile-time behavior. Middleware can inspect an event before handling and can change its resulting state update (reflex/app.py• L929-947, reflex/app.py• L1716-1873, reflex/…/middleware.py• L16-85).
App-level wrappers are ordered by priority and form the shared component tree around each page. A wrapper that does not render its children can hide lower-priority features, so built-in visual wrappers keep portal-like features as reachable siblings in the final page tree (reflex/app.py• L2105-2121, reflex/app.py• L2170-2184).
The app can also define a hydration fallback. An explicit App setting takes precedence over the matching configuration value. A configured dotted import path is optional ambient setup, so a path that cannot load is logged and omitted, while an explicit app callable fails fast (reflex/app.py• L2123-2147).
Plugin page contributions are staged and checked before they become part of the app. The app validates route ownership and dynamic argument types before it commits the batch. This keeps a failed plugin hook from leaving partial routes or dynamic route settings behind (reflex/app.py• L1716-1873).
This composition keeps cross-cutting behavior outside individual pages. The order of middleware and app wrappers therefore affects the path of every event or rendered page.
References: reflex/app.py• L929-947 reflex/app.py• L1716-1873 reflex/app.py• L2105-2121 reflex/app.py• L2123-2147 reflex/app.py• L2170-2184 reflex/…/middleware.py• L16-85
Configuration resolution
Config sources
Config is the typed application setting set. In a normal project it is created as config in rxconfig.py. The settings cover app identity, server addresses, backend paths, database and Redis connections, frontend packages, state storage, plugins, and build behavior (packages/…/config.py• L152-193, packages/…/config.py• L289-326).
The config loader imports rxconfig.py from the current project and caches one resolved config per registration context. A reload reads the project file again. This lets separate workers or contexts use their own current project settings without relying on a stale module import (packages/…/config.py• L805-845, packages/…/config.py• L874-932).
References: packages/…/config.py• L152-193 packages/…/config.py• L289-326 packages/…/config.py• L805-845 packages/…/config.py• L874-932
Configuration precedence
Configuration follows a simple override path. Values in rxconfig.py provide the base. Environment values with the REFLEX_ prefix override matching fields. CLI options such as ports are then written into the environment when they must persist into child processes. The config is reloaded after that (packages/…/config.py• L707-748, packages/…/config.py• L791-803, reflex/reflex.py• L320-362).
Formatted URL defaults follow port changes only when the developer did not set those URLs directly. This keeps a deliberate api_url or deploy_url stable while making default local URLs match selected ports (packages/…/config.py• L759-789).
References: packages/…/config.py• L707-748 packages/…/config.py• L759-803 reflex/reflex.py• L320-362
Environment values
The environment system converts process strings into the types used by the app. It supports values such as booleans, numbers, paths, enums, lists, and plugin classes. Empty values act as unset values. Invalid values fail with a field-specific error instead of silently changing behavior (packages/…/environment.py• L276-391, packages/…/environment.py• L397-472).
Environment files provide another input for configuration. REFLEX_ENV_FILE can name one or more dotenv files, and Config.env_file can load files while a config is created. Files are loaded before config fields read their REFLEX_ overrides, so their values become part of the same resolution path (packages/…/environment.py• L765-823, packages/…/config.py• L707-716).
References: packages/…/environment.py• L276-391 packages/…/environment.py• L397-472 packages/…/environment.py• L765-823 packages/…/config.py• L707-716
Plugin configuration
Plugins extend the app without changing the core startup path. Configured plugin instances are checked and normalized. Plugins named by REFLEX_PLUGINS are required settings and a bad entry stops config loading. Extra plugins from REFLEX_EXTRA_PLUGINS are additive and can be skipped with a warning when an entry cannot load or start. Built-in plugins are added unless disabled (packages/…/config.py• L425-559, packages/…/config.py• L592-609).
This distinction matters during startup. Required plugin configuration is a startup contract. Optional extra plugin configuration does not block the app when it is invalid.
References: packages/…/config.py• L425-559 packages/…/config.py• L592-609 packages/…/environment.py• L175-241
Server rendering setting
Server-side rendering is resolved once for the process and then passed to worker processes through the environment. The command-line setting supplies the value only when REFLEX_SSR is not already set. An existing environment value remains authoritative (reflex/…/exec.py• L1230-1266).
The effective setting controls whether routes are prepared for server rendering. Production mode supplies the default when no explicit setting exists. This keeps development and production startup on different defaults without changing the app definition (reflex/…/exec.py• L1230-1249).
References: reflex/…/exec.py• L1230-1266
Initialization stages
Project initialization
reflex init prepares a new project for the application lifecycle. It validates the app name, prepares frontend dependencies, creates the selected project template, and writes project support files. If the project uses a requirements file, the command also tells the developer how to install the Reflex dependency (reflex/reflex.py• L37-125).
The run and export commands check whether the project has its generated support area and a matching Reflex version. If it does not, they repeat the needed initialization before continuing (reflex/…/prerequisites.py• L724-751, reflex/reflex.py• L344-351). Package version checks use separate per-package timestamps in project metadata. A successful check stays fresh for one day. A failed attempt is retried after one hour (reflex/…/prerequisites.py• L35-186).
The generated frontend work area can be changed with REFLEX_WEB_WORKDIR. The state work area can be changed with REFLEX_STATES_WORKDIR, while backend markers remain under the selected frontend work area. These paths are resolved before readiness checks and app compilation. Custom work areas must remain available to every process that participates in startup (reflex/…/prerequisites.py• L55-84).
This readiness step keeps generated project data and dependency checks aligned with the installed Reflex version. It also avoids making the same network check on every developer command.
References: reflex/reflex.py• L37-125 reflex/…/prerequisites.py• L35-186 reflex/…/prerequisites.py• L55-84 reflex/…/prerequisites.py• L724-751 reflex/reflex.py• L344-351
App initialization
When Python constructs an App, it binds the app to its registration context, reloads configuration, creates the backend API, adds CORS and health endpoints, initializes app mixins, and then enables state services when requested (reflex/app.py• L1048-1087).
The CORS policy has explicit and default paths. An explicit cors_allowed_origins value is used as configured. In development, the open default remains available. In production, the default narrows to the origin in deploy_url for cross-origin requests. The HTTP service accepts only that resolved policy. The event service also accepts the backend's own origin when the policy was not explicit, including when the frontend is served by the backend (reflex/app.py• L504-542, reflex/app.py• L745-878, reflex/app.py• L1437-1465).
State initialization creates the state manager and the Socket.IO event namespace. The namespace is mounted under the configured backend path. This makes the backend path part of the client-server contract rather than only a display setting (reflex/app.py• L1089-1185, packages/…/config.py• L661-681).
References: reflex/app.py• L504-542 reflex/app.py• L745-878 reflex/app.py• L1048-1087 reflex/app.py• L1089-1185 reflex/app.py• L1437-1465 packages/…/config.py• L661-681
Compilation boundary
The app keeps page declarations unevaluated until compilation. Compilation resolves pages, builds their frontend representation, checks route and state relationships, and writes generated output used by the servers. A compile trigger records why the build started, such as an initial run or a hot reload (reflex/app.py• L1875-1911, reflex/app.py• L2224-2287).
Page evaluation is tracked within a worker because evaluating a page can create state classes and other global registrations. A reload or a production worker therefore does not repeat those side effects unnecessarily. The compile boundary also checks route conflicts and records which pages create state for later backend use (reflex/app.py• L1875-1977, reflex/app.py• L2289-2323).
Compilation is also an observability boundary. When telemetry is active, the compile operation records its own span and result. Shared compiler cleanup runs after both successful and failed compilation so later compile passes do not inherit stale build metadata (reflex/app.py• L2224-2287).
Before compilation, the app removes stale external-asset links. In preview mode, a hot reload rebuilds the mounted frontend bundle from the new compiled output. A failed rebuild stops that reload instead of serving an incomplete or stale bundle (reflex/app.py• L1279-1315).
The CLI performs an initial compile when the selected run mode needs a frontend. The backend can then load the exported app object, while development reloads can compile again when source files change (reflex/reflex.py• L128-150, reflex/…/exec.py• L560-607, reflex/…/exec.py• L712-734). See application runtime for the running service boundary.
References: reflex/app.py• L1279-1315 reflex/app.py• L1875-1977 reflex/app.py• L2224-2287 reflex/app.py• L2289-2323 reflex/reflex.py• L128-150 reflex/…/exec.py• L560-607 reflex/…/exec.py• L712-734
Runtime services
ASGI service
The running application is an ASGI service. This is an async interface used by the HTTP server and the websocket event server. App.__call__ compiles the current app, runs plugin post-compile hooks, applies optional API transforms, mounts backend routes, and returns a top-level service with request context and lifespan handling (reflex/app.py• L1279-1381). The request layer restores the Reflex contexts needed by state and event work before it passes control to the mounted service. The outer service also applies the resolved CORS policy when cross-origin access is allowed (reflex/app.py• L371-430, reflex/app.py• L1367-1381).
The service always includes basic ping and health checks. It can add upload routes, a route listing endpoint, and a compiled frontend mount when the relevant feature is in use (reflex/app.py• L1383-1424, reflex/app.py• L1328-1334). The frontend mount uses the compiled route table to return a successful response for valid client-side paths while preserving a not-found response for unknown paths. See uploads and middleware for the upload path (reflex/…/exec.py• L366-452).
References: reflex/app.py• L371-430 reflex/app.py• L1279-1381 reflex/app.py• L1328-1334 reflex/app.py• L1383-1424 reflex/…/exec.py• L366-452
Event service
The event service connects browser sessions to app state. A client session supplies a token. The namespace maps that token to a socket session. Incoming events enter the app event processor, and state changes return to the matching client. The initial connection can also carry the first hydration event, so the client can begin state setup without an extra round trip (reflex/app.py• L2649-2785). State and events explains this runtime contract in more detail.
App code can also change a client's state outside the socket event path through modify_state. This path restores the app context when needed, binds the work to the target client token, and holds exclusive access while awaited work runs. It resolves the resulting state change and emits it to that client before releasing the context lock (reflex/app.py• L2340-2428).
Polling requests whose bodies exceed the Socket.IO message limit are consumed before rejection. The event service returns a bad-request response and closes the session without waiting for a later poll. This prevents an oversized event from leaving the browser connection request pending (reflex/app.py• L433-480).
At connection time, the service captures stable request data such as headers, client address, and session identity. It adds that data to each event so state handlers can use request context without rebuilding it for every message. The service also manages duplicate sessions and reports frontend errors through the app's configured frontend exception handler. Client error reports are accepted only from known sessions and are bounded per session and per time window (reflex/app.py• L2649-2850, reflex/app.py• L3033-3079).
The connection cache is isolated from event data. Each event receives its own header mapping, so a state handler cannot change the cached request context for later events on the same socket. A missing connection record is rebuilt from the socket environment before the event enters the processor (reflex/app.py• L2794-2833, reflex/app.py• L2910-2989). A frontend and backend state mismatch is reported through a fixed client-error path, so the report still reaches the backend when the frontend cannot resolve the expected state event (reflex/app.py• L2730-2758, reflex/app.py• L3033-3079).
When telemetry is enabled, the event transport also records connection changes and message sizes as events cross the socket. This adds visibility without changing the state or event contract (reflex/app.py• L2775-2776, reflex/app.py• L2889-2908).
References: reflex/app.py• L433-480 reflex/app.py• L2340-2428 reflex/app.py• L2649-2785 reflex/app.py• L2730-2758 reflex/app.py• L2775-2776 reflex/app.py• L2794-2833 reflex/app.py• L2889-2908 reflex/app.py• L2910-2989 reflex/app.py• L3033-3079
Lifespan service
The lifespan service owns work that must start and stop with the server. A registered task can be a function, coroutine, async context manager, or already-created async task. The app starts these tasks when the ASGI lifespan begins and cancels active tasks during shutdown (reflex/…/lifespan.py• L43-149).
Shutdown also closes event token resources and the state manager. Developers must register lifespan work before startup because registration after the lifespan begins is rejected (reflex/…/lifespan.py• L150-207).
References: reflex/…/lifespan.py• L43-149 reflex/…/lifespan.py• L150-207 reflex/app.py• L371-430 reflex/app.py• L1367-1378
Developer startup path
Run command
reflex run is the main developer-facing entry point. It selects the environment and whether to run the frontend, backend, or both. It places those choices into internal environment settings, resolves the running mode, validates the project, persists selected connection settings, and then starts the selected services (reflex/reflex.py• L424-521, reflex/…/prerequisites.py• L691-707).
The normal development path uses separate frontend and backend processes. It compiles first, starts the frontend development server when requested, and runs the backend with reload support. Development mode can choose the next open port when the developer did not set one (reflex/reflex.py• L153-208, reflex/…/exec.py• L335-358). The frontend receives a process-local environment for its toolchain, including the development module condition and build output settings, without changing the parent command's environment (reflex/…/exec.py• L225-265). When the developer command exits, the frontend child is also stopped, including a child that finishes starting during shutdown (reflex/…/exec.py• L271-333).
When frontend and backend commands run together, the process supervisor watches both tasks. If one task fails while the main thread is waiting on the other, it interrupts the wait so the original failure reaches the CLI promptly. This prevents a failed child service from leaving the developer-facing command blocked (reflex/…/processes.py• L284-390).
References: reflex/reflex.py• L424-521 reflex/…/prerequisites.py• L691-707 reflex/reflex.py• L153-208 reflex/…/exec.py• L225-358 reflex/…/processes.py• L284-390
Startup sequence
The startup sequence moves from project settings to a compiled app and then to live services. The same broad sequence applies to development, preview, and production, but each mode chooses a different frontend server and reload policy. The developer command also owns the frontend child process, so shutdown removes that child even when startup and shutdown overlap (reflex/…/exec.py• L271-333).
The diagram shows how a developer command becomes a running application.
flowchart LR
A[reflex run] --> B[Resolve config and environment]
B --> C[Check project readiness]
C --> D[Choose run mode and ports]
D --> E[Compile app when needed]
E --> F[Create App and runtime services]
F --> G[Start frontend and backend]
G --> H[Serve requests and events]
H --> I[Run service and child-process cleanup on shutdown]
References: reflex/reflex.py• L291-421 reflex/app.py• L1048-1381 reflex/…/lifespan.py• L92-149 reflex/…/exec.py• L271-333
Preview and production modes
Preview keeps backend hot reload behavior but serves a freshly built frontend bundle from the backend on one port. Production builds the frontend once and starts the selected production server without the development compile loop (reflex/reflex.py• L210-288, reflex/…/exec.py• L951-971). A production frontend mount uses the compiled route table when available. Direct requests to valid client-side routes then keep a successful status while unknown paths keep a not-found status (reflex/…/exec.py• L366-452).
Frontend-only and backend-only modes use the same lifecycle checks but stop at one side of the system. Production and preview require a shared port when both sides run. The CLI rejects conflicting mode and port choices before it starts a service (reflex/reflex.py• L291-421).
References: reflex/reflex.py• L210-288 reflex/reflex.py• L291-421 reflex/…/exec.py• L366-452 reflex/…/exec.py• L951-971
Backend worker startup
The development backend is started as an app factory so a worker creates the current App and its services. Uvicorn or Granian supplies the server process. The runtime selects Granian when requested or when the Uvicorn and Gunicorn path is not available. Otherwise it uses Uvicorn with reload support (reflex/…/exec.py• L494-508, reflex/…/exec.py• L560-607, reflex/…/exec.py• L712-734).
This separation explains why startup configuration must be available in the process environment. The CLI persists values such as ports before it creates child processes, and reload workers load the environment again when they restart. Production workers also receive a skip-compile setting because the frontend build has already completed (packages/…/config.py• L791-803, reflex/…/exec.py• L979-1038, reflex/…/exec.py• L1123-1161).
In Granian development mode, the supervisor holds the listening socket while a worker is replaced. Requests can wait for the replacement during a normal reload. If no worker can serve the app, the supervisor releases the socket so clients receive a refusal instead of waiting on an unusable backlog. A later worker spawn binds the socket again. A worker that exits as part of a requested shutdown is not reported as an unexpected worker failure, while an unsignalled failure keeps the diagnostic (reflex/…/exec.py• L792-905).
References: reflex/…/exec.py• L494-508 reflex/…/exec.py• L560-607 reflex/…/exec.py• L712-734 reflex/…/exec.py• L792-905 reflex/…/exec.py• L979-1038 reflex/…/exec.py• L1123-1161 packages/…/config.py• L791-803
Development reload
Development reload watches the app's project paths and can add or remove paths through environment settings. It ignores common generated, hidden, and data files by default so a change that does not affect app code does not restart the backend (reflex/…/exec.py• L623-709).
The backend marks the first reload-capable worker boot so the app can distinguish its initial compile from a later hot reload. The marker is claimed atomically. If the first compile fails, the next worker still follows the hot-reload path after the developer fixes the error (reflex/…/exec.py• L41-80).
Granian keeps the listening socket in its supervisor during reload and reloads dotenv values when it replaces a worker. Requests continue to wait during a normal worker replacement. When a worker fails without a live replacement, the supervisor closes the socket and recreates it for the next worker, so an unavailable app does not leave clients waiting for a full timeout (reflex/…/exec.py• L792-948).
References: reflex/…/exec.py• L41-80 reflex/…/exec.py• L623-709 reflex/…/exec.py• L792-948
Change checklist
When these files or sections are changed, remember to consider these:
- When changing config field names or types, update the
REFLEX_environment mapping and every CLI option that persists the field into child processes. - When changing
cors_allowed_origins,deploy_url, or production mode resolution, keep HTTP CORS and websocket origins on the same explicit-or-default policy. Preserve backend same-origin access when the policy is ambient. - When changing
backend_path, keep the event namespace, default endpoints, and frontend endpoint URLs aligned. - When changing startup mode selection, preserve the rules for frontend-only, backend-only, shared-port, preview, and production runs.
- When changing app construction order, keep state and event services ready before the ASGI service accepts requests.
- When changing base state validation, keep the single supported application state root and the test-only exception aligned.
- When changing custom exception handler validation, keep the frontend and backend callback contracts aligned with the errors they handle.
- When changing lifespan cleanup, close both event token resources and the state manager so worker shutdown does not leave client or state resources open.
- When changing plugin page registration, preserve route conflict checks, dynamic argument checks, and the all-or-nothing staging boundary.
- When changing app wrapper priorities or wrapper shapes, keep lower-priority wrappers renderable and keep portal components reachable in the final page tree.
- When changing hydration fallback resolution, preserve the precedence of the explicit
Appvalue over config and keep ambient config failures non-fatal. - When changing concurrent service startup, preserve prompt propagation of a child failure and avoid interrupting the main thread after the supervision context exits.
- When changing version-check cache keys or cooldowns, keep package names isolated and preserve the separate retry path for failed network checks.
- When changing compile instrumentation or cleanup, keep the compile outcome visible and clear compile-only caches after failures as well as successes.
- When changing the compile trigger marker, preserve atomic first-boot detection so a failed initial compile does not lose the next hot-reload signal.
- When changing reload path rules, keep the default exclusions and the include, exclude, and override settings aligned with the worker's watched project.
- When changing frontend and backend startup, keep the skip-compile marker, SSR setting, and process environment consistent with the selected run mode.
- When changing frontend child-process startup or shutdown, keep cleanup safe when launch and shutdown happen at the same time.
- When changing production frontend serving, keep compiled route matching aligned with the route manifest and preserve not-found status for unknown paths.
- When changing the Granian reload supervisor, keep the socket open for a planned worker replacement but release it when no worker can serve requests, then bind the same effective port for the next worker.
- When changing frontend or state workdir resolution, keep readiness markers, backend markers, and all worker processes pointed at the same project paths.
- When changing socket connection context, keep cached request data isolated from mutable per-event router data and preserve the fallback rebuild for connections without cached data.
- When changing client error handling, preserve the known-session check and both per-session and process-wide report limits.
- When changing worker exit handling, keep requested shutdowns quiet while preserving unexpected-exit diagnostics and socket release when no worker can serve requests.
- When changing connection boot events, keep token linking and failed-connect cleanup aligned with the hydration event path.
- When changing the event endpoint or its message-size limit, keep oversized polling bodies drained and rejected without waiting for a later poll, then close the matching socket session.
- When changing out-of-band state updates or awaited event handling, preserve target-token context binding, exclusive state access, lock release, and state-delta emission after the work completes.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
Production uses the default CORS setting with no deploy_url | Cross-origin requests are rejected because the backend leaves HTTP CORS unconfigured | Set deploy_url for a separate frontend or set cors_allowed_origins explicitly. |
| An explicit CORS origin does not match the browser's frontend origin | HTTP or websocket requests fail cross-origin checks | Use the exact scheme, host, and non-default port used by the frontend. |
| A same-origin event request passes through an untrusted forwarded host | The event websocket is rejected even when the public frontend and backend share an origin | Forward the original Host header or set trusted_proxy_hops to the number of trusted proxies. |
The app subclasses rx.BaseState directly outside the test environment | App construction stops before the backend starts | Define application state with rx.State instead of a direct rx.BaseState subclass. |
| rxconfig.py has an invalid typed environment override | Config loading fails before the app starts | Use the field's supported value format and check the field named in the configuration error. |
A required plugin in plugins or REFLEX_PLUGINS cannot load | Startup stops with an invalid plugin configuration error | Use a valid fully qualified plugin path or remove the entry. |
| A custom exception handler is a lambda, partial, or has the wrong signature | App initialization fails before requests or events are served | Use a named handler with an Exception argument and a valid backend event-specification return type. |
| Redis state mode has no Redis URL | App construction fails because the selected state store has no connection target | Set redis_url or REFLEX_REDIS_URL before constructing the app. |
| Two pages or plugins claim the same route, or reuse a dynamic segment name with another type | Compilation or page registration fails and the route tree is not reliable | Keep route ownership unique and keep dynamic segment names and types consistent. |
| Two app wrappers have an order or child relationship that hides lower-priority content | A portal or shared visual feature is absent from the rendered page | Keep non-leaf wrappers able to render their children and use a fragment when a wrapper must remain a sibling. |
| A configured hydration fallback path cannot load | The app starts without the configured hydration fallback | Use a valid dotted import path and inspect the saved compiler error when the fallback is needed. |
REFLEX_SSR contains an invalid or conflicting value | Workers can use a different rendering mode than the command expects | Set one valid SSR value and remember that an existing environment value overrides the CLI flag. |
| Frontend and backend ports differ in preview or production full-stack mode | The CLI refuses to start the selected mode | Use one port for both services or select a single-side mode. |
| A lifespan task is registered after the server starts | The task is rejected and cannot join the current server lifetime | Register all startup tasks before reflex run starts the server. |
| A backend worker starts without the current environment values | The worker can use stale ports, paths, or run-mode settings | Persist CLI values through the environment and reload config at worker startup. |
| A frontend or backend child process fails while another service keeps the main thread blocked | The CLI can appear to hang instead of reporting the failed service | Run service commands through the concurrent process supervisor and propagate the task failure. |
| A version check uses a shared or stale package timestamp | One package can suppress another package's update check or trigger repeated network work | Keep normalized per-package success timestamps and the separate one-hour attempt cooldown. |
| A compile fails after creating temporary compile metadata | A later compile can use stale state or report incomplete telemetry | Keep compile cleanup in the final cleanup path and mark failed compile spans before re-raising. |
| The development reload marker cannot be created | The worker is treated as an initial backend startup, so compile-trigger behavior can fall back to startup mode | Keep the project support directory writable and preserve the marker's atomic create path. |
| A reload path includes the app root with an invalid __init__.py | The backend refuses to build a safe module watch path | Keep the app root import layout valid and use explicit reload overrides only when needed. |
| A preview hot reload cannot rebuild the mounted frontend | The reload stops instead of serving the old or incomplete frontend bundle | Fix the frontend build error before retrying the reload. |
| The compiled route manifest is invalid or missing for a standalone production frontend | Valid client-side routes can receive a not-found status instead of the SPA fallback status | Rebuild the frontend so the route manifest is valid; treat unknown paths as real not-found responses. |
| A Granian worker dies without a live replacement | The supervisor closes the listening socket and clients receive a refusal instead of an indefinite wait | Preserve worker liveness checks and recreate the socket before spawning the next worker. |
| The developer command exits while the frontend child is still launching | The frontend can remain running after the command has stopped | Keep the launch and shutdown state protected and terminate a child that appears during shutdown. |
| A custom frontend or state workdir is missing or differs between parent and worker processes | Readiness checks or generated markers use different paths and startup can fail or serve stale output | Set the workdir environment values before startup and make the selected paths available to every worker. |
| A socket event mutates the cached connection headers | Later events on the same connection can see changed request data | Copy the cached headers before adding them to event router data. |
| A client sends malformed or excessive frontend error reports | The report is ignored or further reports are suppressed to protect backend logs | Accept reports only from linked sessions and enforce the per-session and time-window limits. |
| A requested shutdown is treated as an unexpected worker exit | The server logs a false worker failure during normal process termination | Keep the supervisor signal check with the worker exit result and retain the unexpected-exit path for unsignalled failures. |
| A connection's boot hydration event fails after token linking | The refused connection can leave a stale token link or cached connection data | Remove the connection record and unlink the token before propagating the connection error. |
| A polling POST body exceeds the Socket.IO message limit and is not drained before rejection | The browser can wait for a response while the session waits for a later poll, so connection startup can stall | Drain the body, return a 400 response, and close the matching socket without waiting for polling. |
| An out-of-band state update has no initialized app or valid target token | The update fails before it can acquire state or emit a client delta | Initialize the app first and pass a BaseStateToken or a valid legacy token with its state path. |
Key files
| File | Why to read it |
|---|---|
| reflex/app.py | Defines App construction, CORS origin resolution, ASGI assembly, state and event setup, page registration and compilation, hydration fallback resolution, exception-handler validation, connection context, oversized polling protection, out-of-band state updates, and default backend endpoints. |
| reflex/…/__init__.py | Defines the public constants surface used by lifecycle code for config, ports, compile contexts, routes, endpoints, and state modes. |
| packages/…/config.py | Defines the app config contract, config loading and reload behavior, precedence, URL defaults, and plugin normalization. |
| packages/…/environment.py | Defines typed environment values, dotenv loading, conversion rules, and internal runtime switches. |
| reflex/reflex.py | Defines the developer-facing init, run, compile, preview, and production startup paths. |
| reflex/…/prerequisites.py | Defines project readiness checks, app loading and validation, run-mode selection, workdir resolution, compile entry points, and package version-check caching. |
| reflex/…/exec.py | Defines frontend and backend server startup, frontend process environments, compiled frontend route serving, app factory loading, SSR arbitration, compile-trigger detection, child-process cleanup, and development reload paths. |
| reflex/…/processes.py | Defines port checks, child process launch, concurrent service supervision, and process failure reporting. |
| reflex/…/lifespan.py | Defines startup task registration and shutdown cleanup for long-lived services. |
| reflex/…/middleware.py | Defines app middleware ordering around event processing and state updates. |