Introducing a new way to review your PRs.

Read the announcement

rommapp / romm

A beautiful, powerful, self-hosted ROM manager and player.

View on GitHub

22 documents · Updated Nov 23, 2026

docs / backend-runtime-composition

Backend runtime composition

The backend runtime is the service boundary for RomM. It starts the API, connects the API to the database and Redis, serves request and realtime traffic, reports its operating state, and starts companion processes that react to library and sync-folder changes. This page is a child of Backend runtime and operations and links to Background jobs and scheduling, Notifications and audit, and Library scanning and filesystem where queue work, user-facing events, and library discovery need more detail.

Startup lifecycle

The startup lifecycle prepares shared services before the API accepts normal work. In the container runtime, a bootstrap wrapper prepares secrets and nginx settings, then a supervisor starts the API, RQ scheduler, RQ workers, filesystem watchers, and nginx as separate processes.

Startup phases

When the backend starts directly, it checks the configured library layout, applies database migrations, runs startup tasks, and then starts the development Uvicorn server. The startup task phase removes stale scan and scheduler state, repairs outdated metadata stores, submits restart-safe backfill jobs, and loads fixture indexes into Redis without blocking the API on the full repair work. See backend/main.py and backend/startup.py.

In the container, docker/…/docker-entrypoint.sh first loads secret values from *_FILE variables, supplies values used by nginx templates, renders the nginx configuration, and repairs the frontend resource link when the base path changes. It then runs docker/init_scripts/init, which starts internal Valkey when no external Redis host is set, applies migrations, runs startup tasks, and launches the supervised processes. The supervisor checks process IDs, restarts failed children, and stops them in reverse order on termination.

The container keeps web traffic separate from queue work and file events. Gunicorn runs the FastAPI application, RQ processes handle scheduled and queued work, watchers turn file changes into work, and nginx exposes the frontend and backend through one listener. Optional OpenTelemetry wrappers can instrument the API, startup, and watcher processes. See docker/…/docker-entrypoint.sh and docker/init_scripts/init.

The following diagram shows how container bootstrap leads to the supervised runtime processes.

flowchart TD
    B[Container bootstrap] --> S[Runtime supervisor]
    B --> N[Rendered nginx configuration]
    S --> V[Internal Valkey when no external Redis is configured]
    S --> M[Database migrations and startup tasks]
    M --> A[Gunicorn and FastAPI application]
    S --> C[RQ scheduler]
    S --> W[RQ workers]
    S --> F[Library watcher]
    S --> Y[Optional sync-folder watcher]
    N --> A
    N --> U[Frontend and client connections]

References: docker/…/docker-entrypoint.sh• L3-34 docker/…/docker-entrypoint.sh• L36-81 docker/…/init• L90-173 docker/…/init• L175-313 docker/…/init• L339-465

Startup work

Startup work is designed to make the next request safe and useful without doing a full library scan in the web process. It checks for a supported library layout, removes scheduler state left by an older scheduler, drops metadata stores written in an older shape, and fills known metadata and firmware indexes in Redis.

The repair jobs use fixed IDs and skip enqueue when an earlier run still exists. They cover missing save hashes, optional WebP cover conversion, and enabled versioned metadata stores. A database or Redis error is logged and does not prevent the process from moving on. This makes startup tolerant of optional cache trouble while leaving repair work visible for later admin action. See backend/startup.py.

References: backend/startup.py• L46-125 backend/startup.py• L127-165 backend/startup.py• L167-224

Application surface

The FastAPI application combines HTTP routes, middleware, pagination, and two Socket.IO ASGI applications. The HTTP API uses the /api prefix, while general realtime traffic uses /ws and netplay uses /netplay.

HTTP routes

The route groups expose the product areas through one API surface. They cover identity, users and devices, library records, saves and states, play sessions, sync, tasks, metadata-related settings, exports, streaming, notifications, recommendations, music, and system status. The application also publishes interactive API descriptions at /api/docs and /api/redoc.

Route modules own product behavior. backend/main.py is the composition point that gives each router the common /api boundary, so a route feature is part of the running service only after it is included there. The same composition point publishes streaming socket payload descriptions for clients that use the API schema.

References: backend/main.py• L118-139 backend/main.py• L206-245 backend/…/__init__.py• L103-119

Reverse proxy boundary

nginx is the edge process for the container. It serves the built frontend and static resources, forwards /api requests to Gunicorn, upgrades /ws and /netplay connections for realtime traffic, and keeps library and cache files available only through backend-controlled internal redirects.

The proxy also keeps the public port and Gunicorn upstream port aligned through generated settings. It passes the original request scheme and client headers to the backend, applies cache rules to frontend and library resources, and adds cross-origin isolation headers to emulator player paths that need them. See docker/nginx/templates/default.conf.template.

References: docker/…/default.conf.template• L5-15 docker/…/default.conf.template• L17-49 docker/…/default.conf.template• L51-77 docker/…/default.conf.template• L92-141

Realtime applications

Socket.IO provides event traffic that does not fit a request-and-response call. The main application carries activity, scan, sync, device, and admin log events. The netplay application carries room membership and WebRTC signaling for shared play.

Both socket applications use Redis as a shared manager. A worker or watcher can therefore publish an event even though it does not own the web process that holds client connections. The main socket application resolves authenticated users and places them in user rooms. It does not reject an unauthenticated connection, so the scan and sync channels remain available to their own handlers. The device namespace has its own token gate. See backend/…/socket_handler.py, backend/…/logs.py, and backend/…/activity.py.

References: backend/main.py• L13-17 backend/main.py• L242-245 backend/…/socket_handler.py• L24-40 backend/…/socket_handler.py• L60-71 backend/…/logs.py• L35-70 backend/…/devices.py• L100-133 backend/…/activity.py• L46-80 backend/…/sync.py• L18-33 backend/…/netplay.py• L107-116

Configuration model

Configuration has two layers with different jobs. Environment variables define deployment and infrastructure settings. The user YAML file defines library behavior and other server options that the application can expose and persist at runtime.

Environment settings

The backend reads environment values when the config package loads. These values select paths, the database and Redis connection details, auth and cookie behavior, task limits, watcher flags, log behavior, external service access, and development settings. They also control upload staging, patch and conversion work, emulator and streaming features, and proxy-aware outbound access.

The environment layer also selects optional conversion behavior. It supplies the time and concurrency bounds for patch and conversion work, so the web process and workers do not accept more resource-heavy work than the deployment can support.

The container bootstrap can load any supported setting from a file through a matching *_FILE variable before the backend reads it. A direct value and its file form are exclusive, and a missing file stops container startup. The environment layer also supports provider enablement and endpoint overrides for external services. For example, Playmatch and Hasheous can use a configured API base URL instead of their public service.

The auth secret is required by direct backend configuration. The container supervisor generates a random process-only value when it is absent, so deployments that need sessions to survive a restart must provide a stable secret. Database support is limited to MariaDB, MySQL, and PostgreSQL. Missing database credentials, an unsupported driver, or invalid database query JSON stops database setup instead of creating a partial connection. The same layer derives the Redis URL and database connection reuse policy used by the shared clients.

The environment layer also sets limits that must match downstream work. Upload, patch, conversion, scan, task, streaming, and device-install limits shape how much work the runtime accepts and how long it lets that work run. See backend/…/__init__.py and backend/…/config_manager.py.

References: backend/…/__init__.py• L26-108 backend/…/__init__.py• L137-184 backend/…/__init__.py• L194-231 backend/…/__init__.py• L275-369 backend/…/__init__.py• L402-464 docker/…/docker-entrypoint.sh• L3-34 docker/…/init• L398-403 backend/…/config_manager.py• L679-719

User configuration

The user configuration is a YAML document under the RomM base path. ConfigManager loads it as a single shared configuration model, combines it with defaults, validates its shape, and can write changes made through configuration endpoints. If the file is missing, the manager creates an empty file and uses defaults. If YAML is malformed, it keeps the error for display and continues with defaults so the service can start.

The YAML layer controls library exclusions, platform bindings, folder layouts, emulator options, scan priorities and media, export choices, conversion settings, and streaming settings. Conversion settings describe whether downloads and scan metadata use the conversion service, its cache limits, and platform format choices. A filesystem structure template defines where platform and game folders are found. The default and firmware layouts use one template each, while a platform can use one or more ROM layouts. All ROM layouts must agree on the platform-folder root so discovery remains consistent. Invalid shapes, retired folder keys, and layouts that would make discovery unclear stop configuration validation. See backend/…/config_manager.py.

Older folder-name settings are translated to the equivalent structure templates when possible. This keeps existing libraries usable while making the configured layout explicit. A library arranged in a layout that is no longer inferred must declare that layout before discovery can proceed.

Validation also keeps settings that affect later work within known bounds. Unknown scan media and artwork sources are ignored with warnings, while an invalid scan region mode falls back to the default. A legacy streaming container is accepted with a deprecation warning so the service can continue while the deployment moves to the current protocol. Conversion cache values and platform format mappings must also pass their type and range checks.

Configuration updates rewrite the supported YAML sections as one model. Streaming settings are preserved even though the normal update flow does not edit them. This prevents an unrelated settings change from deleting runtime streaming configuration.

References: backend/…/config_manager.py• L36-57 backend/…/config_manager.py• L423-437 backend/…/config_manager.py• L593-719 backend/…/config_manager.py• L738-931 backend/…/config_manager.py• L1004-1125 backend/…/config_manager.py• L1274-1335 backend/…/config_manager.py• L1381-1432 backend/…/config_manager.py• L1434-1531

Configuration exposure

The heartbeat and configuration endpoints connect runtime settings to the web client. The heartbeat reports effective capabilities and selected flags. Configuration update flows change the in-memory model and persist the supported YAML sections while preserving streaming data that is not edited by those flows. See backend/…/heartbeat.py and backend/…/config_manager.py.

References: backend/…/heartbeat.py• L61-142 backend/…/config_manager.py• L1434-1566

Persistence services

The backend uses the relational database for durable application state and Redis for fast shared state and process coordination. The two services support different lifetimes: database records survive restarts, while Redis holds queues, sessions, cache data, pub/sub messages, and short-lived runtime state.

Database access

SQLAlchemy is the common database boundary. A connection URL is built from environment settings, and the database handler layer creates shared sessions with connection liveness checks and a recycle policy for connections that sit idle. The ORM metadata describes durable RomM records such as users, platforms, ROMs, saves, devices, and sync sessions.

MariaDB, MySQL, and PostgreSQL are supported as runtime choices. Database helpers hide dialect differences for JSON values and capability checks, so product code can keep one query model while the supported engines provide their native behavior. Alembic owns schema migration and uses the same connection settings as the application. See backend/…/base_handler.py, backend/…/base.py, backend/…/database.py, and backend/…/env.py.

References: backend/…/base_handler.py• L8-20 backend/…/__init__.py• L1-33 backend/…/base.py• L75-83 backend/…/database.py• L10-43 backend/…/env.py• L18-29 backend/…/env.py• L90-116

Redis services

Redis is the shared coordination layer for processes that do not share memory. The runtime creates synchronous and asynchronous clients from one Redis URL, plus a binary asynchronous client for values that must remain bytes. General work uses high, default, and low priority queues. Long-running scans use a dedicated queue with one worker so library scans do not run at the same time. Streaming teardown and exit-save work use a separate queue because a slow streaming broker must not hold unrelated work. The same service stores web sessions and cached index data.

All runtime Redis clients use the same connection policy and disable the optional maintenance-notification probe. This keeps normal Redis and Valkey deployments compatible while preserving separate clients for decoded text, binary values, and queue work. A small lock API provides short-lived cross-process exclusion for work such as the log forwarder.

Startup cache loading is content-aware. It stores each fixture index with a file hash, so unchanged data does not need to be written again. Metadata stores can also be discarded when their recorded shape belongs to an older release. A Redis failure produces a warning instead of blocking migrations or the main startup path. See backend/…/redis_handler.py, backend/…/cache.py, and backend/startup.py.

References: backend/…/redis_handler.py• L19-66 backend/…/redis_handler.py• L81-160 backend/…/redis_handler.py• L163-196 backend/…/cache.py• L12-51 backend/startup.py• L98-124 backend/startup.py• L193-222

Session storage

Browser sessions are server-side Redis records referenced by a cookie. For HTTP requests, the middleware loads the record, refreshes its expiry on the response, tracks a user's session IDs, and can clear all sessions for a user. For WebSocket scopes, it exposes the session during connection handling. Socket.IO then keeps the server-resolved identity in its own socket session for realtime events. Revocation removes the Redis records and closes matching live socket sessions. This keeps shared HTTP session state available to every web process without relying on process-local memory.

References: backend/…/redis_session_middleware.py• L13-44 backend/…/redis_session_middleware.py• L46-114 backend/…/socket_handler.py• L91-109 backend/…/socket_handler.py• L157-207 backend/…/logs.py• L62-67 backend/…/activity.py• L46-72

Request middleware

Middleware applies shared policy around every HTTP request before a route handler runs. It covers cross-origin access, upload limits, CSRF checks, authentication, sessions, and request-scoped clients.

Request policy

The application allows configured cross-origin browser access with credentials. It rejects oversized save, state, and screenshot upload requests from their declared body length before multipart parsing can spool the body to disk. Memory-card uploads use a lower bound when their broker has a smaller limit. The endpoint layer remains responsible for any later file validation.

CSRF protection checks state-changing requests that use a session-authenticated cookie identity with a double-submit token. Basic and bearer authorization bypass this browser-cookie check only when the request is not already authenticated by a session. If the session middleware has resolved a user, that session identity remains in force and the CSRF check still applies. WebSocket paths and selected token or device exchange paths are exempt because they use different request contracts. See backend/main.py and backend/…/upload_size_middleware.py.

References: backend/main.py• L141-204 backend/…/upload_size_middleware.py• L8-64 backend/…/csrf_middleware.py• L19-96 backend/…/csrf_middleware.py• L148-200

Identity resolution

The authentication middleware presents one request identity to route handlers even when the caller uses different login forms. The hybrid backend checks a Redis session first, then basic credentials or bearer credentials, and finally the optional kiosk identity. It returns the user's effective scopes so route guards can enforce access.

The session middleware loads shared session data for both HTTP and WebSocket scopes. HTTP responses refresh or remove the Redis record through the response path. Socket connect handling stores the resolved user in the Socket.IO session, and event handlers use that stored identity instead of client payloads. See backend/main.py, backend/…/hybrid_auth.py, backend/…/redis_session_middleware.py, and backend/…/activity.py.

References: backend/main.py• L171-204 backend/…/hybrid_auth.py• L20-109 backend/…/redis_session_middleware.py• L46-114 backend/…/logs.py• L35-70 backend/…/activity.py• L46-72

Request context

The lifespan creates one asynchronous aiohttp session and one asynchronous httpx client per web process. Request middleware places those clients into context variables for the duration of each request because lifespan context is not automatically visible in the request-response cycle.

The clients honor deployment proxy settings and validate outbound URLs against the backend's SSRF protection. This gives external provider calls a common network boundary without making each route create its own client. See backend/…/context.py.

References: backend/main.py• L90-95 backend/main.py• L203-204 backend/…/context.py• L31-85

Realtime channels

Realtime channels connect backend events to browser and client state. Redis carries events between processes, while Socket.IO manages rooms and connected clients in the web process.

Activity channel

The activity channel reports which game a user is playing and clears that state when play stops or a socket disconnects. The server resolves the user when the socket connects and stores that identity in the socket session. Start and heartbeat events accept only game and device data from the client, while stop can use the device saved at start time. This prevents a client from publishing activity for another user.

References: backend/…/activity.py• L29-80 backend/…/activity.py• L83-140 backend/…/activity.py• L143-172

Device channel

The device channel connects a device-bound client to its owner’s install and presence state. It uses the /devices namespace inside the main Socket.IO application and admits only a live client token that is bound to that device and has the device-read scope.

After connection, the channel tracks the token's sockets for cross-process revocation and refreshes a short presence key. The device joins its own room, so queued or cancelled install requests can reach the device while status changes can reach the owner's open tabs. The online-device API reads the presence keys rather than treating an old socket record as proof that a device is still connected. Token expiry or socket disconnect removes the tracking state. See backend/…/devices.py and backend/…/install.py.

References: backend/…/devices.py• L24-39 backend/…/devices.py• L76-145 backend/…/devices.py• L148-189 backend/…/install.py• L145-158 backend/…/socket_handler.py• L17-21 backend/…/socket_handler.py• L210-215

Progress channels

Scan and sync work sends progress outside the request that started it. Scan events carry scan statistics and job state. Sync events carry session start, progress, completion, conflict, and error signals. Sync events target the affected user's room, so workers and watchers can notify the right client without owning its socket connection. Write-only Redis managers let these processes publish events without a live web-server object.

Scan requests use the authenticated socket session and require the task-running scope. The request payload rejects unknown options instead of silently turning a misspelled setting into a full-library scan. In normal operation, a live scan worker is required, and a short Redis lock prevents two web workers from queuing the same library scan at once. A normal library scan is not queued again while another library scan is running or waiting, while a scan for named ROMs can be placed ahead of queued library work because it resolves its work from the database. A stop request cancels waiting jobs and sets a shared stop signal for the running job. Progress counters are coalesced to limit Redis and socket traffic. If a worker dies or times out before it reports completion, the failure path emits a terminal error so clients do not show a dead scan forever. See backend/…/scan.py and backend/…/sync.py.

After a successful scan, the runtime refreshes derived library state, updates recommendation data, and can write platform metadata exports when the persisted scan settings enable them. These follow-up actions connect scan results to the files and views that other frontends consume. User-facing scan completion and failure notices also enter the notification and audit flow described in Notifications and audit. The queue and scheduling model that produces the work is described in Background jobs and scheduling. Library discovery rules are described in Library scanning and filesystem.

References: backend/…/scan.py• L147-181 backend/…/scan.py• L1144-1231 backend/…/scan.py• L1495-1585 backend/…/scan.py• L1588-1685 backend/…/sync.py• L1-117 backend/…/socket_handler.py• L60-80

Netplay channel

The netplay channel keeps a room in shared Redis state while players join, leave, and exchange WebRTC signaling data. A signed-in user must be allowed to see the selected ROM, while a password-protected room can admit a guest with the room password. Room membership, capacity, optional passwords, owner changes, and peer signals stay separate from the general activity and scan channel.

Each socket can relay WebRTC signals only to another socket in its current room. Data messages, snapshots, and input events are broadcast to the other players in that room. A room is removed when its last player leaves, and ownership moves to another player when the owner leaves. See backend/…/netplay.py and backend/…/socket_handler.py.

References: backend/…/netplay.py• L22-116 backend/…/netplay.py• L118-218 backend/…/netplay.py• L221-322 backend/…/socket_handler.py• L195-207

Health signals

Health signals describe what the running service can do rather than acting as a full infrastructure probe. The heartbeat is the main client-facing signal for version, setup state, enabled integrations, filesystem visibility, emulation flags, login and log-viewer flags, OIDC state, and selected task schedules.

Heartbeat response

GET /api/heartbeat returns effective runtime capabilities for the frontend. It checks the database for admin setup state and checks the filesystem for visible platforms. A separate metadata heartbeat can test one configured provider and returns a bad request for an unknown provider name.

The heartbeat does not claim that every dependency is healthy. In particular, this area has no single endpoint that proves database, Redis, queue, and external-provider readiness at once. Operators must read the response together with service logs and deployment checks. See backend/…/heartbeat.py.

References: backend/…/heartbeat.py• L61-181

Logging pipeline

Logging sends one human-readable stream to standard output and, outside tests, mirrors records to Redis for the admin log view. The same logger is used by the API, workers, scheduler, and watcher processes, so operational events can be viewed across the backend.

Structured log flow

The formatter adds time, level, and a semantic module label. It can keep or remove terminal color and redacts sensitive values before output. Uvicorn and Alembic are aligned with the RomM log level so startup and server messages use the same visible format.

The Redis handler stores a capped recent-log buffer and publishes each new record to a Redis channel. A single Redis-lock-held forwarder in the main application relays those messages to the admin Socket.IO room. It reads the recent buffer when the log view opens, then relays live messages through the shared socket manager. The lock prevents duplicate delivery when multiple web workers run. Redis errors do not raise into application work; standard output remains the source of truth. See backend/…/logger.py, backend/…/formatter.py, backend/…/log_stream_handler.py, and backend/…/logs.py.

References: backend/…/logger.py• L8-44 backend/…/formatter.py• L21-58 backend/…/formatter.py• L61-82 backend/…/formatter.py• L123-159 backend/…/log_stream_handler.py• L6-54 backend/…/logs.py• L69-170

Watcher processes

Watchers turn filesystem events into backend work without making the web process poll the library. They run as separate watchfiles command processes and use the database, Redis, task scheduler, and sockets to connect a file change to a user-visible result.

Library watcher

The library watcher accepts added and deleted file events under the library path and applies the same exclusion rules as scanning. It maps each event to a platform, ignores duplicate or already covered scans, and schedules a delayed quick scan for affected platforms. A platform-directory change schedules a full scan instead. If no metadata source is enabled, it skips the rescan.

The delay groups bursts of file changes and the pending-job coverage check prevents a file copy from creating work that an existing full or platform scan already covers. The scan itself runs in the queue worker and reports progress through the scan socket channel. See backend/watcher.py and Background jobs and scheduling.

References: backend/watcher.py• L57-124 backend/watcher.py• L127-185 backend/watcher.py• L187-235 backend/watcher.py• L238-259 docker/…/init• L315-325 docker/…/init• L451-454

Sync-folder watcher

The sync-folder watcher handles file-transfer devices that place save files in an incoming folder. It groups changes by device, creates a sync session, matches files to slot-bound saves, and compares the device and server versions.

Each file becomes one of four outcomes: no action when both sides match, upload when the device is newer, download when the server is newer, or conflict when neither side can safely win. The watcher moves conflict files to a conflict folder and sends sync lifecycle events to the device owner. Unknown devices, unsupported sync modes, disabled devices, unknown platforms, and unmatched saves are skipped rather than treated as valid uploads. See backend/sync_watcher.py.

References: backend/sync_watcher.py• L1-10 backend/sync_watcher.py• L46-107 backend/sync_watcher.py• L110-203 backend/sync_watcher.py• L206-342 docker/…/init• L327-337 docker/…/init• L424-435 docker/…/init• L457-459

Change checklist

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

  • When adding or moving an API router, update the FastAPI composition point and the shared /api boundary. Check that its auth and permission contract still matches the middleware chain.
  • When changing the container startup order, process names, PID files, or signal handling, keep migrations, startup tasks, watchdog restart behavior, and reverse-order shutdown aligned.
  • When changing a Redis key, queue, pub/sub channel, or Socket.IO room, update every producer, consumer, backfill reader, and cross-process publisher. This includes worker and watcher processes. Keep the dedicated scan and streaming queues aligned with their worker admission and timeout rules.
  • When changing Redis client options, apply the same compatibility settings to the queue client, decoded sync and async clients, and binary async client. Keep the RQ command-line connection class aligned with those options.
  • When adding a configuration value, decide whether it belongs in environment settings or persisted YAML. Then update validation, runtime exposure, and config-file rewrite behavior as one contract. If the value can use *_FILE, keep direct-value conflict and missing-file behavior clear.
  • When changing conversion settings, keep environment limits and feature flags separate from persisted conversion policy. Keep cache bounds and platform format mappings valid for both scan and download paths.
  • When changing upload, patch, conversion, or streaming limits, keep the environment setting, the early request bound, the downstream broker or subprocess limit, and the client-facing capability contract aligned.
  • When changing nginx routes, ports, forwarded headers, cache rules, or internal aliases, keep the bootstrap exports, Gunicorn bind, public listener, frontend paths, API paths, and websocket upgrade paths aligned.
  • When changing a filesystem structure template or exclusion rule, check startup layout validation, scanner discovery, and watcher path matching together. The platform-folder root must remain shared across default and platform-specific layouts.
  • When changing an external metadata endpoint, check the provider handler, its heartbeat result, and the outbound URL policy together. A deployment override must still point to the provider API rather than a web page.
  • When changing database models or supported drivers, keep the SQLAlchemy URL, Alembic metadata, migration rules, and dialect-specific query helpers aligned.
  • When changing scanner exclusions or library path rules, check both the scanner and watcher.py. Their different path levels must still map the same filesystem event to the same platform.
  • When changing scan socket payload fields, authorization, worker admission, request locking, queue priority, stop behavior, terminal events, or post-scan exports, keep the strict client contract, REST task scope, scan queue, Redis lock, RQ failure callback, shared stop flag, export settings, and frontend event contract aligned.
  • When changing device-token socket admission, presence TTLs, or install events, keep token revocation, device rooms, online-device results, device reports, and owner-room updates aligned.
  • When changing session or socket identity behavior, check HTTP requests, WebSocket connects, activity start, heartbeat, stop, disconnect cleanup, admin log access, user rooms, device-token sockets, and user-session cleanup together. Socket activity identity must continue to come from the server-resolved session rather than event payloads.
  • When changing sync event names or payloads, keep the worker and watcher emitters, user-room routing, and frontend progress contract aligned.
  • When changing netplay room admission or peer events, keep ROM visibility checks, password handling, room membership, owner changes, and peer-target checks aligned.
  • When changing CSRF authentication rules, keep session precedence, bearer and basic bypass behavior, token user binding, and the middleware order aligned. A bearer or basic header must not bypass CSRF when the request already has a resolved session user.
  • When changing startup repair jobs, keep their stable RQ IDs and low-priority placement compatible with restart deduplication.

Important failure modes

TriggerConsequenceGuard
A secret *_FILE variable points to a missing file, or both direct and file forms are setContainer bootstrap stops before nginx or the backend starts.Mount the secret file and use only one form of each setting.
ROMM_AUTH_SECRET_KEY is missing outside the containerThe backend fails during configuration load.Set a stable secret in deployment; the container supervisor only generates a temporary process value when none is supplied.
Database driver or credentials are invalidDatabase engine creation and migration cannot proceed.Use one of the supported drivers and valid database credentials before startup.
YAML configuration is malformedThe service starts with defaults and the user's settings do not apply.Read the parse error surfaced by configuration status and repair the YAML.
A filesystem structure template is invalid or puts a platform outside the default platform rootLibrary discovery fails or the service stops during configuration validation.Use a template with the required platform and game markers, and keep platform roots consistent.
Conversion settings have the wrong type, an invalid cache range, or an unsupported platform formatThe service stops during configuration validation and conversion policy is not loaded.Use the supported boolean, integer, and platform format values in the YAML conversion section.
A Hasheous endpoint override is invalid or unreachableHasheous-backed metadata lookup and its provider heartbeat fail.Use the full API base URL for the configured Hasheous deployment and verify it with the metadata heartbeat.
Redis is unavailable during cache initializationFixture indexes are not refreshed; queue, session, log, and socket features can also lose shared state.Treat standard output and service-level Redis checks as authoritative; restore Redis before relying on those features.
A Redis or Valkey deployment rejects an optional maintenance-notification probeRedis clients fail to connect before queues, cache, sessions, or sockets can use them.Keep the shared client options disabled for maintenance notifications across all Redis clients.
Gunicorn binds to a different port from the nginx upstreamThe public listener returns gateway errors even when the API process runs.Keep DEV_PORT shared by the supervisor and the generated nginx template.
A state-changing request uses session authentication without a valid CSRF cookie and matching headerThe request is rejected with HTTP 403.Use the CSRF cookie and header issued for the current session; do not rely on a bearer or basic header to bypass a resolved session check.
An asset or memory-card request exceeds its early upload limitThe request is rejected before the body is fully spooled, so the upload does not reach the endpoint or broker.Keep client upload sizes within the configured asset limit and the lower memory-card broker limit.
A socket has no server-resolved authenticated userActivity start and heartbeat events are ignored, and activity cannot be attributed to that socket.Complete socket authentication at connect time and keep the stored session identity available.
A scan socket caller lacks the task-running scopeThe scan is rejected and no scan job is created.Grant the required scope through the server-side auth flow; do not trust client-supplied identity data.
A scan payload contains an unknown option, no scan worker is listening, or another web worker holds the library-scan request lockThe request is rejected and no duplicate or ambiguous library scan is queued.Keep the client payload aligned with the strict scan schema, run a scan worker, and let the lock expire or the active enqueue finish.
A scan worker dies or reaches its timeout before a terminal eventClients can otherwise keep showing an active scan.Keep the RQ failure callback and terminal scan events aligned with the client contract.
A device socket uses a missing, expired, unbound, or insufficiently scoped client tokenThe device socket is refused or is closed after token expiry; the device is not reported online and cannot receive install events.Use a live device-bound token with devices.read, keep token revocation connected to socket tracking, and refresh device presence.
Device presence expires while the socket is still expected to be onlineThe online-device result omits the device until a socket refreshes presence.Keep the presence refresh interval below the presence TTL and treat the online result as a short-lived signal.
A netplay user cannot see the selected ROM and does not have the room passwordRoom creation or joining is rejected.Preserve the ROM visibility gate and compare the supplied room password with the server-held value.
A WebRTC signal targets a socket outside the sender's roomThe signal is ignored and peers cannot establish or update that connection.Send signals only to a peer in the same active room.
Log forwarder lock is lost or Redis pub/sub failsAdmin clients may miss live log entries, while normal logging continues to standard output.Keep the log viewer as an aid, not the only log sink; the forwarder retries through its lock loop.
A live login session is revoked while a request is completingThe session is not written back, its cookie is cleared, and matching socket connections are closed.Keep the Redis record, user-session set, response refresh rule, and socket-session close path aligned.
A file event does not match the configured library structure or exclusion rulesNo scan is scheduled, or an irrelevant file could trigger work if the two rule sets drift.Keep scanner and watcher path rules aligned and inspect watcher logs.
A sync file has no matching slot-bound saveThe file is skipped and is not added as a server save.Create or select the device-linked save through the sync flow before sending the file.

Key files

FileWhy to read it
backend/main.pyFastAPI composition point for lifespan, middleware, HTTP routers, sockets, pagination, upload bounds, and direct startup.
docker/…/docker-entrypoint.shContainer bootstrap for secret files, nginx environment values, template rendering, and resource links.
docker/init_scripts/initRuntime process map, migration and startup order, OpenTelemetry wrapping, watchdog restarts, and shutdown.
docker/nginx/templates/default.conf.templatePublic routing boundary for frontend assets, API requests, websocket upgrades, and internal file access.
backend/startup.pyStartup layout checks, cleanup, cache warm-up, metadata repair, and restart-safe backfill enqueue.
backend/…/__init__.pyEnvironment contract for paths, infrastructure, security, task, watcher, external-service, streaming, upload, conversion, and logging settings.
backend/…/config_manager.pyPersisted YAML model, filesystem structure templates, conversion policy, defaults, validation, migration, and runtime configuration updates.
backend/…/base_handler.pyShared SQLAlchemy engine, connection lifetime policy, and session boundary.
backend/…/env.pyDatabase migration connection and ORM metadata boundary.
backend/…/redis_handler.pyShared Redis clients, compatibility options, queue priorities, binary cache access, scan and streaming queues, and cross-process locks.
backend/…/cache.pyContent-aware Redis cache initialization.
backend/…/socket_handler.pySocket.IO applications, namespaces, cross-process Redis managers, and socket revocation tracking.
backend/…/scan.pyScan authorization, strict request validation, queue admission and locking, progress events, stop behavior, post-scan exports, and failure reporting.
backend/…/sync.pyUser-targeted sync lifecycle events emitted by workers and watchers.
backend/…/devices.pyDevice-token socket admission, presence tracking, install delivery, and online-device state.
backend/…/install.pyHTTP install request lifecycle and the online-device contract.
backend/…/logs.pySocket identity and room membership, admin log backfill, and single-forwarder design.
backend/…/heartbeat.pyClient-facing runtime and integration signals.
backend/…/activity.pyConnect-time socket identity, activity lifecycle events, and disconnect cleanup.
backend/…/netplay.pyNetplay room admission, membership, peer signaling, and shared-play events.
backend/…/redis_session_middleware.pyRedis-backed HTTP session refresh, WebSocket session loading, and user-wide session cleanup.
backend/…/csrf_middleware.pySession-aware CSRF policy and token issuance for HTTP requests.
backend/watcher.pyLibrary event filtering, scan coverage checks, and delayed rescan scheduling.
backend/sync_watcher.pyFile-transfer save intake, comparison outcomes, and sync notifications.