Data models and persistence
Data models and persistence give Reflex applications a durable store for records that must outlive a client session or a backend process. The system connects application models to SQL databases through an ORM, manages shared database access, and moves schema changes through tracked migrations. See Backend services for the wider server view and Uploads and middleware for request handling around backend work.
Persistence boundary
Durable application data
The database layer stores application records that can be shared by users and backend workers. A state handler chooses when to read or write these records through a database session, then can place the result in session state for the next client update. This separates durable business data from the temporary state used to render one client session. reflex/model.py
Session state can use memory, disk, or Redis storage, but those stores do not replace the application database. The choice of session store controls how state survives and how workers share it. The database remains the source for records that belong to the application rather than to one client session. See Backend services for the server boundary around this work.
References: reflex/model.py• L66-191 reflex/app.py• L1884-1920
ORM boundary
An object-relational mapper (ORM) maps Python model classes to database tables and turns database rows into Python objects. Reflex exposes SQLModel on top of SQLAlchemy for this work, while the shared metadata path also accepts SQLAlchemy declarative models. The database extra supplies the ORM and migration tools; without it, database entry points report that the required packages are missing at runtime. Type checkers still see the database helpers, models, and migration APIs when those optional packages are not installed. pyproject.toml reflex/model.py
The public rx.Model base remains available for table definitions and is exported with rx.session() and rx.asession(). Reflex marks this base as deprecated and directs new code toward the underlying SQLModel or SQLAlchemy APIs. Its methods remain compatibility helpers around the direct ORM functions. reflex/__init__.py reflex/model.py
References: pyproject.toml• L62-67 reflex/model.py• L17-27 reflex/model.py• L68-281 reflex/model.py• L283-527 reflex/model.py• L529-722 reflex/__init__.py• L179-225
Model definitions
Table models
A table model defines the shape of a durable record. An application marks a SQLModel class as a table and declares its fields with Python types. The common Reflex base supplies an optional integer id primary key when the model does not define another primary key. reflex/model.py
The model definition is both a Python data shape and part of the database schema. Applications use the model class to create records and build queries. Relationships are also part of the model view and can be included when a model is serialized for a state or event boundary. reflex/model.py reflex/model.py
References: reflex/model.py• L521-524 reflex/model.py• L534-547 reflex/model.py• L660-667
Model registry
The model registry is the shared catalog of model classes used by schema tools. It collects the metadata for registered models and combines metadata from SQLModel and SQLAlchemy models when an application uses both. Migration and table-creation work use this combined view rather than a single model class. reflex/model.py
The registry knows about models that the application loads. The built-in Model is registered by Reflex. SQLAlchemy declarative bases can also be detected when their module exposes the base under its qualified name; explicit registration is available when an application needs to control the set of bases. A model base that is not loaded or registered is not part of the metadata used for migration checks. reflex/model.py reflex/model.py
The registry caches the combined metadata after it builds it. This gives table creation and migration checks one stable schema view for the process. reflex/model.py
References: reflex/model.py• L199-320 reflex/model.py• L210-280 reflex/model.py• L637
Database configuration
Database URLs
The application configuration uses db_url for normal database access and async_db_url for asynchronous access. A URL names the database engine and its connection details, so the same model and migration view can work with SQLite or another SQL-compatible database supported by the installed driver. packages/…/config.py packages/…/config.py
DBConfig provides builders for common SQLite and PostgreSQL URL forms. It encodes user and password values when it builds a URL, while database URL settings are treated as sensitive configuration and are not logged as ordinary environment values. packages/…/config.py packages/…/config.py
References: packages/…/config.py• L39-145 packages/…/config.py• L148-169 packages/…/config.py• L215-217
Synchronous and asynchronous access
Applications can use a synchronous session for ordinary handlers or an asynchronous session for async work. The asynchronous URL should point to the same database as db_url when both are configured, because both paths operate on the application’s one durable schema. Reflex warns when the database portions of the two URLs differ. reflex/model.py reflex/model.py
The URL is the boundary between application configuration and connection management. A missing URL prevents the matching engine from being created, so database use must be explicit rather than inferred from the presence of a model.
References: reflex/model.py• L104-186 reflex/model.py• L639-676 packages/…/config.py• L215-217
Connection management
Engine management
An engine is the long-lived database access point for a URL. Reflex creates one synchronous or asynchronous engine per URL and reuses it for later sessions. The engine also applies connection-pool behavior such as checking a connection before use and limiting pool growth. reflex/model.py packages/…/environment.py
The configured pool timeout is converted to the seconds form expected by the database driver. This reuse keeps connection setup outside the record operation while sessions remain short-lived. SQLite receives the connection setting needed for use across the application’s database access paths. reflex/model.py
References: reflex/model.py• L75-135 reflex/model.py• L142-197 packages/…/environment.py• L606-622
Session management
A session is the unit through which application code reads and changes records. The sync and async session helpers bind a session to the matching engine, and application code uses the session as a context-managed resource so its database handle is closed after the operation. reflex/model.py reflex/model.py
A write becomes durable when the application commits the session. This keeps transaction choice with the handler that understands the business action. The database layer supplies access and mapping; it does not turn every state change into a database write.
References: reflex/model.py• L188-197 reflex/model.py• L639-676 reflex/model.py• L534-635
Database health
The database health check opens the configured engine and runs a small query to verify that the service can accept work. The application health endpoint runs this check only when db_url is configured and returns an unavailable HTTP response when a required service check fails. reflex/model.py reflex/app.py
This check reports reachability, not schema correctness or the success of a business transaction. Schema state is checked through the migration path described below.
References: reflex/model.py• L504-524 reflex/app.py• L1884-1920 reflex/…/prerequisites.py• L691-724
Schema lifecycle
Migration initialization
Migration initialization creates the project configuration that tracks schema revisions and creates an initial revision from the model metadata. The reflex db init command loads the application, evaluates pages without rendering them so that lazily imported models are known, creates the Alembic environment, then creates and applies the initial revision. reflex/reflex.py reflex/…/migrations.py
The generated env.py loads the application and takes the database URL from rxconfig.py; the URL in alembic.ini is not the source of database connection settings. Existing applications with the older stock environment are updated in place while the old file is kept as env.old, and existing revisions remain. reflex/…/env.py reflex/…/migrations.py
Initialization requires db_url. If migration configuration already exists, the command stops and directs the application owner to the change and apply commands instead. This protects an existing revision history from being replaced by a new initialization. reflex/…/prerequisites.py reflex/reflex.py
References: reflex/reflex.py• L1120-1185 reflex/…/migrations.py• L90-152 reflex/…/migrations.py• L171-203 reflex/…/env.py• L1-7 reflex/…/prerequisites.py• L840-864
Schema change flow
Schema changes move from model metadata to an Alembic revision script and then to the database. The Reflex database commands are thin wrappers over Alembic, while the generated environment supplies the application model metadata and database settings. Autogeneration compares the registered model metadata with the current database schema. Migration applies the resulting revisions to the configured database. reflex/model.py reflex/…/migrations.py reflex/…/env.py
Before an optional autogeneration step, the migration path applies pending revisions so that comparison starts from the current schema head. This keeps a new revision based on the latest applied state. reflex/model.py
When a new column has a default, migration generation carries that value into the database change so existing rows can receive a value. For a callable default such as a timestamp or UUID factory, the migration path evaluates the callable once to produce the value used for the existing rows. This keeps non-nullable column additions usable while preserving the model’s default behavior for later records. reflex/…/env.py
The main schema lifecycle has three stages:
- Change and load the table model definitions.
- Run
reflex db makemigrationsto create a revision script. - Inspect and apply the script with
reflex db migrate.
The same migration environment also supports the Alembic command line. The compatibility helpers on reflex.model remain available but are deprecated; new code should use the database commands or direct Alembic commands. reflex/model.py
This diagram shows how application model definitions become an applied database schema.
flowchart LR
Models[Loaded model definitions] --> Metadata[Registered metadata]
Metadata --> Compare[Compare with database schema]
Compare --> Revision[Migration revision]
Revision --> Apply[Apply migration]
Apply --> Schema[Current database schema]
References: reflex/model.py• L331-487 reflex/…/migrations.py• L1-7 reflex/…/migrations.py• L55-87 reflex/reflex.py• L1173-1233 reflex/…/env.py• L41-140
Schema checks
The migration tools can report whether the database is at the current revision and whether the loaded model metadata would produce new schema operations. The application checks for drift with Alembic without writing a migration script and tells the owner to generate or apply the needed change. reflex/…/prerequisites.py reflex/reflex.py
Autogeneration cannot represent every model change safely. A change that the migration tool cannot infer can leave startup or migration work blocked until the revision is corrected by hand. The revision history is therefore the record of applied schema changes, while model code is the desired current shape.
References: reflex/…/prerequisites.py• L867-888 reflex/model.py• L416-487 reflex/reflex.py• L1188-1233
Application persistence lifecycle
Record operation flow
Application code owns the record operation inside a state handler or another backend task. It opens a session, reads or changes model objects, commits a successful write, and then updates session state or emits an event when the client needs the result. This keeps the durable write and the client-facing update as related but separate actions.
The persistence path therefore has two outputs: the database stores the committed record, while the event system carries the new view of that record to the client. See Backend services for backend boundaries and Observability and telemetry for service health and operational signals.
This diagram shows the relationship between a backend action, durable data, and a client update.
sequenceDiagram
participant Client
participant Handler as Backend handler
participant Session as Database session
participant DB as Database
participant State as Session state
Client->>Handler: Send event
Handler->>Session: Read or change records
Session->>DB: Query or commit
DB-->>Session: Record result
Session-->>Handler: Return result
Handler->>State: Store client-facing values
State-->>Client: Send state update
References: reflex/model.py• L639-676 reflex/model.py• L521-524 reflex/app.py• L1923-2058
Model serialization
When a model crosses a state or event boundary, Reflex can convert its fields to a dictionary and include loaded relationships. This lets backend code use ORM objects while the client-facing state uses the normal serialized value shape. reflex/model.py reflex_base/serializers.py
Serialization does not make a model change durable. The session must still commit the transaction, and the handler must still place any needed result in state before the event processor sends a delta. For state storage and event delivery, see Backend services.
References: reflex/model.py• L496-502 reflex/state.py• L1880-1905 reflex/state.py• L1947-2024
Change checklist
When these files or sections are changed, remember to consider these:
- Changing a table model requires checking that the application loads it before migration metadata is built.
- Changing a model default requires checking generated migrations for both existing rows and records created after the migration.
- Changing
db_urlorasync_db_urlrequires checking that both access paths target the same durable schema and use compatible drivers. - Changing the model registry requires checking explicit registrations, automatic SQLAlchemy base discovery, mixed SQLModel and SQLAlchemy metadata, and all migration comparisons.
- Changing engine pool settings requires checking connection reuse, stale connection detection, and acquisition timeouts in each deployment mode.
- Changing model serialization requires checking relationship loading and the state or event payload shape that reaches the client.
- Changing migration setup or revision generation requires checking initialization, revision creation, schema application, and startup drift checks as one flow.
- Replacing
rx.Modelrequires checking callers that still rely on its compatibility methods and the deprecation path toward direct ORM APIs. - Changing optional database imports requires checking both runtime dependency errors and type-checking visibility for the database APIs.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Database dependencies are not installed | Model and session entry points fail at runtime instead of providing database access | Install the db extra before enabling database features |
db_url is missing | A synchronous engine or schema command cannot start | Configure a database URL before using models or migrations |
async_db_url points to a different database | Async reads and writes can use a schema that does not match synchronous work | Keep both URLs on the same database and heed the mismatch warning |
| A model base is not loaded or registered | Its table is absent from the metadata used by migration generation | Load each model base through the application or register it before creating or checking revisions |
| A model changes without a new migration | The model shape and database schema diverge | Generate and apply a revision after each schema change |
| A migration is applied to a database behind the expected revision | Migration generation can stop and application work can report schema drift | Run reflex db migrate before generating later revisions |
| A handler changes records without committing its session | The client may see a state update while the database keeps the old record | Commit the session as part of the successful write path |
| A required database health check fails | The health endpoint returns HTTP 503 | Check the database URL, driver, service reachability, and pool limits |
Key files
| File | Why to read it |
|---|---|
| reflex/model.py | Main database boundary. It connects configuration to engines, sessions, model metadata, serialization, and migration wrappers. |
| reflex/…/migrations.py | Coordinates the Alembic command wrappers, app loading, page evaluation, and legacy migration-environment updates. |
| reflex/…/env.py | Defines the generated migration environment and the model comparison rules used by Reflex and Alembic. |
| packages/…/config.py | Defines database URL configuration and the DBConfig helpers. |
| packages/…/environment.py | Defines migration and SQLAlchemy connection settings. |
| reflex/reflex.py | Defines the database commands for initialization, migration, status, and revision generation. |
| reflex/…/prerequisites.py | Checks whether database use is enabled, migrations exist, and model metadata matches the schema. |
| reflex/app.py | Connects database health to the application health endpoint. |
| reflex/__init__.py | Shows the database API exported through the rx namespace. |
| tests/…/test_model.py | Demonstrates the supported model, metadata, migration, and serialization contracts. |
| tests/…/test_db_config.py | Demonstrates database URL construction for supported configuration forms. |