Introducing a new way to review your PRs.

Read the announcement

iv-org / invidious

Invidious is an alternative front-end to YouTube

View on GitHub

19 documents · Updated Oct 12, 2026

docs / application-bootstrap-and-routing

Application bootstrap and request routing

Invidious starts as a Crystal web service that turns one runtime configuration into a working web and API server. The bootstrap path prepares the database, outbound connection pools, logs, background work, shared request state, and route handlers before Kemal accepts traffic. The route layer then sends browser, API, media, image, and companion requests to the feature that owns each flow.

Startup lifecycle

The startup lifecycle moves from process inputs to shared services and then to the listening server. Configuration and database access must exist before jobs or request handlers can use them. The main stages are:

  1. Load and validate configuration.
  2. Open the PostgreSQL connection and create shared outbound connection pools.
  3. Set up logging and optional database table checks.
  4. Register and start enabled background jobs.
  5. Register request preprocessing, routes, error handlers, and server handlers.
  6. Bind Kemal to a TCP host and port or to a Unix socket.

The application also records build information and uses it in the service metadata. This gives downstream pages and operators a stable view of the running build without changing the request flow. References: src/invidious.cr#L60-L97, src/invidious.cr#L137-L193, src/invidious.cr#L199-L262

Runtime configuration

Runtime configuration defines how the service connects to its database, reaches upstream services, protects requests, and exposes its listener. The loader reads YAML from the configured file or from an environment value, then applies top-level environment overrides with the INVIDIOUS_ prefix. References: src/invidious/config.cr#L83-L187, src/invidious/config.cr#L223-L279

Configuration validation stops startup when a required security key or database address is missing. It also checks companion settings and Unix socket settings before the server begins. When the database is supplied as separate fields, the loader combines those fields into the database URL used by the application. References: src/invidious/config.cr#L281-L346

The main configuration controls major service capabilities rather than individual requests:

Configuration areaSystem effect
DatabaseSupplies persistent state for users, channels, videos, playlists, sessions, and related records.
ListenerSelects the TCP address and port or the Unix socket used by clients.
Upstream accessSets connection pool size, proxy use, address-family choice, saved cookies, and companion instances.
Security and privacySets the HMAC key, HTTPS behavior, content proxy limits, CAPTCHA, login, and API abuse controls.
Background workEnables feed, channel, statistics, popular-video, notification, cleanup, and instance refresh work.

Service initialization

The bootstrap creates shared resources so request handlers and background jobs use the same service context. It opens PostgreSQL once, creates pools for YouTube and image requests, and creates a companion pool when companion access is configured. The pools limit concurrent upstream work and can restore a client after an upstream connection fails. References: src/invidious.cr#L63-L97, src/invidious/yt_backend/connection_pool.cr#L5-L45, src/invidious/yt_backend/connection_pool.cr#L68-L104

Database checks are optional. When enabled, they compare the live database with the application’s expected tables and can create or adjust supported tables. Explicit migrations remain available through the command-line migration option, which records completed versions in a migration table and runs pending versions in order. References: src/invidious.cr#L131-L146, src/invidious/database/base.cr#L6-L26, src/invidious/database/migrator.cr#L1-L49

Background jobs extend the server beyond the request path. Bootstrap registers refresh, statistics, feed subscription, and popular-video jobs only when their settings enable them. It also registers notification, expiry cleanup, and instance refresh work as part of the normal service setup. The job runner starts each registered job in its own spawned routine, so feed refresh and maintenance work continue without blocking HTTP requests. References: src/invidious.cr#L184-L214, src/invidious/jobs.cr#L1-L39, src/invidious/jobs/base_job.cr#L1-L31

Request lifecycle

Every request first passes through shared request preparation before a route handler produces the response. This preparation creates request preferences from the user cookie or language header, adds security headers, records proxy-related host data, and loads a signed-in user when a valid session is present. It skips session work for media and proxy paths that do not need a browser session. References: src/invidious.cr#L220-L224, src/invidious/routes/before_all.cr#L14-L147

The registered HTTP handlers then apply cross-cutting rules around the route. API requests receive cross-origin access, authenticated API requests must pass token or session checks, selected video endpoints can be disabled by configuration, and normal pages cannot be framed outside the site. Compression and API error behavior also vary by route family. The child page HTTP middleware and static assets explains these shared request rules and asset delivery. References: src/invidious.cr#L236-L243, src/invidious/helpers/handlers.cr#L22-L165

This diagram shows the high-level path from a client request to a feature response.

flowchart LR
    A[Client request] --> B[Shared request preparation]
    B --> C[HTTP handlers]
    C --> D{Registered route}
    D --> E[Web feature handler]
    D --> F[API feature handler]
    D --> G[Media, image, or companion handler]
    E --> H[HTML or redirect response]
    F --> I[JSON or stream response]
    G --> J[Proxied or static response]

Route registration

The routing registry maps an HTTP method and path pattern to the feature handler that owns the request. Its registration macros enforce leading slashes and keep the route declaration separate from the handler logic. register_all enables the browser routes unless the process runs in API-only mode, then adds shared image, API, manifest, playback, and companion routes. References: src/invidious/routing.cr#L1-L21, src/invidious/routing.cr#L18-L50

The route families cover the main ways clients use Invidious:

FamilyPurpose
Web routesServe the home page, search, channels, watch pages, feeds, accounts, preferences, and playlists.
Embedded routesServe the focused player view for embedded video use.
API v1 routesProvide programmatic access to video data, captions, comments, transcripts, channels, feeds, search, playlists, and authenticated user data.
Playback and manifest routesResolve or proxy media manifests, video streams, live segments, and video byte ranges.
Image routesServe thumbnails, storyboards, and other image resources through the application.
Companion routesForward selected requests to configured Invidious companion services.

The child page Web and API route families describes the route groups and their feature boundaries in more detail. References: src/invidious/routing.cr#L56-L331, src/invidious/routes/api/manifest.cr#L1-L245, src/invidious/routes/video_playback.cr#L1-L314

API route handlers turn upstream video and channel data into stable JSON or media responses. Channel routes expose channel pages, video groups, community data, related channels, and search. Feed routes expose trending and optional popular content. Video routes expose video metadata and related playback data such as captions, storyboards, comments, clips, and transcripts. Authenticated routes add user-scoped preferences, history, subscriptions, playlists, tokens, and notification streams. References: src/invidious/routes/api/v1/channels.cr#L17-L186, src/invidious/routes/api/v1/channels.cr#L188-L545, src/invidious/routes/api/v1/feeds.cr#L1-L45, src/invidious/routes/api/v1/videos.cr#L7-L27, src/invidious/routes/api/v1/videos.cr#L29-L175, src/invidious/routes/api/v1/videos.cr#L182-L524, src/invidious/routes/api/v1/authenticated.cr#L14-L55, src/invidious/routes/api/v1/authenticated.cr#L57-L194, src/invidious/routes/api/v1/authenticated.cr#L196-L493

Playback routes form the media boundary between clients and upstream video hosts. Manifest routes return DASH or HLS descriptions and can rewrite media URLs for local proxy use. Video playback routes validate the upstream host, follow redirects, stream live or range-based media, and resolve fresh download URLs. These routes also honor configuration that disables downloads, DASH, or livestreams. References: src/invidious/routes/api/manifest.cr#L3-L49, src/invidious/routes/api/manifest.cr#L145-L244, src/invidious/routes/video_playback.cr#L4-L123, src/invidious/routes/video_playback.cr#L126-L215, src/invidious/routes/video_playback.cr#L257-L313

The watch route is the main browser video flow. It validates the video request, loads video data with the user’s preferences, prepares playback and caption choices, records watch activity when enabled, and renders the watch page. It can also redirect to a raw stream or hand download requests to the API and playback handlers. References: src/invidious/routes/watch.cr#L4-L197, src/invidious/routes/watch.cr#L208-L331

Route order matters when patterns overlap. Specific channel and playback paths are registered before catch-all paths, so a broad fallback does not take a request that belongs to a more specific feature. Unmatched requests use the 404 route, which can resolve short video or channel-style paths before redirecting to the home page. References: src/invidious/routing.cr#L116-L159, src/invidious/routes/errors.cr#L1-L51

Server binding

After the application prepares its handlers, Kemal starts the HTTP server with a bounded request-line size and the configured log handler. A Unix socket takes priority when configured; otherwise the service binds to the configured host and port. This allows the same application to run behind a local reverse proxy or as a directly reachable HTTP service. References: src/invidious.cr#L260-L283

Change checklist

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

  • Keep configuration validation aligned with the bootstrap resources that consume the value. A new required upstream, database, companion, or socket setting must fail before jobs and routes start.
  • Keep route registration and handler middleware scope aligned. A new API or media path can silently receive browser headers, compression, authentication, or error formatting intended for another family.
  • Keep route order aligned with catch-all patterns. A broad path registered before a specific path can redirect or proxy the request to the wrong feature.
  • Keep API-only registration aligned with every route that must remain available without browser pages.
  • Keep API response shapes and error status rules aligned with clients when channel, feed, video, or authenticated route groups change.
  • Keep manifest URL rewriting and playback host validation aligned. A change in one can break local DASH or HLS playback or weaken the proxy boundary.
  • Keep database integrity checks and migration definitions aligned with the records that startup expects to read.
  • Keep listener binding behavior aligned with deployment changes between TCP and Unix sockets.

Important failure modes

TriggerConsequenceGuard
Missing or empty HMAC keyThe service exits before it can serve requests that depend on signed sessions or subscriptions.Configuration validation requires hmac_key.
No usable database URLStartup exits before sessions, users, jobs, or feature routes can access persistent state.Configuration accepts either database_url or a complete db block and rejects neither.
Configured companion without a valid 16-character keyCompanion mode cannot start safely.Companion validation rejects a missing, placeholder, or wrong-size key.
Catch-all route placed before a specific routeA valid request can reach a redirect or fallback instead of its feature handler.Register specific routes before catch-all patterns.
Authentication handler applied to a non-authenticated API pathA public API request can fail with a 403 response.Scope authentication to /api/v1/auth/*.
Invalid playback host parameterThe media proxy can reject a valid stream request or become an open proxy if host checks are weakened.Playback accepts only approved YouTube media host forms.
Upstream manifest or playback URL is not rewritten consistentlyA local player can receive an unusable upstream URL or fail on CORS or expired media links.Keep manifest local rewriting and playback proxy routes aligned.
Popular, download, DASH, or livestream capability is disabledThe related API or media request returns a controlled 403 instead of serving content.Route handlers check the matching configuration switch before work begins.
Missing or invalid Unix socket directory or permissionsThe server cannot bind to its configured local endpoint.Configuration validates the socket path and octal permission range before binding.

Key files

FileWhy to read it
src/invidious.crShows the complete startup order from configuration and shared services through jobs, routes, handlers, and server binding.
src/invidious/config.crDefines the deployment-facing settings and the checks that decide whether startup may continue.
src/invidious/routing.crDefines the route registry and the boundary between web, API, media, image, and companion request families.
src/invidious/routes/before_all.crShows the request state and security context prepared before feature handlers run.
src/invidious/helpers/handlers.crShows which cross-cutting rules apply to API, authenticated, media, and embedded requests.
src/invidious/routes/watch.crIllustrates the browser video flow and its handoff to playback and API handlers.
src/invidious/routes/api/manifest.crIllustrates how DASH and HLS manifests become client-facing or locally proxied media descriptions.
src/invidious/routes/video_playback.crIllustrates media host checks, range streaming, live playback, and fresh URL resolution.
src/invidious/routes/api/v1/videos.crIllustrates the API boundary for video data, captions, comments, storyboards, and transcripts.
src/invidious/routes/api/v1/channels.crIllustrates how channel data and channel-owned content are exposed through API route families.
src/invidious/routes/api/v1/authenticated.crIllustrates user-scoped API operations and notification streaming.
src/invidious/database/base.crExplains the optional database integrity check used during startup.
src/invidious/database/migrator.crExplains the separate ordered migration flow.
src/invidious/jobs.crShows how configured background work is registered and started.