Ring Platform

    AI Self-Construct

    🏠
    Home
    EntitiesHot
    OpportunitiesNew
    Store
    Platform Concepts
    RING Economy
    Trinity Ukraine
    Global Impact
    AI Meets Web3
    Get Started
    Documentation
    Quick Start
    Deployment Calculator
    Offline
    v1.51•Trinity
    Privacy|Contact
    Ring Platform Logo

    Loading Documentation Hub...

    Scanning documentation library

    Documentation

    📚 Documentation

    Admin API
    Advanced Features
    AI Agent Customization
    API
    Api Examples
    Api Integration
    Apple Sign-in Integration
    Architecture
    Authentication
    Authentication
    Authentication
    Authentication Architecture
    Backup & Recovery
    Basic Setup
    Best Practices
    Branding
    CLI
    Code Structure
    Code Style
    Complete Customization Guide
    Components
    Contributing
    Custom Branding
    Customization
    Data Model
    Database Backend Selection
    Debugging
    Deployment
    Deployment
    Development
    Docker
    Email AI-CRM API
    Email AI-CRM Architecture
    Email AI-CRM System
    Email AI-CRM Tutorial
    Entities
    Entities
    Environment Configuration
    Examples
    Features
    Features
    First Success Validation
    Getting Started
    Installation
    Integrations
    Local Setup
    Localization
    Messaging API
    Mobile Experience
    Monitoring & Analytics
    Multi Tenant
    Multi-tenant Deployment
    Multi-Vendor Store
    News Module - Digital Newspaper Experience
    Next Steps
    NFT Marketplace
    Notifications
    Notifications API
    Opportunities
    Opportunities
    Payment Gateway Integration
    Payment Integration
    Performance
    Performance Optimization
    Performance Optimization Patterns
    Prerequisites
    Quick Start
    Quick Start - Your First Ring Clone
    Real Time
    Real World
    Security
    Security & Compliance
    Store API
    Testing
    Themes
    Token Economics Setup
    Token Staking System
    Troubleshooting
    Tunnel Protocol
    Username Reservation System
    Vercel
    Wallet
    WayForPay Payment Integration
    Web3 Integration
    Web3 Wallet
    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World
    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World
    White Label
    White-label & Customization
    White-label Success Stories
    Whitelabel Navigation
    Workflow

    🌾 Quick Access

    📖 Welcome to GreenFood.live
    👨‍🌾 Complete Farmer Guide
    🛒 Complete Buyer Guide
    💰 DAAR/DAARION Token System
    Ring Platform

    AI Self-Construct

    🏠
    Home
    EntitiesHot
    OpportunitiesNew
    Store
    Platform Concepts
    RING Economy
    Trinity Ukraine
    Global Impact
    AI Meets Web3
    Get Started
    Documentation
    Quick Start
    Deployment Calculator
    Offline
    v1.51•Trinity
    Privacy|Contact
    Ring Platform Logo

    Loading Documentation Hub...

    Scanning documentation library

    Documentation

    📚 Documentation

    Admin API
    Advanced Features
    AI Agent Customization
    API
    Api Examples
    Api Integration
    Apple Sign-in Integration
    Architecture
    Authentication
    Authentication
    Authentication
    Authentication Architecture
    Backup & Recovery
    Basic Setup
    Best Practices
    Branding
    CLI
    Code Structure
    Code Style
    Complete Customization Guide
    Components
    Contributing
    Custom Branding
    Customization
    Data Model
    Database Backend Selection
    Debugging
    Deployment
    Deployment
    Development
    Docker
    Email AI-CRM API
    Email AI-CRM Architecture
    Email AI-CRM System
    Email AI-CRM Tutorial
    Entities
    Entities
    Environment Configuration
    Examples
    Features
    Features
    First Success Validation
    Getting Started
    Installation
    Integrations
    Local Setup
    Localization
    Messaging API
    Mobile Experience
    Monitoring & Analytics
    Multi Tenant
    Multi-tenant Deployment
    Multi-Vendor Store
    News Module - Digital Newspaper Experience
    Next Steps
    NFT Marketplace
    Notifications
    Notifications API
    Opportunities
    Opportunities
    Payment Gateway Integration
    Payment Integration
    Performance
    Performance Optimization
    Performance Optimization Patterns
    Prerequisites
    Quick Start
    Quick Start - Your First Ring Clone
    Real Time
    Real World
    Security
    Security & Compliance
    Store API
    Testing
    Themes
    Token Economics Setup
    Token Staking System
    Troubleshooting
    Tunnel Protocol
    Username Reservation System
    Vercel
    Wallet
    WayForPay Payment Integration
    Web3 Integration
    Web3 Wallet
    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World
    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World
    White Label
    White-label & Customization
    White-label Success Stories
    Whitelabel Navigation
    Workflow

    🌾 Quick Access

    📖 Welcome to GreenFood.live
    👨‍🌾 Complete Farmer Guide
    🛒 Complete Buyer Guide
    💰 DAAR/DAARION Token System
    Ring Platform Logo

    Loading Documentation Hub...

    Scanning documentation library

    Documentation

    📚 Documentation

    Admin API
    Advanced Features
    AI Agent Customization
    API
    Api Examples
    Api Integration
    Apple Sign-in Integration
    Architecture
    Authentication
    Authentication
    Authentication
    Authentication Architecture
    Backup & Recovery
    Basic Setup
    Best Practices
    Branding
    CLI
    Code Structure
    Code Style
    Complete Customization Guide
    Components
    Contributing
    Custom Branding
    Customization
    Data Model
    Database Backend Selection
    Debugging
    Deployment
    Deployment
    Development
    Docker
    Email AI-CRM API
    Email AI-CRM Architecture
    Email AI-CRM System
    Email AI-CRM Tutorial
    Entities
    Entities
    Environment Configuration
    Examples
    Features
    Features
    First Success Validation
    Getting Started
    Installation
    Integrations
    Local Setup
    Localization
    Messaging API
    Mobile Experience
    Monitoring & Analytics
    Multi Tenant
    Multi-tenant Deployment
    Multi-Vendor Store
    News Module - Digital Newspaper Experience
    Next Steps
    NFT Marketplace
    Notifications
    Notifications API
    Opportunities
    Opportunities
    Payment Gateway Integration
    Payment Integration
    Performance
    Performance Optimization
    Performance Optimization Patterns
    Prerequisites
    Quick Start
    Quick Start - Your First Ring Clone
    Real Time
    Real World
    Security
    Security & Compliance
    Store API
    Testing
    Themes
    Token Economics Setup
    Token Staking System
    Troubleshooting
    Tunnel Protocol
    Username Reservation System
    Vercel
    Wallet
    WayForPay Payment Integration
    Web3 Integration
    Web3 Wallet
    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World
    Welcome to Ring Platform - Gateway Between Humanity and the Quantum World
    White Label
    White-label & Customization
    White-label Success Stories
    Whitelabel Navigation
    Workflow

    🌾 Quick Access

    📖 Welcome to GreenFood.live
    👨‍🌾 Complete Farmer Guide
    🛒 Complete Buyer Guide
    💰 DAAR/DAARION Token System

    About Us

    About our platform and services

    Quick Links

    • Entities
    • Opportunities
    • Contact
    • Documentation

    Contact

    195 Shevhenko Blvd, Cherkasy, Ukraine

    contact@ring.ck.ua

    +38 097 532 8801

    Follow Us

    © 2026 Ring

    Privacy PolicyTerms of Service

    About Us

    About our platform and services

    Quick Links

    • Entities
    • Opportunities
    • Contact
    • Documentation

    Contact

    195 Shevhenko Blvd, Cherkasy, Ukraine

    contact@ring.ck.ua

    +38 097 532 8801

    Follow Us

    © 2026 Ring

    Privacy PolicyTerms of Service
    Ring Platform Logo

    Завантаження документації...

    Підготовка контенту платформи Ring

    Ring Platform Logo

    Завантаження документації...

    Підготовка контенту платформи Ring

    Ring Platform Logo

    Завантаження документації...

    Підготовка контенту платформи Ring

    🚇 Tunnel Protocol

    Ring's Multi-Transport Real-Time Communication

    Tunnel Protocol is Ring Platform's intelligent real-time communication system - the Ring analog to Firebase Realtime Database. It provides unified real-time messaging across WebSocket, Server-Sent Events (SSE), Supabase Realtime, and Long-Polling transports with automatic fallback and Edge Runtime compatibility.

    🎯 Why Tunnel Protocol?

    The Problem with Firebase RTDB

    Firebase Realtime Database provides excellent real-time features but creates vendor lock-in:

    • ❌ Vendor Lock-in: Tied to Firebase infrastructure
    • ❌ Edge Runtime Incompatible: Cannot run on Vercel Edge
    • ❌ Cost Scaling: Pay-per-operation pricing
    • ❌ Limited Control: Cannot optimize for specific use cases
    • ❌ Single Transport: WebSocket only

    The Ring Solution: Tunnel Protocol

    ✅ Transport Abstraction: Unified API across 5+ transports
    ✅ Edge Runtime Compatible: SSE support for Vercel Edge
    ✅ Zero Vendor Lock-in: Use any backend (PostgreSQL, Supabase, Firebase)
    ✅ Intelligent Fallback: Automatic cascade on transport failures
    ✅ Cost Optimized: Self-hosted options, pay only for infrastructure
    ✅ Anonymous Support: Real-time features for unauthenticated users


    🏗️ Architecture Overview

    🚇 Tunnel Protocol

    Ring's Multi-Transport Real-Time Communication

    Tunnel Protocol is Ring Platform's intelligent real-time communication system - the Ring analog to Firebase Realtime Database. It provides unified real-time messaging across WebSocket, Server-Sent Events (SSE), Supabase Realtime, and Long-Polling transports with automatic fallback and Edge Runtime compatibility.

    🎯 Why Tunnel Protocol?

    The Problem with Firebase RTDB

    Firebase Realtime Database provides excellent real-time features but creates vendor lock-in:

    • ❌ Vendor Lock-in: Tied to Firebase infrastructure
    • ❌ Edge Runtime Incompatible: Cannot run on Vercel Edge
    • ❌ Cost Scaling: Pay-per-operation pricing
    • ❌ Limited Control: Cannot optimize for specific use cases
    • ❌ Single Transport: WebSocket only

    The Ring Solution: Tunnel Protocol

    ✅ Transport Abstraction: Unified API across 5+ transports
    ✅ Edge Runtime Compatible: SSE support for Vercel Edge
    ✅ Zero Vendor Lock-in: Use any backend (PostgreSQL, Supabase, Firebase)
    ✅ Intelligent Fallback: Automatic cascade on transport failures
    ✅ Cost Optimized: Self-hosted options, pay only for infrastructure
    ✅ Anonymous Support: Real-time features for unauthenticated users


    🏗️ Architecture Overview

    🚇 Tunnel Protocol

    Ring's Multi-Transport Real-Time Communication

    Tunnel Protocol is Ring Platform's intelligent real-time communication system - the Ring analog to Firebase Realtime Database. It provides unified real-time messaging across WebSocket, Server-Sent Events (SSE), Supabase Realtime, and Long-Polling transports with automatic fallback and Edge Runtime compatibility.

    🎯 Why Tunnel Protocol?

    The Problem with Firebase RTDB

    Firebase Realtime Database provides excellent real-time features but creates vendor lock-in:

    • ❌ Vendor Lock-in: Tied to Firebase infrastructure
    • ❌ Edge Runtime Incompatible: Cannot run on Vercel Edge
    • ❌ Cost Scaling: Pay-per-operation pricing
    • ❌ Limited Control: Cannot optimize for specific use cases
    • ❌ Single Transport: WebSocket only

    The Ring Solution: Tunnel Protocol

    ✅ Transport Abstraction: Unified API across 5+ transports
    ✅ Edge Runtime Compatible: SSE support for Vercel Edge
    ✅ Zero Vendor Lock-in: Use any backend (PostgreSQL, Supabase, Firebase)
    ✅ Intelligent Fallback: Automatic cascade on transport failures
    ✅ Cost Optimized: Self-hosted options, pay only for infrastructure
    ✅ Anonymous Support: Real-time features for unauthenticated users


    🏗️ Architecture Overview

    Ring Analog to Firebase RTDB

    Tunnel Protocol is Ring's equivalent to Firebase Realtime Database, providing the same real-time capabilities with multi-transport flexibility and zero vendor lock-in.

    Unified Transport API

    Ring Analog to Firebase RTDB

    Tunnel Protocol is Ring's equivalent to Firebase Realtime Database, providing the same real-time capabilities with multi-transport flexibility and zero vendor lock-in.

    Unified Transport API

    Ring Analog to Firebase RTDB

    Tunnel Protocol is Ring's equivalent to Firebase Realtime Database, providing the same real-time capabilities with multi-transport flexibility and zero vendor lock-in.

    Unified Transport API

    // Single API works across ALL transports
    import { publishToTunnel, subscribeToTunnel } from '@/lib/tunnel/publisher'
    
    // Publish message (works on any transport)
    await publishToTunnel(channel, eventType, data)
    
    // Subscribe to updates (works on any transport)
    const unsubscribe = subscribeToTunnel(channel, (message) => {
      console
    
    // Single API works across ALL transports
    import { publishToTunnel, subscribeToTunnel } from '@/lib/tunnel/publisher'
    
    // Publish message (works on any transport)
    await publishToTunnel(channel, eventType, data)
    
    // Subscribe to updates (works on any transport)
    const unsubscribe = subscribeToTunnel(channel, (message) => {
      console
    
    // Single API works across ALL transports
    import { publishToTunnel, subscribeToTunnel } from '@/lib/tunnel/publisher'
    
    // Publish message (works on any transport)
    await publishToTunnel(channel, eventType, data)
    
    // Subscribe to updates (works on any transport)
    const unsubscribe = subscribeToTunnel(channel, (message) => {
      console
    

    Supported Transports

    Supported Transports

    Supported Transports

    TransportLatencyThroughputUse Case
    WebSocket<50ms10K msg/sSelf-hosted, K8s clusters
    SSE<100ms1K msg/sVercel Edge Runtime
    Supabase Realtime<50ms5K msg/sSupabase deployments
    Firebase Realtime<200ms1K msg/sFirebase-full mode
    Long-Polling500ms-2s100 msg/sUltimate fallback
    TransportLatencyThroughputUse Case
    WebSocket<50ms10K msg/sSelf-hosted, K8s clusters
    SSE<100ms1K msg/sVercel Edge Runtime
    Supabase Realtime<50ms5K msg/sSupabase deployments
    Firebase Realtime<200ms1K msg/sFirebase-full mode
    Long-Polling500ms-2s100 msg/sUltimate fallback
    TransportLatencyThroughputUse Case
    WebSocket<50ms10K msg/sSelf-hosted, K8s clusters
    SSE<100ms1K msg/sVercel Edge Runtime
    Supabase Realtime<50ms5K msg/sSupabase deployments
    Firebase Realtime<200ms1K msg/sFirebase-full mode
    Long-Polling500ms-2s100 msg/sUltimate fallback

    🚀 Quick Start

    Publishing Real-Time Updates

    Replace Firebase RTDB calls with Tunnel:

    Before (Firebase RTDB):


    🚀 Quick Start

    Publishing Real-Time Updates

    Replace Firebase RTDB calls with Tunnel:

    Before (Firebase RTDB):


    🚀 Quick Start

    Publishing Real-Time Updates

    Replace Firebase RTDB calls with Tunnel:

    Before (Firebase RTDB):

    import { getAdminRtdb } from '@/lib/firebase-admin.server'
    
    const rtdb = getAdminRtdb()
    await rtdb.ref(`messages/${messageId}`).set(messageData)
    import { getAdminRtdb } from '@/lib/firebase-admin.server'
    
    const rtdb = getAdminRtdb()
    await rtdb.ref(`messages/${messageId}`).set(messageData)
    import { getAdminRtdb } from '@/lib/firebase-admin.server'
    
    const rtdb = getAdminRtdb()
    await rtdb.ref(`messages/${messageId}`).set(messageData)

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    import { publishToTunnel } from '@/lib/tunnel/publisher'
    
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', messageData)
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', messageData)
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', messageData)

    Subscribing to Updates

    Before (Firebase RTDB):

    Subscribing to Updates

    Before (Firebase RTDB):

    Subscribing to Updates

    Before (Firebase RTDB):

    const ref = rtdb.ref(`messages/${messageId}`)
    ref.on('value', (snapshot) => {
      const data = snapshot.val()
      handleUpdate(data)
    })
    const ref = rtdb.ref(`messages/${messageId}`)
    ref.on('value', (snapshot) => {
      const data = snapshot.val()
      handleUpdate(data)
    })
    const ref = rtdb.ref(`messages/${messageId}`)
    ref.on('value', (snapshot) => {
      const data = snapshot.val()
      handleUpdate(data)
    })

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    After (Tunnel Protocol):

    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    const unsubscribe = subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'message:new') {
        handleUpdate(message.payload)
    
    
    
    
    
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    const unsubscribe = subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'message:new') {
        handleUpdate(message.payload)
    
    
    
    
    
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    const unsubscribe = subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'message:new') {
        handleUpdate(message.payload)
    
    
    
    
    

    💡 Real-World Examples

    Example 1: Chat Messages

    Server-side (publish):


    💡 Real-World Examples

    Example 1: Chat Messages

    Server-side (publish):


    💡 Real-World Examples

    Example 1: Chat Messages

    Server-side (publish):

    'use server'
    
    import { initializeDatabase, getDatabaseService } from '@/lib/database/DatabaseService'
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    import { revalidatePath } from 'next/cache'
    
    export async function sendMessage(conversationId: string, content: string
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use server'
    
    import { initializeDatabase, getDatabaseService } from '@/lib/database/DatabaseService'
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    import { revalidatePath } from 'next/cache'
    
    export async function sendMessage(conversationId: string, content: string
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use server'
    
    import { initializeDatabase, getDatabaseService } from '@/lib/database/DatabaseService'
    import { publishToTunnel } from '@/lib/tunnel/publisher'
    import { revalidatePath } from 'next/cache'
    
    export async function sendMessage(conversationId: string, content: string
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    Client-side (subscribe):

    Client-side (subscribe):

    Client-side (subscribe):

    'use client'
    
    import { useEffect, useState } from 'react'
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    export function ChatMessages({ conversationId }) {
      const [messages, setMessages] = useState([])
      
      useEffect
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use client'
    
    import { useEffect, useState } from 'react'
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    export function ChatMessages({ conversationId }) {
      const [messages, setMessages] = useState([])
      
      useEffect
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    'use client'
    
    import { useEffect, useState } from 'react'
    import { subscribeToTunnel } from '@/lib/tunnel/client'
    
    export function ChatMessages({ conversationId }) {
      const [messages, setMessages] = useState([])
      
      useEffect
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    Example 2: Typing Indicators

    Publish typing status:

    Example 2: Typing Indicators

    Publish typing status:

    Example 2: Typing Indicators

    Publish typing status:

    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })

    Subscribe to typing:

    Subscribe to typing:

    Subscribe to typing:

    subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'typing:start') {
        showTypingIndicator(message.payload.userName)
      }
    })
    subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'typing:start') {
        showTypingIndicator(message.payload.userName)
      }
    })
    subscribeToTunnel(`conversation:${conversationId}`, (message) => {
      if (message.type === 'typing:start') {
        showTypingIndicator(message.payload.userName)
      }
    })

    Example 3: Like/Unlike Updates

    Publish like update:

    Example 3: Like/Unlike Updates

    Publish like update:

    Example 3: Like/Unlike Updates

    Publish like update:

    await publishToTunnel(`entity:${entityId}`, 'like:toggled', {
      likeCount: newCount,
      liked: true,
      userId
    })
    await publishToTunnel(`entity:${entityId}`, 'like:toggled', {
      likeCount: newCount,
      liked: true,
      userId
    })
    await publishToTunnel(`entity:${entityId}`, 'like:toggled', {
      likeCount: newCount,
      liked: true,
      userId
    })

    🎛️ Transport Selection

    Tunnel automatically selects optimal transport based on deployment:

    Kubernetes + PostgreSQL

    // Detected: postgres.*.svc.cluster.local
    // Selected: WebSocket (wss://)
    // Fallback: Long-Polling

    Vercel Edge Runtime

    // Detected: VERCEL=1
    // Selected: SSE (Edge compatible)
    // Fallback: Long-Polling

    Supabase Deployment

    // Detected: SUPABASE_URL configured
    // Selected: Supabase Realtime
    // Fallback: SSE → Long-Polling

    Firebase Mode


    🎛️ Transport Selection

    Tunnel automatically selects optimal transport based on deployment:

    Kubernetes + PostgreSQL

    // Detected: postgres.*.svc.cluster.local
    // Selected: WebSocket (wss://)
    // Fallback: Long-Polling

    Vercel Edge Runtime

    // Detected: VERCEL=1
    // Selected: SSE (Edge compatible)
    // Fallback: Long-Polling

    Supabase Deployment

    // Detected: SUPABASE_URL configured
    // Selected: Supabase Realtime
    // Fallback: SSE → Long-Polling

    Firebase Mode


    🎛️ Transport Selection

    Tunnel automatically selects optimal transport based on deployment:

    Kubernetes + PostgreSQL

    // Detected: postgres.*.svc.cluster.local
    // Selected: WebSocket (wss://)
    // Fallback: Long-Polling

    Vercel Edge Runtime

    // Detected: VERCEL=1
    // Selected: SSE (Edge compatible)
    // Fallback: Long-Polling

    Supabase Deployment

    // Detected: SUPABASE_URL configured
    // Selected: Supabase Realtime
    // Fallback: SSE → Long-Polling

    Firebase Mode

    // Detected: DB_BACKEND_MODE=firebase-full
    // Selected: Firebase Realtime
    // Fallback: SSE → Long-Polling

    🔧 Configuration

    Environment Variables

    // Detected: DB_BACKEND_MODE=firebase-full
    // Selected: Firebase Realtime
    // Fallback: SSE → Long-Polling

    🔧 Configuration

    Environment Variables

    // Detected: DB_BACKEND_MODE=firebase-full
    // Selected: Firebase Realtime
    // Fallback: SSE → Long-Polling

    🔧 Configuration

    Environment Variables

    # Transport selection (optional - auto-detected)
    NEXT_PUBLIC_TUNNEL_TRANSPORT=websocket # or sse, supabase, firebase
    
    # WebSocket configuration
    TUNNEL_WEBSOCKET_URL=wss://your-domain.com/api/tunnel/ws
    
    # SSE configuration (Edge Runtime)
    TUNNEL_SSE_URL=https://your-domain.com/api/tunnel/sse
    
    # Fallback settings
    TUNNEL_ENABLE_FALLBACK=true
    TUNNEL_FALLBACK_TIMEOUT=5000 # 5 seconds
    # Transport selection (optional - auto-detected)
    NEXT_PUBLIC_TUNNEL_TRANSPORT=websocket # or sse, supabase, firebase
    
    # WebSocket configuration
    TUNNEL_WEBSOCKET_URL=wss://your-domain.com/api/tunnel/ws
    
    # SSE configuration (Edge Runtime)
    TUNNEL_SSE_URL=https://your-domain.com/api/tunnel/sse
    
    # Fallback settings
    TUNNEL_ENABLE_FALLBACK=true
    TUNNEL_FALLBACK_TIMEOUT=5000 # 5 seconds
    # Transport selection (optional - auto-detected)
    NEXT_PUBLIC_TUNNEL_TRANSPORT=websocket # or sse, supabase, firebase
    
    # WebSocket configuration
    TUNNEL_WEBSOCKET_URL=wss://your-domain.com/api/tunnel/ws
    
    # SSE configuration (Edge Runtime)
    TUNNEL_SSE_URL=https://your-domain.com/api/tunnel/sse
    
    # Fallback settings
    TUNNEL_ENABLE_FALLBACK=true
    TUNNEL_FALLBACK_TIMEOUT=5000 # 5 seconds

    Backend Mode Integration

    Tunnel respects your database backend mode:

    Backend Mode Integration

    Tunnel respects your database backend mode:

    Backend Mode Integration

    Tunnel respects your database backend mode:

    // lib/database/backend-mode-config.ts
    export const BACKEND_MODES = {
      'k8s-postgres-fcm': {
        tunnel: 'websocket' // Primary transport
      },
      'firebase-full': {
        tunnel: 'firebase' // Use Firebase Realtime
      },
      'supabase-fcm': {
    
    
    
    // lib/database/backend-mode-config.ts
    export const BACKEND_MODES = {
      'k8s-postgres-fcm': {
        tunnel: 'websocket' // Primary transport
      },
      'firebase-full': {
        tunnel: 'firebase' // Use Firebase Realtime
      },
      'supabase-fcm': {
    
    
    
    // lib/database/backend-mode-config.ts
    export const BACKEND_MODES = {
      'k8s-postgres-fcm': {
        tunnel: 'websocket' // Primary transport
      },
      'firebase-full': {
        tunnel: 'firebase' // Use Firebase Realtime
      },
      'supabase-fcm': {
    
    
    

    📊 Performance Characteristics

    Latency Comparison


    📊 Performance Characteristics

    Latency Comparison


    📊 Performance Characteristics

    Latency Comparison

    WebSocket:          <50ms   // Best for self-hosted
    SSE:                <100ms  // Best for Edge Runtime
    Supabase Realtime:  <50ms   // Best for Supabase deployments
    Firebase Realtime:  <200ms  // When using Firebase mode
    Long-Polling:       500ms-2s // Universal fallback
    WebSocket:          <50ms   // Best for self-hosted
    SSE:                <100ms  // Best for Edge Runtime
    Supabase Realtime:  <50ms   // Best for Supabase deployments
    Firebase Realtime:  <200ms  // When using Firebase mode
    Long-Polling:       500ms-2s // Universal fallback
    WebSocket:          <50ms   // Best for self-hosted
    SSE:                <100ms  // Best for Edge Runtime
    Supabase Realtime:  <50ms   // Best for Supabase deployments
    Firebase Realtime:  <200ms  // When using Firebase mode
    Long-Polling:       500ms-2s // Universal fallback

    Throughput Comparison

    Throughput Comparison

    Throughput Comparison

    WebSocket:          10,000 messages/second
    SSE:                1,000 messages/second
    Supabase Realtime:  5,000 messages/second
    Firebase Realtime:  1,000 messages/second
    Long-Polling:       100 messages/second
    WebSocket:          10,000 messages/second
    SSE:                1,000 messages/second
    Supabase Realtime:  5,000 messages/second
    Firebase Realtime:  1,000 messages/second
    Long-Polling:       100 messages/second
    WebSocket:          10,000 messages/second
    SSE:                1,000 messages/second
    Supabase Realtime:  5,000 messages/second
    Firebase Realtime:  1,000 messages/second
    Long-Polling:       100 messages/second

    🛡️ Security Features

    Encrypted Channels

    All transports support encryption:


    🛡️ Security Features

    Encrypted Channels

    All transports support encryption:


    🛡️ Security Features

    Encrypted Channels

    All transports support encryption:

    await publishToTunnel(`secure:${userId}`, 'sensitive:data', {
      encrypted: true,
      data: encryptedPayload
    })
    await publishToTunnel(`secure:${userId}`, 'sensitive:data', {
      encrypted: true,
      data: encryptedPayload
    })
    await publishToTunnel(`secure:${userId}`, 'sensitive:data', {
      encrypted: true,
      data: encryptedPayload
    })

    Rate Limiting

    Built-in protection against abuse:

    Rate Limiting

    Built-in protection against abuse:

    Rate Limiting

    Built-in protection against abuse:

    // Automatic rate limiting per user/IP
    Max 100 messages/minute per user
    Max 1000 messages/minute per IP
    // Automatic rate limiting per user/IP
    Max 100 messages/minute per user
    Max 1000 messages/minute per IP
    // Automatic rate limiting per user/IP
    Max 100 messages/minute per user
    Max 1000 messages/minute per IP

    DDoS Protection

    Transport-level protection:

    • Connection limits per IP
    • Message size limits
    • Automatic ban for abusive patterns

    🎯 Migration Guide

    From Firebase RTDB

    DDoS Protection

    Transport-level protection:

    • Connection limits per IP
    • Message size limits
    • Automatic ban for abusive patterns

    🎯 Migration Guide

    From Firebase RTDB

    DDoS Protection

    Transport-level protection:

    • Connection limits per IP
    • Message size limits
    • Automatic ban for abusive patterns

    🎯 Migration Guide

    From Firebase RTDB

    Firebase RTDBTunnel Protocol
    rtdb.ref(path).set(data)publishToTunnel(channel, type, data)
    rtdb.ref(path).on('value', cb)subscribeToTunnel(channel, cb)
    rtdb.ref(path).off()unsubscribe()
    rtdb.ref(path).onDisconnect()Handled by transport layer
    Firebase RTDBTunnel Protocol
    rtdb.ref(path).set(data)publishToTunnel(channel, type, data)
    rtdb.ref(path).on('value', cb)subscribeToTunnel(channel, cb)
    rtdb.ref(path).off()unsubscribe()
    rtdb.ref(path).onDisconnect()Handled by transport layer
    Firebase RTDBTunnel Protocol
    rtdb.ref(path).set(data)publishToTunnel(channel, type, data)
    rtdb.ref(path).on('value', cb)subscribeToTunnel(channel, cb)
    rtdb.ref(path).off()unsubscribe()
    rtdb.ref(path).onDisconnect()Handled by transport layer

    Code Example

    Before:

    Code Example

    Before:

    Code Example

    Before:

    const rtdb = getAdminRtdb()
    await rtdb.ref(`typing/${conversationId}/${userId}`).set(typingData)
    await rtdb.ref(`typing/${conversationId}/${userId}`).
    const rtdb = getAdminRtdb()
    await rtdb.ref(`typing/${conversationId}/${userId}`).set(typingData)
    await rtdb.ref(`typing/${conversationId}/${userId}`).
    const rtdb = getAdminRtdb()
    await rtdb.ref(`typing/${conversationId}/${userId}`).set(typingData)
    await rtdb.ref(`typing/${conversationId}/${userId}`).

    After:

    After:

    After:

    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    // Disconnect handling automatic in Tunnel transport layer
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    // Disconnect handling automatic in Tunnel transport layer
    await publishToTunnel(`conversation:${conversationId}`, 'typing:start', {
      userId,
      userName,
      timestamp: Date.now()
    })
    // Disconnect handling automatic in Tunnel transport layer

    🔥 Advanced Features

    Message Types

    Tunnel supports typed messages:


    🔥 Advanced Features

    Message Types

    Tunnel supports typed messages:


    🔥 Advanced Features

    Message Types

    Tunnel supports typed messages:

    type TunnelMessageType = 
      | 'DATA'          // Generic data
      | 'NOTIFICATION'  // Push notifications
      | 'MESSAGE'       // Chat messages
      | 'PRESENCE'      // User presence/typing
      | 'HEARTBEAT'     // Keep-alive
      | 'ACK'           // Acknowledgments
      | '
    
    
    
    
    type TunnelMessageType = 
      | 'DATA'          // Generic data
      | 'NOTIFICATION'  // Push notifications
      | 'MESSAGE'       // Chat messages
      | 'PRESENCE'      // User presence/typing
      | 'HEARTBEAT'     // Keep-alive
      | 'ACK'           // Acknowledgments
      | '
    
    
    
    
    type TunnelMessageType = 
      | 'DATA'          // Generic data
      | 'NOTIFICATION'  // Push notifications
      | 'MESSAGE'       // Chat messages
      | 'PRESENCE'      // User presence/typing
      | 'HEARTBEAT'     // Keep-alive
      | 'ACK'           // Acknowledgments
      | '
    
    
    
    

    Channel Patterns

    Organize channels by feature:

    Channel Patterns

    Organize channels by feature:

    Channel Patterns

    Organize channels by feature:

    `conversation:${id}`     // Chat conversations
    `entity:${id}`           // Entity updates
    `opportunity:${id}`      // Opportunity updates
    `user:${id}`             // User-specific channel
    `typing:${conversationId}` // Typing indicators
    `presence:${
    
    `conversation:${id}`     // Chat conversations
    `entity:${id}`           // Entity updates
    `opportunity:${id}`      // Opportunity updates
    `user:${id}`             // User-specific channel
    `typing:${conversationId}` // Typing indicators
    `presence:${
    
    `conversation:${id}`     // Chat conversations
    `entity:${id}`           // Entity updates
    `opportunity:${id}`      // Opportunity updates
    `user:${id}`             // User-specific channel
    `typing:${conversationId}` // Typing indicators
    `presence:${
    

    🎖️ Best Practices Summary


    🎖️ Best Practices Summary


    🎖️ Best Practices Summary

    Tunnel Protocol Best Practices
    1. Use Tunnel for real-time, DatabaseService for persistence
    2. Channel naming: Use feature:id pattern
    3. Message types: Use semantic types (message:new, typing:start, etc.)
    4. Error handling: Tunnel failures should not break core functionality
    5. React 19: Combine with revalidatePath() for cache updates
    6. Performance: Tunnel is async, don't await unless critical
    7. Cleanup: Always unsubscribe in useEffect cleanup
    Tunnel Protocol Best Practices
    1. Use Tunnel for real-time, DatabaseService for persistence
    2. Channel naming: Use feature:id pattern
    3. Message types: Use semantic types (message:new, typing:start, etc.)
    4. Error handling: Tunnel failures should not break core functionality
    5. React 19: Combine with revalidatePath() for cache updates
    6. Performance: Tunnel is async, don't await unless critical
    7. Cleanup: Always unsubscribe in useEffect cleanup
    Tunnel Protocol Best Practices
    1. Use Tunnel for real-time, DatabaseService for persistence
    2. Channel naming: Use feature:id pattern
    3. Message types: Use semantic types (message:new, typing:start, etc.)
    4. Error handling: Tunnel failures should not break core functionality
    5. React 19: Combine with revalidatePath() for cache updates
    6. Performance: Tunnel is async, don't await unless critical
    7. Cleanup: Always unsubscribe in useEffect cleanup

    Built by Legion Commander for Emperor Ray
    Ring analog to Firebase RTDB - Zero vendor lock-in - Maximum flexibility
    🔥⚔️👑

    .
    log
    (
    '
    Received:
    '
    ,
    message
    )
    })
    }
    })
    // Cleanup
    unsubscribe()
    )
    {
    await initializeDatabase()
    const db = getDatabaseService()

    Built by Legion Commander for Emperor Ray
    Ring analog to Firebase RTDB - Zero vendor lock-in - Maximum flexibility
    🔥⚔️👑

    .
    log
    (
    '
    Received:
    '
    ,
    message
    )
    })
    }
    })
    // Cleanup
    unsubscribe()
    )
    {
    await initializeDatabase()
    const db = getDatabaseService()

    Built by Legion Commander for Emperor Ray
    Ring analog to Firebase RTDB - Zero vendor lock-in - Maximum flexibility
    🔥⚔️👑

    .
    log
    (
    '
    Received:
    '
    ,
    message
    )
    })
    }
    })
    // Cleanup
    unsubscribe()
    )
    {
    await initializeDatabase()
    const db = getDatabaseService()
    // Save to database (persistence)
    // Save to database (persistence)
    // Save to database (persistence)
    const result = await db.create('messages', {
    const result = await db.create('messages', {
    const result = await db.create('messages', {
    conversationId,
    content,
    timestamp: new Date()
    })
    if (!result.success) throw result.error
    // Publish real-time update (Tunnel replaces Firebase RTDB)
    conversationId,
    content,
    timestamp: new Date()
    })
    if (!result.success) throw result.error
    // Publish real-time update (Tunnel replaces Firebase RTDB)
    conversationId,
    content,
    timestamp: new Date()
    })
    if (!result.success) throw result.error
    // Publish real-time update (Tunnel replaces Firebase RTDB)
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', {
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', {
    await publishToTunnel(`conversation:${conversationId}`, 'message:new', {
    id: result.data.id,
    content,
    timestamp: Date.now()
    })
    // Revalidate (React 19 pattern)
    revalidatePath(`/[locale]/chat/${conversationId}`)
    return result.data
    id: result.data.id,
    content,
    timestamp: Date.now()
    })
    // Revalidate (React 19 pattern)
    revalidatePath(`/[locale]/chat/${conversationId}`)
    return result.data
    id: result.data.id,
    content,
    timestamp: Date.now()
    })
    // Revalidate (React 19 pattern)
    revalidatePath(`/[locale]/chat/${conversationId}`)
    return result.data
    }
    (
    ()
    =>
    {
    // Subscribe to real-time updates
    const unsubscribe = subscribeToTunnel(
    `conversation:${conversationId}`,
    (message) => {
    if (message.type === 'message:new') {
    }
    (
    ()
    =>
    {
    // Subscribe to real-time updates
    const unsubscribe = subscribeToTunnel(
    `conversation:${conversationId}`,
    (message) => {
    if (message.type === 'message:new') {
    }
    (
    ()
    =>
    {
    // Subscribe to real-time updates
    const unsubscribe = subscribeToTunnel(
    `conversation:${conversationId}`,
    (message) => {
    if (message.type === 'message:new') {
    setMessages(prev => [...prev, message.payload])
    }
    }
    )
    return () => unsubscribe()
    }, [conversationId])
    setMessages(prev => [...prev, message.payload])
    }
    }
    )
    return () => unsubscribe()
    }, [conversationId])
    setMessages(prev => [...prev, message.payload])
    }
    }
    )
    return () => unsubscribe()
    }, [conversationId])
    return <div>{messages.map(msg => <Message key={msg.id} {...msg} />)}</div>
    return <div>{messages.map(msg => <Message key={msg.id} {...msg} />)}</div>
    return <div>{messages.map(msg => <Message key={msg.id} {...msg} />)}</div>
    }
    tunnel
    :
    '
    supabase
    '
    // Use Supabase Realtime
    }
    }
    onDisconnect
    ()
    .
    remove
    ()
    ERROR
    '
    // Error messages
    | 'AUTH' // Authentication
    | 'DB_INSERT' // Database insert event
    | 'DB_UPDATE' // Database update event
    }
    tunnel
    :
    '
    supabase
    '
    // Use Supabase Realtime
    }
    }
    onDisconnect
    ()
    .
    remove
    ()
    ERROR
    '
    // Error messages
    | 'AUTH' // Authentication
    | 'DB_INSERT' // Database insert event
    | 'DB_UPDATE' // Database update event
    }
    tunnel
    :
    '
    supabase
    '
    // Use Supabase Realtime
    }
    }
    onDisconnect
    ()
    .
    remove
    ()
    ERROR
    '
    // Error messages
    | 'AUTH' // Authentication
    | 'DB_INSERT' // Database insert event
    | 'DB_UPDATE' // Database update event
    | 'DB_DELETE' // Database delete event
    userId
    }
    `
    // User presence
    `global:announcements` // Broadcast channel
    | 'DB_DELETE' // Database delete event
    userId
    }
    `
    // User presence
    `global:announcements` // Broadcast channel
    | 'DB_DELETE' // Database delete event
    userId
    }
    `
    // User presence
    `global:announcements` // Broadcast channel