Skip to main content
Build a production-ready serverless platform that executes functions on-demand, optimizes cold starts, handles events, and manages resources. This cookbook demonstrates how to create a serverless platform similar to AWS Lambda using HopX.

Overview

Serverless platforms execute functions in response to events without managing servers. The platform handles function execution, optimizes cold starts, routes events, and allocates resources dynamically. This pattern is used by platforms like AWS Lambda, Vercel Functions, and Netlify Functions.

Prerequisites

  • HopX API key (Get one here)
  • Python 3.8+ or Node.js 16+
  • Understanding of serverless architecture
  • Basic knowledge of event-driven systems

Architecture

┌──────────────┐
│   Event      │ Trigger function
└──────┬───────┘


┌─────────────────┐
│  Function       │ Route & execute
│   Router        │
└──────┬──────────┘


┌─────────────────┐
│  HopX Sandbox   │ Function execution
└──────┬──────────┘


┌─────────────────┐
│  Response       │ Return result
└─────────────────┘

Implementation

Step 1: Function Execution

Execute serverless functions:
from hopx_ai import Sandbox
import os
import json
from typing import Dict, Any, Callable

class ServerlessFunction:
    def __init__(self, function_id: str, code: str, runtime: str = "python"):
        self.function_id = function_id
        self.code = code
        self.runtime = runtime
        self.sandbox = None
    
    def initialize(self, api_key: str):
        """Initialize function sandbox"""
        self.sandbox = Sandbox.create(
            template="code-interpreter",
            api_key=api_key,
            timeout_seconds=300  # 5 minute timeout
        )
    
    def invoke(self, event: Dict[str, Any], context: Dict[str, Any] = None) -> Dict[str, Any]:
        """Invoke function with event"""
        try:
            # Prepare function code with event
            function_code = f"""
import json

# Event data
event = {json.dumps(event)}

# Context data
context = {json.dumps(context or {})}

# User function
{self.code}
"""
            
            # Execute function
            result = self.sandbox.run_code(function_code, timeout=30)
            
            return {
                "success": result.success,
                "result": result.stdout,
                "error": result.stderr if not result.success else None,
                "execution_time": result.execution_time
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }
    
    def cleanup(self):
        """Clean up function resources"""
        if self.sandbox:
            self.sandbox.kill()
            self.sandbox = None

class ServerlessPlatform:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.functions = {}
    
    def register_function(self, function_id: str, code: str, runtime: str = "python"):
        """Register a serverless function"""
        func = ServerlessFunction(function_id, code, runtime)
        func.initialize(self.api_key)
        self.functions[function_id] = func
    
    def invoke_function(self, function_id: str, event: Dict[str, Any]) -> Dict[str, Any]:
        """Invoke registered function"""
        if function_id not in self.functions:
            return {
                "success": False,
                "error": f"Function {function_id} not found"
            }
        
        return self.functions[function_id].invoke(event)
    
    def cleanup_all(self):
        """Clean up all functions"""
        for func in self.functions.values():
            func.cleanup()

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

# Register function
platform.register_function(
    "hello_world",
    """
def handler(event, context):
    name = event.get('name', 'World')
    return f"Hello, {name}!"
""",
    "python"
)

# Invoke function
result = platform.invoke_function("hello_world", {"name": "HopX"})
print(result)

platform.cleanup_all()

Step 2: Cold Start Optimization

Optimize function cold starts:
class OptimizedServerlessPlatform(ServerlessPlatform):
    def __init__(self, api_key: str):
        super().__init__(api_key)
        self.warm_pool = {}  # Keep sandboxes warm
    
    def _warm_function(self, function_id: str):
        """Warm up function sandbox"""
        if function_id not in self.warm_pool:
            func = self.functions[function_id]
            # Keep sandbox alive
            self.warm_pool[function_id] = func.sandbox
    
    def invoke_function_optimized(self, function_id: str, event: Dict[str, Any]) -> Dict[str, Any]:
        """Invoke with cold start optimization"""
        # Warm function if not already warm
        if function_id not in self.warm_pool:
            self._warm_function(function_id)
        
        return self.invoke_function(function_id, event)

# Usage
platform = OptimizedServerlessPlatform(api_key=os.getenv("HOPX_API_KEY"))
platform.register_function("my_function", "def handler(e, c): return 'OK'")
platform._warm_function("my_function")  # Pre-warm

result = platform.invoke_function_optimized("my_function", {})
print(result)

Best Practices

  1. Cold Start Optimization: Pre-warm frequently used functions
  2. Resource Limits: Set appropriate timeouts and memory limits
  3. Error Handling: Handle errors gracefully
  4. Event Routing: Route events efficiently

Real-World Examples

This pattern is used by:
  • AWS Lambda: Serverless compute service
  • Vercel Functions: Serverless functions for web apps
  • Netlify Functions: Serverless functions platform

Next Steps

  1. Implement function versioning
  2. Add event source integrations
  3. Create function monitoring dashboard
  4. Implement auto-scaling
  5. Add function deployment pipeline