Skip to main content
Serverless Functions

RUNTIME Quickstart Guide

Deploy event-driven serverless functions for stream orchestration. Multi-language support with JavaScript, Python, Go, and Rust. Sub-50ms cold starts, stateful processing, and seamless integration with EDGE, MESH, and VAULT.

<50ms
Cold Start
275+
Global Regions
4
Languages
10,000
Max Concurrency
Docs/Quickstart/RUNTIME Setup

Prerequisites

Complete these steps before deploying your first function

1
Install WAVE CLI
npm install -g @wave/cli
2
Authenticate
wave auth:login
3
Initialize Project
wave runtime:init my-functions
4
Verify Setup
wave runtime:whoami

Choose Your Language

RUNTIME supports four languages, each optimized for different use cases. Select based on your performance requirements and team expertise.

🟨
JavaScript
Node.js 20+
Cold Start~35ms
Memory128MB - 1GB
Best for:
API integrations, webhooks, real-time processing
🐍
Python
Python 3.11+
Cold Start~45ms
Memory128MB - 2GB
Best for:
ML inference, data processing, automation
🔵
Go
Go 1.21+
Cold Start~15ms
Memory64MB - 512MB
Best for:
High-performance processing, concurrent tasks
🦀
Rust
Rust 1.75+
Cold Start~10ms
Memory32MB - 256MB
Best for:
Ultra-low latency, memory-critical workloads

1Create Your Function

🟨 JavaScript Function
handler.js

// handler.js - Content moderation with AI
import { WaveRuntime } from '@wave/runtime';

export const config = {
  trigger: 'stream.started',
  timeout: 30000,
  memory: '256MB',
  retries: 3
};

export async function handler(event, ctx) {
  const { streamId, creatorId, settings } = event.data;

  ctx.logger.info(`Processing stream ${streamId} for creator ${creatorId}`);

  // Get creator preferences from VAULT
  const preferences = await ctx.vault.get(`creator:${creatorId}:preferences`);

  // Enable AI moderation if configured
  if (preferences?.autoModeration) {
    await ctx.edge.process({
      streamId,
      effects: ['content-detection', 'profanity-filter'],
      sensitivity: preferences.moderationLevel || 'medium',
      webhook: `${process.env.APP_URL}/api/webhooks/moderation`
    });
  }

  // Initialize viewer analytics
  await ctx.state.set(`stream:${streamId}:stats`, {
    startedAt: new Date().toISOString(),
    peakViewers: 0,
    totalViews: 0,
    chatMessages: 0,
    donations: 0
  });

  // Record to PULSE analytics
  await ctx.analytics.record({
    event: 'stream_initialized',
    streamId,
    creatorId,
    settings,
    timestamp: Date.now()
  });

  return {
    success: true,
    moderationEnabled: preferences?.autoModeration ?? false,
    streamId
  };
}

2Deploy Your Function

# Deploy JavaScript function
wave runtime:deploy handler.js \
  --name content-moderator \
  --trigger stream.started \
  --memory 256MB \
  --timeout 30s \
  --env-file .env.production

# View deployment status
wave runtime:status content-moderator

# Test function locally
wave runtime:dev handler.js --port 3001

3Subscribe to Events

Functions are triggered by events from the WAVE platform. Here are the available event types:

EventDescriptionPayload
stream.startedStream goes livestreamId, creatorId, settings
stream.endedStream endsstreamId, duration, stats
viewer.joinedViewer connectsviewerId, streamId, region
viewer.leftViewer disconnectsviewerId, watchTime, engagement
chat.messageChat message sentmessageId, userId, content
donation.receivedDonation processedamount, currency, donorId
moderation.flaggedContent flaggedstreamId, reason, severity
milestone.reachedViewer milestonestreamId, milestone, type

Environment Configuration

Configure secrets and environment variables securely. Sensitive values are stored in VAULT and injected at runtime.

# .env.runtime - Environment configuration

# Required
WAVE_API_KEY=wave_live_xxxxxxxxxxxx
WAVE_PROJECT_ID=proj_xxxxxxxxxxxx

# Database connections (auto-injected)
DATABASE_URL=${WAVE_DATABASE_URL}
REDIS_URL=${WAVE_REDIS_URL}

# Custom secrets (stored in VAULT)
STRIPE_SECRET_KEY=${vault:stripe_secret}
OPENAI_API_KEY=${vault:openai_key}
TWILIO_AUTH_TOKEN=${vault:twilio_token}

# Feature flags
ENABLE_ML_MODERATION=true
MODERATION_THRESHOLD=0.85
MAX_CONCURRENT_STREAMS=100

# Monitoring
SENTRY_DSN=${vault:sentry_dsn}
ENABLE_TRACING=true

Local Development & Testing

Test functions locally before deploying. The development server simulates the RUNTIME environment with hot reloading.

# Local development server
wave runtime:dev handler.js --port 3001 --watch

# Send test events
curl -X POST http://localhost:3001/invoke \
  -H "Content-Type: application/json" \
  -d '{
    "event": "stream.started",
    "data": {
      "streamId": "test-stream-123",
      "creatorId": "creator-456",
      "settings": { "quality": "1080p" }
    }
  }'

# Run unit tests
wave runtime:test handler.test.js

# Generate test coverage
wave runtime:test --coverage --threshold 80

# Mock external services
wave runtime:dev handler.js \
  --mock-edge \
  --mock-vault \
  --mock-analytics

Advanced Patterns

Build complex workflows with these battle-tested patterns for distributed function orchestration.

Function Chaining

Sequential execution with data passing

// Chain multiple functions
const result = await ctx.runtime.chain([
  { fn: 'validate-input', data: event.data },
  { fn: 'process-payment', map: r => r.validated },
  { fn: 'send-notification', map: r => r.paymentId }
]);

Fan-Out / Fan-In

Parallel execution with aggregation

// Fan-out to multiple functions
const results = await ctx.runtime.fanOut([
  { fn: 'analyze-audio', data: { streamId } },
  { fn: 'analyze-video', data: { streamId } },
  { fn: 'analyze-chat', data: { streamId } }
]);

// Aggregate results
const combined = aggregateAnalysis(results);

Saga Pattern

Distributed transactions with rollback

// Saga with automatic rollback
const saga = ctx.runtime.saga([
  {
    execute: 'reserve-inventory',
    compensate: 'release-inventory'
  },
  {
    execute: 'charge-payment',
    compensate: 'refund-payment'
  },
  {
    execute: 'fulfill-order',
    compensate: 'cancel-fulfillment'
  }
]);

await saga.execute(orderData);

Circuit Breaker

Automatic failure isolation

// Configure circuit breaker
export const config = {
  circuitBreaker: {
    failureThreshold: 5,
    resetTimeout: 30000,
    halfOpenRequests: 3
  }
};

// Function automatically protected
// Opens circuit after 5 failures
// Resets after 30 seconds

Troubleshooting Guide

Common issues and their solutions. Click to expand for detailed diagnostics and fixes.

Cold Start Too Slow
Out of Memory Errors
Function Timeout
Events Not Triggering
State Not Persisting
Concurrency Limits Hit

Real-World Success Stories

Real-Time Content Moderation

StreamGuard MediaGaming & Esports

Challenge

Processing 50,000+ chat messages per second across 2,000 concurrent streams with <100ms latency

Solution

Deployed Rust-based moderation functions at the edge with ML model inference

Results

99.7% accuracy on toxic content detection
23ms average processing time
4M messages moderated daily
"

RUNTIME's edge execution reduced our moderation latency from 200ms to 23ms. We can now catch toxic content before it reaches viewers.

MC
Marcus Chen
VP of Trust & Safety

Dynamic Ad Insertion

AdStream NetworksAdvertising Technology

Challenge

Inserting personalized mid-roll ads in live streams without buffering or quality degradation

Solution

Go functions for sub-50ms ad decision making integrated with EDGE transcoding

Results

18ms ad decision time
340% increase in ad engagement
$2.3M additional monthly revenue
"

The combination of RUNTIME and EDGE gave us seamless ad insertion. Viewers don't even notice the transition.

SW
Sarah Williams
CTO

Viewer Analytics Pipeline

InsightStreamAnalytics Platform

Challenge

Processing 100M+ viewer events daily with real-time aggregation and alerting

Solution

Python functions for ML-based viewer segmentation with fan-out aggregation pattern

Results

Real-time viewer segments
67% improvement in churn prediction
Sub-second dashboard updates
"

We replaced our entire Spark cluster with RUNTIME functions. Same capabilities, 80% cost reduction.

DP
David Park
Head of Data Engineering

Pricing & Limits

TierInvocationsCompute (GB-s)ConcurrencySupport
Free100K/month400K GB-s10Community
Pro5M/month10M GB-s100Email
Business50M/month100M GB-s1,000Priority
EnterpriseUnlimitedUnlimited10,00024/7 Dedicated

Next Steps

API Reference

Complete RUNTIME API documentation with all methods and types

View API docs
EDGE Integration

Combine RUNTIME with EDGE for AI processing at the edge

EDGE quickstart
PULSE Analytics

Monitor function performance and business metrics

Analytics guide
VAULT Secrets

Secure secrets management and encryption

VAULT docs
WAVE - Enterprise Live Streaming Platform