Decentralized serverless platform that runs on itself
A GraphQL API server powering the Alternate Futures platform - serverless functions infrastructure built with GraphQL Yoga, Prisma, and PostgreSQL. Deploy your backend to distributed compute networks like Akash while managing everything through a unified API.
# Install dependencies
npm install
# Set up environment
cp .env.example .env
# Set up database
npm run db:push
# Seed test data
npm run db:seed
# Start development server
npm run devServer runs at: http://localhost:4000/graphql
- Node.js 18+
- PostgreSQL (local or managed)
- Redis (required for usage buffering and auth service)
- pnpm (recommended)
- Auth Service (required for authentication) - See service-auth
Deploy to decentralized compute infrastructure for 60-85% cost savings.
Cost: ~$18-27/month vs $50-130/month on traditional cloud Guide: See AKASH_DEPLOYMENT.md for complete instructions
# Build Docker image
docker build -t ghcr.io/alternatefutures/service-cloud-api:latest .
docker push ghcr.io/alternatefutures/service-cloud-api:latest
# Deploy to Akash (see AKASH_DEPLOYMENT.md for detailed steps)
akash tx deployment create deploy.yaml --from defaultEnvironment Variables are stored in GitHub Secrets for CI/CD deployment.
Traditional cloud deployment option available as backup. See DEPLOYMENT_GUIDE.md for Railway deployment instructions.
Redis is required for usage buffer aggregation (97% cost reduction on DB writes).
Local Development:
# macOS (Homebrew)
brew install redis
brew services start redis
# Ubuntu/Debian
sudo apt install redis-server
sudo systemctl start redis
# Docker
docker run -d -p 6379:6379 redis:alpineProduction Configuration:
Enable persistence for data integrity:
# RDB Snapshots (recommended)
save 60 1 # Save every 60 seconds if 1+ keys changed
# AOF (Append-Only File) - more durable
appendonly yes
appendfsync everysecCloud Providers:
- Akash Network: Include Redis in deploy.yaml
- Railway: Add Redis service via dashboard
- Upstash: Serverless Redis with persistence
- AWS ElastiCache: Configure snapshot retention
After seeding:
- Token:
af_local_test_token_12345 - Project ID:
proj-1
This repository includes automated workflows for continuous integration:
- Runs on: Pull requests and pushes to
main,staging,develop - Tests: Vitest test suite with PostgreSQL and Redis
- Type checking: TypeScript compilation
- Build verification: Ensures code compiles successfully
- Branch name validation: Enforces
feature/ALT-###-descriptionorfeat/alt-###-descriptionformat - PR title validation: Requires Linear ticket number in PR title
- Status checks: All checks must pass before merging
- AI-powered code reviews on every pull request
- Uses Claude Sonnet 4.5 to analyze changes
- Posts review comments directly on PRs
- Identifies bugs, security issues, and suggests improvements
Setup: Add ANTHROPIC_API_KEY to your repository secrets.
See .github/SETUP.md for configuration details.
main- Production (protected)staging- Pre-production testingdevelop- Active development
Workflow:
- Feature branches → Merge into
develop- Naming:
feature/ALT-123-descriptionorfeat/alt-123-description
- Naming:
- Bug fixes → Can merge directly into
staging- Naming:
fix/ALT-789-description
- Naming:
- Hotfixes → Merge directly into
main(emergency only)- Naming:
hotfix/ALT-999-description
- Naming:
GraphQL Playground available at /graphql
Bring your own domain from any registrar (GoDaddy, Namecheap, Cloudflare, etc.)
Verification Methods:
- TXT Record verification
- CNAME Record verification
- A Record verification
SSL/TLS:
- Automatic Let's Encrypt certificate provisioning
- Auto-renewal (30 days before expiry)
- HTTP-01 and DNS-01 ACME challenges
Web3 Domains:
- ArNS (Arweave Name System)
- ENS (Ethereum Name System)
- IPNS (IPFS Name System)
- Real-time usage tracking (storage, bandwidth, compute)
- Automatic invoice generation
- Stripe integration
- Customer portal access
- Branded invoice PDFs with company logo
Preview Invoice Template:
npm run generate:invoiceCreates a sample invoice PDF with:
- Alternate Futures logo and Instrument Sans typography
- Sample customer data
- Example usage charges
- Professional styling
Payment Retries:
Failed payments handled automatically via Stripe's Smart Retries. Configure in Stripe Dashboard: Settings → Billing → Automatic collection
Recommended retry schedule:
- First retry: 3 days after failure
- Second retry: 5 days after first retry
- Third retry: 7 days after second retry
- Final retry: 9 days after third retry
All payment webhooks are handled via /billing/webhook endpoint.
- IPFS (self-hosted & Pinata)
- Arweave permanent storage
- Filecoin decentralized storage
Note: PAT management has been migrated to the dedicated auth service.
- Secure token generation with rate limiting
- 50 tokens per day limit per user
- Maximum 500 active tokens per user
- Automatic expired token cleanup (handled by auth service)
- XSS prevention and input validation
- Required: Set
AUTH_SERVICE_URLin.envto connect to the auth service
Built-in request routing and proxying without external packages.
- Path-based routing with wildcard support
- API gateway patterns
- Multi-backend service routing
- Automatic request proxying
- Route caching with configurable TTL
- Comprehensive error handling
Configuration:
mutation CreateGateway {
createAFFunction(
name: "API Gateway"
routes: {
"/api/users/*": "https://users-service.com"
"/api/products/*": "https://products-service.com"
"/*": "https://default.com"
}
) {
id
invokeUrl
routes
}
}See docs/route-configuration.md for complete routing documentation.
Create Function:
mutation {
createAFFunction(name: "my-api") {
id
name
invokeUrl
}
}Deploy Function:
mutation {
deployAFFunction(functionId: "clxxx", cid: "QmXXX") {
id
cid
}
}Add Custom Domain:
mutation {
createDomain(
input: {
hostname: "example.com"
siteId: "site-123"
verificationMethod: TXT
}
) {
id
hostname
txtVerificationToken
verified
}
}Create Personal Access Token:
mutation {
createPersonalAccessToken(name: "My API Token") {
id
token
name
createdAt
}
}- GraphQL Yoga 5 - GraphQL server
- Prisma - ORM
- PostgreSQL - Database
- Redis - Rate limiting and usage buffering
- TypeScript - Language
- Vitest - Testing framework
- Docker - Containerization
src/
├── schema/ # GraphQL schema
├── resolvers/ # Resolvers
│ ├── auth.ts # Authentication (proxies to auth service)
│ ├── domain.ts # Custom domains
│ ├── billing.ts # Stripe billing
│ └── function.ts # Functions management
├── services/ # Business logic
│ ├── billing/ # Stripe integration
│ ├── dns/ # Domain verification & SSL
│ └── storage/ # IPFS, Arweave, Filecoin
├── jobs/ # Background jobs
│ └── sslRenewal.ts # SSL certificate renewal
├── utils/ # Utilities
└── index.ts # Server entry
prisma/
└── schema.prisma # Database schema
This backend can be deployed as an Alternate Futures Function to run on itself!
See DEPLOYMENT_GUIDE.md for details on self-hosting the platform.
Generate TypeScript types from GraphQL schema:
npm run generate:types
# Watch mode
npm run generate:types:watchSee CODEGEN.md for details.
# Run all tests
npm test
# Run specific test suite
npm test src/services/billing
# Watch mode
npm test -- --watch# Push schema changes
npm run db:push
# Generate migration
npm run db:migrate
# Seed database
npm run db:seed- CLI - Command-line interface
- SDK - Software development kit
- App - Web application dashboard
- Website - Company website
- Compute: $20/month
- PostgreSQL: $10/month
- Redis: $10/month
- Pinata IPFS: $20-100/month
- Total: $60-140/month
- Compute (API): ~$3-5/month
- PostgreSQL: ~$5-7/month
- Redis: ~$3-5/month
- Self-hosted IPFS: ~$10-15/month
- Total: $21-32/month
Savings: 60-85% cost reduction
- Rate Limiting: Redis-based sliding window algorithm
- Input Validation: XSS prevention, dangerous pattern detection
- Token Security: Separated GraphQL types to prevent exposure
- Structured Logging: Production-ready JSON logs for monitoring
- SSL/TLS: Automatic certificate provisioning and renewal
- Database Transactions: Race condition prevention
- Audit Logging: Track all API key operations
MIT
Documentation:
- Akash Deployment Guide
- General Deployment Guide
- GraphQL Code Generation
- OpenRegistry Deployment
- Decentralized Registry Architecture
Routing System Documentation:
- Route Configuration API - Configure route mappings and validation
- Runtime Routing Implementation - Core routing architecture and usage
- Runtime Integration Guide - Integrating routing into function runtime