Skip to content

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

  1. Build Documentation

    # Install MkDocs dependencies
    pip install -r requirements.txt
    
    # Build documentation
    mkdocs build
    

  2. Build the Project

    npm run build
    

  3. Run Tests

    npm run test
    

  4. Deploy to Production

    # Deploy to Cloudflare Pages (main branch for production)
    wrangler pages deploy dist --project-name telco-api --branch main
    
    # Verify the deployment
    wrangler pages deployment list
    

  5. 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

  1. Database Optimization
  2. Use appropriate indexes
  3. Implement caching strategies
  4. Monitor query performance

  5. Resource Management

  6. Configure worker limits
  7. Optimize memory usage
  8. Implement request queuing

  9. 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

  1. Backup Strategy
  2. Regular database backups
  3. Configuration backups
  4. Automated backup verification

  5. Recovery Procedures

  6. Database restoration
  7. Configuration recovery
  8. Service restoration

Best Practices

  1. Deployment
  2. Use staged deployments
  3. Implement rollback procedures
  4. Maintain deployment documentation

  5. Monitoring

  6. Set up comprehensive logging
  7. Configure alerting thresholds
  8. Regular performance reviews

  9. Security

  10. Regular security audits
  11. Certificate rotation
  12. Access control reviews

Troubleshooting

Common issues and solutions: 1. Connection timeouts 2. Database errors 3. Memory limits 4. Rate limiting issues

References

  1. Cloudflare Workers Documentation
  2. Cloudflare D1 Documentation
  3. 3GPP TS 23.203: Policy and charging control architecture