Skip to main content

Architecture Overview

This document provides a high-level overview of Cinephage's architecture, explaining how the major components work together.

System Architecture

Cinephage follows a modern web application architecture with clear separation of concerns:

┌─────────────────────────────────────────────────────────────┐
│ User Interface │
│ (SvelteKit + Svelte 5) │
└───────────────────────┬─────────────────────────────────────┘
│ HTTP/WebSocket

┌─────────────────────────────────────────────────────────────┐
│ API Layer │
│ (SvelteKit Routes + Request Handlers) │
└───────────────────────┬─────────────────────────────────────┘

┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Services │ │ Database │ │ External │
│ (Business │ │ (SQLite) │ │ Services │
│ Logic) │ │ │ │ │
└──────────────┘ └──────────────┘ └──────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ Background Services (Workers) │
│ (Download Monitoring, Library Scanning, Searching) │
└─────────────────────────────────────────────────────────────┘

Core Components

1. Web Interface

Technology: SvelteKit + Svelte 5

The user interface is a modern, reactive web application:

  • Server-Side Rendering (SSR) - Fast initial page loads
  • Client-Side Hydration - Interactive after load
  • Real-time Updates - WebSocket connections for live data
  • Responsive Design - Works on desktop, tablet, and mobile

Key UI Modules:

  • Dashboard - Overview and statistics
  • Library - Movie and TV management
  • Discover - TMDB browsing and search
  • Settings - Configuration interface
  • Activity - Download queue and history

2. API Layer

Technology: SvelteKit Routes

RESTful API endpoints handle all data operations:

/api/library/movies      - Movie CRUD operations
/api/search - Multi-indexer search
/api/download/* - Download management
/api/queue/* - Queue operations
/api/settings/* - Configuration

Features:

  • Request validation with Zod schemas
  • Authentication via Better Auth
  • API key support for external access
  • Rate limiting for protection

3. Services Layer

Business Logic

Services contain the core application logic:

ServiceResponsibility
LibraryServiceMedia management, file organization
SearchServiceMulti-indexer search orchestration
DownloadServiceDownload client integration
MonitoringServiceAutomated content monitoring
SubtitleServiceSubtitle search and management
QualityServiceScoring and format evaluation

Design Pattern:

  • Singleton services with lazy initialization
  • Clear interfaces for testability
  • Error handling with typed errors

4. Database

Technology: SQLite 3

Single-file embedded database:

Advantages:

  • No separate database server required
  • Easy backups (simple file copy)
  • Zero configuration
  • Excellent performance for single-user workloads

Schema Organization:

  • 60+ tables organized by feature
  • Foreign key relationships
  • Indexes for query performance
  • Schema versioning for migrations

Major Table Groups:

  • Authentication (Better Auth tables)
  • Library (movies, series, episodes)
  • Downloads (queue, history, clients)
  • Indexers (definitions, status)
  • Quality (profiles, formats, scoring)
  • Subtitles (providers, languages, files)
  • Live TV (portals, channels, EPG)

5. External Integrations

Cinephage integrates with numerous external services:

Metadata:

  • TMDB - Movie and TV metadata
  • TVDB - Additional TV data
  • IMDB - External ID linking

Download Clients:

  • Torrent: qBittorrent, Transmission, Deluge, rTorrent, aria2
  • Usenet: SABnzbd, NZBGet, NZB-Mount

Indexers:

  • Torrent trackers (via YAML definitions)
  • Usenet indexers (Newznab/Torznab)
  • Streaming providers

Subtitles:

  • 14 subtitle providers
  • OpenSubtitles, Addic7ed, SubDL, etc.

Media Servers:

  • Jellyfin notifications
  • Emby notifications

6. Background Services

Technology: Node.js with custom worker system

Long-running background processes:

Service Manager:

  • Registers all background services
  • Manages startup/shutdown
  • Handles service health monitoring

Key Services:

ServicePurposeSchedule
LibrarySchedulerPeriodic library scansConfigurable
DownloadMonitorQueue monitoring and importReal-time
MonitoringSchedulerAutomated searchesConfigurable
ExternalIdServiceTMDB ID cachingPeriodic
SubtitleSchedulerSubtitle searchingConfigurable
EpgSchedulerEPG data updatesConfigurable
CaptchaSolverCloudflare bypassOn-demand

7. Worker System

Concurrent Task Processing

Workers handle background operations with concurrency limits:

Worker Types:

  • ImportWorker - File import operations
  • SearchWorker - Indexer searches
  • SubtitleSearchWorker - Subtitle downloads
  • StreamWorker - HLS streaming
  • PortalScanWorker - Stalker portal scanning
  • ChannelSyncWorker - Channel synchronization

Concurrency Control:

environment:
- WORKER_MAX_STREAMS=10
- WORKER_MAX_IMPORTS=5
- WORKER_MAX_SCANS=2

Data Flow

Adding a Movie

User clicks "Add to Library"

API receives request

Validate input with Zod

Insert into movies table

If monitored: Trigger search

SearchWorker queries indexers

Score releases

Grab best release

Send to download client

DownloadMonitor waits for completion

ImportWorker imports file

Organize file according to naming settings

Send notifications

Library Scanning

Scheduler triggers scan

Scan directory for video files

For each file:
- Extract metadata (ffprobe)
- Match to TMDB
- Insert/update database

Mark unmatched files

Update library statistics

Search and Download

Monitoring task or manual search

Query all enabled indexers

Aggregate results

Remove duplicates

Score each release:
- Base score (resolution)
- Source bonus (BluRay, WEB-DL)
- Codec bonus (x265, AV1)
- Custom format scores

Select highest scoring

Send to download client

Add to download queue

Authentication System

Technology: Better Auth

Modern authentication with multiple methods:

Features:

  • Session-based authentication
  • API key support
  • Role-based access control
  • CSRF protection
  • Secure password hashing

Components:

  • User table - Account storage
  • Session table - Active sessions
  • API key table - External access
  • Rate limiting - Abuse prevention

Configuration Management

Environment Variables

Server-level configuration via environment:

  • Server binding (HOST, PORT)
  • URLs (ORIGIN, BETTER_AUTH_URL)
  • System (PUID, PGID, TZ)
  • Workers (WORKERMAX*)
  • Advanced (timeouts, limits)

Database Settings

User-configurable via UI:

  • Quality profiles
  • Indexer configurations
  • Download client settings
  • Language profiles
  • All stored in database

YAML Definitions

Custom indexer definitions:

  • Stored in database
  • Editable via UI
  • Hot-reloadable

Scalability Considerations

Single-User Design

Cinephage is optimized for personal use:

  • SQLite handles single-user workloads excellently
  • No need for complex database clustering
  • Simple deployment model

Resource Limits

Worker limits prevent resource exhaustion:

  • Concurrent operations capped
  • Memory usage controlled
  • CPU-intensive tasks queued

Caching Strategy

Multiple cache layers:

  • In-memory caching for hot data
  • Database caching for metadata
  • File system caching for streams
  • External ID caching to reduce TMDB calls

Security Architecture

Defense in Depth

Multiple security layers:

  1. Authentication - Verify user identity
  2. Authorization - Check permissions
  3. Input Validation - Zod schemas
  4. CSRF Protection - Token validation
  5. Rate Limiting - Prevent abuse
  6. API Keys - Scoped access

Secrets Management

Sensitive data handling:

  • API keys stored encrypted
  • Environment variables for server secrets
  • Database for user credentials (hashed)
  • Never log sensitive data

Network Security

  • HTTPS recommended for production
  • Origin validation for CSRF
  • Trusted origins whitelist
  • Secure cookie settings

Deployment Architecture

Containerized deployment:

  • Single container with all components
  • Volume mounts for persistence
  • Environment variables for configuration
  • Health checks for monitoring

Process Model

Inside the container:

Main Process (Node.js)
├── SvelteKit Server (HTTP requests)
├── Service Manager (background services)
└── Worker Pool (concurrent tasks)

Monitoring and Observability

Logging

Structured logging throughout:

  • Request/response logging
  • Service activity logging
  • Error logging with stack traces
  • Configurable log levels

Health Checks

Endpoints for monitoring:

  • /api/health - Basic health
  • /api/ready - Ready for traffic
  • Service status reporting

Metrics

Key metrics tracked:

  • Library size
  • Download queue depth
  • Search performance
  • Error rates

Future Architecture Considerations

Potential Enhancements

  • Read Replicas - For very large libraries
  • Distributed Workers - Separate worker processes
  • Plugin System - Third-party extensions
  • GraphQL API - Alternative to REST

Current Limitations

  • Single-node design
  • SQLite for database
  • In-process workers
  • File-system based storage

Technology Stack Summary

LayerTechnology
FrontendSvelteKit, Svelte 5, TypeScript
BackendNode.js, SvelteKit
DatabaseSQLite 3
AuthenticationBetter Auth
ValidationZod
TestingVitest
ContainerDocker

See Also