Persistence and schema migrations
Persistence gives Invidious one PostgreSQL-backed store for account state, sessions, subscriptions, cached content, and playlists. The database layer keeps these records aligned with the application data types, while schema setup and migrations let a new or upgraded instance reach a usable database shape.
Database role
Database abstraction
The database abstraction presents one shared PostgreSQL connection to the application. Domain modules use it to read and change records, and serializable data types turn database rows into the objects used by routes and background jobs. This keeps database access near the data domain instead of spreading SQL across every caller. The connection URL comes from the database configuration, and a connection failure stops startup with a clear error. (See src/invidious/database/base.cr#L1-L4 and src/invidious.cr#L60-L69.)
References: src/…/base.cr• L1-4 src/invidious.cr• L60-69 src/…/macros.cr• L1-27
Persistence domains
The database stores durable user state and selected service data. Each domain has a small access boundary for the operations that other parts of the application need.
| Domain | Purpose |
|---|---|
| Users | Account identity, preferences, watch history, subscriptions, and notifications |
| Sessions and nonces | Login sessions and short-lived one-time values |
| Channels and channel videos | Followed channel state and feed items |
| Playlists and playlist videos | User-created libraries and their ordered items |
| Videos | A replaceable cache of fetched video data |
| Annotations | An optional cache for video annotations |
These domains support the account, subscription, playlist, and watch flows described in Accounts, sessions, and preferences and container, database, and service deployment. (See src/invidious/database/users.cr#L3-L27, src/invidious/database/sessions.cr#L3-L18, src/invidious/database/playlists.cr#L6-L21, and src/invidious/database/videos.cr#L3-L14.)
References: src/…/users.cr• L3-27 src/…/sessions.cr• L3-18 src/…/playlists.cr• L6-21 src/…/videos.cr• L3-14 src/…/nonces.cr• L3-17
Application state
Account state
The user record is the main store for personal application state. It joins account identity with preferences, watched video IDs, subscribed channel IDs, notification IDs, and a flag that tells feed work that the subscription view needs refresh. Preferences and cached video information cross the database boundary as structured data stored in text form. (See src/invidious/user/user.cr#L3-L16 and src/invidious/database/users.cr#L42-L184.)
References: src/…/user.cr• L3-24 src/…/users.cr• L42-184
Session state
Session state links a session ID to an account and records when the session was issued. Nonces use a separate expiry record for one-time or short-lived checks. Cleanup jobs can remove expired values so temporary state does not become permanent account data. (See src/invidious/database/sessions.cr#L10-L72, src/invidious/database/nonces.cr#L10-L53, and src/invidious/jobs/clear_expired_items_job.cr#L1-L40.)
References: src/…/sessions.cr• L10-72 src/…/nonces.cr• L10-53 src/…/clear_expired_items_job.cr• L1-40
Content and library state
Channel and playlist records preserve the user-facing view of subscribed content and saved media. Channel videos are shared feed data. Playlist videos belong to one playlist and keep its order. Video records are different: they act as a replaceable cache for fetched video data rather than the source of account state. (See src/invidious/database/channels.cr#L6-L157, src/invidious/database/playlists.cr#L6-L262, and src/invidious/database/videos.cr#L6-L50.)
References: src/…/channels.cr• L6-157 src/…/playlists.cr• L6-262 src/…/videos.cr• L6-50 src/…/videos.cr• L7-36
Schema initialization
SQL schema
The SQL files under config/sql/ describe the baseline PostgreSQL shape for a fresh instance. They create the tables, keys, indexes, grants, and the playlist privacy type needed by the application. The table definitions mirror the serializable application records, so column names and order form part of the database contract.
The baseline has these important relationships and data choices:
usershas a unique account email and a case-insensitive email index.session_idsuses the session ID as its primary key.playlistsuses theprivacyenum, andplaylist_videosrefers to its parent playlist.channelsandchannel_videosuse channel and video IDs to support feed lookup.videosis an unlogged table because its contents can be fetched again.annotationsexists for an optional cache and is checked only when annotation caching is enabled.
The container database starts by loading these SQL definitions in dependency order. The same files are also the reference shape used by the application’s table check. (See docker/init-invidious-db.sh• L1-12, config/…/playlists.sql• L1-29, and config/…/playlist_videos.sql• L1-19.)
References: docker/init-invidious-db.sh• L1-12 config/…/users.sql• L1-29 config/…/session_ids.sql• L1-23 config/…/channels.sql• L1-25 config/…/channel_videos.sql• L1-30 config/…/videos.sql• L1-23 config/…/nonces.sql• L1-22 config/…/annotations.sql• L1-12 config/…/playlists.sql• L1-29 config/…/playlist_videos.sql• L1-19
Startup integrity checks
The optional check_tables setting lets normal startup create missing tables and add or remove columns so the live database matches the application records. It is disabled by default in the example configuration, while the development container enables it. This check is a repair aid for simple shape drift; it is not a substitute for a planned data migration. (See src/invidious/database/base.cr#L6-L26, src/invidious/database/base.cr#L44-L123, and config/config.example.yml• L41-48.)
The check covers the core tables and checks annotations only when annotation caching is active. The playlist privacy type is part of the schema, but the current enum check does not change it. (See src/invidious/database/base.cr#L10-L25 and src/invidious/database/base.cr#L32-L41.)
References: src/…/base.cr• L6-26 src/…/base.cr• L32-41 src/…/base.cr• L44-123 src/invidious.cr• L139-146 config/config.example.yml• L41-48 docker-compose.yml• L25-37
Migration execution
Versioned migrations
Versioned migrations move an existing database from one known shape to the next. Each migration has one version, runs its change inside a transaction, and records that version only after the change succeeds. The migrator creates its tracking table, skips recorded versions, and runs pending versions in numeric order. This makes an upgrade repeatable without applying the same step twice. (See src/invidious/database/migration.cr#L1-L38 and src/invidious/database/migrator.cr#L1-L49.)
The current migration set builds the core tables, adds the playlist structures, and changes the video cache to an unlogged table. The SQL files remain the baseline definition for new databases; the versioned migrations describe the path for databases that already have earlier state. (See src/invidious/database/migrations/0001_create_channels_table.cr#L1-L30 and src/invidious/database/migrations/0010_make_videos_unlogged.cr#L1-L11.)
References: src/…/migration.cr• L1-38 src/…/migrator.cr• L1-49 src/…/0001_create_channels_table.cr• L1-30 src/…/0008_create_playlists_table.cr• L1-50 src/…/0010_make_videos_unlogged.cr• L1-11
Migration flow
Migration work is an explicit command rather than an automatic part of every normal start. The process connects to PostgreSQL, reads the migration ledger, applies pending changes in order, and exits when the requested work is complete.
This diagram shows the path from an operator request to a recorded schema version.
flowchart LR
A[Start with migration command] --> B[Connect to PostgreSQL]
B --> C[Read migration ledger]
C --> D[Sort pending versions]
D --> E[Run one migration in a transaction]
E --> F[Record completed version]
F --> G{Pending versions remain?}
G -->|Yes| E
G -->|No| H[Exit]
Older direct psql scripts remain under config/migrate-scripts/. They show historical changes such as new feed fields, session-table creation, and data backfills. Treat them as explicit upgrade material for the schema states they name, not as the baseline for a new database. (See src/invidious.cr#L99-L137, config/…/migrate-db-3646395.sh• L1-8, and config/…/migrate-db-6e51189.sh• L1-7.)
References: src/invidious.cr• L63-69 src/invidious.cr• L99-137 src/…/migration.cr• L19-29 config/…/migrate-db-3646395.sh• L1-8 config/…/migrate-db-6e51189.sh• L1-7
Change checklist
When these files or sections are changed, remember to consider these:
- A change to a serializable record must stay aligned with its SQL table, its database access module, and any migration that upgrades existing rows.
- A new migration must have a new version and must preserve the order and transaction contract used by the migration ledger.
- A change to playlist ownership or deletion must keep the parent playlist and its ordered
playlist_videosrows consistent. - A change to cached video data must account for both the database JSON shape and
Video::SCHEMA_VERSION, because old cache entries can outlive a release. - A change to optional annotations must keep the SQL table,
cache_annotations, and startup integrity check in agreement. - A fresh database path and an upgrade path must produce the same supported schema, even though one uses
config/sql/and the other uses migrations.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| PostgreSQL cannot accept the configured connection | Invidious exits before it serves requests | Check the database URL and PostgreSQL service before startup |
| A migration statement fails | Its transaction does not record the version, so later runs still see it as pending | Fix the schema or data issue before retrying the same version |
Required tables or columns are missing while check_tables is false | Database-backed routes and jobs fail when they query the missing shape | Run the versioned migration path or enable the check during controlled setup |
| The integrity check finds an unexpected column or order | It can drop columns with dependent objects while reshaping the table | Back up the database and use planned migrations for non-trivial changes |
| The unlogged video cache is lost | Video metadata must be fetched again, but durable account state remains separate | Treat videos as rebuildable cache data |
Key files
| File | Why to read it |
|---|---|
src/invidious/database/base.cr | Defines the shared database boundary and optional schema integrity checks |
src/invidious/database/migrator.cr | Shows how pending migration versions are found and ordered |
src/invidious/database/migration.cr | Shows the transaction and migration-ledger contract |
src/invidious/database/users.cr | Shows how account state reaches the database |
src/invidious/database/playlists.cr | Shows the relationship between playlists and ordered playlist items |
src/invidious/database/channels.cr | Shows channel and feed persistence used by subscription work |
src/invidious/database/videos.cr | Shows the replaceable video cache boundary |
src/invidious.cr | Shows database connection, explicit migration startup, and integrity-check timing |
| docker/init-invidious-db.sh | Shows fresh database initialization order |
config/sql/ table definitions | Defines the baseline PostgreSQL schema for supported deployment paths |
src/invidious/database/migrations/ | Defines the ordered path from older schema versions to the current migration set |