> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Edge Function Execution

> Build edge computing functions with geographic distribution, low-latency execution, resource constraints, and request routing

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](https://console.hopx.dev/api-keys))
* 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:

<CodeGroup>
  ```python Python theme={null}
  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()
  ```

  ```javascript JavaScript theme={null}
  import { Sandbox } from '@hopx-ai/sdk';

  class EdgeFunctionPlatform {
      constructor(apiKey) {
          this.apiKey = apiKey;
          this.edgeSandboxes = {};  // Region -> sandbox mapping
      }
      
      async getEdgeSandbox(region) {
          if (!this.edgeSandboxes[region]) {
              this.edgeSandboxes[region] = await Sandbox.create({
                  template: 'code-interpreter',
                  apiKey: this.apiKey,
                  timeoutSeconds: 300,
                  region  // Specify region if supported
              });
          }
          return this.edgeSandboxes[region];
      }
      
      async executeAtEdge(functionCode, region, event) {
          try {
              const sandbox = await this.getEdgeSandbox(region);
              
              // Prepare function with event
              const fullCode = `
  const event = ${JSON.stringify(event)};
  ${functionCode}
  `;
              
              const result = await sandbox.runCode(fullCode, { timeout: 10 });  // Fast execution for edge
              
              return {
                  success: result.success,
                  result: result.stdout,
                  region,
                  executionTime: result.execution_time
              };
          } catch (error) {
              return {
                  success: false,
                  error: error.message,
                  region
              };
          }
      }
      
      async routeToNearest(userLocation, functionCode, event) {
          // Simple routing logic (in production, use geolocation)
          const regionMap = {
              us: 'us-east-1',
              eu: 'eu-west-1',
              asia: 'ap-southeast-1'
          };
          
          const region = regionMap[userLocation] || 'us-east-1';
          return await this.executeAtEdge(functionCode, region, event);
      }
      
      async cleanupAll() {
          await Promise.all(
              Object.values(this.edgeSandboxes).map(sandbox => sandbox.kill())
          );
          this.edgeSandboxes = {};
      }
  }

  // Usage
  const platform = new EdgeFunctionPlatform(process.env.HOPX_API_KEY);

  const result = await platform.routeToNearest(
      'us',
      "print('Hello from edge!')",
      {}
  );
  console.log(result);

  await platform.cleanupAll();
  ```
</CodeGroup>

## 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

## Related Cookbooks

* [Custom Serverless Platform](/cookbooks/serverless/custom-functions) - Serverless functions

## 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
