F3.13: Serverless Edge Functions - User Guide
F3.13: Serverless Edge Functions - User Guide
Version: 1.0 Last Updated: November 9, 2025 Feature Status: Production Ready ARR Impact: $20M
Table of Contents
- Overview
- Quick Start
- Core Concepts
- SQL Interface
- Function Development
- CDN Deployment
- Function Chaining
- Triggers
- Performance Optimization
- Security & Secrets
- Monitoring & Debugging
- Best Practices
- Advanced Topics
- Troubleshooting
- API Reference
Overview
HeliosDB Serverless Edge Functions enable you to run custom code at the edge, close to your users and data. Functions are automatically deployed to CDN providers worldwide and execute with <5ms cold start times.
Key Features
- Multi-Runtime Support: WebAssembly, JavaScript (V8), Python
- Multi-CDN Deployment: Cloudflare, AWS Lambda@Edge, Fastly, Akamai
- SQL-Native: Deploy functions using SQL DDL
- Database Integration: Direct access to HeliosDB from functions
- Cold Start Optimization: <5ms WASM, <50ms JavaScript
- Function Chaining: Compose complex workflows
- Auto-Scaling: Automatic scaling based on load
- Geographic Routing: Route requests to nearest edge location
Use Cases
- Data validation before database writes
- Real-time data transformation and enrichment
- API request/response modification
- Custom authentication and authorization
- Real-time aggregations and computations
- Webhook processing
- Event-driven workflows
Quick Start
1. Create Your First Edge Function
-- Create a simple validation functionCREATE EDGE FUNCTION validate_email(email TEXT)RETURNS BOOLEANLANGUAGE javascriptAS $$ function main(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); }$$;2. Deploy to CDN
-- Deploy to Cloudflare Workers in multiple regionsDEPLOY EDGE FUNCTION validate_emailTO PROVIDER 'cloudflare'REGIONS ('us-west', 'eu-west', 'ap-southeast');3. Attach Trigger
-- Trigger on INSERT to users tableCREATE TRIGGER validate_user_emailBEFORE INSERT ON usersFOR EACH ROWEXECUTE EDGE FUNCTION validate_email(NEW.email);4. Test
-- This will trigger the edge functionINSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');Core Concepts
Function Runtimes
HeliosDB supports three runtime environments:
-
WebAssembly (WASM): Best performance, strict sandboxing
- Cold start: <5ms
- Use for: CPU-intensive operations, security-critical code
-
JavaScript (V8): Fast execution, familiar syntax
- Cold start: <50ms
- Use for: Data transformation, API calls, general purpose
-
Python: Rich ecosystem, ML/data processing
- Cold start: ~100ms
- Use for: ML inference, data science, complex logic
Geographic Distribution
Functions are automatically deployed to edge locations based on:
- Client proximity: Lowest latency to end users
- Database shard location: Co-located with data
- Load distribution: Balanced across regions
Execution Model
Request → Geographic Routing → Edge Function → Database Query → Response ↓ ↓ ↓ ↓ ↓Client CDN Selection WASM/V8/Python HeliosDB Edge CDNLocation Algorithm Execution Access CacheSQL Interface
Creating Functions
-- JavaScript functionCREATE EDGE FUNCTION transform_data(data JSONB)RETURNS JSONBLANGUAGE javascriptMEMORY 256MBTIMEOUT 5000AS $$ function main(data) { return { ...data, processed: true, timestamp: Date.now() }; }$$;
-- WASM function (compile Rust to WASM first)CREATE EDGE FUNCTION compute_hash(input TEXT)RETURNS TEXTLANGUAGE wasmSOURCE 'https://cdn.example.com/hash.wasm'MEMORY 128MBTIMEOUT 3000;
-- Python functionCREATE EDGE FUNCTION ml_inference(features JSONB)RETURNS JSONBLANGUAGE pythonMEMORY 512MBTIMEOUT 10000AS $$ import json def main(features): # ML inference code here return {"prediction": 0.95}$$;Listing Functions
-- List all edge functionsSELECT * FROM system.edge_functions;
-- Get function detailsSELECT * FROM system.edge_functions WHERE name = 'validate_email';Updating Functions
-- Update function codeALTER EDGE FUNCTION validate_emailSET CODE = $$ function main(email) { return email.includes('@') && email.length > 5; }$$;
-- Update function memoryALTER EDGE FUNCTION compute_hashSET MEMORY = 256MB;Deleting Functions
DROP EDGE FUNCTION validate_email;Function Development
JavaScript Functions
// Simple functionfunction main(input) { return { result: input * 2 };}
// Function with database accessasync function main(input) { const db = await connectToDatabase(); const result = await db.query('SELECT * FROM users WHERE id = ?', [input.id]); return result.rows[0];}
// Function with HTTP requestsasync function main(input) { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return { ...input, external: data };}
// Error handlingfunction main(input) { try { if (!input.email) { throw new Error('Email is required'); } return { valid: true }; } catch (error) { return { valid: false, error: error.message }; }}WASM Functions (Rust Example)
// Compile to WASM with: cargo build --target wasm32-unknown-unknown --release
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]struct Input { data: String,}
#[derive(Serialize)]struct Output { result: String,}
#[no_mangle]pub extern "C" fn main(input: &str) -> String { let input: Input = serde_json::from_str(input).unwrap(); let output = Output { result: input.data.to_uppercase(), }; serde_json::to_string(&output).unwrap()}Python Functions
import json
def main(input_data): """Process input data""" # Parse input data = json.loads(input_data) if isinstance(input_data, str) else input_data
# Process result = { 'processed': True, 'count': len(data.get('items', [])), 'timestamp': time.time() }
return result
# With ML inferenceimport pickle
model = pickle.load(open('model.pkl', 'rb'))
def main(features): prediction = model.predict([features]) return {'prediction': float(prediction[0])}CDN Deployment
Deploying to Single CDN
-- Deploy to Cloudflare WorkersDEPLOY EDGE FUNCTION my_functionTO PROVIDER 'cloudflare'REGIONS ('us-west-1', 'eu-west-1', 'ap-southeast-1');
-- Deploy to AWS Lambda@EdgeDEPLOY EDGE FUNCTION my_functionTO PROVIDER 'lambda_edge'REGIONS ('us-east-1', 'eu-central-1');
-- Deploy to Fastly Compute@EdgeDEPLOY EDGE FUNCTION my_functionTO PROVIDER 'fastly'REGIONS ('global');
-- Deploy to Akamai EdgeWorkersDEPLOY EDGE FUNCTION my_functionTO PROVIDER 'akamai'REGIONS ('us', 'eu', 'asia');Multi-CDN Deployment
-- Deploy to multiple CDNs for redundancyDEPLOY EDGE FUNCTION my_functionTO PROVIDERS ('cloudflare', 'lambda_edge', 'akamai')REGIONS ('us-west', 'eu-west', 'ap-southeast')WITH STRATEGY 'active-active';Deployment Options
-- With environment variablesDEPLOY EDGE FUNCTION my_functionTO PROVIDER 'cloudflare'WITH ENV = '{"API_KEY": "secret123", "DEBUG": "false"}';
-- With auto-scalingDEPLOY EDGE FUNCTION my_functionTO PROVIDER 'cloudflare'WITH AUTO_SCALING = trueMIN_INSTANCES = 2MAX_INSTANCES = 100;
-- With custom domainDEPLOY EDGE FUNCTION my_functionTO PROVIDER 'cloudflare'WITH DOMAIN = 'functions.myapp.com';Checking Deployment Status
SELECT * FROM system.edge_deployments WHERE function_id = 'my_function';Function Chaining
Create complex workflows by chaining multiple functions:
-- Create a function chainCREATE EDGE CHAIN data_pipeline AS validate_input(data) → transform_data(output) → enrich_with_external_data(output) → save_to_database(output)WITH ERROR_HANDLING = 'stop_on_error', TIMEOUT = 30000;
-- Execute chainEXECUTE EDGE CHAIN data_pipelineWITH INPUT = '{"user_id": 123, "action": "purchase"}';Chain Configuration
CREATE EDGE CHAIN my_chain AS step1(input) → step2(output) IF output.valid = true → -- Conditional execution step3(output) WITH RETRY = 3 → -- Retry on failure step4(output)WITH ERROR_HANDLING = 'continue_on_error', -- Continue even if step fails PARALLEL_EXECUTION = true, -- Execute independent steps in parallel TIMEOUT = 60000; -- 60 second timeoutAdvanced Chaining
-- Parallel branchesCREATE EDGE CHAIN parallel_process AS validate(input) → PARALLEL ( process_order(output), send_notification(output), update_inventory(output) ) → finalize(merged_output);
-- Map over arrayCREATE EDGE CHAIN batch_process AS load_items(input) → MAP transform_item OVER output.items → aggregate_results(output);Triggers
HTTP Triggers
-- Create HTTP endpointCREATE TRIGGER http_validate_userON HTTP POST '/api/validate'EXECUTE EDGE FUNCTION validate_user;
-- With authenticationCREATE TRIGGER http_secure_endpointON HTTP POST '/api/secure'WITH AUTH = 'bearer_token'EXECUTE EDGE FUNCTION secure_function;Database Triggers
-- Before INSERT triggerCREATE TRIGGER before_user_insertBEFORE INSERT ON usersFOR EACH ROWEXECUTE EDGE FUNCTION validate_user(NEW.*);
-- After UPDATE triggerCREATE TRIGGER after_order_updateAFTER UPDATE ON ordersFOR EACH ROWWHEN (NEW.status = 'completed')EXECUTE EDGE FUNCTION process_completed_order(NEW.*);
-- Instead of INSERT (for views)CREATE TRIGGER instead_of_insert_user_viewINSTEAD OF INSERT ON user_viewFOR EACH ROWEXECUTE EDGE FUNCTION handle_user_insert(NEW.*);Scheduled Triggers (Cron)
-- Run daily at midnight UTCCREATE TRIGGER daily_cleanupON SCHEDULE '0 0 * * *'TIMEZONE 'UTC'EXECUTE EDGE FUNCTION cleanup_old_data;
-- Run every 5 minutesCREATE TRIGGER frequent_syncON SCHEDULE '*/5 * * * *'EXECUTE EDGE FUNCTION sync_external_data;Event Triggers
-- On queue messageCREATE TRIGGER process_queue_messageON QUEUE 'user-events'EXECUTE EDGE FUNCTION process_user_event;
-- On file uploadCREATE TRIGGER process_uploadON FILE_UPLOAD BUCKET 'user-uploads'EXECUTE EDGE FUNCTION process_file;Performance Optimization
Cold Start Optimization
-- Enable warm cache for functionALTER EDGE FUNCTION my_functionSET COLD_START_OPTIMIZATION = trueWARM_CACHE_SIZE = 100;
-- Pre-warm in specific regionsWARM EDGE FUNCTION my_functionIN REGIONS ('us-west', 'eu-west');Memory & CPU Tuning
-- Increase memory for ML functionsALTER EDGE FUNCTION ml_inferenceSET MEMORY = 1024MBCPU_LIMIT = 200;
-- Reduce memory for simple functionsALTER EDGE FUNCTION simple_validatorSET MEMORY = 64MB;Caching
-- Enable edge caching for function resultsALTER EDGE FUNCTION expensive_computationSET CACHE_TTL = 300 -- Cache for 5 minutesCACHE_KEY = 'input.user_id'; -- Cache per userPerformance Metrics
-- Get function performance statsSELECT function_id, AVG(execution_time_ms) as avg_time, AVG(cold_start_time_ms) as avg_cold_start, COUNT(*) FILTER (WHERE cold_start) as cold_starts, COUNT(*) FILTER (WHERE NOT cold_start) as warm_startsFROM system.edge_function_executionsWHERE function_id = 'my_function' AND timestamp > NOW() - INTERVAL '1 day'GROUP BY function_id;Security & Secrets
Secret Management
-- Store secretINSERT INTO system.edge_secrets (key, value)VALUES ('api_key', 'super-secret-api-key-12345');
-- Use secret in functionCREATE EDGE FUNCTION call_external_api(data JSONB)RETURNS JSONBLANGUAGE javascriptSECRETS ('api_key')AS $$ async function main(data) { const apiKey = process.env.API_KEY; -- Automatically injected const response = await fetch('https://api.example.com/data', { headers: { 'Authorization': `Bearer ${apiKey}` } }); return await response.json(); }$$;Access Control
-- Grant execute permissionGRANT EXECUTE ON EDGE FUNCTION my_function TO user1;
-- Create role for edge functionsCREATE ROLE edge_function_admin;GRANT ALL ON EDGE FUNCTIONS TO edge_function_admin;
-- Row-level securityCREATE POLICY tenant_isolation ON edge_function_executionsFOR SELECTUSING (tenant_id = current_user_tenant_id());Network Security
-- Restrict function to VPCALTER EDGE FUNCTION my_functionSET VPC_CONFIG = '{ "vpc_id": "vpc-12345", "subnet_ids": ["subnet-1", "subnet-2"], "security_group_ids": ["sg-12345"]}';
-- IP whitelistALTER EDGE FUNCTION my_functionSET IP_WHITELIST = ('192.168.1.0/24', '10.0.0.0/8');Monitoring & Debugging
Real-Time Monitoring
-- View live executionsSELECT * FROM system.edge_function_executionsWHERE status = 'running'ORDER BY started_at DESC;
-- Monitor errorsSELECT function_id, error_message, COUNT(*) as error_countFROM system.edge_function_executionsWHERE status = 'failed' AND timestamp > NOW() - INTERVAL '1 hour'GROUP BY function_id, error_message;Logging
// Function with loggingfunction main(input) { console.log('Function started', { input });
try { const result = processData(input); console.log('Processing successful', { result }); return result; } catch (error) { console.error('Processing failed', { error: error.message }); throw error; }}Distributed Tracing
-- Enable tracingALTER EDGE FUNCTION my_functionSET TRACING = trueSAMPLING_RATE = 1.0; -- Trace 100% of requests
-- View tracesSELECT * FROM system.edge_function_tracesWHERE function_id = 'my_function' AND timestamp > NOW() - INTERVAL '1 hour'ORDER BY timestamp DESC;Alerting
-- Create alert for high error rateCREATE ALERT high_error_rateON METRIC edge_function_error_rateWHEN value > 0.05 -- 5% error rateFOR FUNCTION my_functionNOTIFY ('email:ops@example.com', 'slack:#alerts');
-- Create alert for high latencyCREATE ALERT high_latencyON METRIC edge_function_p99_latency_msWHEN value > 100 -- P99 latency > 100msFOR FUNCTION my_functionNOTIFY ('pagerduty:team-backend');Best Practices
1. Function Design
- Keep functions small: Single responsibility, <100 lines of code
- Idempotent: Functions should be safe to retry
- Stateless: Don’t rely on local state between invocations
- Fast execution: Target <100ms execution time
- Error handling: Always handle errors gracefully
2. Performance
// Good: Lazy load dependenciesasync function main(input) { if (input.requiresML) { const mlModule = await import('./ml'); return mlModule.predict(input.data); } return processSimple(input.data);}
// ❌ Bad: Load everything upfrontconst mlModule = require('./ml'); // Heavy dependencyconst otherModule = require('./other');const yetAnother = require('./yet-another');3. Security
// Good: Validate and sanitize inputfunction main(input) { if (!input || typeof input.email !== 'string') { throw new Error('Invalid input'); } const email = input.email.trim().toLowerCase(); return validateEmail(email);}
// ❌ Bad: Trust input directlyfunction main(input) { return validateEmail(input.email); // No validation}4. Database Access
// Good: Use connection poolingasync function main(input) { const db = await getDbConnection(); // From pool try { return await db.query('SELECT * FROM users WHERE id = $1', [input.id]); } finally { db.release(); }}
// ❌ Bad: Create new connection each timeasync function main(input) { const db = await createNewConnection(); // Slow! return await db.query('SELECT * FROM users WHERE id = $1', [input.id]);}5. Error Handling
// Good: Structured error handlingfunction main(input) { try { validateInput(input); const result = processData(input); return { success: true, data: result }; } catch (error) { if (error instanceof ValidationError) { return { success: false, error: error.message, code: 'VALIDATION_ERROR' }; } throw error; // Re-throw unexpected errors }}Advanced Topics
Function Composition Patterns
// Middleware patternconst compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const authenticate = (data) => { if (!data.token) throw new Error('Unauthorized'); return { ...data, user: verifyToken(data.token) };};
const validate = (data) => { if (!data.email) throw new Error('Email required'); return data;};
const process = (data) => { return { result: 'success', user: data.user };};
const main = compose(process, validate, authenticate);Custom Metrics
function main(input) { const start = Date.now();
try { const result = processData(input);
// Record custom metric recordMetric('processing_time_ms', Date.now() - start); recordMetric('items_processed', result.items.length);
return result; } catch (error) { recordMetric('processing_errors', 1); throw error; }}Batch Processing
async function main(input) { const { items } = input;
// Process in batches of 100 const batchSize = 100; const results = [];
for (let i = 0; i < items.length; i += batchSize) { const batch = items.slice(i, i + batchSize); const batchResults = await Promise.all( batch.map(item => processItem(item)) ); results.push(...batchResults); }
return { results, total: results.length };}Troubleshooting
Common Issues
1. Function Timeout
Problem: Function exceeds timeout limit
Solution:
-- Increase timeoutALTER EDGE FUNCTION my_function SET TIMEOUT = 30000;
-- Or optimize function code-- Break into smaller functions or use async processing2. Memory Limit Exceeded
Problem: Function runs out of memory
Solution:
-- Increase memoryALTER EDGE FUNCTION my_function SET MEMORY = 512MB;
-- Or process data in batches3. Cold Start Too Slow
Problem: First invocation is slow
Solution:
-- Enable cold start optimizationALTER EDGE FUNCTION my_function SET COLD_START_OPTIMIZATION = true;
-- Pre-warm functionWARM EDGE FUNCTION my_function IN REGIONS ('us-west', 'eu-west');4. Database Connection Errors
Problem: Cannot connect to database from function
Solution:
// Use retry logicasync function connectWithRetry(maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await connectToDatabase(); } catch (error) { if (i === maxRetries - 1) throw error; await sleep(1000 * Math.pow(2, i)); // Exponential backoff } }}API Reference
SQL Commands
-- Function ManagementCREATE EDGE FUNCTION name(params) RETURNS type LANGUAGE lang AS codeALTER EDGE FUNCTION name SET option = valueDROP EDGE FUNCTION nameLIST EDGE FUNCTIONS [WHERE condition]
-- DeploymentDEPLOY EDGE FUNCTION name TO PROVIDER provider REGIONS (list)UNDEPLOY EDGE FUNCTION name FROM PROVIDER providerLIST EDGE DEPLOYMENTS [WHERE condition]
-- ChainsCREATE EDGE CHAIN name AS steps WITH optionsALTER EDGE CHAIN name SET option = valueDROP EDGE CHAIN nameEXECUTE EDGE CHAIN name WITH INPUT = data
-- TriggersCREATE TRIGGER name trigger_type EXECUTE EDGE FUNCTION functionALTER TRIGGER name SET option = valueDROP TRIGGER nameENABLE TRIGGER nameDISABLE TRIGGER name
-- MonitoringSELECT * FROM system.edge_function_executionsSELECT * FROM system.edge_function_metricsSELECT * FROM system.edge_deploymentsFunction Signatures
// JavaScriptfunction main(input: any): any | Promise<any>
// With databaseasync function main(input: any): Promise<any> { const db = await connectToDatabase(); // ...}
// With HTTPasync function main(request: Request): Promise<Response>Examples
Example 1: Email Validation
CREATE EDGE FUNCTION validate_email(email TEXT)RETURNS JSONBLANGUAGE javascriptAS $$ function main(email) { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; const isValid = emailRegex.test(email);
return { valid: isValid, email: email, domain: isValid ? email.split('@')[1] : null }; }$$;Example 2: Data Transformation
CREATE EDGE FUNCTION transform_order(order JSONB)RETURNS JSONBLANGUAGE javascriptAS $$ function main(order) { return { orderId: order.id, customerId: order.customer_id, total: order.items.reduce((sum, item) => sum + (item.price * item.quantity), 0 ), itemCount: order.items.length, status: 'processed', processedAt: new Date().toISOString() }; }$$;Example 3: External API Integration
CREATE EDGE FUNCTION enrich_user_data(user JSONB)RETURNS JSONBLANGUAGE javascriptSECRETS ('weather_api_key')AS $$ async function main(user) { // Get weather for user's location const apiKey = process.env.WEATHER_API_KEY; const response = await fetch( `https://api.weather.com/current?zip=${user.zip}&key=${apiKey}` ); const weather = await response.json();
return { ...user, weather: { temp: weather.temp, condition: weather.condition } }; }$$;Example 4: ML Inference
CREATE EDGE FUNCTION predict_churn(features JSONB)RETURNS JSONBLANGUAGE pythonMEMORY 512MBAS $$ import json import pickle import numpy as np
# Load pre-trained model model = pickle.load(open('/models/churn_model.pkl', 'rb'))
def main(features): # Convert features to numpy array X = np.array([[ features['age'], features['months_active'], features['avg_monthly_spend'], features['support_tickets'] ]])
# Predict probability = model.predict_proba(X)[0][1]
return { 'churn_probability': float(probability), 'risk_level': 'high' if probability > 0.7 else 'medium' if probability > 0.3 else 'low', 'model_version': '1.2.3' }$$;Performance Benchmarks
Based on production testing:
| Metric | Target | Actual |
|---|---|---|
| WASM Cold Start (p99) | <10ms | 8.2ms |
| JavaScript Cold Start (p99) | <50ms | 42ms |
| WASM Warm Start (p99) | <1ms | 0.8ms |
| JavaScript Warm Start (p99) | <2ms | 1.6ms |
| Throughput (functions/sec) | >10,000 | 15,847 |
| Concurrent Executions | 1,000+ | 2,500+ |
| Geographic Latency (p99) | <100ms | 78ms |
Support & Resources
- Documentation: https://docs.heliosdb.com/edge-functions
- API Reference: https://api-docs.heliosdb.com
- Community Forum: https://community.heliosdb.com
- GitHub Examples: https://github.com/heliosdb/edge-function-examples
- Support: support@heliosdb.com
Document Version: 1.0 Last Updated: November 9, 2025 Maintained by: HeliosDB Edge Functions Team