Skip to content
All field notes

5 min read

Implementing Real-Time Video Streaming for Livestock Auctions

A technical deep dive into the challenges and solutions of building a reliable video streaming system for CattleUSA

  • WebRTC
  • WebSockets
  • Video Streaming
  • Real-Time Communication
  • Angular

"Low-latency video technologies are foundational to live selling. Without speedy video delivery, interactivity just isn't possible. Real-time video enables engagement via questions, comments, and bids — resulting in an immersive experience." — Wowza, Video Streaming Platform

One of the most technically challenging aspects of building the CattleUSA platform was implementing a reliable, low-latency video streaming system for livestock auctions. This post details the architecture, implementation, and optimization of the video streaming system that powers CattleUSA's virtual auctions. According to Fortune Business Insights (2025), the global WebRTC market size is projected to grow from $9.56 billion in 2025 to $94.07 billion by 2032, at a CAGR of 38.6% during the forecast period, underscoring the rapidly growing demand for real-time communication technologies.

The Challenge

Livestock auctions have unique requirements that make video streaming particularly challenging:

  1. Low Latency: Bidders need to see the livestock in real-time to make informed decisions. Even a few seconds of delay can result in missed opportunities.

  2. Variable Network Conditions: Users access the platform from various locations, including rural areas with limited connectivity.

  3. Multiple Concurrent Streams: A single auction may have multiple camera angles or multiple auctions happening simultaneously.

  4. High Reliability: Auctions are time-sensitive events where downtime or technical issues can have significant financial implications.

  5. Quality Requirements: Bidders need to clearly see the livestock to assess their quality and make informed bids.

Technical Architecture

After evaluating various technologies, we implemented a hybrid solution using WebRTC for low-latency streaming and WebSockets for signaling and real-time data exchange.

WebRTC Implementation

WebRTC (Web Real-Time Communication) was chosen as the primary technology for video streaming due to its:

  • Peer-to-peer architecture that reduces server load
  • Built-in support for adaptive bitrate streaming
  • Low-latency capabilities (typically under 500ms)
  • Native support in modern browsers without plugins

The implementation involved:

TypeScript
// Simplified WebRTC connection setup
export class VideoStreamComponent implements OnInit, OnDestroy {
  private peerConnection: RTCPeerConnection;
  private dataChannel: RTCDataChannel;
  
  constructor(private signalService: SignalService) {}
  
  async initConnection(streamId: string): Promise<void> {
    // Create peer connection with STUN/TURN servers for NAT traversal
    this.peerConnection = new RTCPeerConnection({
      iceServers: [
        { urls: 'stun:stun.cattleusa.com:3478' },
        {
          urls: 'turn:turn.cattleusa.com:3478',
          username: 'cattleusa',
          credential: 'dynamicTokenHere'
        }
      ]
    });
    
    // Set up event handlers
    this.peerConnection.onicecandidate = (event) => {
      if (event.candidate) {
        this.signalService.sendIceCandidate(streamId, event.candidate);
      }
    };
    
    this.peerConnection.ontrack = (event) => {
      // Attach the remote stream to the video element
      const videoElement = document.getElementById('auction-video') as HTMLVideoElement;
      if (videoElement.srcObject !== event.streams[0]) {
        videoElement.srcObject = event.streams[0];
      }
    };
    
    // Create data channel for bidding and other real-time data
    this.dataChannel = this.peerConnection.createDataChannel('bidding');
    this.setupDataChannel();
    
    // Connect to the signaling server and start the handshake process
    await this.signalService.connect(streamId);
  }
  
  // ... additional methods for handling signaling, ICE candidates, etc.
}

WebSocket Signaling

WebSockets provide the signaling mechanism for WebRTC and handle real-time auction data:

TypeScript
// Simplified WebSocket signaling service
export class SignalService {
  private socket: WebSocket;
  
  connect(streamId: string): Promise<void> {
    return new Promise((resolve, reject) => {
      this.socket = new WebSocket(`wss://signal.cattleusa.com/ws/${streamId}`);
      
      this.socket.onopen = () => {
        console.log('WebSocket connection established');
        resolve();
      };
      
      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        reject(error);
      };
      
      this.socket.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.handleSignalingMessage(message);
      };
    });
  }
  
  sendOffer(streamId: string, offer: RTCSessionDescriptionInit): void {
    this.socket.send(JSON.stringify({
      type: 'offer',
      streamId,
      offer
    }));
  }
  
  sendAnswer(streamId: string, answer: RTCSessionDescriptionInit): void {
    this.socket.send(JSON.stringify({
      type: 'answer',
      streamId,
      answer
    }));
  }
  
  sendIceCandidate(streamId: string, candidate: RTCIceCandidate): void {
    this.socket.send(JSON.stringify({
      type: 'ice-candidate',
      streamId,
      candidate
    }));
  }
  
  // ... additional methods for handling different message types
}

Optimizations for Reliability

Several optimizations were implemented to ensure reliable streaming:

1. Adaptive Bitrate Streaming

We implemented adaptive bitrate streaming to dynamically adjust video quality based on network conditions:

TypeScript
// Simplified adaptive bitrate implementation
private setupAdaptiveBitrate(): void {
  // Monitor connection quality
  setInterval(() => {
    const stats = this.peerConnection.getStats();
    stats.then((report) => {
      report.forEach((stat) => {
        if (stat.type === 'inbound-rtp' && stat.kind === 'video') {
          const packetsLost = stat.packetsLost;
          const packetsReceived = stat.packetsReceived;
          const lossRate = packetsLost / (packetsLost + packetsReceived);
          
          // Adjust video quality based on loss rate
          if (lossRate > 0.08) {
            this.requestLowerQuality();
          } else if (lossRate < 0.02) {
            this.requestHigherQuality();
          }
        }
      });
    });
  }, 5000);
}

2. Connection Resilience

To handle network interruptions, we implemented automatic reconnection logic:

TypeScript
private setupConnectionResilience(): void {
  // Monitor connection state
  this.peerConnection.oniceconnectionstatechange = () => {
    const state = this.peerConnection.iceConnectionState;
    
    if (state === 'disconnected' || state === 'failed') {
      console.log('Connection lost, attempting to reconnect...');
      this.reconnect();
    }
  };
}

private async reconnect(): Promise<void> {
  // Close existing connection
  this.peerConnection.close();
  
  // Wait a moment before reconnecting
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  // Reinitialize the connection
  await this.initConnection(this.currentStreamId);
}

3. STUN/TURN Server Infrastructure

We deployed a global network of STUN and TURN servers to facilitate connections through firewalls and NATs:

  • Primary STUN servers in US East, US West, and Central US regions
  • TURN servers in multiple regions for fallback when direct connections fail
  • Automatic server selection based on user location and network conditions

Mobile Optimization

The video streaming system was optimized for mobile devices, which are increasingly used by bidders:

  1. Bandwidth Detection: Automatically detecting available bandwidth and adjusting stream quality
  2. Battery Optimization: Reducing resolution and frame rate when the device is on battery power
  3. Touch Interface: Implementing touch-friendly controls for video playback
  4. Background Mode: Continuing audio streaming when the app is in the background

Results and Impact

The implementation of this video streaming system has had significant impacts:

  1. Increased Participation: Remote bidders can now participate in auctions from anywhere, increasing the number of bidders by over 200%.
  2. Reduced Latency: Average streaming latency was reduced from 10+ seconds (with traditional HLS/DASH) to under 500ms.
  3. Higher Reliability: Connection success rate improved to 99.8%, even in areas with limited connectivity.
  4. Scalability: The system now supports over 500 concurrent viewers per auction without quality degradation.

"Participants place bids in real-time, both in-person and online, under an auctioneer's supervision, fostering a competitive environment that can drive higher bids." — Dolby.io, Real-Time Streaming Platform

These results align with broader industry trends. According to webrtcHacks, WebRTC usage saw a dramatic increase of up to 100x during the pandemic, demonstrating the technology's critical role in enabling real-time communication. This widespread adoption has validated our choice of WebRTC for CattleUSA's video streaming system, as it continues to be the leading technology for low-latency, browser-based video communication.

Lessons Learned

Implementing real-time video streaming for livestock auctions taught us several valuable lessons:

  1. WebRTC Complexity: While powerful, WebRTC requires careful implementation and extensive testing across different browsers and network conditions.
  2. Signaling Infrastructure: A robust signaling server is critical for reliable WebRTC connections.
  3. Fallback Mechanisms: Always implement fallback mechanisms for users with unsupported browsers or extreme network limitations.
  4. User Experience: Technical performance metrics matter, but user perception of quality and reliability is equally important.

Conclusion

Building a reliable, low-latency video streaming system for livestock auctions was a significant technical challenge that required innovative solutions and careful optimization. The resulting system has transformed how livestock auctions operate, enabling remote participation and expanding market reach for sellers.

This project demonstrates how modern web technologies like WebRTC and WebSockets can be leveraged to create real-time applications that were previously only possible with native applications or specialized hardware.