Skip to main content
Build a production-ready edge function execution platform that runs code close to users for low latency. This cookbook demonstrates how to create an edge computing platform using HopX.

Overview

Edge functions execute code at geographic locations close to users, reducing latency. The platform routes requests to appropriate edge locations, executes functions with resource constraints, and returns results quickly.

Prerequisites

  • HopX API key (Get one here)
  • Python 3.8+ or Node.js 16+
  • Understanding of edge computing
  • Basic knowledge of request routing

Architecture

┌──────────────┐
│   User       │ Request
└──────┬───────┘


┌─────────────────┐
│  Edge Router    │ Route to nearest
└──────┬──────────┘


┌─────────────────┐
│  Edge Sandbox   │ Execute function
│  (Region-based)  │
└─────────────────┘

Implementation

Step 1: Edge Function Execution

Execute functions at edge locations:
from hopx_ai import Sandbox
import os
from typing import Dict, Any

class EdgeFunctionPlatform:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.edge_sandboxes = {}  # Region -> sandbox mapping
    
    def get_edge_sandbox(self, region: str) -> Sandbox:
        """Get or create edge sandbox for region"""
        if region not in self.edge_sandboxes:
            self.edge_sandboxes[region] = Sandbox.create(
                template="code-interpreter",
                api_key=self.api_key,
                timeout_seconds=300,
                region=region  # Specify region if supported
            )
        return self.edge_sandboxes[region]
    
    def execute_at_edge(self, function_code: str, region: str, event: Dict[str, Any]) -> Dict[str, Any]:
        """Execute function at edge location"""
        try:
            sandbox = self.get_edge_sandbox(region)
            
            # Prepare function with event
            import json
            full_code = f"""
import json
event = {json.dumps(event)}
{function_code}
"""
            
            result = sandbox.run_code(full_code, timeout=10)  # Fast execution for edge
            
            return {
                "success": result.success,
                "result": result.stdout,
                "region": region,
                "execution_time": result.execution_time
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "region": region
            }
    
    def route_to_nearest(self, user_location: str, function_code: str, event: Dict[str, Any]) -> Dict[str, Any]:
        """Route request to nearest edge location"""
        # Simple routing logic (in production, use geolocation)
        region_map = {
            "us": "us-east-1",
            "eu": "eu-west-1",
            "asia": "ap-southeast-1"
        }
        
        region = region_map.get(user_location, "us-east-1")
        return self.execute_at_edge(function_code, region, event)
    
    def cleanup_all(self):
        """Clean up all edge sandboxes"""
        for sandbox in self.edge_sandboxes.values():
            sandbox.kill()
        self.edge_sandboxes.clear()

# Usage
platform = EdgeFunctionPlatform(api_key=os.getenv("HOPX_API_KEY"))

result = platform.route_to_nearest(
    user_location="us",
    function_code="print('Hello from edge!')",
    event={}
)
print(result)

platform.cleanup_all()

Best Practices

  1. Low Latency: Optimize for fast execution
  2. Resource Constraints: Use minimal resources at edge
  3. Geographic Distribution: Deploy to multiple regions
  4. Request Routing: Route to nearest edge location

Next Steps

  1. Implement geolocation-based routing
  2. Add edge location management
  3. Create request routing logic
  4. Implement resource optimization
  5. Add edge monitoring