PGB Hub Documentation & Architecture Guides

PGB Hub Documentation

Technical guides, client SDK references, and runnable recipes for all 8 programmable cloud subsystems: compute, microVMs, PostgreSQL 17, maps, auth, storage, transactional mail, and AI agent MCP.

PGB Hub Architecture & AI Agent Guide

Explore complete ingress specifications, Model Context Protocol integration, and multi-language SDK recipes.

Read Master Guide

Cloud Categories

PGB Hub Console

Launch and manage your sovereign cloud infrastructure.

Open Console →
Getting Started

Unified Programmable Cloud Architecture

PGB Hub unifies compute, microVMs, databases, geospatial maps, auth, storage, transactional mail, and AI agents into a single sovereign control plane under https://<project>.pgbhub.app.

import { createClient } from "@pgbox/client";

// One client connects to all 8 cloud services:
export const pgb = createClient({
  endpoint: process.env.PGB_ENDPOINT || "https://my-app.pgbhub.app",
  apiKey: process.env.PGB_API_KEY
});

// Access compute, database, auth, storage, maps & mail with zero glue code:
const user = await pgb.auth.getUser();
const orders = await pgb.table("orders").find({ user_id: user.id });

Subsystem Architecture

  • Zero Vendor Fragmentation: Eliminates separate accounts for AWS, Mapbox, Supabase, Auth0, S3, Postmark, and Pinecone.
  • Single Sovereign Ingress: Every project receives a dedicated wildcard domain (https://<project>.pgbhub.app) with TLS 1.3 encryption.
  • Edge-Native Connection Pooling: Sub-millisecond internal routing between compute, database, and microVM container services.
Production Note: Set PGB_ENDPOINT in your environment variables to seamlessly switch between local Docker and PGB Hub Cloud.
Compute & Functions

Serverless Compute & Function Handlers

Deploy Node.js and Python functions with sub-10ms cold starts, automatic HTTP routing, cron schedules, and database change listeners.

// functions/payments/create-order.ts
import { FunctionContext, FunctionEvent } from "@pgbox/functions";

export async function handle(event: FunctionEvent, ctx: FunctionContext) {
  const { user } = ctx.auth;
  const { items, total } = event.body;

  // Direct transactional database access with automatic RLS scoping
  const order = await ctx.db.table("orders").create({
    user_id: user.id,
    items,
    total,
    status: "CONFIRMED"
  });

  // Dispatch transactional email
  await ctx.mail.send({
    to: user.email,
    subject: `Order #${order.id} Confirmed`,
    html: `<p>Your order of $${total} is confirmed!</p>`
  });

  return { statusCode: 200, body: { orderId: order.id } };
}

Subsystem Architecture

  • Sub-10ms Warmup: V8 isolates and Python runners start instantaneously without standard VM cold-start lag.
  • Context-Injected Services: The second parameter ctx contains authenticated user context, database transaction handles, storage, and mail clients.
  • Zero Routing Boilerplate: Functions are automatically routed by filename under https://<project>.pgbhub.app/functions/<module>/<filename>.
Production Note: Use 'pgb dev --functions' locally to test serverless functions with hot reloading against your local database.
MicroVM Containers

MicroVM Containers & CRIU Scale-to-Zero

Run full Docker OCI containers with hardware cgroups v2 isolation and CRIU memory snapshots that scale to 0 RAM when idle.

// pgb.services.yml
version: "1.0"
services:
  api:
    image: ghcr.io/ridemesh/ridemesh-api:v2.4.1
    port: 5010
    env:
      - NODE_ENV=production
      - DATABASE_URL=postgresql://app:token@db.pgbhub.app:5433/db?sslmode=require
    scale:
      min_replicas: 0 # Scales to 0 MB RAM after 5m idle via CRIU snapshot
      max_replicas: 10
      target_cpu: 70%

Subsystem Architecture

  • CRIU Memory Snapshotting: Idle containers have their exact Linux process memory snapshotted to NVMe, freeing up 100% of RAM while preserving state.
  • Sub-30ms Instant Wakeup: Incoming HTTP requests restore the container state into active RAM in under 30 milliseconds.
  • OCI Compatibility: Any container built with Docker, Podman, or BuildKit runs with zero modifications.
Production Note: Set min_replicas: 0 for development, staging, or internal microservices to reduce compute costs to zero when traffic stops.
PGB Maps & Geospatial

Self-Hosted PGB Maps & Location Gateway

100% Mapbox-compatible vector/raster tiles, Search Box autocomplete, reverse geocoding, and turn-by-turn routing with $0 Mapbox API fees.

// Flutter / Dart (MapLibre / RideMesh integration)
import 'package:maplibre_gl/maplibre_gl.dart';

class RideMapWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MapLibreMap(
      styleString: "https://<project>.pgbhub.app/maps/styles/v1/mapbox/streets-v12",
      initialCameraPosition: CameraPosition(
        target: LatLng(37.7749, -122.4194),
        zoom: 14.0,
      ),
    );
  }
}

Subsystem Architecture

  • Zero Mapbox Bills: Self-hosted OpenMapTiles and Valhalla routing engine replaces Mapbox and Google Maps billing.
  • 100% Protocol Compatibility: Supports Mapbox GL JS, MapLibre GL Native (iOS/Android/Flutter), and standard Web Mercator tiles.
  • Direct PostGIS Integration: Combine vector tiles with your database spatial queries (ST_DWithin, ST_MakePoint) in the same datacenter.
Production Note: Use dynamic key fetching in your mobile apps so you can switch map styles and proxy layers remotely without app store rebuilds.
Auth & Identity

Built-In Auth as a Service & Row-Level Security

Complete identity management supporting 6-digit passwordless OTP, magic links, JWT session verification, and automatic PostgreSQL Row-Level Security.

import { createClient } from "@pgbox/client";

const pgb = createClient({ endpoint: "https://<project>.pgbhub.app" });

// 1. Request 6-Digit Passwordless OTP via email
await pgb.auth.sendOtp({ email: "driver@ridemesh.com" });

// 2. Verify OTP & Obtain Session JWT
const { session, user } = await pgb.auth.verifyOtp({
  email: "driver@ridemesh.com",
  token: "849201"
});

console.log("Logged in user:", user.id, "JWT:", session.accessToken);

// 3. PostgreSQL RLS automatically filters rows for this user
const myRides = await pgb.table("rides").find(); // Returns only rides owned by user.id

Subsystem Architecture

  • Zero Identity Dependencies: Built directly into PGB Hub, eliminating external dependencies on Auth0, Clerk, or Firebase Auth.
  • PostgreSQL RLS Alignment: Every authenticated request automatically sets request.jwt.claim.sub in PostgreSQL session variables.
  • Hardware-Fast JWT: Issued JWTs verify locally at edge ingress with zero database round-trip overhead.
Object Storage & CDN

Partitioned Object Storage & Presigned URLs

S3-compatible bucket storage with 15-minute presigned upload URLs, media streaming, and edge CDN distribution.

import { createClient } from "@pgbox/client";

const pgb = createClient({ endpoint: "https://<project>.pgbhub.app", apiKey: "..." });

// 1. Generate 15-minute secure presigned upload URL
const { uploadUrl, fileKey } = await pgb.storage.getPresignedUploadUrl({
  path: "avatars/driver_984.jpg",
  contentType: "image/jpeg",
  expiresInSeconds: 900 // 15 mins
});

// 2. Upload file directly from browser / mobile client
await fetch(uploadUrl, {
  method: "PUT",
  headers: { "Content-Type": "image/jpeg" },
  body: fileBlob
});

// 3. Obtain public CDN delivery URL
const cdnUrl = pgb.storage.getPublicUrl(fileKey);

Subsystem Architecture

  • Per-Project Storage Partitions: Each project receives isolated storage buckets with automated quota management.
  • S3 API Compatibility: Works seamlessly with AWS SDK, MinIO, and standard multipart upload clients.
  • Edge CDN Acceleration: Assets are cached at global Cloudflare edge points for instant low-latency delivery.
Transactional Mail

Transactional Mail Engine & SES Webhooks

Enterprise email dispatch with automated AWS SES bounce and complaint handling, template rendering, and reputation monitoring.

import { createClient } from "@pgbox/client";

const pgb = createClient({ endpoint: "https://<project>.pgbhub.app", apiKey: "..." });

// Send transactional email with deliverability tracking
const res = await pgb.mail.send({
  to: "customer@domain.com",
  subject: "Your Ride Receipt #9842",
  html: "<h1>Thanks for riding with RideMesh</h1><p>Total: $24.50</p>",
  trackOpens: true,
  trackClicks: true
});

console.log('Message Dispatched:', res.messageId);

Subsystem Architecture

  • Automated Bounce & Complaint Handling: AWS SES SNS webhooks automatically flag invalid recipients in PostgreSQL to protect domain reputation.
  • SPF & DKIM Verified: Pre-configured DKIM signature keys guarantee 99.8%+ inbox placement rates.
  • Synchronous Delivery Confirmation: Returns exact SES Message-ID for end-to-end auditability.
AI & MCP Integration

Agent-Native MCP Server (`@pgbox/mcp-server`)

Connect Claude Desktop, Cursor IDE, and autonomous AI agents directly to your live database schemas and cloud APIs via Model Context Protocol.

// Add to claude_desktop_config.json or cursor.json:
{
  "mcpServers": {
    "pgbox": {
      "command": "npx",
      "args": ["-y", "@pgbox/mcp-server"],
      "env": {
        "PGB_ENDPOINT": "https://<project>.pgbhub.app",
        "PGB_API_KEY": "pgb_live_secret_token"
      }
    }
  }
}

Subsystem Architecture

  • Standard MCP Protocol: Implements the official Anthropic Model Context Protocol specification over stdio transport.
  • Zero Hallucination: AI coding models inspect live column types and foreign key relationships before generating SQL.
  • Transactional Dry-Run: AI agents test queries inside isolated rollback transactions before applying mutations.
Production Note: Use '@pgbox/mcp-server' in Cursor to let AI agents build complete features against your live backend automatically.
PostgreSQL 17 & JSONB Core

PostgreSQL 17 Engine, JSONB Collections & PostGIS 3.4

Store schema-free JSON document collections with automated GIN path indexing, PostGIS 3.4 geospatial queries, and pgvector embeddings.

-- 1. Query JSONB document collections with GIN index acceleration
SELECT id, data->>'name' AS venue, data->'pricing'->>'tier' AS tier
FROM venues
WHERE data @> '{"status": "OPEN", "category": "restaurant"}'::jsonb;

-- 2. PostGIS 3.4 Spatial Nearest Neighbor Calculation
SELECT id, data->>'name' AS name,
  ST_Distance(geom::geography, ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography) AS distance_meters
FROM venues
WHERE ST_DWithin(geom::geography, ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography, 5000)
ORDER BY distance_meters ASC
LIMIT 10;

Subsystem Architecture

  • ACID Reliability: Full transaction safety with serializable isolation, multi-version concurrency control (MVCC), and WAL logging.
  • GIN jsonb_path_ops: Index dynamic nested JSON fields with up to 3x faster queries than traditional document databases.
  • Native PostGIS 3.4: Calculate geospatial distances, polygons, intersections, and geofences natively inside the database engine.
Infrastructure & Backups

PgBouncer Connection Pooling & Automated Backups

Handle thousands of concurrent clients with built-in PgBouncer transaction pooling and automated daily AES-256-GCM encrypted snapshot vaults.

-- Connect via standard psql CLI with mandatory TLS 1.3 encryption
psql "postgresql://app_user:token@db.pgbhub.app:5433/production_db?sslmode=require"

-- PgBouncer is pre-configured on port 6543 for massive serverless concurrency
SHOW POOLS;

Subsystem Architecture

  • High-Concurrency PgBouncer: Transaction-level pooling multiplexes thousands of frontend connections over a resilient core connection pool.
  • Zero-Ops Automated Snapshots: Daily automated backups encrypted at rest with AES-256-GCM and replicated offsite.
  • 1-Click Point-in-Time Restore: Restore database state directly from the Cloud Console or CLI in under 60 seconds.