Core API & Orchestration

Backend Core

The heart of AudioFlux. A high-concurrency Node.js engine orchestrating real-time state synchronization, unified music search, and massive multi-user room management.

Synchronous Tick System

How AudioFlux keeps thousands of users on the same beat.

The PlaybackManager implements a 1-second authoritative tick. Unlike traditional players that rely on client-side timers, AudioFlux treats the Backend as the source of truth for "Time Elapsed."

  • Centrally managed intervals calculate drift for every active room.
  • Automatic song transitions triggered server-side when currentTime >= duration.
  • Empty room detection with auto-pause after 30 seconds of inactivity.
Simplified Tick Pulse
// Every 1000ms per active room
tick(roomId) {
  const state = await redis.getState(roomId);
  if (state.playing) {
    state.currentTime += 1;
    if (state.currentTime >= state.duration) {
      return this.handleSongEnd(roomId);
    }
  }
  this.io.to(roomId).emit('stateUpdate', state);
}

Global State Engine

Redis key-value schema for persistent ecosystem data.

Key PatternTypeValue / Purpose
room:{id}:stateJSON StringPlaying status, current song ID, position, loop mode.
room:{id}:queueList / ArrayOrdered list of Song objects pending playback.
user:{id}:historySorted SetRecent songs played by user with timestamp scores.
room:{id}:viewersSetActive user IDs currently connected to the room.

Technical API Reference

Complete endpoint specifications with request/response schemas.

GET

/api/search/songs

Multi-Source

Unified search across JioSaavn and YouTube. Returns up to 20 results with intelligent deduplication based on title similarity.

curl "https://api.audioflux.io/api/search/songs?q=Blinding+Lights"
GET

/api/lyrics/:artist/:title

Aggregator

Multi-provider lyrics engine. Queries JioSaavn for synced LRC format first, then falls back to Musixmatch/Genius for plain text.

{
  "lyrics": "[00:12.30] Example lyrics...",
  "synced": true,
  "source": "JioSaavn",
  "url": "https://..."
}
GET

/api/proxy/yt/:videoId

Streaming Proxy

Bypasses YouTube region blocks by proxying audio streams through the backend. Implements chunked transfer encoding for instant playback start.

POST

/api/playlist

Persist a song to user's library in Redis with automatic deduplication.

{
  "userId": "12345678",
  "song": {
    "id": "song_id_123",
    "title": "Example Song",
    "artist": "Artist Name"
  }
}

Socket.IO Event Registry

Complete bidirectional event protocol for real-time synchronization.

Inbound (Client → Server)
join

Initial handshake to join a room and receive full state snapshot.

addSong

Queue a new track with metadata and user attribution.

play/pause

Toggle playback state for the entire room.

skip

Force transition to next song in queue.

seek

Jump to specific timestamp (seconds) in current track.

loopToggle

Cycles through Off, Track, and Queue loop modes.

autoPlayToggle

Enables AI-suggested playback when queue is exhausted.

removeSong

Removes specific index from room queue (Owner Only).

previous

Rewinds to the last song in room history.

Outbound (Server → Client)
initialState

Full room snapshot sent on join (queue, viewers, playback state).

stateUpdate

1-second heartbeat with current playback position and metadata.

queueUpdated

Fired when songs are added/removed from the queue.

player_notification

Toast messages (e.g., 'User joined', 'New song added').

viewersUpdated

Real-time presence array of current active listeners.

historyUpdate

Fired when a song finishes to update history panels.

error

Targeted error messages for failed commands.

Security Architecture

HMAC-SHA256 verification for Telegram WebApp authentication.

To prevent unauthorized access, the backend implements HMAC-SHA256 signature verification on the initData provided by Telegram WebApp SDK.

1. Extract Hash

The hash is stripped from the query parameters.

2. Secret Generation

A secret key is derived from the BOT_TOKEN.

3. Validation

Data is re-signed locally; mismatch results in 401.

Error Handling Registry

StatusError CodeReason
401UNAUTHORIZEDInvalid or missing Telegram WebApp initData signature.
403FORBIDDENUser ID does not have administrative permissions.
404NOT_FOUNDTarget room, song, or user resource does not exist.

Performance Note

The backend is optimized for the V8 engine. It uses async/await heavily to prevent event-loop blocking during heavy I/O (Redis/Search). For deployments exceeding 1,000 concurrent rooms, we recommend a Redis Cluster and Socket.IO Redis Adapter for horizontal scaling.