WorkerSQL
WorkerSQL
Section titled “WorkerSQL”MySQL-compatible edge database platform built on Cloudflare Workers
Features • Quick Start • API Reference • Documentation • Contributing
Overview
Section titled “Overview”WorkerSQL is a high-performance, MySQL-compatible edge database platform that brings your data closer to your users. Built on Cloudflare Workers, it provides:
- Edge-native architecture with sub-50ms query latency globally
- MySQL compatibility for seamless migration from existing applications
- Automatic scaling with zero cold starts
- Multi-tenant isolation with built-in security
- Real-time caching with cache-aside pattern implementation
- ACID transactions via Durable Objects
Features
Section titled “Features”🚀 Performance
Section titled “🚀 Performance”- Sub-50ms latency globally via Cloudflare’s edge network
- Intelligent caching with configurable TTL and stale-while-revalidate
- Connection pooling and query optimization
- Automatic shard management based on data size and access patterns
🔒 Security
Section titled “🔒 Security”- JWT-based authentication with role-based access control (RBAC)
- Tenant isolation ensuring complete data separation
- SQL injection prevention with parameterized queries
- Encryption at rest and in transit using industry standards
- Audit logging for compliance and monitoring
🛠 Developer Experience
Section titled “🛠 Developer Experience”- MySQL-compatible SQL - use existing tools and knowledge
- RESTful API with comprehensive OpenAPI specification
- WebSocket support for real-time updates
- Multi-language SDKs (JavaScript/TypeScript, Python, PHP)
- Local development tools with Miniflare integration
📊 Monitoring & Observability
Section titled “📊 Monitoring & Observability”- Real-time metrics and performance monitoring
- Health checks and status endpoints
- Detailed logging with configurable levels
- Integration ready for external monitoring tools
Quick Start
Section titled “Quick Start”Prerequisites
Section titled “Prerequisites”- Node.js 18+ and npm
- Cloudflare account with Workers enabled
- Wrangler CLI installed globally
Installation
Section titled “Installation”# Clone the repositorygit clone https://github.com/healthfees-org/workersql.gitcd workersql
# Install dependenciesnpm install
# Set up development environmentnpm run setup:dev
# Start local development servernpm run dev
Basic Usage
Section titled “Basic Usage”# Test the health endpointcurl http://localhost:8787/health
# Execute a SQL querycurl -X POST http://localhost:8787/v1/query \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -d '{ "sql": "SELECT * FROM users WHERE active = ?", "params": [true] }'
API Reference
Section titled “API Reference”Authentication
Section titled “Authentication”All API requests require a valid JWT token:
Authorization: Bearer <jwt_token>
Core Endpoints
Section titled “Core Endpoints”Method | Endpoint | Description |
---|---|---|
POST | /v1/query | Execute SQL query |
POST | /v1/query/batch | Execute multiple queries |
POST | /v1/transactions | Begin transaction |
POST | /v1/transactions/{id}/commit | Commit transaction |
POST | /v1/transactions/{id}/rollback | Rollback transaction |
GET | /v1/schema | Get database schema |
GET | /v1/health | Health check |
GET | /v1/metrics | Performance metrics |
Example Query
Section titled “Example Query”{ "sql": "SELECT * FROM products WHERE price > ? AND category = ?", "params": [100, "electronics"], "hints": { "consistency": "strong", "cacheTtl": 300000, "shardKey": "tenant_123" }}
Response Format
Section titled “Response Format”{ "success": true, "data": { "rows": [...], "rowsAffected": 1, "insertId": 123, "metadata": { "fromCache": false, "shardId": "shard_0", "executionTimeMs": 15 } }}
Client SDKs
Section titled “Client SDKs”JavaScript/TypeScript
Section titled “JavaScript/TypeScript”import { WorkerSQL } from '@workersql/client';
const db = new WorkerSQL({ apiKey: 'your-api-key', baseUrl: 'https://api.workersql.com',});
const users = await db.query('SELECT * FROM users WHERE id = ?', [123]);
Python
Section titled “Python”from workersql import Client
db = Client(api_key='your-api-key')result = db.query('SELECT * FROM users WHERE id = %s', [123])
<?phpuse WorkerSQL\Client;
$db = new Client(['api_key' => 'your-api-key']);$result = $db->query('SELECT * FROM users WHERE id = ?', [123]);
Architecture
Section titled “Architecture”WorkerSQL is built on a distributed architecture optimized for edge computing:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Client SDK │────│ Edge Gateway │────│ Durable Object ││ │ │ (Workers) │ │ Shards │└─────────────────┘ └─────────────────┘ └─────────────────┘ │ ┌─────────────────┐ │ KV Cache │ │ & Queues │ └─────────────────┘
Key Components
Section titled “Key Components”- Edge Gateway: Request routing, authentication, and caching
- Durable Object Shards: ACID-compliant data storage
- KV Cache: High-performance query result caching
- Event Queues: Asynchronous operations and cache invalidation
- Connection Manager: Efficient connection pooling and management
Development
Section titled “Development”Setup Development Environment
Section titled “Setup Development Environment”# Install dependenciesnpm install
# Set up pre-commit hooksnpm run prepare
# Configure Wranglercp wrangler.toml.template wrangler.tomlwrangler auth login
# Create Cloudflare resourcesnpm run setup:cloudflare
Testing
Section titled “Testing”# Run all testsnpm test
# Run specific test suitesnpm run test:unitnpm run test:integrationnpm run test:e2e
# Run tests with coveragenpm run test:coverage
# Watch mode for developmentnpm run test:watch
Code Quality
Section titled “Code Quality”# Lint codenpm run lint
# Format codenpm run format
# Type checkingnpm run type-check
# Complete quality checknpm run workflow:check
Local Development
Section titled “Local Development”# Start development server with hot reloadnpm run dev
# Build for productionnpm run build
# Deploy to stagingnpm run deploy:staging
Documentation
Section titled “Documentation”- 📖 API Specification
- 🔧 Developer Setup Guide
- 🏗️ Architecture Documentation
- 🔒 Security Guidelines
- ⚙️ Environment Configuration
- 🚀 Local Development Setup
Deployment
Section titled “Deployment”Environment Setup
Section titled “Environment Setup”- Development: Local testing with Miniflare
- Staging: Pre-production testing environment
- Production: Live production deployment
Deployment Commands
Section titled “Deployment Commands”# Deploy to stagingwrangler deploy --env staging
# Deploy to productionwrangler deploy --env production
# View deployment logswrangler tail --env production
Environment Variables
Section titled “Environment Variables”Variable | Description | Default |
---|---|---|
ENVIRONMENT | Deployment environment | development |
LOG_LEVEL | Logging verbosity | info |
MAX_SHARD_SIZE_GB | Maximum shard size | 10 |
CACHE_TTL_MS | Cache TTL in milliseconds | 300000 |
JWT_SECRET | JWT signing secret | (required) |
Performance
Section titled “Performance”Benchmarks
Section titled “Benchmarks”- Query Latency: <50ms globally (p95)
- Throughput: 10,000+ queries/second per edge location
- Cache Hit Rate: 85%+ for typical workloads
- Cold Start: 0ms (edge-native architecture)
Optimization Tips
Section titled “Optimization Tips”- Use appropriate cache TTL for your data freshness requirements
- Optimize shard keys for even data distribution
- Batch related queries to reduce round trips
- Use read replicas for analytics workloads
Contributing
Section titled “Contributing”We welcome contributions! Please see our Contributing Guidelines for details.
Development Workflow
Section titled “Development Workflow”- Fork the repository
- Create a feature branch
- Make your changes with tests
- Run
npm run workflow:check
- Submit a pull request
Code of Conduct
Section titled “Code of Conduct”This project follows the Contributor Covenant Code of Conduct.
License
Section titled “License”This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Support
Section titled “Support”Community
Section titled “Community”Commercial Support
Section titled “Commercial Support”For enterprise support, SLA guarantees, and custom development:
- 📧 Sales: [email protected]
- 📧 Support: [email protected]
- 🔒 Security: [email protected]
Roadmap
Section titled “Roadmap”Current (Q3 2025)
Section titled “Current (Q3 2025)”- ✅ Core SQL compatibility
- ✅ Authentication & authorization
- ✅ Multi-tenant isolation
- ✅ Real-time caching
Upcoming (Q4 2025)
Section titled “Upcoming (Q4 2025)”- 🔄 Advanced analytics queries
- 🔄 Cross-region replication
- 🔄 GraphQL API support
- 🔄 Enhanced monitoring dashboard
Future (Q1+ 2026)
Section titled “Future (Q1+ 2026)”- 📋 Full-text search capabilities
- 📋 Advanced encryption features
- 📋 Machine learning integrations
Acknowledgments
Section titled “Acknowledgments”- Built on Cloudflare Workers
- Inspired by PlanetScale and Neon
- Thanks to all contributors