Edge Functions

Write server-side JavaScript or Python functions and invoke them via API, webhooks, or cron triggers. Full database access via the built-in zMesh SDK, automatic version history, and sandboxed execution.

Custom-Built Serverless Runtime

zMesh Edge Functions are built from scratch — no AWS Lambda, no Cloudflare Workers, no third-party FaaS. Each function runs in an isolated subprocess with OS-level resource limits (CPU, memory, file size, process count), ephemeral workspaces, and automatic cleanup. The runtime injects a pre-authenticated zMesh SDKwith direct database access to your project's PostgreSQL instance.

Architecture

🔒

Subprocess Isolation

Each invocation runs in its own process with RLIMIT_AS, RLIMIT_CPU, RLIMIT_NPROC, RLIMIT_FSIZE enforced at the OS level.

🗄️

Direct DB Access

The zmesh.db SDK connects directly to your project's PostgreSQL via an auto-injected DSN. No API layer overhead.

🛡️

Secret Stripping

Platform secrets (JWT_SECRET_KEY, DATABASE_URL, etc.) are stripped from the subprocess environment before execution.

📁

Ephemeral Workspace

Each run uses a TemporaryDirectory with HOME and TMPDIR redirected. Cleaned up automatically after execution.

🔄

Concurrency Control

Dual-layer semaphores — global platform limit + per-project limit — prevent resource exhaustion.

📜

Auto Version History

Every code update snapshots the previous version. Rollback to any version instantly.

Execution Flow

1Trigger — API call, webhook, cron, or dashboard invoke
2Auth & Limits — Verify API key/user, check monthly invocation cap
3Prepare — Fetch code, env vars, generate project DB DSN
4Inject SDK — Wrap code with zMesh SDK (JS: new Function(), Python: exec())
5Execute — Launch subprocess with resource limits & filtered env
6Capture — Parse JSON result from stdout, log invocation to DB

Create a Function

POST /projects/{project_id}/functionsJSON
{
  "name": "send-welcome",
  "language": "javascript",
  "entry_point": "handler",
  "code": "exports.handler = async (payload, zmesh) => { ... }",
  "timeout_ms": 5000,
  "env_vars": {
    "GREETING": "Hello"
  }
}

Supported Languages

LanguageRuntimeDB DriverSDK Injection
JavaScriptNode.jspg (auto-included)new Function() wrapper
PythonPython 3.11psycopg2 (auto-included)exec() with SDK class

zMesh SDK (In-Function)

Every function receives a zmesh object with built-in database access and env vars:

MethodDescription
zmesh.db.query(sql, params)Execute raw SQL, returns rows
zmesh.db.queryOne(sql, params)Execute SQL, return single row
zmesh.db.insert(table, data)Insert row, returns inserted data
zmesh.db.select(table, where, params)Select rows with conditions
zmesh.db.update(table, data, where, params)Update rows matching condition
zmesh.db.remove(table, where)Delete rows matching condition
zmesh.env.KEY_NAMEAccess environment variables
zmesh.projectIdCurrent project identifier
JavaScriptNode.js
exports.handler = async (payload, zmesh) => {
  // Raw SQL query
  const rows = await zmesh.db.query(
    "SELECT * FROM users WHERE age > $1", [18]
  );

  // Single row fetch
  const user = await zmesh.db.queryOne(
    "SELECT * FROM users WHERE id = $1", [payload.id]
  );

  // Insert a record
  const log = await zmesh.db.insert("logs", {
    action: "signup",
    user_id: payload.id,
  });

  // Update records
  await zmesh.db.update(
    "users",
    { name: "New Name" },
    "id = $1",
    [payload.id]
  );

  // Delete records
  await zmesh.db.remove("sessions", "expired_at < NOW()");

  // Access env vars
  const greeting = zmesh.env.GREETING;

  return { users: rows.length, greeting };
};
PythonPython 3.11
def handler(payload, zmesh):
    # Raw SQL query
    rows = zmesh.db.query(
        "SELECT * FROM users WHERE age > %s", (18,)
    )

    # Single row
    user = zmesh.db.query_one(
        "SELECT * FROM users WHERE id = %s",
        (payload["id"],)
    )

    # Insert
    zmesh.db.insert("logs", {
        "action": "signup",
        "user_id": payload["id"],
    })

    # Access env vars
    greeting = zmesh.env.GREETING

    return {"users": len(rows), "greeting": greeting}

Invoke (Dashboard Auth)

POST /projects/{project_id}/functions/{function_id}/invokeAuth Required
// Request
{
  "payload": { "user_id": "abc123" }
}

// Response
{
  "status": "success",
  "result": { "message": "Welcome Rahul" },
  "duration_ms": 230
}

Public Invoke (API Key Auth)

Invoke functions from your app using an API key and the function slug:

POST /api/functions/{slug}API Key
curl -X POST https://api.zmesh.in/api/functions/send-welcome \
  -H "x-api-key: zb_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"user_id": "abc123"}'

API Reference

MethodPathDescription
GET/functionsList all functions
POST/functionsCreate function
GET/functions/{id}Get function details + code
PATCH/functions/{id}Update function code/config
DELETE/functions/{id}Delete function
POST/functions/{id}/invokeInvoke function (dashboard auth)
POST/api/functions/{slug}Invoke function (API key auth)
GET/functions/{id}/invocationsInvocation history & logs
GET/functions/{id}/versionsVersion history
POST/functions/{id}/versions/{v}/rollbackRollback to version

Version History & Rollback

Automatic Snapshots

Every time you update a function's code via PATCH, the previous version is automatically saved to the function_versions table with timestamp and entry point.

Instant Rollback

Rollback saves the current state as a new version before overwriting with the historical snapshot. This means rolling back is always safe — you can rollback-the-rollback.

Sandbox Limits

ResourceLimitEnforcement
TimeoutConfigurable per function (default 10s)asyncio timeout
Memory256 MB (configurable)RLIMIT_AS
CPU Timetimeout + 2 secondsRLIMIT_CPU
File Output10 MBRLIMIT_FSIZE
Processes50 max child processesRLIMIT_NPROC
ConcurrencyGlobal + per-project semaphoresApplication-level
NetworkFull outbound HTTP accessUnrestricted

CLI Usage

Terminal
# Deploy a function
zmesh functions deploy ./send-welcome.js

# List all functions
zmesh functions list

# Invoke a function
zmesh functions invoke send-welcome --data '{"user_id": "abc123"}'

# View invocation logs
zmesh functions logs send-welcome