WebSockets

Llana ships with WebSockets so you can keep your frontend applications fully synchronized with your database.

Socket Connection

WebSockets use the same Hosts and Authentication settings as the main API endpoints. If you have user authentication setup then the WebSockets expect a a JWT token to be passed either as as a Bearer token or via the Auth > Token value:

import { io } from "socket.io-client";
import { $llanaInstanceUrl, $llanaAccessToken } from "@/plugins/llana"

export const socket = io($llanaInstanceUrl, {
    extraHeaders: {
        Authorization: 'Bearer ' + $llanaAccessToken()
        'x-llana-table': table,
    },
    auth: {
        token: $llanaAccessToken()
    }
});

It is important to pass your table in the extraHeaders > x-llana-table value, as we will use this to check permissions during the socket creation process.

Subscribing

You can subscribe to specific table updates, you will receive payloads as follows:

{
    type: 'INSERT' | 'UPDATE' | 'DELETE'
    [table_primary_key]: string | number
}

Here is an example subscription to the users_notifications table via a Pinia Store:

export const useNotificationsStore = defineStore('notificationStore', {
    state: () => <ListResponse<Notification>>defaultList(),
    actions: {
        bindEvents() {
            try{
                socket.on(users_notifications, (data: SocketData) => {
                    switch (data.type) {
                        case 'INSERT':
                        case 'UPDATE':
                            this.getNotification(data.id)
                            break
                        case 'DELETE':
                            this.deleteNotification(data.id)
                            break
                    }
                });
            }catch(e: any){
                console.error(e)
                socket.off(table)
            }
          },
    }
})

If you are using our frontend plugins like Nuxt, we handle the WebSocket integration automatically.

Optional Configuration

The following .env values can be used:

VariableDetails
CACHE_WS_IDENTITY_DATA_TTLThe TTL for caching websocket identities, defaults to 2 days

Multi-Server Setup

When deploying Llana in a multi-server environment, additional configuration is required to ensure that WebSocket connections are synchronized across all servers in the cluster. By default, WebSockets will only function in a single-instance setup. In a cluster, servers must communicate with each other using Redis.

Setting Up Redis for WebSocket Communication

To enable WebSocket functionality in a multi-server cluster:

  1. Install Redis
    Ensure that a Redis server is installed and running. This can be on the same machine (localhost) or on a dedicated Redis server.
  2. Add Redis Configuration to .env
    Include the following environment variables in your .env file to configure Redis:
    REDIS_HOST=127.0.0.1  # Replace with your Redis server's IP address
    REDIS_PORT=6379       # Replace with your Redis server's port
    
    • REDIS_HOST: The hostname or IP address of the Redis server.
    • REDIS_PORT: The port number Redis is running on.
  3. Cluster Communication
    When Redis is configured, the WebSocket servers will use Redis Pub/Sub to synchronize state and events across all instances in the cluster. This ensures seamless real-time communication regardless of which server the WebSocket client connects to.

Without Redis

If Redis is not set up, WebSockets will only work in a single-instance setup. This means:

  • Clients connected to one server will not receive WebSocket updates from another server in the cluster.
  • This limitation can cause inconsistent real-time behavior in multi-server deployments.

To ensure full functionality in a multi-server environment, Redis is a mandatory requirement for multi-instance setups.


Example Redis Deployment

For a production setup, you can deploy Redis using Docker:

docker run -d --name redis -p 6379:6379 redis

Ensure the REDIS_HOST points to the Docker container’s IP (or localhost if running locally).


Verifying the Setup

Once Redis is configured and your .env file updated:

  1. Restart all servers to ensure they pick up the new Redis configuration.
  2. Make sure the following warning does NOT appear on the boot: REDIS_PORT or REDIS_HOST not found - Websockets will NOT work in a multi-instance setup

With Redis properly set up, your multi-server deployment will fully support WebSockets, keeping your application synchronized in real time.