Skip to main content

WebSocket Communication

Audience: End users, system administrators, technical stakeholders Last Updated: 2026-04-06 Version: 2.0.0


Table of Contents

  1. Overview
  2. Key Concepts
  3. What WebSocket Provides
  4. How It Works
  5. Real-Time Updates
  6. Connection Management
  7. Configuration
  8. Integration with Other Features
  9. Error Handling & Reliability
  10. Technical Specifications
  11. Security Considerations
  12. Troubleshooting
  13. Related Documentation

Overview

WebSocket communication enables real-time, bidirectional messaging between the Llamafin app and your Jellyfin server. Unlike traditional HTTP requests where the client must repeatedly ask for updates, WebSocket maintains a persistent connection that allows the server to push updates to the app instantly as they happen.

Why It Matters

Without WebSocket, the app would need to constantly poll the server for changes (e.g., "Has my library changed? Has anyone started playing music?"), wasting battery, network bandwidth, and server resources. WebSocket eliminates this inefficiency by allowing the server to notify the app immediately when something changes.

Key Benefits

BenefitDescription
Instant UpdatesLibrary changes, playback events, and user updates arrive in real-time
Battery EfficientNo polling required — the connection stays open with minimal keep-alive pings
Server FriendlyReduces server load by eliminating repetitive status-check requests
Multi-User AwareSee what other users are doing on the same server (remote control, sessions)
Self-HealingAutomatically recovers library data if the connection drops and reconnects

Key Concepts

What Is WebSocket?

WebSocket is a communication protocol that provides a full-duplex (two-way) communication channel over a single, long-lived connection. Think of it as a phone call (persistent, both parties can speak at any time) versus sending letters (request-response, one at a time).

How Llamafin Uses WebSocket

Llamafin uses WebSocket for five primary purposes:

  1. Library synchronisation: Receive instant notifications when new music is added, existing items are updated, or content is removed from your library
  2. User Data Updates: Stay in sync with your play state, favorites, and watched status across devices
  3. Session Awareness: Track active playback sessions on the server (useful for remote control and remote control)
  4. Server Health: Detect when the server is shutting down or restarting, providing a graceful user experience
  5. Connection Monitoring: Provide real-time connection status to the app's network management system

What WebSocket Is NOT Used For

WebSocket is not used for:

  • Music Streaming: Audio is streamed via HTTP with HLS (HTTP Live Streaming)
  • Initial Library Loading: Library data is fetched via REST API on demand
  • P2P Remote Control: The Llamafin Connect (P2P) feature uses separate encrypted channels, not this WebSocket
  • Settings Sync: Settings are stored locally, not synced via WebSocket

What WebSocket Provides

Real-Time Notifications

When events occur on your Jellyfin server, the server pushes notifications to the app through the WebSocket connection:

Event TypeWhat Triggers ItWhat the App Does
New Music AddedServer scans and imports new albums/songsFetches details for new items, updates library views, shows notification
Music UpdatedMetadata changes (tags, artwork, etc.)Fetches updated details, refreshes affected views
Music RemovedContent deleted from libraryRemoves items from all local library views
Folder Structure ChangedLibrary folders reorganizedUpdates folder browsing navigation
User Data ChangedPlay state, favorites, or ratings updated on another deviceSyncs local data with server changes
Session ChangedPlayback starts/stops on any deviceUpdates remote control session list
User Profile UpdatedAccount details modifiedRefreshes user profile data
Server Shutting DownAdministrator restarts or stops serverShows user-friendly "server shutting down" alert
Server Restart RequiredServer needs restart after updateFlags that a restart is pending

Connection Status Tracking

The app continuously monitors the WebSocket connection status and surfaces it through the unified network status system:

StatusWhat It MeansUser Experience
ConnectedReal-time updates are flowing normallyLibrary updates arrive instantly
ConnectingApp is establishing a new connectionBrief delay before real-time updates resume
DisconnectedNo active WebSocket connectionUpdates will arrive when connection restores
ErrorConnection failed due to an errorApp will retry when conditions change

How It Works

Connection Lifecycle

┌─────────────────────────────────────────────────────────────────┐
│ WEBSOCKET CONNECTION LIFECYCLE │
└─────────────────────────────────────────────────────────────────┘

1. USER LOGS IN / SESSION READY

├── App validates: server URL, auth token, device ID, network status
├── If offline: connection attempt is skipped (saves battery)
└── If all checks pass: app builds WebSocket URL and connects

2. CONNECTION ESTABLISHED

├── Server confirms connection
├── App fetches fresh user profile data
├── App begins sending keep-alive pings every 10 seconds
└── Real-time updates begin flowing

3. SERVER PUSHES UPDATES (ongoing)

├── Library changes → app updates relevant views
├── User data changes → app syncs play state/favorites
├── Session changes → app updates remote control status
└── Server shutdown → app shows friendly alert message

4. CONNECTION ENDS

├── User logs out → app cleanly closes connection
├── Device goes offline → app closes connection to save resources
├── Server shuts down → connection drops, app notifies user
└── Network blip → connection drops (no automatic reconnect)

Keep-Alive Mechanism

To prevent the connection from being closed by proxies, load balancers, or the server itself due to inactivity, the app sends a lightweight "keep-alive" ping every 10 seconds. This is similar to occasionally saying "I'm still here" during a phone call to keep the line open.

Impact: Negligible bandwidth (~50 bytes every 10 seconds, or ~432 KB per day).

Message Routing

When the server sends a message, the app acts as a smart router:

  1. Receives the raw message from the WebSocket connection
  2. Identifies the message type (library change, user data change, etc.)
  3. Routes it to the appropriate feature within the app
  4. Reacts accordingly (fetches new data, updates the UI, shows a notification)

This ensures that each part of the app only handles the messages relevant to it, keeping the system organised and efficient.


Real-Time Updates

Library Updates

When your Jellyfin server adds, updates, or removes library content, the app receives granular notifications with item IDs rather than generic "something changed" messages.

Small Updates (50 items or fewer):

  • App fetches details only for the changed items
  • Updates specific sections of the library views
  • Shows a rich notification describing the change

Large Updates (more than 50 items):

  • App recognises this as a major library change
  • Refreshes the "recently added" and "recently played" views entirely
  • Shows a general notification about library updates

This threshold-based approach ensures efficiency: small updates are handled surgically, while large updates trigger a broader refresh.

User Data Sync

If you mark a song as favorite, change its play state, or update its rating on one device, those changes are instantly reflected on all your other devices through WebSocket push notifications.

Use Case: You're listening on your phone and mark an album as favorite. When you open the app on your tablet, that album is already favorited — no manual refresh needed.

Session Awareness

The app tracks active playback sessions across all devices connected to your Jellyfin server. This powers:

  • Remote Device Control: See what's playing on other devices
  • Remote Control: Control playback on another device from your current device
  • Activity Monitoring: Know which users are actively listening

Connection Management

When Connections Are Established

TriggerDescription
Successful LoginAfter you authenticate with your Jellyfin server
Session RehydrationWhen the app restores your session on startup
Manual ReconnectWhen you explicitly trigger a reconnect from settings
Server URL ChangeAfter you switch to a different server (disconnects first, then reconnects to new server)

When Connections Are Closed

TriggerDescription
User LogoutClean disconnect when you sign out
Session ExpiredServer invalidates your session token
Device Goes OfflineNetwork loss, airplane mode, or force offline mode enabled
Server ShutdownServer stops or restarts
Server URL ChangeDisconnects from old server before connecting to new one

Reconnection Behaviour

Important: The WebSocket system does not automatically reconnect after unexpected disconnects (e.g., network blips, server restarts). Reconnection requires one of the following:

  1. Manual Reconnect: You can trigger a reconnect from the network settings
  2. Re-authentication: Logging in again will establish a new connection
  3. Network Recovery + App Resume: When the network returns and the app re-validates your session

This is a known limitation. The app compensates with self-healing mechanisms (see below).

Self-Healing Mechanisms

Even without automatic reconnection, the app includes several self-healing features:

MechanismHow It Works
Library Recovery on ReconnectWhen a connection is re-established, the app checks if library data is empty. If so, it automatically reloads the library from the server.
Connection Status NotificationsThe app notifies you when the connection is lost and when it's restored (with debouncing to avoid spam).
Server Shutdown AlertsIf the server signals an intentional shutdown, the app shows a specific, user-friendly alert rather than a generic "offline" message.
Offline GatekeeperIf the device is offline when a connection attempt is made, the app skips the attempt entirely (saves battery and prevents errors).

Configuration

User-Facing Settings

WebSocket behaviour is mostly automatic and not directly configurable by users. However, some settings indirectly affect WebSocket:

SettingLocationEffect on WebSocket
Server URLSettings → SourceDetermines which server to connect to
Force Offline ModeSettings → NetworkWhen enabled, WebSocket connection is closed and not attempted
Network DetectionAutomaticApp monitors network status and manages WebSocket accordingly

Developer/Advanced Configuration

ParameterValueDescription
Keep-Alive Interval10 secondsFrequency of ping messages to keep connection alive
Update Threshold50 itemsBoundary between targeted and bulk library updates
Notification Debounce5 secondsMinimum time between connection status notifications
Protocol DerivationHTTP → WS, HTTPS → WSSWebSocket protocol is derived from server URL protocol

Integration with Other Features

Library Management

WebSocket is the primary trigger for library updates. When the server signals that items have been added, updated, or removed, the library feature reacts by:

  1. Fetching fresh data for the affected items
  2. Updating the local state (store)
  3. Refreshing the UI to reflect changes
  4. Showing a notification to the user

Without WebSocket, the library would only update when you manually refresh or navigate to a different view.

Authentication

After a successful login and WebSocket connection, the app fetches your full user profile to ensure it has the latest data. When you log out, the WebSocket connection is cleanly closed to prevent stale connections.

Network Management

The WebSocket connection status is fed into the app's unified network status system, which combines:

  • Device network connectivity (WiFi/cellular/offline)
  • Server reachability
  • WebSocket connection status

This unified view powers the app's "online/offline" indicators and gates API calls appropriately.

Notifications

The app monitors WebSocket connection status changes and shows user notifications:

  • "Connection restored" when the connection is re-established
  • "Connection lost" when the connection drops

These notifications are debounced (5-second delay) to prevent spam during unstable network conditions. The first connection during app startup is suppressed (no notification).

Remote Device Control

WebSocket session updates inform the app about active playback sessions on other devices. This powers the remote control feature, allowing you to see and control what's playing elsewhere.


Error Handling & Reliability

What Happens When Things Go Wrong

ScenarioApp BehaviourUser Impact
Network dropsWebSocket closes, app enters offline modeReal-time updates pause until network returns
Server restartsConnection drops, app shows "server shutting down" alertBrief interruption, updates resume after server is back
Server URL changesOld connection closed, new connection establishedBrief pause during transition
Token expiresConnection fails, app prompts for re-authenticationMust log in again to restore real-time updates
Large library changeApp detects >50 items and refreshes entire viewsSlightly longer update process, but complete
Message parsing failsApp logs error, connection stays openSingle message lost, subsequent messages work normally

Graceful Degradation

The app is designed to function without WebSocket. If the connection fails or is unavailable:

  • Library browsing still works (data is cached locally)
  • Music playback still works (uses HTTP streaming, not WebSocket)
  • Search still works (REST API calls)
  • Settings still work (stored locally)

The only functionality lost is real-time updates. You can still manually refresh views to see the latest data.

Resource Management

ResourceManagement Strategy
BatteryOffline gatekeeper prevents connection attempts when device is offline
NetworkKeep-alive pings are minimal (~50 bytes every 10 seconds)
MemorySingle WebSocket connection, cleaned up on disconnect
Server LoadNo polling — server pushes updates only when needed

Technical Specifications

Connection Details

SpecificationValue
ProtocolWebSocket (RFC 6455)
Secure ProtocolWSS (WebSocket Secure over TLS) when server uses HTTPS
PortSame as server HTTP/HTTPS port (8096 default for Jellyfin)
AuthenticationQuery parameter (api_key) with user access token
Device IdentificationQuery parameter (deviceId) with unique device UUID
Connection URL Pattern[ws/wss]://[server-host]:[port]/socket?api_key=[TOKEN]&deviceId=[UUID]
Keep-Alive Interval10 seconds
Keep-Alive Message{ "MessageType": "KeepAlive", "Data": {} }

Message Types

The app handles 8 of 17 known server message types:

Handled TypesUnhandled Types (ignored)
LibraryChangedPackageInstallationCompleted
UserDataChangedPackageInstallationFailed
SessionsPackageInstalling
UserUpdatedGeneralCommand
UserDeletedPlay
ServerRestartingPlayState
ServerShuttingDownPlayStateCommand
RestartRequiredSyncPlayCommand
KeepAlive (server response to client ping)

State Tracking

PropertyPossible Values
Connection Statusdisconnected, connecting, connected, error
Error Messagenull (no error) or string describing last error

Performance Characteristics

MetricValue
Connection Setup TimeTypically < 500ms on stable network
Message Delivery LatencyTypically < 100ms from server event
Keep-Alive Bandwidth~432 KB per day
Memory per ConnectionMinimal (single socket, no message buffering)
Max Concurrent Connections1 per app instance

Security Considerations

Authentication Security

  • Token in URL: The authentication token is passed as a URL query parameter. While convenient, this means the token appears in browser dev tools and server logs.
  • Transport Security: When connecting to an HTTPS server, the WebSocket connection uses WSS (WebSocket Secure), which encrypts all traffic via TLS.
  • No Additional Encryption: Unlike the P2P remote control feature (which uses ECDH key exchange + AES-256-GCM encryption), the WebSocket connection itself has no additional encryption beyond TLS.

Best Practices for Users

  1. Use HTTPS: Always connect to your Jellyfin server via HTTPS to ensure WebSocket traffic is encrypted (WSS)
  2. Secure Your Server: Ensure your Jellyfin server is properly secured with strong passwords and, if exposed to the internet, a reverse proxy with TLS
  3. Monitor Sessions: Regularly check active sessions in Jellyfin to detect unauthorized access

Known Limitations

LimitationRisk LevelDescription
Token in URL query parameterLow-MediumToken visible in server logs and browser dev tools
No token refreshMediumIf token expires, WebSocket silently fails until re-authentication
No certificate pinningLowApp accepts any valid TLS certificate (vulnerable to MITM if CA is compromised)
No automatic reconnectionLowUser must manually reconnect after unexpected disconnects

Troubleshooting

Common Issues

IssueLikely CauseSolution
Real-time updates not workingWebSocket connection not establishedCheck network connection, verify server URL, try manual reconnect
Library not updating automaticallyServer not sending WebSocket notificationsVerify Jellyfin server WebSocket is enabled and accessible
"Connection lost" notificationNetwork drop or server restartWait for network to recover, or manually reconnect
"Server shutting down" alertServer administrator is restartingWait for server to come back online
Connection fails after server URL changeOld connection still activeWait a moment for reconnect, or manually reconnect

Diagnostic Steps

If real-time updates are not working:

  1. Check Network Status: Ensure your device has an active internet connection
  2. Verify Server URL: Confirm the server URL in Settings → Source is correct and accessible
  3. Check Server Status: Ensure your Jellyfin server is running and WebSocket is enabled
  4. Try Manual Reconnect: Use the network settings to trigger a manual reconnect
  5. Re-authenticate: Log out and log back in to establish a fresh connection

When to Seek Help

Contact support if:

  • WebSocket connection consistently fails despite correct server URL and network connectivity
  • Real-time updates work on some devices but not others (may be server configuration issue)
  • You see frequent "Connection lost" notifications on stable networks


Last Updated: 2026-04-06 Version: 2.0.0