You are viewing archived documentation for v0.105. Go to latest →

Otavi Architecture

A distributed bird sound identification system built on the BirdNET deep learning model.

Overview

Otavi decouples audio capture, processing, and visualization into independently deployable components that communicate over a message broker. This enables community-contributed satellites (microphone nodes), shared inference infrastructure, and multiple UI clients — all with multi-tenant isolation from day one.

About the name. Otavi is oto- (ear) + avi- (bird): an ear for birds. The classifier it runs is Cornell's BirdNET.

flowchart TD
    subgraph satellites["Satellites"]
        Pi["Raspberry Pi
capture, YAMNet filter,
optional BirdNET, outbox"] Phone["Android phone
native engine, same pipeline"] end People["People
web browser"] Proxy["Reverse proxy (Traefik)
TLS for the app, broker and docs names"] satellites -->|"MQTT over WSS: audio, hits, heartbeats
HTTPS with the device key: settings, species"| Proxy People -->|HTTPS| Proxy subgraph hub["Hub (Docker Compose)"] web["web
nginx: the app, /api proxied"] docs["docs
this site"] broker["broker
Mosquitto, dynamic security"] api["api
Fastify: REST, WebSocket"] dispatcher["dispatcher
ingester, detection watcher,
alerts, monitors, image worker"] worker["worker × N
BirdNET, Perch v2"] database[("database
PostgreSQL")] queue[("queue
Redis, BullMQ")] objects[("objects
MinIO (Silo): audio,
photos, models, APKs")] backup["backup
nightly copy"] end Proxy --> web & docs & broker web --> api broker <-->|"satellite messages,
configuration"| dispatcher api -->|configuration pushes| broker api <-->|events| queue dispatcher -->|inference jobs| queue queue --> worker api & dispatcher & worker --> database api & dispatcher & worker --> objects backup -.-> database & objects & broker Outside["Outside services
eBird, iNaturalist, Wikimedia, Open-Meteo,
Nominatim, mail, alert channels"] api & dispatcher -.-> Outside classDef satellite stroke-width:2px classDef person stroke-width:2px classDef transport stroke-width:2px classDef app stroke-width:2px classDef work stroke-width:2px classDef store stroke-width:2px classDef outside stroke-width:1.5px,stroke-dasharray:5 4 class Pi,Phone satellite class People person class Proxy,broker transport class web,docs,api,dispatcher app class worker work class database,queue,objects store class backup,Outside outside

api and dispatcher are the two halves of the hub, run as separate containers with the split profile or as one process (full mode, below). Only the proxy faces the internet: the store, the database and the queue sit on the internal network, and positions sent to outside services are rounded to about 1 km.

Components

Satellite (packages/satellite)

Lightweight Node.js agent running on a Raspberry Pi with an attached microphone.

Audio Pipeline:

  • Captures 3-second WAV chunks at 48kHz mono (BirdNET's native window)
  • On-device pre-filtering: RMS silence gate + YAMNet VAD (per-category bird-likelihood scoring)
  • Filter settings pushed from hub tenant settings via MQTT config channel
  • Local SQLite outbox queue (sql.js) — never blocks on network
  • MQTT upload with acknowledgment and exponential backoff

Recording Scheduler:

  • Sunrise/sunset calculation from GPS coordinates (NOAA algorithm)
  • Profile-based scheduling: dawn_chorus, night_migration, low_power, continuous
  • Profiles pushed from hub via MQTT, resolved locally against sun times
  • Capture loop pauses outside recording windows

Heartbeat:

  • Sends lightweight keepalive at configurable interval (default 30s, MQTT QoS 1)
  • Reports state: recording, paused, scheduled_off, error, the profile it applies and its next change (Pi 2.3.0, phone 3.1.0)
  • Reports noise_floor_rms for adaptive filter calibration
  • Reports satellite package version for version tracking
  • Heartbeat interval configurable from hub tenant settings
  • Decouples online status from audio chunk sending (satellite stays online even when all chunks are filtered)

Capture Modes: alsa (real hardware), simulate (sine wave), replay (pre-recorded WAV files)

Mobile App (packages/mobile)

Android phone satellite built with Capacitor.

  • A native satellite engine (Java) phone 3.0.0 does the satellite's work with the screen on or off: gapless 3-second chunks from AudioRecord, the bird filter (YAMNet), optional on-device BirdNET, an SQLite outbox, the MQTT connection (over a WebSocket), heartbeats, telemetry, the configuration and the GPS. A foreground service keeps it running while recording, with a Stop button in its notification
  • The app's screens (web view) show what the engine reports and send it requests; they never speak MQTT themselves
  • Position from the phone's GPS or a fixed one, as the hub's Use GPS and Refresh every settings say
  • The Live tab's listening circle starts and pauses recording; the app starts paused unless Start recording on launch is on or an update interrupted a recording
  • Settings page: each setting the phone may set for itself, with what it inherits from the team and the hub
  • Hub in the header opens the hub's web app in a viewer over the app
  • Verbose chunk logging toggle
  • Every hub filter setting received and applied via MQTT
  • Heartbeat and telemetry (battery, free storage, network latency)
  • In-app log viewer for diagnostics

Hub API (packages/hub)

Central Fastify server coordinating the entire system. The hub can run in three modes via the OTAVI_HUB_MODE environment variable:

Mode What runs
full (default) API server + all background workers in a single process
api Stateless HTTP + WebSocket server only (scalable with replicas)
dispatcher Background workers only: MQTT ingester, monitors, webhook dispatch, image worker (single instance)

In full mode, everything runs in one process (the original behavior). In split mode, api and dispatcher run as separate containers. A Redis pub/sub event bridge carries events between them (e.g., detection alerts from the dispatcher are published to Redis and delivered to WebSocket clients by the API). The API process uses a lightweight MqttConfigPusher to push configuration to satellites without running the full MQTT ingester. The image worker writes stats to Redis and polls settings from the database, so it operates correctly in both modes.

System page: Hub admins see every container of the hub on the System page (GET /api/system/status, services/system-status.ts), under its compose name, each figure read from the service itself:

Service Source
api, dispatcher Each process writes its version, uptime, memory and address to Redis every 15 s (otavi:registry:{service}:{instanceId}, 30-second expiry)
worker Each inference worker writes the same to otavi:worker:{id}:status, with its job counts and the classifier and embedding model it runs
web Its version, nginx's, its start time and connection counts, on port 8081, which only the containers on its networks reach
docs Its version, uptime and memory on port 8081, over the internal status network
backup Each run's outcome, left in Redis (otavi:backup:last, otavi:backup:last-ok, and otavi:backup:running while one runs)
database Queries: version, uptime, size, connections, applied migrations
queue INFO: version, uptime, memory, clients, keys, last save to disk
broker Its $SYS topics, read by the hub's admin login: version, uptime, clients, subscriptions, messages a minute, dropped messages
objects Its Prometheus metrics, served to a token signed with the S3 secret key: version, usage per bucket, free disk

A service that does not answer shows as down. The backup shows as late when its last success is older than 26 hours, like pnpm ops:check. While a service is down, or the last backup failed or is late, hub admins see a banner on every page. Under the services, the page counts satellites (archived ones apart), detections, species images, audio chunks, teams and people; its Workers tab shows the inference queue and recent jobs.

Core Services (API):

  • JWT cookie + Bearer token authentication
  • Role-based access control with tenant isolation
  • Satellite credential provisioning via Mosquitto dynamic security (MqttAdmin)
  • WebSocket server for real-time client notifications
  • MqttConfigPusher: pushes config to satellites via MQTT (in api mode)

MQTT Connection Resilience:

Both MqttAdmin (credential provisioning) and MqttConfigPusher (satellite config push) maintain persistent MQTT connections with auto-reconnect. When running multiple API instances (--scale api=N), each instance maintains its own MQTT connection. If a connection is temporarily lost (e.g., Mosquitto restart, network blip), API requests that need MQTT will wait up to 10 seconds for reconnection rather than failing immediately. This makes scaled deployments reliable without requiring sticky sessions or a shared MQTT connection.

Background Workers (Dispatcher):

  • MQTT Ingester: receives audio, on-satellite hits, telemetry and heartbeats; stores audio in MinIO; enqueues inference jobs via BullMQ (a second-opinion job for each on-satellite hit); keeps when each satellite listened, from the chunk counts in its heartbeats
  • SatelliteMonitor: runs the absence alert rules every 60 s (not for a quiet satellite whose last heartbeat said paused). A satellite's status is derived when read (satellite_live), its health flags kept from its telemetry by the ingester
  • DetectionWatcher: rarity checks, first-of-season flagging, WebSocket events, webhook dispatch. When a detection is the first observation of a species in the current season for a tenant, it sets is_first_of_season on the detection and generates an alert.
  • SpeciesImageWorker: downloads bird thumbnails from Wikipedia (max 2 concurrent), stores in MinIO, with Wikimedia rate limiting (500 req/hr unauthenticated, 10,000 req/hr with OAuth 2.0)
  • AlertRulesEngine: evaluates every alert rule and delivers the alert in the app, to the team's phones and through its channels (webhook with an HMAC signature, email, Slack, Discord, Telegram, Google Chat)
  • AuditService: comprehensive audit logging of all user, admin, and detection actions to audit_log table (real client IPs via X-Forwarded-For)

Session Grouping: Audio chunks are grouped into recording sessions based on a 5-minute gap boundary. If the time between two consecutive chunks from the same satellite exceeds 5 minutes, a new session begins. The Sessions API exposes these groupings, with per-session chunk counts and detection summaries.

Inference Workers (packages/inference)

Python 3.11 processes running BirdNET TFLite, and Perch v2 beside it.

  • Pull jobs from BullMQ/Redis queue
  • Download audio from MinIO, run inference via birdnetlib, with each satellite's minimum confidence and range filter
  • Run Perch v2 on the same audio hub 0.97.0: its acoustic embedding, and its second opinion on each species BirdNET names (also for the hits satellites send, on their stored audio)
  • Geo-aware species filtering (GPS + date)
  • Enhanced re-processing for uncertain detections (0.4–0.7 confidence):
    • Extended audio window (6s)
    • Frequency isolation (1–10kHz bandpass)
    • Cross-chunk correlation
  • Scale with docker compose up --scale worker=N

Web UI (packages/web)

React 19 SPA served by nginx, responsive for mobile.

Pages, as the sidebar groups them. Every page follows one anatomy: a title row (title, a one-line subtitle naming the team and the window, actions at the right, a view toggle where a page has views), one toolbar, the main block, a 300 px rail with the window's figures, an index at the left where the page has sections, all capped at 1440 px (components/PageLayout.tsx):

  • Birds: Dashboard (period figures, two charts, recent detections, highlights and hub health in the rail), Detections (the species-grouped overview and the full list, with the SpectrogramPlayer and the votes on each row), Timeline (species by hour, the stretches where no satellite listened), Species (the catalog and each species' profile), Map (satellites and detections)
  • Satellites: the fleet list and each satellite's page (status, configuration with its history, schedule, outbox, logs, actions)
  • Analyze: Analytics (detections per day, by hour, the weekly pattern, weather, through the year; diversity and top species in the rail), Compare (two satellites side by side: figures as rows, one species table, the hour charts on one scale)
  • Team: Verification (the queue of what a vote would change, My votes, Stats), Field notes (rows by day, the editor in a side drawer), Alerts (Inbox, Rules and Channels; a rule or a channel is edited in a side drawer), Activity (alerts and team changes, by kind, person and window), Members (requests, members, invites and blocked), Team settings
  • Account: profile, security (password, two-factor, passkeys, remembered devices), preferences, your data
  • Hub (hub admins, their own sidebar): Hub settings, Users, Teams, System (with Workers), Model precision, Audit log, Design

Features:

  • Species thumbnails from Wikipedia (downloaded in background, served from MinIO)
  • Multi-language bird names (38 languages from BirdNET label files)
  • Species name display: primary bold, secondary in parentheses, Latin italic, clickable thumbnail with lightbox
  • Real-time WebSocket notifications for rare species (translated names)
  • Responsive layout: a 232 px sidebar collapsible to a 56 px icon rail, a drawer on phones; four groups (Birds, Satellites, Analyze, Team) and a hub sidebar for hub admins
  • Spectrogram visualization (Cooley-Tukey FFT, Viridis colormap, 0–12kHz)
  • Full i18n support (English + French, ~500+ translation keys, locale-aware formatting)
  • Language and theme in the avatar menu

MQTT Channels

{prefix}/{tenant_id}/{satellite_id}/{channel}

{prefix} is birdnet for Pi 1.x and phone 1.x, otavi from Pi 2.0.0 and phone 2.0.0; the hub speaks both hub 0.81.0. See MQTT.

Channel Direction QoS Purpose
audio Satellite → Hub 1 Audio chunk (base64 WAV)
telemetry Satellite → Hub 1 Battery, storage, CPU, GPS
heartbeat Satellite → Hub 1 Keepalive (default 30 s), carries filter + outbox stats + stream + version
config-request Satellite → Hub 1 Sent on (re)connect to pull effective config
live-audio Satellite → Hub 0 Live-audio chunks during an active session
log-response Satellite → Hub 1 Reply to a hub-side log-request
config Hub → Satellite 2 Recording profile + filter + outbox caps + excluded YAMNet categories
ack Hub → Satellite 1 Chunk acknowledgment
update Hub → Satellite 1 Trigger otavi-update.sh on the satellite
detection Hub → Satellite 1 New-detection notification (hub 0.32.4, mobile DetectionsFeed)
live-start / live-stop Hub → Satellite 1 Start/stop a live-audio session
log-request Hub → Satellite 1 Request a tail of the satellite's journal

See reference/mqtt.md for message shapes.

Authentication

Resolved in this order on every request:

  1. Internal API key — Authorization: Bearer ${OTAVI_HUB_INTERNAL_API_KEY} for the nginx proxy and trusted internal callers.
  2. JWT cookie — session httpOnly cookie set by /api/auth/login.
  3. Bearer JWT — Authorization: Bearer <jwt> for user-scoped clients (mobile, scripts).
  4. Bearer API key — Authorization: Bearer <hex-key> for machine-to-machine. Either tenant-scoped (a team's API key) or satellite-scoped (minted by POST /api/satellites and rotatable via POST /api/satellites/:id/rotate-api-key).

API keys are SHA-256 hashed in storage; raw key is shown once at creation. The auth resolver populates request.auth.satelliteId for satellite-scoped keys (migration 072) so future routes can scope to one satellite.

Roles (tenant-scoped): viewer < member < admin < owner. Hub admin: cross-tenant access, designated via DB flag or OTAVI_AUTH_PLATFORM_ADMIN_EMAILS env var. MFA enrollment mandatory.

Multi-Factor Authentication

Optional second factor for any user, mandatory for hub admins.

  • TOTP (RFC 6238, ±30 s tolerance): scan a QR with any authenticator app (Google Authenticator, 1Password, Authy…). Secret stored AES-256-GCM-encrypted at rest with OTAVI_AUTH_MFA_ENCRYPTION_KEY (32-byte hex env var)
  • WebAuthn passkeys: Touch ID, Windows Hello, YubiKey, etc., registered against an authenticated session and used as an alternative second factor. Requires OTAVI_AUTH_WEBAUTHN_RP_ID/OTAVI_AUTH_WEBAUTHN_RP_NAME/OTAVI_AUTH_WEBAUTHN_ORIGIN (auto-derived from OTAVI_APP_FQDN)
  • Backup codes: 10 single-use Crockford-alphabet codes shown once at TOTP enrollment, bcrypt-hashed at rest, popped on consume. Regeneratable from /account (re-enter password)
  • Login challenge: /login returns {mfaRequired, mfaToken} instead of the session cookie when MFA is enabled. The 5-min mfaToken JWT bridges the password and second-factor steps; up to 5 wrong codes per token (Redis-backed counter) before it's burned and the user has to re-enter the password
  • Forced-enrollment gate: hub admins land on a full-page enrollment screen before the AppShell renders if they haven't enrolled yet
  • Remember this device (30 days): opt-in cookie that skips the second factor on the same browser. Token is sha256-hashed at rest in mfa_remembered_devices; per-device list with revoke on /account. Logout does NOT clear the cookie (matches Google / GitHub / Microsoft)
  • Reset escape hatches: hub admin "Reset MFA" action on PlatformUsers; CLI emergency reset at pnpm --filter @otavi/hub exec mfa:reset <email> for the case where the only hub admin loses both their device and backup codes
  • Audit: every MFA action logged (enabled, disabled, login_failed, passkey_added/removed, reset_by_admin, etc.)

Multi-Tenancy

  • Row-level isolation via tenant_id on all data tables
  • Users are global; membership via tenant_members join table
  • Each user can have different roles in different tenants
  • MQTT ACLs enforce per-satellite topic scoping
  • MinIO paths prefixed by tenant: {tenant_id}/{satellite_id}/{chunk_id}.wav
  • Species images are global (not tenant-scoped)

Database

PostgreSQL 17. The schema comes from the migrations in packages/hub/src/db/migrate.ts, which run at every hub start (the ones applied are recorded in migrations). Team data carries a tenant_id and every query on it is scoped to a team; the tables without one are global (people, the species reference, models, app releases, hub settings) or belong to a row that has one.

Area Tables
Teams and people tenants, users, tenant_members, invites, join_requests, tenant_blocks, api_keys
Sign-in user_passkeys, mfa_remembered_devices, password_reset_tokens, login_attempts
Satellites satellites, satellite_config_overrides, satellite_config_history, satellite_telemetry
Recordings and detections audio_chunks, detections, verification_votes, detection_annotations, detection_comments, confidence_calibration, shadow_detections (model comparison)
Species species_images, species_image_files, species_descriptions, species_facts, species_frequency_bands, species_ranges (the species pages' observation maps), geocode_cache
Alerts and exports alert_rules, alert_channels, alerts, scheduled_exports
Settings platform_settings (hub), tenant_settings (team), setting_locks, and the views tenant_settings_effective and satellite_settings_effective, which give readers that cannot call the resolver each team's and each satellite's resolved values
Field notes field_notes, field_note_photos
Other models (the classifier and embedding registry), mobile_releases (APKs), audit_log

Species Images

Bird thumbnails are managed by a background download queue:

  1. When a species is first seen, it's queued in species_images table
  2. SpeciesImageWorker processes the queue (max 2 concurrent, configurable delay)
  3. Fetches the original image URL from Wikipedia (pageimages prop), then downloads both the 800px display thumb and the full-resolution original in a single pass — stored as species-images/{slug}.{jpg|png} and species-images/{slug}_orig.{jpg|png} respectively
  4. Up to N additional images per species (species_extra_images_count) are pulled from the page's images prop; each extra also stores both sizes ({slug}_{position}.jpg + {slug}_{position}_orig.jpg)
  5. Proxy endpoint serves from MinIO with immutable cache headers; ?original=1 returns the full-resolution copy, or the display copy when it weighs more than &maxBytes=
  6. Frontend shows placeholder (pulsing dots) until download completes; the lightbox uses originals up to 8 MB (PHOTO_ORIGINAL_MAX_BYTES in @otavi/shared; a few are 20 to 170 MB scans), with click-to-zoom + drag-pan
  7. Backfill rotates across species ordered by (extras_count ASC, fetched_at ASC); species whose image list is exhausted are marked extras_exhausted_at and skipped for 7 days
  8. Hub admin can clear cache, retry failed downloads, adjust download delay

Rate limiting:

  • Sliding 1-hour request window with auto-throttle (slow down at 80%, pause at 95%)
  • Respects Retry-After header on 429 responses
  • Unauthenticated: 500 req/hr (with proper User-Agent)
  • Authenticated (OAuth 2.0): 10,000 req/hr
  • Wikimedia OAuth token and contact email configurable in Hub settings

Versioning

Three independent SemVer streams:

Stream Includes Tag prefix
hub hub, web, inference, shared, docs, root vhub-X.Y.Z
satellite packages/satellite only vsat-X.Y.Z
mobile packages/mobile only vapk-X.Y.Z

A hub release does not mark satellites outdated: each stream is compared with its own latest release. Bump per scope:

pnpm version:bump --scope hub patch
pnpm version:bump --scope satellite minor
pnpm version:bump --scope mobile patch

The hub knows the latest release of each stream (the versions it was built with, and for phones the newer of that and the last APK uploaded) and exposes them at GET /api/system/versions. Each satellite reports its stream field on heartbeat so the hub can compare against the right target. Pi update script checks out the latest vsat-* tag; mobile versionCode derives from the SemVer.

Technology Stack

Component Technology
Satellite agent TypeScript / Node.js
Local satellite DB sql.js (SQLite)
Transport MQTT (Mosquitto 2.x, dynamic security plugin)
Hub API TypeScript / Fastify
Authentication JWT cookies + Bearer API keys (bcrypt, SHA-256), MFA via TOTP (otplib) + WebAuthn (@simplewebauthn)
Job queue BullMQ + Redis
Database PostgreSQL 17 (71 migrations)
Object storage MinIO (audio + species images, originals + 800px thumbs)
Inference Python 3.11 / TFLite / birdnetlib
Web UI TypeScript / React 19 / Mantine v9 / Vite / nginx
Mobile app Capacitor (Android) / native AudioRecord plugin
Species translations 38 languages from BirdNET label files
Documentation Express + markdown-it
Reverse proxy Traefik (HTTPS + WSS for MQTT)
Containers Docker Compose (8 default, 9 with split mode)
Monorepo pnpm workspaces