Skip to content

WASM Plugin Extensions for Custom Logic: Business Use Case for HeliosDB-Lite

WASM Plugin Extensions for Custom Logic: Business Use Case for HeliosDB-Lite

Document ID: 50_WASM_PLUGIN_EXTENSIONS.md Version: 1.0 Created: 2025-12-15 Category: Performance & Optimization HeliosDB-Lite Version: 2.5.0+


Executive Summary

Modern database applications require domain-specific customization—custom authentication schemes, tenant-specific data transformations, compliance filtering, specialized query rewriting rules, real-time data validation—yet traditional databases offer only rigid extension mechanisms (stored procedures, triggers) that are slow, insecure, and operationally complex. HeliosDB-Lite’s HeliosProxy WebAssembly (WASM) Plugin System provides a revolutionary approach: developers write custom middleware logic in any language (Rust, Go, C++, AssemblyScript), compile to WASM, and load plugins into HeliosProxy for execution at near-native speed (10-100x faster than interpreted stored procedures) with complete sandboxing (no database access leaks or security breaches). Organizations deploying WASM plugins achieve 90-99% reduction in custom middleware operational overhead, 5-50x performance improvement over database triggers, zero-downtime plugin updates, and the ability to implement complex business logic (row-level security, data masking, custom caching strategies) without modifying database core or application code. For SaaS platforms, regulated industries, multi-tenant applications, and API gateways requiring extensibility without compromising security or performance, HeliosDB-Lite’s WASM plugin system transforms the database from a static data store into a programmable, domain-aware execution platform.


Problem Being Solved

Core Problem Statement

Applications require domain-specific database logic—multi-tenant row filtering, PII masking for GDPR compliance, custom authentication, real-time data validation, specialized query transformations—but traditional extension mechanisms (stored procedures, database triggers, application middleware) are inadequate: stored procedures are slow and insecure (full database access), triggers are performance killers (synchronous execution on every write), and application middleware adds network latency (2-10ms per query), forcing organizations to choose between implementing critical business logic inefficiently or accepting security/compliance risks.

Root Cause Analysis

FactorImpact on OperationsCurrent WorkaroundLimitation of Workaround
Stored Procedure PerformancePL/pgSQL, PL/Python stored procs are 10-100x slower than native code; interpreted execution adds 50-500ms overheadRewrite critical logic in C/C++ database extensions (requires recompiling database)Extremely high development cost ($100K-500K for custom extensions); breaks on database upgrades; security nightmare (full DB access)
Database Trigger OverheadBEFORE/AFTER triggers execute synchronously on every INSERT/UPDATE; adds 5-50ms per rowDisable triggers, move logic to application layerApplication must implement validation; easy to bypass; no centralized enforcement point
Application Middleware LatencyCustom logic in application layer adds network round-trips (2-10ms per query); scales poorly (must deploy middleware fleet)Deploy middleware close to database (same AZ); use connection poolingStill adds latency; operational complexity of managing middleware fleet; middleware becomes SPOF
Extension Security RisksDatabase extensions (PL/Python, PL/Perl) can access filesystem, network, other databases; major security breach vectorCarefully audit extension code; restrict database user permissionsHuman error in audits; extensions can escalate privileges; compliance failures (SOC2, HIPAA)
Update/Deployment ChallengesUpdating stored procedures requires DDL locks (blocks queries); extensions require database restartSchedule maintenance windows for updates; deploy during low-traffic periodsDowntime for updates; slow iteration velocity; can’t A/B test logic changes

Business Impact Quantification

MetricWithout WASM PluginsWith HeliosDB-Lite WASMImprovement
Custom Logic Execution Time50-500ms (stored procedures)0.5-5ms (WASM near-native)100-1000x faster
Security Incident Risk10-30% of database extensions have vulnerabilities< 1% (sandboxed WASM, no DB access)90-97% risk reduction
Plugin Update Downtime5-30 minutes (DDL locks, restarts)0 seconds (hot-reload)100% elimination
Development Cost for Custom Extensions$100K-500K (C++ database extension development)$10K-50K (WASM plugin in Rust/Go)80-95% cost reduction
Middleware Infrastructure Costs$5K-20K/month (dedicated middleware fleet)$0 (embedded in HeliosProxy)100% savings

Who Suffers Most

  1. SaaS Platform Security Teams: Building multi-tenant applications with strict tenant isolation requirements where a single query must never access another tenant’s data. They implement row-level security through database triggers or middleware filters, suffering 20-50ms latency overhead per query while worrying about bypass vulnerabilities that could cause catastrophic data leaks affecting thousands of tenants.

  2. Regulated Industry Engineering (Healthcare, Finance): Operating under GDPR, HIPAA, PCI-DSS compliance requiring PII data masking, audit logging, and access controls at the database layer. They build complex stored procedures for data redaction (SSN → XXX-XX-1234) that add 100-500ms to query execution, while external auditors flag stored procedure code as potential compliance risks due to overly broad database access.

  3. API Gateway Platform Teams: Running high-throughput API platforms (100K+ req/s) requiring custom authentication, rate limiting, request transformation, and response filtering at the database proxy layer. They deploy separate middleware services (Kong, Envoy) adding 5-15ms latency and $10K-50K/month infrastructure costs, while struggling to maintain consistency between middleware logic and database schema changes.


Why Competitors Cannot Solve This

Technical Barriers

Competitor TypeCore LimitationWhy It PersistsBusiness Consequence
Traditional RDBMS (PostgreSQL, MySQL)Extensions require C/C++ code compiled into database binary; full database access (security risk); no sandboxingDatabase architecture predates modern sandboxing technologies (WASM); backwards compatibility constraints prevent major changesCustom extensions are expensive, insecure, and break on upgrades
Stored Procedures (PL/pgSQL, PL/Python)Interpreted languages are 10-100x slower than native code; synchronous execution blocks queries; can access filesystem/networkLegacy design for simple business logic; never intended for complex/high-performance extensionsUnsuitable for performance-critical or security-sensitive logic
Serverless Functions (AWS Lambda, Cloud Functions)Network latency (10-50ms per invocation); cold start delays (100-1000ms); expensive at scale ($0.20+ per 1M invocations)Designed for stateless event processing, not database query pathToo slow and expensive for per-query custom logic
Database Middleware (ProxySQL, PgBouncer)Focus on connection pooling and basic routing; no extensibility framework for custom logicBuilt as transport-layer proxies; no SQL-aware plugin systemMust fork and modify source code for customization (not practical)

Architecture Requirements

  1. SQL-Aware Plugin Hooks in HeliosProxy: Requires a proxy layer that intercepts queries at multiple points (pre-parse, post-parse, pre-execution, post-execution, result transformation) and invokes WASM plugins with structured context (query AST, user metadata, table schemas, execution plans). Traditional databases cannot add this without breaking client/server protocol compatibility.

  2. Secure WASM Sandboxing with Capability-Based Security: Demands a WASM runtime (Wasmtime, Wasmer) integrated into HeliosProxy with fine-grained capability controls—plugins can only access explicitly granted resources (specific tables, environment variables, HTTP endpoints) and cannot escape the sandbox to access filesystem, network, or other processes. Building this security model requires deep systems programming expertise and formal verification.

  3. Hot-Reload Plugin Management with Zero Downtime: Must support loading, updating, and unloading WASM plugins while HeliosProxy is running and serving queries, with atomic plugin version switches (no query sees inconsistent plugin state) and rollback capability if new plugin version fails. This requires sophisticated plugin lifecycle management and state isolation—far beyond what database extension mechanisms provide.

Competitive Moat Analysis

HeliosDB-Lite WASM Plugin Moat
├─ Technical Moats (5-10 year lead)
│ ├─ Integrated WASM Runtime
│ │ ├─ Wasmtime embedded in HeliosProxy (near-native performance)
│ │ ├─ Multi-language support (Rust, Go, C++, AssemblyScript)
│ │ └─ Ahead-of-time (AOT) compilation for production (10-30% faster)
│ │
│ ├─ Secure Sandboxing
│ │ ├─ Capability-based security model (WASI)
│ │ ├─ No filesystem/network access by default
│ │ ├─ Fine-grained resource grants (table-level, column-level)
│ │ └─ Memory isolation between plugins
│ │
│ ├─ SQL-Aware Plugin API
│ │ ├─ Pre/post query hooks at multiple execution stages
│ │ ├─ Access to query AST, execution plan, table metadata
│ │ ├─ Result set transformation (add/remove/modify rows/columns)
│ │ └─ Custom caching strategies (override default cache behavior)
│ │
│ └─ Plugin Lifecycle Management
│ ├─ Hot-reload without database restart or downtime
│ ├─ Atomic version switching (no inconsistent states)
│ ├─ Rollback on plugin failure (automatic fallback)
│ └─ A/B testing (route % of queries to new plugin version)
├─ Developer Experience Moats (3-5 year lead)
│ ├─ Rich Plugin SDK
│ │ ├─ Rust SDK with type-safe query manipulation
│ │ ├─ Go SDK for familiar syntax
│ │ ├─ AssemblyScript SDK (TypeScript-like, compiles to WASM)
│ │ └─ Plugin templates and examples library
│ │
│ ├─ Local Development Workflow
│ │ ├─ heliosdb-lite plugin dev subcommand for local testing
│ │ ├─ Plugin debugger with query replay
│ │ └─ Performance profiler for plugin optimization
│ │
│ └─ Observability
│ ├─ Per-plugin metrics (execution time, invocation count, errors)
│ ├─ Distributed tracing integration (OpenTelemetry)
│ └─ Logging with plugin context (structured logs)
└─ Operational Moats (1-3 year lead)
├─ Zero-downtime updates (100% uptime during plugin changes)
├─ Versioned plugin registry (git-like plugin management)
└─ Multi-tenant plugin isolation (tenant-specific logic without code duplication)

HeliosDB-Lite Solution

Architecture Overview

┌─────────────────────────────────────────────────────────────────┐
│ Application Layer │
│ (Any PostgreSQL-compatible client or ORM) │
└────────────────┬────────────────────────────────────────────────┘
│ SQL Queries
┌─────────────────────────────────────────────────────────────────┐
│ HeliosProxy Layer │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ Query Parser & Analyzer │ │
│ └─────┬─────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ Plugin Execution Pipeline │ │
│ │ │ │
│ │ Hook 1: Pre-Parse │ │
│ │ ├─ Authentication plugins │ │
│ │ ├─ Rate limiting plugins │ │
│ │ └─ Query logging/audit plugins │ │
│ │ ▼ │ │
│ │ [SQL Parser] │ │
│ │ ▼ │ │
│ │ Hook 2: Post-Parse / Pre-Execution │ │
│ │ ├─ Query rewriting plugins │ │
│ │ ├─ Row-level security filters │ │
│ │ ├─ Tenant isolation enforcement │ │
│ │ └─ Custom optimization rules │ │
│ │ ▼ │ │
│ │ [Query Optimizer] │ │
│ │ ▼ │ │
│ │ Hook 3: Pre-Storage Execution │ │
│ │ ├─ Data validation plugins │ │
│ │ ├─ Constraint enforcement │ │
│ │ └─ Pre-flight checks │ │
│ │ ▼ │ │
│ │ [Execute Query on Storage Engine] │ │
│ │ ▼ │ │
│ │ Hook 4: Post-Execution / Result Transformation │ │
│ │ ├─ PII masking plugins (GDPR compliance) │ │
│ │ ├─ Result filtering (column-level access control) │ │
│ │ ├─ Data enrichment (add computed columns) │ │
│ │ └─ Result caching strategy plugins │ │
│ │ ▼ │ │
│ │ [Return Results to Client] │ │
│ └───────────────────────────────────────────────────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────────┐ │
│ │ WASM Plugin Runtime (Wasmtime) │ │
│ │ │ │
│ │ Plugin Instances (Sandboxed): │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ tenant-isolation.wasm │ │ │
│ │ │ - Language: Rust │ │ │
│ │ │ - Hook: Post-Parse │ │ │
│ │ │ - Function: Add WHERE tenant_id = $current │ │ │
│ │ │ - Capabilities: Read query AST, modify predicates │ │ │
│ │ │ - Memory: 16MB limit │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ pii-masking.wasm │ │ │
│ │ │ - Language: Go │ │ │
│ │ │ - Hook: Post-Execution │ │ │
│ │ │ - Function: SSN → XXX-XX-1234, email → a***@b.com │ │ │
│ │ │ - Capabilities: Read/modify result rows │ │ │
│ │ │ - Memory: 32MB limit │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ ┌─────────────────────────────────────────────────────┐ │ │
│ │ │ custom-auth.wasm │ │ │
│ │ │ - Language: AssemblyScript │ │ │
│ │ │ - Hook: Pre-Parse │ │ │
│ │ │ - Function: Validate JWT, extract user context │ │ │
│ │ │ - Capabilities: HTTP call to auth service │ │ │
│ │ │ - Memory: 8MB limit │ │ │
│ │ └─────────────────────────────────────────────────────┘ │ │
│ │ │ │
│ │ Sandbox Enforcement (WASI): │ │
│ │ - No filesystem access (unless explicitly granted) │ │
│ │ - No network access (unless explicitly granted) │ │
│ │ - No database access (only via HeliosProxy API) │ │
│ │ - Memory limits per plugin │ │
│ │ - CPU time limits (prevent runaway plugins) │ │
│ └───────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Storage Engine Layer │
│ (Helios Core - MVCC, B-trees, WAL, etc.) │
└─────────────────────────────────────────────────────────────────┘
Plugin Development Workflow:
┌────────────────────────────────────────────────────────────┐
│ 1. Developer writes plugin in Rust/Go/AssemblyScript │
│ 2. Compile to WASM: cargo build --target wasm32-wasi │
│ 3. Test locally: heliosdb-lite plugin test <.wasm> │
│ 4. Deploy: heliosdb-lite plugin deploy <.wasm> │
│ 5. Hot-reload: HeliosProxy loads new version (0ms) │
│ 6. Monitor: Prometheus metrics per plugin │
└────────────────────────────────────────────────────────────┘

Key Capabilities

CapabilityImplementationDeveloper BenefitBusiness Value
Multi-Hook Plugin SystemPlugins execute at 4 stages (pre-parse, post-parse, pre-execution, post-execution); access to query AST, execution plans, result setsImplement custom logic at optimal point in query lifecycle; fine-grained control over database behaviorEnables complex use cases (row-level security, PII masking, custom caching) without application changes
Near-Native PerformanceWASM compiled ahead-of-time (AOT) to native machine code; 10-100x faster than interpreted stored proceduresCustom logic executes in 0.5-5ms (vs. 50-500ms for PL/pgSQL); no performance penalty for extensibilityEnables performance-critical custom logic (real-time validation, per-query transformations)
Secure SandboxingWASI capability-based security; plugins can’t access filesystem, network, or other databases unless explicitly grantedZero security vulnerabilities from plugins; passes SOC2/HIPAA/PCI-DSS auditsEliminates 90-97% of database extension security risks; meets compliance requirements
Zero-Downtime UpdatesHot-reload plugins while HeliosProxy is serving queries; atomic version switching; automatic rollback on errorsDeploy plugin updates 10-100x per day; A/B test plugin logic; no maintenance windows100% uptime during updates; fast iteration velocity; reduced operational burden

Concrete Examples with Code, Config & Architecture

Example 1: Multi-Tenant Row-Level Security Plugin (Rust)

Scenario: SaaS application with 10K tenants. Every query must be automatically filtered to current tenant’s data to prevent data leaks.

HeliosDB-Lite Configuration (heliosdb-saas.toml):

[database]
name = "saas_multitenant"
port = 5432
[proxy.plugins]
enabled = true
plugin_dir = "/etc/heliosdb/plugins"
# Tenant isolation plugin
[[proxy.plugins.plugin]]
name = "tenant-isolation"
file = "tenant_isolation.wasm"
hook = "post_parse" # Execute after SQL parsing, before execution
enabled = true
priority = 100 # High priority (execute first)
# Plugin capabilities (fine-grained security)
[[proxy.plugins.plugin.capabilities]]
allow_query_modification = true
allow_table_access = ["users", "orders", "products", "transactions"]
allow_metadata_access = true # Can read table schemas
deny_network_access = true
deny_filesystem_access = true
[proxy.plugins.config]
# Pass configuration to plugin via environment
tenant_id_header = "X-Tenant-ID"
tenant_id_session_var = "app.current_tenant_id"

Rust Plugin Code (tenant_isolation.wasm):

use heliosdb_plugin_sdk::{
Plugin, PluginContext, QueryHook, QueryModification,
AstNode, PredicateNode, Result,
};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Config {
tenant_id_header: String,
tenant_id_session_var: String,
}
struct TenantIsolationPlugin {
config: Config,
}
impl Plugin for TenantIsolationPlugin {
fn name(&self) -> &str {
"tenant-isolation"
}
fn version(&self) -> &str {
"1.0.0"
}
fn on_query_post_parse(&self, ctx: &PluginContext) -> Result<QueryModification> {
// Extract tenant ID from session or header
let tenant_id = self.get_tenant_id(ctx)?;
// Parse query AST
let mut ast = ctx.query_ast();
// If query touches multi-tenant tables, add tenant filter
if self.is_multitenant_query(&ast) {
self.inject_tenant_filter(&mut ast, tenant_id)?;
}
Ok(QueryModification::Modified(ast))
}
}
impl TenantIsolationPlugin {
fn get_tenant_id(&self, ctx: &PluginContext) -> Result<i64> {
// Try session variable first
if let Some(tenant_id) = ctx.session_var(&self.config.tenant_id_session_var) {
return tenant_id.parse().map_err(|_| "Invalid tenant ID");
}
// Fall back to HTTP header (if available)
if let Some(tenant_id) = ctx.http_header(&self.config.tenant_id_header) {
return tenant_id.parse().map_err(|_| "Invalid tenant ID");
}
Err("No tenant ID found in session or headers".into())
}
fn is_multitenant_query(&self, ast: &AstNode) -> bool {
// Check if query references multi-tenant tables
let tables = ast.referenced_tables();
tables.iter().any(|t| {
matches!(t.as_str(), "users" | "orders" | "products" | "transactions")
})
}
fn inject_tenant_filter(&self, ast: &mut AstNode, tenant_id: i64) -> Result<()> {
// Add "WHERE tenant_id = $tenant_id" predicate to query
// This is simplified; real implementation handles complex queries
match ast {
AstNode::Select(ref mut select) => {
// Create tenant_id predicate
let tenant_predicate = PredicateNode::Equals {
left: Box::new(PredicateNode::Column("tenant_id".into())),
right: Box::new(PredicateNode::Literal(tenant_id.into())),
};
// Add to WHERE clause (or create if doesn't exist)
match &mut select.where_clause {
Some(existing) => {
// Combine with AND
select.where_clause = Some(PredicateNode::And {
left: Box::new(existing.clone()),
right: Box::new(tenant_predicate),
});
}
None => {
select.where_clause = Some(tenant_predicate);
}
}
Ok(())
}
AstNode::Update(ref mut update) => {
// Similar logic for UPDATE queries
// ... (omitted for brevity)
Ok(())
}
AstNode::Delete(ref mut delete) => {
// Similar logic for DELETE queries
// ... (omitted for brevity)
Ok(())
}
_ => Ok(()), // INSERT doesn't need filtering (validated elsewhere)
}
}
}
// Plugin entry point (called by HeliosProxy)
#[no_mangle]
pub extern "C" fn heliosdb_plugin_init() -> *mut dyn Plugin {
let config: Config = heliosdb_plugin_sdk::load_config()
.expect("Failed to load plugin config");
Box::into_raw(Box::new(TenantIsolationPlugin { config }))
}

Build and Deploy:

Terminal window
# Build plugin (Rust → WASM)
cd tenant-isolation-plugin
cargo build --target wasm32-wasi --release
# Copy to plugin directory
cp target/wasm32-wasi/release/tenant_isolation.wasm /etc/heliosdb/plugins/
# Deploy (hot-reload, zero downtime)
heliosdb-lite plugin deploy tenant_isolation.wasm
# Verify loaded
heliosdb-lite plugin list
# Output:
# tenant-isolation v1.0.0 post_parse enabled 0.8ms avg execution

Application Code (Python - unchanged, transparent filtering):

import psycopg2
# Set tenant ID in session
conn = psycopg2.connect("host=localhost port=5432 dbname=saas_multitenant")
conn.cursor().execute("SET app.current_tenant_id = 12345")
# Query WITHOUT explicit tenant filter
# Plugin automatically adds "WHERE tenant_id = 12345"
cur = conn.cursor()
cur.execute("SELECT * FROM orders WHERE status = 'pending'")
# Plugin transforms to:
# SELECT * FROM orders WHERE status = 'pending' AND tenant_id = 12345
# Result: Only tenant 12345's orders returned (data leak impossible!)
orders = cur.fetchall()

Performance Results:

MetricManual App-Level FilteringDatabase TriggersWASM PluginImprovement vs. Triggers
Query overhead0ms (but easy to forget)8-15ms per query0.5-1ms8-30x faster
Security guaranteeNone (application bypass risk)EnforcedEnforcedSame security, 10x performance
Development costHigh (every query needs filter)Medium (trigger maintenance)Low (single plugin)90% reduction in code

Example 2: PII Masking Plugin for GDPR Compliance (Go)

Scenario: Healthcare application must mask PII (SSN, email, phone) for non-admin users to comply with HIPAA/GDPR.

Go Plugin Code (pii_masking.wasm):

package main
import (
"fmt"
"regexp"
"strings"
sdk "github.com/heliosdb/plugin-sdk-go"
)
type PIIMaskingPlugin struct {
config Config
}
type Config struct {
MaskSSN bool `json:"mask_ssn"`
MaskEmail bool `json:"mask_email"`
MaskPhone bool `json:"mask_phone"`
AdminRoles []string `json:"admin_roles"`
}
func (p *PIIMaskingPlugin) Name() string {
return "pii-masking"
}
func (p *PIIMaskingPlugin) Version() string {
return "1.0.0"
}
// Hook: Post-execution (modify result set before returning to client)
func (p *PIIMaskingPlugin) OnQueryPostExecution(ctx *sdk.PluginContext) (sdk.ResultModification, error) {
// Skip masking for admin users
userRole := ctx.SessionVar("app.user_role")
if p.isAdmin(userRole) {
return sdk.NoModification(), nil
}
// Get result set
results := ctx.Results()
// Mask PII columns
for _, row := range results.Rows {
for colName, value := range row {
switch {
case p.config.MaskSSN && p.isSSNColumn(colName):
row[colName] = p.maskSSN(value)
case p.config.MaskEmail && p.isEmailColumn(colName):
row[colName] = p.maskEmail(value)
case p.config.MaskPhone && p.isPhoneColumn(colName):
row[colName] = p.maskPhone(value)
}
}
}
return sdk.Modified(results), nil
}
func (p *PIIMaskingPlugin) isAdmin(role string) bool {
for _, adminRole := range p.config.AdminRoles {
if role == adminRole {
return true
}
}
return false
}
func (p *PIIMaskingPlugin) isSSNColumn(colName string) bool {
return strings.Contains(strings.ToLower(colName), "ssn") ||
strings.Contains(strings.ToLower(colName), "social_security")
}
func (p *PIIMaskingPlugin) isEmailColumn(colName string) bool {
return strings.Contains(strings.ToLower(colName), "email")
}
func (p *PIIMaskingPlugin) isPhoneColumn(colName string) bool {
return strings.Contains(strings.ToLower(colName), "phone") ||
strings.Contains(strings.ToLower(colName), "mobile")
}
func (p *PIIMaskingPlugin) maskSSN(value interface{}) interface{} {
ssn, ok := value.(string)
if !ok || ssn == "" {
return value
}
// 123-45-6789 → XXX-XX-6789
re := regexp.MustCompile(`\d{3}-\d{2}-(\d{4})`)
return re.ReplaceAllString(ssn, "XXX-XX-$1")
}
func (p *PIIMaskingPlugin) maskEmail(value interface{}) interface{} {
email, ok := value.(string)
if !ok || email == "" {
return value
}
// john.doe@example.com → j***@example.com
parts := strings.Split(email, "@")
if len(parts) != 2 {
return value
}
username := parts[0]
domain := parts[1]
if len(username) <= 1 {
return email
}
masked := string(username[0]) + "***@" + domain
return masked
}
func (p *PIIMaskingPlugin) maskPhone(value interface{}) interface{} {
phone, ok := value.(string)
if !ok || phone == "" {
return value
}
// (555) 123-4567 → (XXX) XXX-4567
re := regexp.MustCompile(`\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?(\d{4})`)
return re.ReplaceAllString(phone, "(XXX) XXX-$1")
}
// Plugin entry point
//export heliosdb_plugin_init
func heliosdb_plugin_init() *PIIMaskingPlugin {
config := sdk.LoadConfig().(Config)
return &PIIMaskingPlugin{config: config}
}
func main() {}

Configuration:

[[proxy.plugins.plugin]]
name = "pii-masking"
file = "pii_masking.wasm"
hook = "post_execution"
enabled = true
[proxy.plugins.plugin.config]
mask_ssn = true
mask_email = true
mask_phone = true
admin_roles = ["admin", "compliance_officer", "super_admin"]

Performance Results:

MetricApplication-Level MaskingDatabase View with Masking FunctionsWASM PluginAdvantage
Masking overhead per query2-5ms (network round-trip)50-200ms (PL/pgSQL functions)1-3ms2-200x faster
Code duplicationHigh (every app endpoint)None (centralized)NoneSame as view, 50x faster
Compliance auditHard (application bypass risk)Easy (database enforced)EasySame compliance, better performance

Example 3: Custom Authentication Plugin (AssemblyScript)

Scenario: API gateway requires JWT validation and rate limiting at database layer.

AssemblyScript Plugin Code:

// auth_plugin.ts (compiles to WASM)
import {
Plugin,
PluginContext,
QueryModification,
HttpClient,
} from "@heliosdb/plugin-sdk-assemblyscript";
@plugin
export class CustomAuthPlugin implements Plugin {
name(): string {
return "custom-auth";
}
version(): string {
return "1.0.0";
}
// Hook: Pre-parse (before any query processing)
onQueryPreParse(ctx: PluginContext): QueryModification {
// Extract JWT from connection parameters
const authHeader = ctx.connectionParam("Authorization");
if (!authHeader) {
return QueryModification.reject("Missing Authorization header");
}
// Validate JWT (call external auth service)
const jwt = authHeader.replace("Bearer ", "");
const user = this.validateJWT(jwt);
if (!user) {
return QueryModification.reject("Invalid or expired JWT");
}
// Check rate limit
if (!this.checkRateLimit(user.userId)) {
return QueryModification.reject("Rate limit exceeded");
}
// Inject user context into session for use by other plugins
ctx.setSessionVar("app.user_id", user.userId.toString());
ctx.setSessionVar("app.user_role", user.role);
ctx.setSessionVar("app.user_email", user.email);
return QueryModification.allow();
}
private validateJWT(token: string): User | null {
// Call auth service via HTTP (capability granted in config)
const http = new HttpClient();
const response = http.post(
"https://auth.example.com/api/validate",
{ token: token },
{ timeout: 100 } // 100ms timeout
);
if (response.status !== 200) {
return null;
}
const data = JSON.parse(response.body);
return {
userId: data.user_id,
role: data.role,
email: data.email,
};
}
private checkRateLimit(userId: i64): bool {
// Use HeliosProxy's built-in rate limiter
const limiter = RateLimiter.forUser(userId);
return limiter.allow({
maxRequests: 1000,
windowSeconds: 60,
});
}
}
class User {
userId: i64;
role: string;
email: string;
}

Build:

Terminal window
# Compile AssemblyScript to WASM
asc auth_plugin.ts -o auth_plugin.wasm --optimize
# Deploy
heliosdb-lite plugin deploy auth_plugin.wasm

Performance Results:

MetricSeparate Auth Middleware (Kong/Envoy)WASM PluginImprovement
Auth latency8-15ms (network hop)1-2ms (in-process)4-15x faster
Throughput50K req/s (middleware bottleneck)200K req/s (near-native)4x higher
Infrastructure cost$5K-10K/month (middleware fleet)$0 (embedded)100% savings

Example 4: Custom Caching Strategy Plugin (Rust)

Scenario: E-commerce site wants to cache product queries but invalidate cache on inventory changes without invalidating entire cache tier.

Rust Plugin Code:

use heliosdb_plugin_sdk::{Plugin, PluginContext, CacheDecision, Result};
struct ProductCachePlugin;
impl Plugin for ProductCachePlugin {
fn on_cache_lookup(&self, ctx: &PluginContext) -> Result<CacheDecision> {
let query = ctx.query_ast();
// Custom caching for product queries
if self.is_product_query(&query) {
let product_id = self.extract_product_id(&query)?;
// Check custom cache (Redis, in-memory, etc.)
if let Some(cached_result) = self.get_from_custom_cache(product_id) {
return Ok(CacheDecision::UseCustomCache(cached_result));
}
// Cache miss: allow query to execute
return Ok(CacheDecision::Miss);
}
// Use default HeliosDB caching for other queries
Ok(CacheDecision::UseDefault)
}
fn on_query_post_execution(&self, ctx: &PluginContext) -> Result<()> {
let query = ctx.query_ast();
// If product write, invalidate custom cache
if self.is_product_write(&query) {
let product_id = self.extract_product_id(&query)?;
self.invalidate_custom_cache(product_id)?;
}
Ok(())
}
}

Example 5: Kubernetes Deployment with Plugin Management

Kubernetes ConfigMap for Plugins:

apiVersion: v1
kind: ConfigMap
metadata:
name: heliosdb-plugins
data:
tenant-isolation.wasm: |
<base64-encoded-wasm-binary>
pii-masking.wasm: |
<base64-encoded-wasm-binary>
custom-auth.wasm: |
<base64-encoded-wasm-binary>
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: heliosdb-with-plugins
spec:
replicas: 3
template:
spec:
containers:
- name: heliosdb
image: heliosdb/heliosdb-lite:2.5.0
volumeMounts:
- name: plugins
mountPath: /etc/heliosdb/plugins
env:
- name: HELIOSDB_PLUGINS_ENABLED
value: "true"
- name: HELIOSDB_PLUGINS_DIR
value: "/etc/heliosdb/plugins"
volumes:
- name: plugins
configMap:
name: heliosdb-plugins

Market Audience

Primary Segments

1. Multi-Tenant SaaS Platforms (TAM: $65B)

AttributeDetails
CharacteristicsB2B applications with thousands of tenants requiring strict data isolation; row-level security is critical (data leaks = catastrophic); compliance requirements (SOC2, ISO 27001) demand centralized access control; rapid feature iteration requires frequent custom logic changes
Pain PointsManual tenant filtering in application code is error-prone (90% of data breaches from application bugs); database triggers add 10-50ms latency overhead; stored procedures are slow and hard to test; updating security logic requires maintenance windows
HeliosDB-Lite ValueWASM plugins enforce tenant isolation at database layer (zero bypass risk); 10-100x faster than triggers (0.5-5ms overhead); hot-reload updates without downtime; passes SOC2/HIPAA audits
Key BuyersVP Engineering, Security Architects, Compliance Teams
Revenue Potential$100K-500K annual value (avoided breach costs + compliance)

2. Regulated Industries (Healthcare, Finance) (TAM: $42B)

AttributeDetails
CharacteristicsHIPAA, PCI-DSS, GDPR compliance mandates PII masking, audit logging, access controls; regulators require database-level enforcement (application-level insufficient); security audits are frequent and expensive ($50K-200K per audit)
Pain PointsPL/pgSQL stored procedures for PII masking add 100-500ms per query; external compliance auditors flag stored procedure security risks (overly broad database access); updating compliance logic requires database restarts (downtime)
HeliosDB-Lite ValueSandboxed WASM plugins (no filesystem/network access) pass audits; near-native performance (1-5ms PII masking); zero-downtime compliance updates; 90-97% reduction in security audit findings
Key BuyersCISO, Compliance Officers, Healthcare IT Directors
Revenue Potential$200K-1M annual savings (audit costs + avoided fines)

3. API Gateway & Microservices Platforms (TAM: $35B)

AttributeDetails
CharacteristicsHigh-throughput API platforms (100K-1M req/s) requiring custom authentication, rate limiting, request transformation; middleware services (Kong, Envoy) add 5-15ms latency and $10K-50K/month infrastructure costs; need domain-specific routing logic
Pain PointsSeparate middleware fleet adds operational complexity (5+ additional services to manage); latency overhead kills performance SLAs; middleware logic duplicates database schema knowledge (high maintenance burden); can’t version middleware logic with database schema
HeliosDB-Lite ValueEmbedded WASM plugins eliminate middleware fleet (100% infra savings); 1-2ms authentication overhead (vs. 5-15ms network hop); plugin logic versioned with database schema; 4-15x latency improvement
Key BuyersPlatform Engineers, API Infrastructure Teams
Revenue Potential$100K-500K annual savings (middleware infrastructure + latency improvements)

Buyer Personas

PersonaPrimary MotivationEvaluation CriteriaDecision Authority
VP Engineering (SaaS)Eliminate tenant data leak risks (single breach = company-ending); reduce security engineering burden 80%+ by centralizing access controlProof of tenant isolation enforcement; security audit report showing zero vulnerabilities; benchmark showing < 5ms plugin overheadFinal decision maker; budget $100K-500K
CISO (Regulated Industries)Pass HIPAA/PCI-DSS/GDPR audits without expensive stored procedure rewrites; reduce audit findings 90%+ with sandboxed pluginsThird-party security assessment of WASM sandbox; compliance certification (SOC2 Type II); reference customers in healthcare/financeFinal decision maker for security architecture
Platform Architect (API Platforms)Eliminate middleware fleet complexity; reduce API latency 50%+ by embedding logic in database proxyBenchmark showing 5-15ms latency reduction; TCO analysis of middleware elimination; proof of 100K+ req/s throughputStrong influencer; recommends to CTO

Technical Advantages

Why HeliosDB-Lite Excels

DimensionPostgreSQL Extensions (C/C++)Stored Procedures (PL/pgSQL/PL/Python)Serverless Functions (Lambda)HeliosDB-Lite WASM Plugins
PerformanceNative (0.1-1ms)Slow (50-500ms interpreted)Very slow (10-100ms network)Near-native (0.5-5ms)
SecurityFull DB access (high risk)Filesystem/network access riskNetwork calls (audit trail gaps)Sandboxed (WASI, no escape)
DeploymentRequires recompiling databaseDDL locks (5-30min downtime)Separate infrastructureHot-reload (0s downtime)
Language SupportC/C++ onlyPL/pgSQL, PL/Python, PL/PerlAny (but separate service)Rust, Go, C++, AssemblyScript
Development CostVery high ($100K-500K)Medium ($10K-50K)Medium + ongoing infra costsLow ($10K-50K) + zero infra
ObservabilityPoor (logs only)Limited (query logs)Good (CloudWatch, etc.)Excellent (per-plugin metrics)

Performance Characteristics

Use CaseStored Procedure (PL/pgSQL)Database Extension (C++)WASM PluginAdvantage
Tenant Isolation Filter15-30ms (parse + execute)0.5-1ms (native)0.5-1.5msSame as native, easier to develop
PII Masking (10 columns)200-500ms (regex in PL/pgSQL)2-5ms (native regex)3-8ms25-167x faster than stored proc
JWT Validation100-300ms (HTTP call from PL/Python)N/A (can’t do HTTP easily)1-3ms (async HTTP)Unique capability
Custom Cache Lookup50-100ms (trigger + cache check)1-2ms (but hard to implement)1-3ms25-100x faster than trigger

Adoption Strategy

Phase 1: Plugin Development (Weeks 1-4)

  1. Identify Custom Logic Use Cases: Review application code for database-related custom logic (tenant filtering, PII masking, validation, etc.). Prioritize by business impact (security > compliance > performance). Target: Document top 5 plugin opportunities.

  2. Develop First Plugin: Implement highest-priority plugin (e.g., tenant isolation) in Rust or Go. Test locally with HeliosDB-Lite dev environment. Benchmark performance vs. current implementation (stored procedures or app-level logic). Target: 10x+ performance improvement.

  3. Security Audit: Have security team review plugin code and WASM sandbox configuration. Verify capability restrictions (no filesystem/network unless required). Test for sandbox escape attempts. Target: Zero security vulnerabilities found.

Phase 2: Staging Deployment (Weeks 5-8)

  1. Deploy Plugins to Staging: Load plugins into HeliosProxy on staging environment. Run production workload replay with plugins enabled. Monitor plugin execution time, error rates, and correctness. Target: < 5ms plugin overhead, zero functional regressions.

  2. Load Testing: Stress test with 2-10x production traffic to verify plugin performance under load. Check for memory leaks or CPU spikes. Verify hot-reload works correctly (update plugin version without downtime). Target: Maintain performance at 10x load.

Phase 3: Production Rollout (Weeks 9-12)

  1. Canary Rollout: Enable plugins for 10% of production traffic. Monitor for 1 week. Compare latency, error rates, and security metrics to baseline. Target: No degradation in P95 latency or error rates.

  2. Full Rollout: Gradually increase to 100% traffic over 2-4 weeks. Decommission legacy implementations (stored procedures, middleware services). Document plugin development workflow for engineering team. Target: 100% traffic on plugins, legacy code removed.


Key Success Metrics

Technical KPIs

MetricBaseline (Before)Target (After 3 Months)Measurement
Custom Logic Execution Time50-500ms (stored procs)1-5ms (WASM)HeliosDB metrics per plugin
Plugin Hot-Reload Downtime5-30 minutes (DDL locks)0 secondsDeployment logs
Security Audit Findings5-15 (stored proc vulnerabilities)0-1 (WASM sandbox verified)Annual audit reports
Plugin Update Frequency1-2x per quarter (downtime risk)10-50x per month (hot-reload)Deployment frequency metrics

Business KPIs

MetricBaselineTarget (After 6 Months)Business Impact
Middleware Infrastructure Cost$10K-50K/month$0 (eliminated)100% savings = $120K-600K annual
Data Breach RiskHigh (app-level filtering bypass)Low (database-enforced)Avoided breach costs ($1M-50M)
Compliance Audit Costs$100K-300K per audit$20K-60K (fewer findings)70-80% reduction
Development Velocity2-4 weeks per custom logic feature2-5 days (plugin development)5-10x faster iteration

Conclusion

WASM plugin extensions represent the future of database extensibility: combining the performance of native code with the security of sandboxed execution and the operational simplicity of hot-reloadable modules. HeliosDB-Lite’s HeliosProxy WASM Plugin System delivers on this vision with near-native performance (0.5-5ms vs. 50-500ms for stored procedures), bulletproof security (WASI sandboxing with zero filesystem/network access), and zero-downtime updates that enable 10-100x higher deployment frequency.

For multi-tenant SaaS platforms, regulated industries, and API gateway architectures, the business value is immediate: 90-97% reduction in security risks (sandboxed plugins pass SOC2/HIPAA audits), 100% elimination of middleware infrastructure costs ($120K-600K annual savings), and 5-10x faster development velocity for custom database logic. The competitive advantage is insurmountable: traditional databases offer only slow stored procedures or insecure native extensions, while external middleware adds latency and operational complexity.

As applications become more sophisticated—with real-time compliance requirements, complex multi-tenancy models, and domain-specific optimizations—the need for secure, performant database extensibility will only grow. HeliosDB-Lite’s WASM plugin system positions it as the embedded database that bridges this gap, transforming from a static data store into a programmable platform that adapts to each organization’s unique requirements without compromising performance, security, or operational simplicity.


References

  1. HeliosDB-Lite WASM Plugin System: https://docs.heliosdb.io/lite/plugins/overview
  2. Plugin SDK Documentation (Rust, Go, AssemblyScript): https://docs.heliosdb.io/lite/plugins/sdk
  3. WebAssembly Security Model: https://webassembly.org/docs/security/
  4. WASI (WebAssembly System Interface): https://wasi.dev
  5. Wasmtime Runtime Performance Benchmarks: https://github.com/bytecodealliance/wasmtime/blob/main/docs/benchmarks.md
  6. PostgreSQL Extension Security Risks: “PostgreSQL Extension Security” by PostgreSQL Security Team (2023)
  7. Serverless Cold Start Latency Analysis: AWS Lambda Performance Study, AWS re:Invent 2024
  8. Database Trigger Performance Impact: “The Cost of Database Triggers” by Percona (2024)

Document Classification: Business Confidential Review Cycle: Quarterly Owner: Product Marketing Adapted for: HeliosDB-Lite Embedded Database