🏗️ System Architecture Overview
LibreFolio is designed as a modern web application with a clear separation between the backend API and the frontend user interface.
🗺️ High-Level Diagram
The architecture can be visualized as three main components:
graph TD
subgraph User's Browser
Frontend[SvelteKit Frontend]
end
subgraph Server
Backend[FastAPI Backend]
Database[(SQLite Database)]
end
subgraph External Services
direction TB
BrokerAPIs[Broker APIs / CSVs]
PricingAPIs[Pricing APIs]
FXAPIs[FX Rate APIs]
WebSearch[Web Search Engine<br/>ddgs metasearch]
end
subgraph Plugins
direction TB
B_Plugins[BRIM Plugins]
A_Plugins[Asset Plugins]
F_Plugins[FX Plugins]
R_Plugins[Risk Analytics]
T_Plugins[Tool Plugins]
end
Frontend -- HTTP API Calls --> Backend
Backend -- SQLAlchemy ORM --> Database
Backend -- Uses --> Plugins
B_Plugins -- Parses --> BrokerAPIs
A_Plugins -- Fetches --> PricingAPIs
F_Plugins -- Fetches --> FXAPIs
A_Plugins -. Last-resort URL resolve .-> WebSearch
🧱 Components
-
🖥️ Frontend (SvelteKit): A single-page application (SPA) that runs in the user's browser. It communicates with the backend via a RESTful API to fetch and display data.
-
⚙️ Backend (FastAPI): A Python-based API server that handles all business logic, including:
- 🔐 User authentication and authorization.
- 🗃️ Database operations (CRUD).
- 📥 Data import from brokers (BRIM).
- 📈 Fetching asset prices and FX rates from external sources.
-
🗄️ Database (SQLite): A single-file database that stores all user data, including transactions, assets, user settings, and cached data.
-
🔌 Provider Plugins: A system of pluggable modules that abstract the interaction with external data sources. This makes it easy to add support for new brokers, pricing APIs, or FX rate providers without modifying the core application logic. The same registry mechanism also discovers plugins that call no external service: the risk analytics and the Tools.
🔑 Key Subsystems
For detailed architectural documentation of specific subsystems, see:
- 🗃️ Database Schema: Data models and relationships.
- 👤 Users & Brokers: Authentication and multi-user access control.
- 🔐 Access Control (RBAC): Role-based broker access (Owner/Editor/Viewer).
- ⚙️ Settings System: User preferences and global settings.
- 📥 BRIM Architecture: Broker Report Import Manager.
- 📈 Asset Pricing: Asset data fetching and metadata.
- 🔎 See also: Asset Search & Link-Finder for the three-layer interactive search (on-site →
ddgsweb link-finder →resolve_url); best-effort, last-resort, and never used on automated price fetches.
- 🔎 See also: Asset Search & Link-Finder for the three-layer interactive search (on-site →
- 💱 FX Architecture: Foreign Exchange system.
- 🔀 See also: FX Configuration & Routing for multi-provider setup.
- 🧮 Financial Math Layer:
backend/app/services/financial_math/, the one home of financial calculations — package map, layer rules, guards. - 📉 Risk Engine: Bulk risk analytics over a portfolio, a broker, an asset or a selection of assets — plugin catalogue, eligibility verdicts, and simulation and optimization in spawned worker pools.
- 🧰 Tool Plugins: Atomic, typed calculations behind a versioned catalogue (first tool: the PAC allocator), each computed in a spawned process the executor owns.
- 🧭 Onboarding Guides: Welcome setup, intro tour and contextual guides, with versioned per-user progress kept by the backend.
- 📁 File Upload System: Custom uploads stored with a JSON metadata sidecar, and the default avatars seeded at startup (
backend/app/services/files/static_uploads.py); image previews go through an in-memory cache (PreviewCacheinbackend/app/api/v1/uploads.py: 50 MB by default,PREVIEW_CACHE_MAX_MB, entries expire after 1 hour). Broker report files belong to BRIM. Where all these files live: Data Directory on Disk.
🔄 Request Flow Example: Displaying Portfolio
- User logs in and navigates to the dashboard.
- The Frontend makes an API request to
GET /api/v1/portfolio. - The Backend receives the request, authenticates the user, and queries the Database for the user's transactions.
- For each asset, the backend may need to fetch the latest price. It calls the appropriate Asset Provider Plugin (e.g., Yahoo Finance).
- If currency conversion is needed, the backend calls the FX Provider Plugin to get the latest exchange rate.
- The backend processes the data, calculates portfolio metrics, and returns a JSON response to the frontend.
- The Frontend receives the JSON data and renders the portfolio dashboard.
🚀 Server Startup
backend/app/main.py sets up the test mode and the logging, then builds the app: FastAPI(..., lifespan=lifespan), install_middleware(app), install_validation_error_handler(app) (backend/app/api/validation_errors.py: a 422 that never sends the request's input back, see Validation Errors Without the Input), install_response_validation_handler(app) (backend/app/api/response_validation.py: a response that breaks its model is logged without its content, see Request Logs), install_server_error_handler(app) (backend/app/api/server_errors.py: a 5xx answers with the request id and the type of its failure, and its cause reaches the log once, see Error Answers), the API v1 router under API_V1_PREFIX, and install_static_site(app) (backend/app/services/platform/static_site.py). The latter registers the documentation (/mkdocs), /, the /_app chunks when the frontend build has them and, last, the SPA catch-all GET /{path:path}: a GET route added after it would never be reached. The catch-all serves the file of frontend/build/ that the path names, once its .. segments are resolved (/assets/../favicon.png is served); a path that would leave the build (confined_path()), or whose resolved location inside the build has a name starting with . (_hidden_in_build(): the build's markers .build-debug, .build-version and .tool-contract-inputs, the emoji font's .cache_manifest.json), gets the SPA fallback instead, 200.html, else index.html (tests: ./dev.py test utils static-route-confinement). The /_app mount and /mkdocs/{path} refuse a path with a name starting with . too (/mkdocs/{path} through _hidden_below(), which _hidden_in_build() uses; the mount checks the names of the path Starlette hands it; same tests), each with its own 404: the mount answers as for a missing file, once Starlette has resolved the .. segments (/_app/immutable/../.DS_Store names the build's _app/.DS_Store), and /mkdocs/{path} answers the documentation's 404, as for a path leaving mkdocs_src/site/. backend.app.main:app stays uvicorn's entry point.
Browser caching. The static site gives each kind of file its own Cache-Control (static_site.py; tests: ./dev.py test services static-cache-policy):
- Revalidated,
no-cache, must-revalidate(REVALIDATE_HTML): every HTML document, of the web app's build (index.html, the SPA fallback200.html,offline.html) or of/mkdocs, and every file of/_appoutside/_app/immutable/(todayenv.jsandversion.json), whose name does not change with its content. The browser checks with the server before it reuses its copy, so it picks up a new build at its next load. - Kept for a year,
public, max-age=31536000, immutable(IMMUTABLE_CACHE_CONTROL): the chunks under/_app/immutable/, whose names change with their content. - No
Cache-Control: any other file of the build or of the documentation (icons, fonts, the manifest, the documentation's style sheets, scripts and images); the browser may keep it by heuristic freshness, from itsLast-Modified. - Private,
private, max-age=3600, outside the static site: the image previews of uploads (GET /api/v1/uploads/file/{id}?img_preview=WxH), which the browser may reuse for an hour and a shared cache must not store; see Uploaded Files: Common and Personal.
In the static site, only the /_app mount (ImmutableStaticFiles, a StaticFiles) answers 304 Not Modified when the browser's copy is current, and its 304 keeps the file's Cache-Control. The other files come from a route's FileResponse, which answers no 304, so an HTML document is sent whole each time. All these responses also carry the security headers, and install_static_site() first calls register_served_types(), so that every file served goes out with its right MIME type, which nosniff requires.
The lifespan (lifespan() in backend/app/services/platform/app_lifespan.py) prepares everything before the first request by running STARTUP_STEPS, in this order:
shutdown-watchdog: installs the shutdown watchdog (install_shutdown_watchdog(), inshutdown_budget.py), only where uvicorn serves from the main thread with its own signal handlers and the budget is not 0. The first SIGTERM or SIGINT arms it: when the budget runs out, it logsShutdown budget exhausted: ending the process, ends the child processes and exits with status 1, whatever still holds the server.announce: logsStarting LibreFoliowith the version, the database path and the test mode.configuration-checks: runs the configuration checks (log_configuration_audit(), in a thread): a configured secret that cannot be used stops the server, every other finding is logged.signal-plugins: checks the signal-plugin runtime (validate_signal_runtime()) and discovers the signal plugins.tool-catalog: loads the Tool catalogue (ToolPluginRegistry.get_snapshot(), in a thread).pending-restore: applies a restore confirmed for the next start (apply_pending_restore(), inbackend/app/services/platform/instance_backup/apply.py, in a thread), before any step reads the data: it swaps the folders with the checked copy (The Swap), leaves the restore waiting with its reason, or undoes a swap a start that was killed left half done.restore-state: asks whether the state of the restore can be read (probe_restore_state(), inbackend/app/services/platform/restore_guard.py, in a thread; lot B-33). When it cannot, a restore may have stopped half way: the step logs one error and never stops the start, but from here on the process serves no data (restore_interrupted()): the eight later steps that repair, write or warm up the data are skipped (post-migration-fixes,lone-transfer-legs,admin-bootstrap,stored-currencies,provider-prewarm,market-holidays,brim-parse-poolandscheduler, each with aStartup step skippedline), and every API route but a few answers423 instance_restore_interrupted(A Restore Stopped Half Way).data-directories: creates the data directories (ensure_data_dirs()).serving-lock: takes the shared serving lock on the data directory (hold_serving_lock(), in a thread), held until the process exits: from here on no restore swaps or undoes the data under this process.risk-scenarios: loads the risk scenario catalogue (initialize_risk_scenario_catalog()).default-avatars: seeds the default avatars (seed_default_avatars()).database: creates or migrates the database (ensure_database_exists()indatabase_bootstrap.py); a failedalembic upgrade headstops the server (sys.exit(1)).post-migration-fixes: runs the post-migration fixes in a thread; they never stop the startup.lone-transfer-legs: turns the lone giving legs ofTRANSFERs that older broker deletions left intoADJUSTMENTs taking the units out, without a value (decision 47, N78-1;convert_lone_giving_legs_at_startup()). With something to convert, it first runsPRAGMA quick_checkand leaves a damaged database as it is; it never stops the startup.global-settings: seeds the missing global settings (_initialize_global_settings()).admin-bootstrap: applies the variables of the initial administrator (startup_admin_bootstrap(), inbackend/app/services/accounts/bootstrap_admin_service.py): on an instance without accounts it creates the administrator, inactive, with its setup link; a generated link goes out by email in a background task, so the step never waits for the mail server.restore-commit: completes a restore this start applied (finish_pending_restore(), in a thread): every session ends, the backup's one-time links are revoked, and the restore is recorded as committed. A step before it that raises rolls the restore back at the next start; one after it no longer does (decision N57).restore-owner: after a restore from the app on a managed instance, gives the owner the account the administrator chose (assign_restored_owner(), inbackend/app/services/platform/instance_backup/owner.py), then asks whether anything still keeps the owner from it (probe_owner_assignment(), inrestore_guard.py; lot H5-3). It never raises. While the owner has no account (pending, or the code of a refusal) the process serves no data, as for an unreadable restore state, and the steps after it that warm up the data or run jobs are skipped (A Restore Stopped Half Way).backup-leftovers: removes what runs of the backup killed outright left in clear (sweep_backup_leftovers(), inbackend/app/services/platform/instance_backup/leftovers.py, in a thread; decision N66): the checks a stopped server left running and the decrypted archives in the copies, the folders of adev.py backup inspectolder than an hour, the work files of the backups that died with their process, and the backups past their hour (What a Run Killed Outright Leaves). It never touches what a running process holds, nor anything through a link. It never raises, since afterrestore-commita step that raises would stop every start: a part that fails is logged as an error, and the others still run.plugin-secrets-check: runs the plugin secrets check (log_plugin_secrets_check()): stored system secrets of the plugin settings that the instance key cannot read are one error in the log, with their count; it never stops the startup.stored-currencies: once the repairs are done and the restore is settled, starts the audit of the stored currency codes in the background, in a worker thread, and goes on at once (log_stored_currency_audit()inbackend/app/services/platform/stored_currencies.py): its scans take about 0.6 s at a million price rows. Read-only, on a connection withtrusted_schemaoff, it logs one warning when the database holds currency codes that are not ISO 4217 codes (admin guide, Command-Line Tools, «Currency Codes That Are Not ISO Codes»), names or numbers an earlier version saved as written. It reports on the data, so it starts afterrestore-commit(decision N57); it never stops the startup.provider-prewarm: starts the provider cache pre-warm in the background (_prewarm_provider_caches()).market-holidays: starts building the market-holiday table in the background, in its own process (start_market_holiday_prewarm()).brim-parse-pool: with the warm-up on (brim_prewarm_enabled()inbackend/app/config/brim.py, fromLIBREFOLIO_BRIM_PREWARM: off by default, on in test mode), starts the BRIM parse pool's forkserver in the background, in a worker thread (prewarm()inbackend/app/services/brim/brim_parse_pool.py), preloaded with the BRIM module and its plugins: the first parse after a start then forks a ready worker. Off, the step does nothing; a value it cannot use is logged as a warning and starts nothing either. It never stops the startup: a failed warm-up is logged, and the first parse starts the forkserver, as with the warm-up off.scheduler: starts the scheduler task (scheduler_loop()).idle-monitor: only withLIBREFOLIO_IDLE_SUSPEND_MODE=fly, registers the busy checkstoolsandbackupon the activity record and starts the idle monitor task (start_idle_monitor(), insleep_wake/idle_monitor.py), which asks Fly.io to suspend the machine when nothing is busy and no user's request has come forLIBREFOLIO_IDLE_SUSPEND_MINUTES.
On shutdown, the lifespan's finally runs FINALLY_STEPS: tool-executor stops the Tool executor, also when serving ended with an error. Then, only after a normal end, it logs Shutting down LibreFolio and runs SHUTDOWN_STEPS: idle-monitor (sets the idle monitor's stop event and awaits its task, when it runs), scheduler (sets the scheduler's stop event and awaits its task), providers (the asset, FX and BRIM providers), brim-parse-pool, quant-pools, market-holidays (ends any holiday build at once), caches (closes the TTL caches) and child-processes (terminates the child processes still alive, such as parse, risk and Tool workers, so that none outlives the server; only where the watchdog is installed).
🧩 Steps and Middleware: the Contract
backend/app/services/platform/lifecycle.py runs the steps; it imports nothing of the app.
- Adding a step takes one line at its place in
STARTUP_STEPS,SHUTDOWN_STEPSorFINALLY_STEPS:Step("my-step", lambda: my_function()).runreturnsNoneor an awaitable (a coroutine, aTask), which the runner awaits; a blocking startup call goes throughasyncio.to_thread(), aspost-migration-fixesdoes. The lambda findsmy_functioninapp_lifespanwhen the step runs, so a test replaces it withmonkeypatch.setattr(app_lifespan, "my_function", ...). - Startup (
run_startup_steps()): each step runs to its end, in order. An exception stops the startup, and no shutdown step runs. - Shutdown order is declared, not derived:
SHUTDOWN_STEPSis not the reverse ofSTARTUP_STEPS, and a step that must also run after a serving error belongs inFINALLY_STEPS. - Shutdown (
run_shutdown_steps(steps, deadline)): a step that raises is logged as an error (Shutdown step failed) and the next step runs anyway.deadlineis an instant ontime.monotonic(): the lifespan'sfinallygets it once fromshutdown_deadline()(backend/app/services/platform/shutdown_budget.py) and gives it to bothFINALLY_STEPSandSHUTDOWN_STEPS. After a SIGTERM or a SIGINT in a process where the shutdown watchdog is installed, it is the watchdog's deadline (the signal plus the budget) lessCLEANUP_MARGIN_SECONDS(0.75 s), kept for the last step. Without a signal, or without a watchdog, it is the current time plus the budget less uvicorn's drain share (shutdown_drain_seconds(): 3/8 of the budget, at least 1 s), worked out at each call. The budget isLIBREFOLIO_SHUTDOWN_TIMEOUT_SECONDS, 8 s by default: 0 means no limit, and thenshutdown_deadline()returnsNoneand no step is ever cut; a value that cannot be used is logged once and the 8 s apply (see Stopping the Server in Configuration). Under a deadline, each step gets the time left, never less thanMIN_STEP_SECONDS(0.2 s), so the short steps still run after an overrun; a step past its time is cut (the coroutine or task it awaits is cancelled) and logged as a warning (Shutdown step cut by the deadline). The runner returns oneStepOutcomeper step. blocking=Truemarks a synchronous call that may block (brim-parse-pool): under a deadlinerun()is called in a worker thread, so the deadline holds; the thread cannot be stopped, and the sequence moves on without it. Whatrun()returns is awaited as for any step. Without a deadline, and at startup, the flag changes nothing. A synchronous step without it runs on the event loop, where a deadline cannot cut it.current_step()names the step in progress,startup:<name>orshutdown:<name>, and isNonebetween steps and while the app serves: a watchdog thread can read it to name a step that hangs.- Adding a middleware takes one
MiddlewareEntry(name, cls, options)at its place inMIDDLEWARE_STACK(backend/app/services/platform/middleware.py). The first entry is the outermost, the first to see a request and the last to see its response:activity(ActivityMiddleware,backend/app/services/platform/sleep_wake/activity.py: the user's presence and the requests in flight; outermost, so that it sees every request first and counts the compression of a response as in flight, while the probes are not counted, and the scheduled wake-up,/system/wake-sync(WAKE_PATHS), is counted as in flight but never as the user's presence, as are the hosting panel's routes under/backup/panel/and/panel/(PANEL_PATH_PREFIXES, lot H-61)), thenrequest_id(RequestIdMiddleware,backend/app/services/platform/request_id.py: an id for every request, in every log line of the request and in theX-Request-Idof its response, the500of an exception nobody handled included; see Request Logs), thensecurity_headers(SecurityHeadersMiddleware,backend/app/services/platform/security_headers.py:X-Content-Type-Options: nosniffandReferrer-Policyon every response, plus frame protection and, on the web app's pages, a report-only Content-Security-Policy whenLIBREFOLIO_FRAME_PROTECTIONandLIBREFOLIO_CSP_REPORT_ONLYare on, as in the managed profile, each unless the route set its own; see Response Headers), thengzip, thencors.activityalso adds to every/api/answer but a probe's the response headers that a feature registers on the activity record (register_response_header()), unless the route set that header itself: today the scheduler'sX-LibreFolio-Price-Refresh, present while prices catch up (see Catch-up Progress).install_middleware(app)adds the entries from the last, because Starlette puts each middleware outside the ones added before it.
🐳 Docker Image
The production image is runtime-only: the frontend (SvelteKit) and the documentation (MkDocs) are built on the host and copied in, so the image carries neither Node.js nor the documentation toolchain. ./dev.py docker build prepares those builds first (see Developer Workflow → Docker Integration); the release workflow builds and tags the published images (see Release & CI/CD Pipeline).
graph LR
subgraph "Host (build)"
FE["frontend/src"]
MK["mkdocs_src/"]
BE["backend/"]
PF["Pipfile*"]
end
subgraph "Docker Image (runtime)"
FB["frontend/build/"]
MS["mkdocs_src/site/"]
BC["backend/"]
PP["Python packages"]
end
FE -- "npm run build" --> FB
MK -- "mkdocs build" --> MS
BE -- "copy" --> BC
PF -- "pipenv requirements" --> PP
- Build stages (
Dockerfile):docs-fullanddocs-lighttake the pre-builtmkdocs_src/site/, anddocs-lightdeletes the gallery images before they reach the final image (theDOCS_VARIANTbuild argument picks one).frontendrunsscripts/docker/check_frontend_build.sh, which refuses a debug, coverage-instrumented or sourcemappedfrontend/build/.pybuilderinstallsrequirements.txtwith the compiler toolchain, and only the installed packages reach the finalpython:3.13-slimstage, which addsgosu,sqlite3,tzdataandtzdata-legacy.zoneinforeads the system's time zone database (the PyPItzdatapackage is not a dependency), and Debian keeps old names such asAsia/CalcuttaandUS/Easternintzdata-legacy: without it, a scheduler time zone saved under such a name would fall back to UTC. - Contents:
backend/,scripts/,dev.py, the checked frontend build, the documentation site,VERSION(the git version frozen at build time, since the image has no.git/) and.env.examplecopied as/app/.env..dockerignorekeeps out, among others,backend/data/,backend/test_scripts/, the documentation sources and the developer journal.dev.pyregisters a command group only when the directories it needs exist, so in the imagetest,i18n,mkdocs translateandmkdocs translate-validatestay listed but answer not available in this installation and exit with2(see Test Mode in the Container). - Startup:
entrypoint.shstarts as root, creates the data directory and hands it to the numericLIBREFOLIO_UID:LIBREFOLIO_GID(theUID/GIDbuild arguments, default1000:1000), thenexec gosureplaces itself with the command. The default command isuvicorn backend.app.main:app --host 0.0.0.0 --port 6040: one worker, PID 1 of the container, always on port6040, the only port the imageEXPOSEs.PORTonly changes the host side of the Compose port mapping: both Compose files setPORT=6040inenvironment:, so thedev.pycommands run in the container read the port the server listens on. The image'sHEALTHCHECKprobes/api/v1/system/healthon6040too../dev.py docker execruns its command throughgosuwith the same numeric ids, so what it creates in the data directory belongs to the server's user. - Database: the container runs the same startup sequence as any server, so pending migrations and the post-migration fixes are applied before the first request: a container never needs a manual
db upgrade.
🧰 Tech Stack
⚙️ Backend
- 🚀 FastAPI: A high-performance web framework for building APIs with Python (LibreFolio requires Python 3.13), based on standard Python type hints. It generates the OpenAPI schema and can serve interactive documentation (Swagger UI and ReDoc); LibreFolio serves them on debug and test instances only (API Reference).
- 🗃️ SQLAlchemy: The SQL toolkit and Object-Relational Mapper (ORM) used for all database interactions. LibreFolio uses SQLAlchemy's asyncio support for non-blocking database queries.
- 📋 Pydantic: A data validation and settings management library. Used extensively for defining data schemas, validating API requests, and managing application settings.
- 🔄 Alembic: A lightweight database migration tool for SQLAlchemy. See Database Migrations.
- 🗄️ SQLite: The default database engine. Simple, serverless, and perfect for a self-hosted application. Configured in WAL (Write-Ahead Logging) mode for better concurrency.
🎨 Frontend
- 🖥️ SvelteKit: A web application framework for building fast, modern user interfaces with server-side rendering, routing, and great developer experience.
- 📝 TypeScript: A statically typed superset of JavaScript that adds type safety to the frontend codebase.
- 🎨 TailwindCSS: A utility-first CSS framework for rapidly building custom designs.
- ⚡ Vite: The build tool and development server. Provides extremely fast Hot Module Replacement (HMR).
🧪 Testing
- 🐍 Pytest: The framework used for writing and running backend tests.
- 🎭 Playwright: A framework for end-to-end testing of the web application.
- 📊 Coverage.py: A tool for measuring code coverage of Python programs.