AgentShield
JavaScript Beacon

Worker Mode

Optimize performance with WebWorker support in AgentShield Beacon

Overview

WebWorker mode moves beacon processing to a background thread, ensuring zero impact on your application's UI performance. This is especially important for high-traffic applications or those with complex interactions.

Benefits

Performance Advantages

  • Non-blocking execution - Main thread remains responsive
  • Parallel processing - Events processed while UI renders
  • Better batching - Efficient queue management in background
  • Improved reliability - Isolated from main thread errors
  • Resource optimization - Better memory management

When to Use Worker Mode

ScenarioWorker ModeDirect Mode
High-traffic siteRecommendedMay impact performance
Complex UI interactionsRecommendedUse with caution
Real-time applicationsRecommendedAvoid
Simple static siteOptionalSufficient
Legacy browsersNot supportedFallback

Basic Setup

Automatic Worker Mode

// Worker mode is enabled by default
const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true, // Default: true
});

// The beacon automatically:
// 1. Creates a worker instance
// 2. Establishes communication channel
// 3. Falls back if workers unavailable

Custom Worker URL

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  workerUrl: '/static/beacon-worker.js', // Custom location
});

Inline Worker (Blob URL)

// For CSP-restricted environments
const workerCode = `
  self.addEventListener('message', (event) => {
    // Worker logic
  });
`;

const blob = new Blob([workerCode], { type: 'application/javascript' });
const workerUrl = URL.createObjectURL(blob);

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  workerUrl: workerUrl,
});

Worker Configuration

Health Monitoring

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  workerConfig: {
    // Health check configuration
    heartbeatInterval: 5000, // Check every 5 seconds
    maxUnhealthyCount: 3, // Restart after 3 failures
    healthCheckTimeout: 1000, // Health check timeout

    // Auto-restart configuration
    maxRestartAttempts: 3, // Maximum restart attempts
    restartDelay: 2000, // Delay between restarts
    restartBackoff: true, // Exponential backoff
  },
});

Message Compression

Compression reduces message size by up to 70%, improving performance for large event payloads.

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  workerConfig: {
    enableCompression: true, // Enable compression
    compressionThreshold: 1024, // Compress if > 1KB
    compressionLevel: 6, // 1-9 (speed vs size)
  },
});

Memory Management

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  workerConfig: {
    maxMemoryUsage: 10485760, // 10MB limit
    gcInterval: 30000, // Garbage collection interval
    maxQueueSize: 1000, // Maximum queued events
    queueStrategy: 'drop-oldest', // What to do when full
  },
});

Worker Lifecycle

Initialization

// Monitor worker initialization
const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  onWorkerInit: (worker) => {
    console.log('Worker initialized:', worker);
  },
  onWorkerError: (error) => {
    console.error('Worker error:', error);
    // Automatically falls back to direct mode
  },
});

State Management

// Check worker state
if (beacon.isWorkerActive()) {
  console.log('Worker is running');
}

// Get worker statistics
const stats = await beacon.getWorkerStats();
console.log('Worker stats:', {
  eventsProcessed: stats.eventsProcessed,
  memoryUsage: stats.memoryUsage,
  uptime: stats.uptime,
  errors: stats.errors,
});

Termination

// Graceful shutdown
beacon.destroy(); // Automatically terminates worker

// Force terminate worker
beacon.terminateWorker();

// Restart worker
beacon.restartWorker();

Communication Protocol

Message Types

// Worker receives these message types
const messageTypes = {
  INIT: 'init', // Initialize worker
  EVENT: 'event', // Track event
  BATCH: 'batch', // Send batch
  FLUSH: 'flush', // Force flush
  CONFIG: 'config', // Update config
  PING: 'ping', // Health check
  TERMINATE: 'terminate', // Shutdown
};

// Worker sends these message types
const responseTypes = {
  READY: 'ready', // Worker ready
  SUCCESS: 'success', // Operation successful
  ERROR: 'error', // Operation failed
  STATS: 'stats', // Statistics update
  PONG: 'pong', // Health response
};

Custom Worker Implementation

// beacon-worker.js
let config = {};
let eventQueue = [];
let flushTimer = null;

self.addEventListener('message', async (event) => {
  const { type, data } = event.data;

  switch (type) {
    case 'init':
      config = data;
      self.postMessage({ type: 'ready' });
      break;

    case 'event':
      eventQueue.push(data);
      if (eventQueue.length >= config.batchSize) {
        await flush();
      } else {
        scheduleFlush();
      }
      break;

    case 'flush':
      await flush();
      break;

    case 'ping':
      self.postMessage({ type: 'pong', timestamp: Date.now() });
      break;
  }
});

function scheduleFlush() {
  if (flushTimer) return;

  flushTimer = setTimeout(async () => {
    await flush();
    flushTimer = null;
  }, config.flushInterval);
}

async function flush() {
  if (eventQueue.length === 0) return;

  const batch = eventQueue.splice(0, config.batchSize);

  try {
    const response = await fetch(config.endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': config.apiKey,
      },
      body: JSON.stringify({ events: batch }),
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    self.postMessage({
      type: 'success',
      count: batch.length,
    });
  } catch (error) {
    self.postMessage({
      type: 'error',
      error: error.message,
    });

    // Re-queue events for retry
    eventQueue.unshift(...batch);
  }
}

Fallback Strategies

Automatic Fallback

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  fallbackMode: 'auto', // Automatic fallback
  onFallback: (reason) => {
    console.log('Falling back to direct mode:', reason);
    // Reasons: 'not-supported', 'error', 'timeout'
  },
});

Manual Fallback Control

// Check worker support
if (!('Worker' in window)) {
  console.log('Workers not supported');
  beacon.updateConfig({ useWorker: false });
}

// Force fallback on error
beacon.on('worker:error', (error) => {
  if (error.critical) {
    beacon.disableWorker();
  }
});

Progressive Enhancement

function createBeacon() {
  const hasWorkerSupport = 'Worker' in window;
  const isModernBrowser = 'requestIdleCallback' in window;

  return new AgentShieldBeacon({
    apiKey: 'your-api-key',
    useWorker: hasWorkerSupport,
    fallbackMode: isModernBrowser ? 'idle' : 'direct',
  });
}

Performance Optimization

Batch Optimization

// Optimize for high-traffic
const highTrafficConfig = {
  apiKey: 'your-api-key',
  useWorker: true,
  batchSize: 100,
  flushInterval: 10000,
  workerConfig: {
    enableCompression: true,
    maxQueueSize: 5000,
  },
};

// Optimize for real-time
const realTimeConfig = {
  apiKey: 'your-api-key',
  useWorker: true,
  batchSize: 1,
  flushInterval: 1000,
  workerConfig: {
    enableCompression: false, // Reduce latency
  },
};

Memory Optimization

// Monitor and control memory usage
const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  workerConfig: {
    maxMemoryUsage: 5242880, // 5MB
    onMemoryWarning: (usage) => {
      console.warn(`Worker memory high: ${usage} bytes`);
      beacon.flush(); // Force flush to free memory
    },
  },
});

CPU Optimization

// Throttle processing in worker
const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  workerConfig: {
    processingDelay: 100, // Delay between batches
    maxConcurrent: 2, // Max concurrent requests
    priorityQueue: true, // Process high-priority first
  },
});

Debugging Worker Mode

Enable Debug Logging

const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  debug: true,
  logLevel: 'debug',
  workerConfig: {
    debug: true, // Enable worker debug logs
  },
});

Chrome DevTools

  1. Open Chrome DevTools
  2. Go to Sources tab
  3. Find worker in left panel under "Workers"
  4. Set breakpoints and debug like regular JavaScript

Worker Console

// In worker file
console.log('[Worker]', 'Processing event', event);

// Messages appear in main console with [Worker] prefix

Performance Profiling

// Profile worker performance
const beacon = new AgentShieldBeacon({
  apiKey: 'your-api-key',
  useWorker: true,
  onWorkerStats: (stats) => {
    console.log('Worker performance:', {
      eventsPerSecond: stats.throughput,
      avgProcessingTime: stats.avgTime,
      memoryUsage: stats.memory,
      queueLength: stats.queueSize,
    });
  },
});

Security Considerations

Workers have access to limited APIs. Ensure your worker code doesn't attempt to access DOM or other restricted APIs.

Content Security Policy

Content-Security-Policy:
  worker-src 'self' blob:;
  script-src 'self';

Sandboxing

// Workers are sandboxed by default
// No access to:
// - DOM
// - localStorage
// - sessionStorage
// - document/window objects

// Workers have access to:
// - fetch API
// - IndexedDB
// - WebSockets
// - Crypto API

Browser Compatibility

BrowserWorker SupportFallback
Chrome 60+FullN/A
Firefox 55+FullN/A
Safari 11+FullN/A
Edge 79+FullN/A
IE 11NoneDirect mode

Best Practices

  1. Always enable worker mode in production
  2. Test fallback scenarios thoroughly
  3. Monitor worker health and performance
  4. Handle worker errors gracefully
  5. Optimize batch sizes based on traffic
  6. Use compression for large payloads
  7. Implement proper cleanup on page unload

Next Steps

Command Palette

Search for a command to run...