Data persistence
Kener's persistence layer keeps the durable state behind monitoring, status pages, incidents, maintenances, alerts, access, and notifications. It gives web requests and background jobs one domain-based data service, while Redis provides a shared short-lived path for fast status reads.
Persistence model
Database boundary
The database boundary gives server code one shared data service. The service is built from the Knex database configuration and exposes domain operations through a common facade. Repositories keep callers away from table layout and return records or combined views that match product needs.
This boundary separates stored rows from application types. The shared database types describe both row shapes and views such as an incident with affected monitors or a maintenance event with monitor details. This keeps the meaning of data consistent across controllers, jobs, and repositories.
References: src/…/db.ts• L1-5 src/…/dbimpl.ts• L25-49 src/…/db.ts• L1-36 src/…/db.ts• L284-306
Repository domains
Repositories group persistence around product capabilities. The database facade exposes these groups so requests and background work can use domain operations without depending on schema details.
| Domain | Persistence responsibility |
|---|---|
| Monitoring | Time-stamped samples, latest values, history, counts, and aggregates |
| Monitors | Monitor identity, schedules, rules, and page visibility |
| Incidents and maintenances | Service events, planned windows, affected monitors, comments, and impact |
| Alerts and triggers | Alert state, rules, health checks, and notification links |
| Pages and site data | Public page definitions, monitor placement, site settings, and analytics settings |
| Access and delivery | Users, roles, permissions, API keys, subscribers, subscriptions, and templates |
| Images | Uploaded image data and metadata |
The relationships between these domains carry product meaning. Pages connect monitors through page links. Incidents and maintenance events connect operational context to monitors. Notification reads connect subscriber identity, delivery method, and event subscription so inactive parts do not receive messages. Site data uses key prefixes so a feature can own a group of settings without a separate storage path for every key.
References: src/…/index.ts• L1-17 src/…/site-data.ts• L7-34 src/…/monitoring.ts• L39-66 src/…/incidents.ts• L453-485 src/…/maintenances.ts• L469-542 src/…/pages.ts• L82-90 src/…/subscriptionSystem.ts• L242-345 src/…/users.ts• L23-83
Persistence flow
Request and job access
Web requests and background jobs share the same repositories but use separate database connection capacity when the database supports it. A request uses the web pool. A queue worker enters a worker context and uses the worker pool. This keeps monitoring checks and scheduled jobs from using all connections needed for page loads.
The pool choice stays below the domain layer. A repository reads the current database connection, so the same operation works from a request, scheduler, or queue worker.
The diagram shows how both work types reach the same repositories while keeping their connection pools apart.
flowchart LR
Request[Web request] --> WebPool[Web database pool]
Job[Queue job or scheduler] --> WorkerContext[Worker database context]
WorkerContext --> WorkerPool[Worker database pool]
WebPool --> Repositories[Domain repositories]
WorkerPool --> Repositories
Repositories --> Database[(Relational database)]
References: src/…/poolContext.ts• L4-26 src/…/base.ts• L35-56 src/…/q.ts• L32-52 src/…/dbimpl.ts• L390-408 src/…/dbimpl.ts• L868-874
Startup lifecycle
The server prepares the database before normal application work starts. It applies pending migrations, runs seeds, closes the setup connection, and then starts schedulers. A new or upgraded database is therefore ready before monitoring and maintenance jobs run.
The startup sequence is:
- Read the database URL and build the database configuration.
- Apply migrations up to the latest recorded version.
- Add seed records when the seed rules allow it.
- Start schedulers and serve requests.
References: scripts/main.ts• L69-107 src/…/startup.ts• L3-12 package.json• L43-50
Database configuration
Supported database backends
Kener uses DATABASE_URL to select SQLite, PostgreSQL, or MySQL. SQLite is the default and stores its file at ./database/kener.sqlite.db when no URL is set. Network databases use pooled connections for web and worker activity.
Network database settings use short connection acquire and create limits. This helps requests fail fast during an outage. The web and worker pool limits must fit within the connection limit for every running replica.
References: knexfile.ts• L1-15 knexfile.ts• L17-21 knexfile.ts• L30-56 knexfile.ts• L69-115
Schema history
Knex migrations describe changes to the persistent model. They build the monitoring, identity, event, page, maintenance, alert, subscription, and template areas. Later migrations add fields, links, indexes, and access rules as the product grows.
Monitoring history also has a retention path. On PostgreSQL, the monitoring-data migration makes cleanup easier for vacuum and statistics refresh. SQLite and MySQL use their own row-reclaim behavior.
Schema evolution has its own child page: Data model migrations. Use it when a change affects table shape, constraints, indexes, stored JSON, or compatibility between old and new application versions.
References: migrations/20250111153517_init.ts• L3-145 migrations/20260107120000_add_pages_tables.ts• L3-48 migrations/20260109120000_add_maintenances_tables.ts• L3-67 migrations/20260124120000_add_monitor_alerts_config_tables.ts• L3-53 migrations/20260330120000_add_rbac_tables.ts• L3-51 migrations/20260613120000_add_confirmation_threshold_and_raw_status.ts• L3-14 migrations/20260831120000_monitoring_data_autovacuum.ts• L3-27
Seed data
Default records
Seed data gives a fresh installation a usable starting state. It creates site settings, a home page, and two example monitors. The home page links the example monitors when they exist, which gives a new installation an initial dashboard.
The seed runner adds site settings only when a key is missing. It adds pages and monitors only when their tables are empty. Normal seed runs therefore do not replace operator data.
References: src/…/seedSiteData.ts• L1-4 src/…/seedPagesData.ts• L1-10 src/…/seedMonitorData.ts• L1-58 seeds/site_data.ts• L4-21 seeds/pages.ts• L4-53 seeds/monitors.ts• L4-30
Default settings
The site seed also supplies safe fallback values for settings that are not yet stored. Layout, maintenance, and notification views use saved site data when present and use the seed value when a key is absent. This lets a new setting reach existing installations without rewriting settings that operators already changed.
References: src/…/layoutController.ts• L76-80 src/…/layoutController.ts• L144-183 src/…/maintenanceController.ts• L104-110 src/…/get.ts• L15-30 src/…/seedSiteData.ts• L1-197
Cache-facing data access
Redis cache
Redis provides a shared cache for values that support fast status reads. Processes that use the same REDIS_URL can share these values. The cache stores JSON under a Kener namespace and gives entries a time limit. A read can use a supplied fetch function to rebuild a missing value from the database.
Redis is not the durable record. Missing, expired, or unreadable values are cache misses, so callers must keep a valid miss path. Redis access requires REDIS_URL.
References: src/…/cache.ts• L1-41 src/…/EGM.md• L3-28 src/…/redisConnector.ts• L7-19 src/…/redisConnector.ts• L21-54
Monitor status cache
Kener caches the latest monitoring sample and the last heartbeat signal by monitor tag. Status reads use the cached sample when present and fall back to monitoring history. Heartbeat reads follow the same pattern. Grouped status counts use the monitor set and time range as part of their cache identity.
Monitor deletion clears the per-monitor cache entries. The latest-value repository path returns one newest sample per requested monitor and skips monitors with no sample. This keeps status reads bounded when a page contains many monitors.
Latest status data remains cached for one day. Heartbeat data remains cached for 45 days. These limits speed up reads without replacing long-term history in the database.
References: src/…/setGet.ts• L3-27 src/…/EGM.md• L5-28 src/…/heartbeatCall.ts• L1-28 src/…/monitorsController.ts• L295-305 src/…/monitorsController.ts• L332-365 src/…/monitorsController.ts• L443-451 src/…/monitoring.ts• L149-169 src/…/monitoring.test.ts• L14-69
Operational data relationships
Monitoring history
Monitoring data is the time series behind status pages and uptime views. Each sample belongs to a monitor and a time. It carries status, latency, type, and optional error detail. The repository supports recent, range, grouped, and aggregate reads so the same durable history can serve live status, charts, uptime summaries, and alert checks.
The monitor record supplies the identity and rules that give each sample context. Raw observed status and special sample types remain available so confirmation logic can separate scheduled observations from manual values and event overlays.
References: src/…/monitoring.ts• L14-36 src/…/monitoring.ts• L41-66 src/…/monitoring.ts• L341-439 src/…/monitoring.ts• L666-710 src/…/db.ts• L5-36 src/…/monitors.ts• L19-46
Incidents and maintenances
Incidents and maintenances add human and planned context to monitor history. An incident links a service event to affected monitors and comments. A maintenance defines planned windows and creates events that move through scheduled, ready, ongoing, and completed states.
Repository reads combine event records with monitor details for status pages and event views. Global events can appear without monitor links. Linked hidden monitors do not appear in public monitor lists or public event results, even when a hidden tag is requested. Authorized detail reads can still include hidden monitor links.
The operational flow connects durable event records to public status views.
flowchart LR
Incident[Incident record] --> IncidentLinks[Incident monitor links]
Maintenance[Maintenance plan] --> Events[Maintenance events]
Events --> MaintenanceLinks[Maintenance monitor links]
IncidentLinks --> PublicViews[Public status and event views]
MaintenanceLinks --> PublicViews
Comments[Active incident comments] --> PublicViews
The repository tests protect this visibility rule for both incidents and maintenance events. They also cover global records with no visible monitor and records whose linked monitor no longer exists.
References: src/…/incidents.ts• L453-524 src/…/incidents.ts• L841-902 src/…/maintenances.ts• L214-345 src/…/maintenances.ts• L469-677 src/…/maintenances.test.ts• L95-159 src/…/incidents.test.ts• L143-220
Change checklist
When these files or sections are changed, remember to consider these:
- A new stored setting must align the site seed, site-data reads and writes, and every typed or parsed view that consumes it.
- A new monitor field must align the migration, database types, repository writes, seed records, and any cache or API view that exposes it.
- A new parent-child link must align repository deletion paths with foreign-key behavior so removed monitors do not leave stale links.
- A change to monitoring sample meaning must align sample writers, status and alert readers, aggregates, confirmation logic, and latest-value cache fallback.
- A change to background database load must preserve the worker context and the combined web and worker pool budget.
- A change to public incident or maintenance views must preserve the rule that hidden monitors do not appear in public results.
- A change to a cache key or time limit must align writers, readers, fallback fetchers, grouped status inputs, and monitor deletion cleanup.
- A schema change must also follow Data model migrations.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
DATABASE_URL uses an unsupported scheme | The process exits during database setup | Use SQLite, PostgreSQL, or MySQL URLs only |
| Web and worker pools exceed the database connection limit | Replicas can exhaust database connections | Budget both pool limits for every replica |
| A migration changes a field without matching repository or type changes | Reads or writes can fail or silently omit data | Treat migrations, repositories, and database types as one contract |
| Seed defaults change without a plan for existing rows | Existing installations keep old values while new installs get new values | Decide if the change is fallback-only or needs a data migration |
| Redis is unavailable and a status caller has no database fallback | Cache-backed status reads fail | Keep a database fallback for status paths |
| A monitor is removed without link and cache cleanup | Old event links or status values can remain visible | Use domain deletion paths and monitor cache cleanup |
| A public event query matches only through a hidden monitor | Private monitor data can appear in public views | Apply visibility and active-monitor filters before grouping results |
| Maintenance event state does not advance with time | Planned impact can remain missing or active at the wrong time | Keep scheduled, ready, ongoing, and completed transitions tied to time-range queries |
Key files
| File | Why to read it |
|---|---|
| src/…/db.ts | Entry point for the shared database service |
| src/…/dbimpl.ts | Map of persistence domains and the web/worker database boundary |
| src/…/base.ts | Common connection choice for requests and background work |
| src/…/monitoring.ts | Durable monitoring history and latest-value access |
| src/…/incidents.ts | Incident links, comments, public visibility, and monitor-facing event views |
| src/…/maintenances.ts | Planned windows, event states, monitor impact, and public visibility |
| src/…/incidents.test.ts | Contract for hidden-monitor filtering in incident views |
| src/…/maintenances.test.ts | Contract for hidden-monitor filtering in maintenance views |
| src/…/db.ts | Shared record shapes at the persistence boundary |
| knexfile.ts | Database backend selection and pool policy |
| scripts/main.ts | Startup order for migrations, seeds, and schedulers |
| seeds/site_data.ts | Site setting seed behavior and preservation of existing values |
| seeds/pages.ts | Initial page and monitor placement |
| src/…/seedMonitorData.ts | Initial example monitors and monitoring defaults |
| src/…/seedSiteData.ts | Default site settings and missing-setting fallbacks |
| src/…/cache.ts | General Redis cache and fallback contract |
| src/…/setGet.ts | Monitor status and heartbeat cache contract |
| migrations/20250111153517_init.ts | Initial persistent model |
| migrations/20260109120000_add_maintenances_tables.ts | Maintenance plan, event, and monitor-link model |
| migrations/20260831120000_monitoring_data_autovacuum.ts | PostgreSQL maintenance policy for retained monitoring history |