Production Deployment¶
Overview¶
This guide outlines the steps and best practices for deploying TelcoAPI in a production environment using Cloudflare Pages and D1 database.
Prerequisites¶
- Node.js 18 or higher
- Cloudflare account with Pages and D1 enabled
- Wrangler CLI installed (
npm install -g wrangler
) - Valid SSL certificates for secure communication
- Access to production Diameter/SS7 network elements
- MkDocs for documentation building
Environment Setup¶
1. Configure Pages Project¶
Create or update your wrangler.toml
:
name = "telco-api"
main = "src/index.ts"
compatibility_date = "2024-01-01"
# Production environment configuration
[env.production]
route = "api.telco-sec.com/*"
zone_id = "your_zone_id"
# Database bindings
[[d1_databases]]
binding = "DB"
database_name = "telco_production"
database_id = "your_database_id"
# KV namespace bindings
[[kv_namespaces]]
binding = "SESSIONS"
id = "your_kv_namespace_id"
# Pages configuration
[build]
command = "npm run build && mkdocs build"
output = "dist"
[site]
bucket = "./public"
2. Environment Variables¶
Set up your production secrets in the Cloudflare Pages dashboard or using wrangler:
# Set production secrets
wrangler pages project set-env-var --branch main DIAMETER_HOST "your-diameter-host"
wrangler pages project set-env-var --branch main DIAMETER_PORT "your-diameter-port"
wrangler pages project set-env-var --branch main DIAMETER_ORIGIN_HOST "your-origin-host"
wrangler pages project set-env-var --branch main DIAMETER_ORIGIN_REALM "your-origin-realm"
wrangler pages project set-env-var --branch main API_KEY "your-api-key"
Database Migration¶
1. Create Migration Files¶
// migrations/001_initial.sql
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
subscriber_id TEXT NOT NULL,
type TEXT NOT NULL,
status TEXT NOT NULL,
data TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_sessions_subscriber ON sessions(subscriber_id);
CREATE INDEX idx_sessions_status ON sessions(status);
2. Apply Migrations¶
# Apply migrations to production
wrangler d1 execute telco_production --file=./migrations/001_initial.sql
Deployment Steps¶
-
Build Documentation
-
Build the Project
-
Run Tests
-
Deploy to Production
-
Configure Custom Domain
After deployment, configure your custom domain in the Cloudflare Pages dashboard: - Add custom domain: api.telco-sec.com
- Verify DNS configuration - Enable SSL/TLS
Documentation Structure¶
Ensure your mkdocs.yml
includes all necessary pages:
site_name: TelcoAPI Documentation
site_url: https://api.telco-sec.com/docs
nav:
- Home: index.md
- Getting Started: getting-started/index.md
- API Reference: api-reference/index.md
- Protocols:
- Diameter: protocols/diameter/index.md
- SS7: protocols/ss7/index.md
- SIP: protocols/sip/index.md
- IPX/GRX: protocols/ipx-grx/index.md
- Development:
- Setup: development/setup.md
- Production Deployment: development/production-deployment.md
- Integration:
- Overview: integration/index.md
- Security: integration/security.md
- Contributing: CONTRIBUTING.md
- Security: SECURITY.md
- License: LICENSE
plugins:
- search
- minify:
minify_html: true
theme:
name: material
custom_dir: docs/overrides
features:
- navigation.tabs
- navigation.sections
- navigation.expand
Security Configuration¶
1. API Authentication¶
// Example middleware configuration
app.use(async (request: Request, env: Env, ctx: ExecutionContext) => {
const apiKey = request.headers.get('X-API-Key');
if (!apiKey || apiKey !== env.API_KEY) {
return new Response('Unauthorized', { status: 401 });
}
return null;
});
2. Rate Limiting¶
Configure rate limiting in wrangler.toml
:
[[rules]]
type = "Security"
zone_id = "your_zone_id"
expression = '(http.request.uri.path contains "/api/")'
ratelimit = {characteristics = ["ip"], period = 60, requests_per_period = 100}
Monitoring and Logging¶
1. Cloudflare Analytics¶
Enable request analytics in your Cloudflare dashboard: - HTTP traffic metrics - Error rates - Cache performance - Worker execution metrics
2. Custom Metrics¶
interface MetricsCollector {
// Session metrics
recordSessionCreation(type: string): void;
recordSessionTermination(type: string): void;
// Performance metrics
recordLatency(operation: string, duration: number): void;
// Error metrics
recordError(type: string, details: string): void;
}
class CloudflareMetricsCollector implements MetricsCollector {
constructor(private env: Env) {}
async recordSessionCreation(type: string): Promise<void> {
await this.env.METRICS.writeDataPoint({
blobs: [type],
doubles: [1],
indexes: ['session_creation']
});
}
// ... other implementations
}
Health Checks¶
1. Endpoint Configuration¶
router.get('/health', async (request: Request, env: Env) => {
try {
// Check database connection
await env.DB.prepare('SELECT 1').first();
// Check KV access
await env.SESSIONS.get('test');
return new Response('OK', { status: 200 });
} catch (error) {
return new Response('Service Unavailable', { status: 503 });
}
});
2. Monitoring Setup¶
Configure Cloudflare Health Checks: - Set up periodic checks - Configure notification thresholds - Set up alerting
Scaling Considerations¶
- Database Optimization
- Use appropriate indexes
- Implement caching strategies
-
Monitor query performance
-
Resource Management
- Configure worker limits
- Optimize memory usage
-
Implement request queuing
-
Cache Strategy
class CacheManager { constructor(private cache: KVNamespace) {} async get<T>(key: string): Promise<T | null> { const cached = await this.cache.get(key); return cached ? JSON.parse(cached) : null; } async set<T>(key: string, value: T, ttl: number): Promise<void> { await this.cache.put(key, JSON.stringify(value), { expirationTtl: ttl }); } }
Disaster Recovery¶
- Backup Strategy
- Regular database backups
- Configuration backups
-
Automated backup verification
-
Recovery Procedures
- Database restoration
- Configuration recovery
- Service restoration
Best Practices¶
- Deployment
- Use staged deployments
- Implement rollback procedures
-
Maintain deployment documentation
-
Monitoring
- Set up comprehensive logging
- Configure alerting thresholds
-
Regular performance reviews
-
Security
- Regular security audits
- Certificate rotation
- Access control reviews
Troubleshooting¶
Common issues and solutions: 1. Connection timeouts 2. Database errors 3. Memory limits 4. Rate limiting issues