chain-rdeveloper portal
build

Performance Optimization

Overview

This guide covers performance optimization strategies for the Chainr platform, focusing on identifying bottlenecks and implementing improvements.

Performance Monitoring

Key Metrics to Track

Response Time Metrics

  • P50, P95, P99 response times for all API endpoints

  • Time to first byte (TTFB) for critical requests

  • Database query execution time

  • External API call duration

Throughput Metrics

  • Requests per second (RPS) by endpoint

  • Concurrent users supported

  • Queue depth for background jobs

  • Cache hit rates

Resource Metrics

  • CPU utilization per service

  • Memory usage and leak detection

  • Disk I/O and storage performance

  • Network bandwidth and latency

Monitoring Setup

# Prometheus metrics for performance
from prometheus_client import Histogram, Counter, Gauge

# Response time histograms
api_request_duration = Histogram(
    'api_request_duration_seconds',
    'API request duration in seconds',
    ['method', 'endpoint', 'status_code']
)

# Database query metrics
db_query_duration = Histogram(
    'db_query_duration_seconds',
    'Database query duration',
    ['table', 'operation']
)

# Cache performance
cache_operation_duration = Histogram(
    'cache_operation_duration_seconds',
    'Cache operation duration',
    ['operation', 'result']  # hit/miss
)

# Resource gauges
active_connections = Gauge(
    'active_connections',
    'Number of active connections',
    ['service']
)

Database Optimization

Query Optimization

1. Index Analysis

-- Find missing indexes
SELECT
    schemaname,
    tablename,
    attname,
    n_distinct,
    correlation
FROM pg_stats
WHERE schemaname = 'public'
AND n_distinct > 1000
ORDER BY n_distinct DESC;

-- Check index usage
SELECT
    indexname,
    idx_scan,
    idx_tup_read,
    idx_tup_fetch
FROM pg_stat_user_indexes
ORDER BY idx_scan DESC;

-- Create composite indexes for common query patterns
CREATE INDEX CONCURRENTLY idx_projects_owner_status ON projects(owner_id, status);
CREATE INDEX CONCURRENTLY idx_documents_project_created ON documents(project_id, created_at DESC);

2. Query Optimization

# Bad: N+1 query problem
projects = await db.query(Project).all()
for project in projects:
    documents = await db.query(Document).filter(Document.project_id == project.id).all()

# Good: Use joins or selectinload
projects = await db.query(Project).options(
    selectinload(Project.documents)
).all()

3. Connection Pool Tuning

# SQLAlchemy engine configuration
engine = create_async_engine(
    DATABASE_URL,
    pool_size=10,          # Base pool size
    max_overflow=20,       # Max additional connections
    pool_timeout=30,       # Connection timeout
    pool_recycle=3600,     # Recycle connections after 1 hour
    echo=False,            # Disable SQL logging in production
)

Database Maintenance

-- Analyze tables for query planning
ANALYZE VERBOSE;

-- Vacuum for space reclamation
VACUUM (VERBOSE, ANALYZE);

-- Reindex for performance
REINDEX TABLE CONCURRENTLY projects;

-- Monitor table bloat
SELECT
    schemaname,
    tablename,
    n_dead_tup,
    n_live_tup,
    ROUND(n_dead_tup::float / (n_live_tup + n_dead_tup) * 100, 2) as bloat_ratio
FROM pg_stat_user_tables
WHERE n_live_tup + n_dead_tup > 0
ORDER BY bloat_ratio DESC;

Caching Strategies

Multi-Level Caching

1. Application-Level Caching

from cachetools import TTLCache
from functools import lru_cache

# TTL cache for expensive operations
user_cache = TTLCache(maxsize=1000, ttl=300)  # 5 minutes

@lru_cache(maxsize=128)
def get_user_permissions(user_id: str) -> List[str]:
    # Expensive database operation
    return db.query(...).all()

# Redis caching for distributed data
async def get_project_with_cache(project_id: str):
    cache_key = f"project:{project_id}"

    # Try cache first
    cached = await redis.get(cache_key)
    if cached:
        return json.loads(cached)

    # Cache miss - fetch from database
    project = await db.query(Project).filter(Project.id == project_id).first()
    if project:
        # Cache for 10 minutes
        await redis.setex(cache_key, 600, json.dumps(project.dict()))

    return project

2. HTTP Caching

# Cache-Control headers
@app.get("/api/projects")
async def list_projects(response: Response):
    projects = await get_projects()
    response.headers["Cache-Control"] = "public, max-age=300"  # 5 minutes
    return projects

# ETag for conditional requests
@app.get("/api/documents/{document_id}")
async def get_document(document_id: str, request: Request, response: Response):
    document = await get_document_by_id(document_id)
    etag = hashlib.md5(str(document.updated_at).encode()).hexdigest()

    if request.headers.get("If-None-Match") == etag:
        response.status_code = 304
        return

    response.headers["ETag"] = etag
    return document

3. CDN Integration

# Nginx CDN headers
location /static/ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    add_header X-Cache-Status $upstream_cache_status;
}

location /api/ {
    # Short cache for API responses
    expires 5m;
    add_header Cache-Control "private, max-age=300";
}

Application Optimization

Async/Await Best Practices

# Bad: Blocking operations in async functions
@app.get("/api/report")
async def generate_report():
    # This blocks the event loop!
    result = subprocess.run(["python", "heavy_script.py"], capture_output=True)
    return result.stdout

# Good: Use async alternatives
@app.get("/api/report")
async def generate_report():
    # Run in thread pool
    result = await asyncio.get_event_loop().run_in_executor(
        None, subprocess.run, ["python", "heavy_script.py"], {"capture_output": True}
    )
    return result.stdout

Background Job Processing

# Celery for background tasks
from celery import Celery

celery_app = Celery('chainr', broker='redis://localhost:6379/0')

@celery_app.task
def process_document(document_id: str):
    # Heavy processing here
    analyze_document(document_id)
    generate_thumbnail(document_id)
    update_search_index(document_id)

@app.post("/api/documents")
async def upload_document(file: UploadFile):
    document = await save_document(file)
    # Queue background processing
    process_document.delay(str(document.id))
    return {"document_id": document.id, "status": "processing"}

Memory Optimization

# Streaming responses for large data
@app.get("/api/documents/{document_id}/download")
async def download_document(document_id: str):
    document = await get_document(document_id)
    file_path = get_document_path(document)

    # Stream file instead of loading into memory
    return StreamingResponse(
        open(file_path, "rb"),
        media_type="application/octet-stream",
        headers={"Content-Disposition": f"attachment; filename={document.filename}"}
    )

# Generator for large result sets
async def get_projects_batch(last_id: str = None, batch_size: int = 100):
    query = select(Project).where(Project.id > last_id).limit(batch_size)
    result = await db.execute(query)
    return result.scalars().all()

@app.get("/api/projects/stream")
async def stream_projects():
    last_id = None
    while True:
        batch = await get_projects_batch(last_id)
        if not batch:
            break

        for project in batch:
            yield f"data: {json.dumps(project.dict())}\n\n"
            last_id = project.id

        await asyncio.sleep(0.1)  # Prevent overwhelming client

Infrastructure Optimization

Container Optimization

# Multi-stage build for smaller images
FROM python:3.11-slim as builder

# Install build dependencies
RUN apt-get update && apt-get install -y gcc libpq-dev && rm -rf /var/lib/apt/lists/*

# Install Python dependencies
COPY requirements.txt .
RUN pip install --user -r requirements.txt

FROM python:3.11-slim as runtime

# Copy installed packages
COPY --from=builder /root/.local /root/.local
ENV PATH=/root/.local/bin:$PATH

# Copy application
COPY . /app
WORKDIR /app

# Use non-root user
RUN useradd --create-home app && chown -R app:app /app
USER app

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Load Balancing

# Upstream configuration
upstream api_backend {
    least_conn;  # Least connections algorithm
    server svc-core-1:8000 weight=1 max_fails=3 fail_timeout=30s;
    server svc-core-2:8000 weight=1 max_fails=3 fail_timeout=30s;
    server svc-core-3:8000 weight=1 max_fails=3 fail_timeout=30s;
    keepalive 32;
}

server {
    location /api/ {
        proxy_pass http://api_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    }
}

Horizontal Scaling

# Docker Compose scaling
services:
  svc-core:
    deploy:
      replicas: 3
      resources:
        limits:
          cpus: "1.0"
          memory: 1G
        reservations:
          cpus: "0.5"
          memory: 512M
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s

Frontend Optimization

Bundle Optimization

// Code splitting with React.lazy
const ProjectsPage = lazy(() => import("./pages/ProjectsPage"));
const DocumentsPage = lazy(() => import("./pages/DocumentsPage"));

// Bundle analysis
// Use webpack-bundle-analyzer or vite-bundle-analyzer
// npm install --save-dev webpack-bundle-analyzer

Image Optimization

// Responsive images with lazy loading
import { LazyLoadImage } from "react-lazy-load-image-component";

<LazyLoadImage
  src={imageSrc}
  srcSet={`${imageSrc}?w=400 400w, ${imageSrc}?w=800 800w`}
  sizes="(max-width: 600px) 400px, 800px"
  alt="Document preview"
/>;

API Optimization

// Request batching
const batchRequests = (requests) => {
  return fetch("/api/batch", {
    method: "POST",
    body: JSON.stringify({ requests }),
  });
};

// Debounced search
const debouncedSearch = useMemo(
  () => debounce((query) => searchAPI(query), 300),
  [],
);

Performance Testing

Load Testing

# Artillery load testing
echo '
config:
  target: "http://localhost:8000"
  phases:
    - duration: 300
      arrivalRate: 20
      name: "Warm up"
    - duration: 600
      arrivalRate: 50
      name: "Load test"
scenarios:
  - name: "API usage"
    weight: 70
    requests:
      - get:
          url: "/api/projects"
      - get:
          url: "/api/documents"
  - name: "File upload"
    weight: 30
    requests:
      - post:
          url: "/api/documents"
          body: "test file content"
' > load-test.yml

artillery run load-test.yml --output report.json

Profiling Tools

# Python profiling
python -m cProfile -o profile.prof app/main.py
snakeviz profile.prof  # Visualize results

# Memory profiling
from memory_profiler import profile
mprof run app/main.py
mprof plot  # Generate memory usage plots

# Database profiling
# Use pg_stat_statements
# Enable in postgresql.conf: shared_preload_libraries = 'pg_stat_statements'

Performance Budgets

Define Performance Targets

// Web performance budgets (in Lighthouse)
const performanceBudget = {
  // Core Web Vitals
  "first-contentful-paint": 1800, // ms
  "largest-contentful-paint": 2500, // ms
  "first-input-delay": 100, // ms
  "cumulative-layout-shift": 0.1, // score

  // Bundle sizes
  "bundle-size": 500 * 1024, // 500KB
  "css-size": 50 * 1024, // 50KB

  // API performance
  "api-response-time-p95": 500, // ms
};

API Performance Budgets

# API response time budgets
API_BUDGETS = {
    'GET /api/projects': 200,      # ms
    'GET /api/documents': 300,     # ms
    'POST /api/documents': 1000,   # ms (file upload)
    'POST /api/workflows': 500,    # ms
}

@app.middleware("http")
async def performance_budget_middleware(request, call_next):
    start_time = time.time()
    response = await call_next(request)
    duration = (time.time() - start_time) * 1000  # ms

    endpoint = f"{request.method} {request.url.path}"
    budget = API_BUDGETS.get(endpoint)

    if budget and duration > budget:
        logger.warning(
            f"Performance budget exceeded for {endpoint}: "
            f"{duration:.0f}ms > {budget}ms budget"
        )

    return response

Continuous Performance Monitoring

Automated Performance Regression Testing

# GitHub Actions performance test
name: Performance Tests
on:
  pull_request:
    branches: [main]

jobs:
  performance:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Run performance tests
        run: |
          # Start services
          docker-compose up -d

          # Wait for services
          sleep 30

          # Run load test
          artillery run tests/performance/load-test.yml --output report.json

          # Check performance budgets
          node scripts/check-performance-budget.js report.json

Performance Dashboards

# Grafana panels configuration
PERFORMANCE_PANELS = [
    {
        "title": "API Response Times",
        "type": "graph",
        "targets": [
            {
                "expr": "histogram_quantile(0.95, rate(api_request_duration_seconds[5m]))",
                "legendFormat": "P95 Response Time"
            }
        ]
    },
    {
        "title": "Database Query Performance",
        "type": "table",
        "targets": [
            {
                "expr": "rate(db_query_duration_seconds[5m])",
                "legendFormat": "{{table}} {{operation}}"
            }
        ]
    },
    {
        "title": "Cache Hit Rate",
        "type": "singlestat",
        "targets": [
            {
                "expr": "rate(cache_hits_total[5m]) / (rate(cache_hits_total[5m]) + rate(cache_misses_total[5m])) * 100",
                "legendFormat": "Cache Hit Rate %"
            }
        ]
    }
]

Performance Optimization Checklist

Database

  • [ ] Indexes on frequently queried columns

  • [ ] Query optimization (avoid N+1 problems)

  • [ ] Connection pool tuning

  • [ ] Regular maintenance (VACUUM, ANALYZE)

Application

  • [ ] Async/await for I/O operations

  • [ ] Background job processing for heavy tasks

  • [ ] Memory-efficient data structures

  • [ ] Response streaming for large data

Caching

  • [ ] Multi-level caching strategy

  • [ ] Appropriate TTL values

  • [ ] Cache invalidation policies

  • [ ] Cache performance monitoring

Infrastructure

  • [ ] Horizontal scaling configuration

  • [ ] Load balancer tuning

  • [ ] Container optimization

  • [ ] CDN integration

Frontend

  • [ ] Code splitting and lazy loading

  • [ ] Image optimization

  • [ ] Bundle size monitoring

  • [ ] API request optimization

Monitoring

  • [ ] Performance metrics collection

  • [ ] Alerting on performance degradation

  • [ ] Automated performance testing

  • [ ] Performance budget enforcement

Regular performance optimization ensures the Chainr platform can handle growing user demands while maintaining excellent user experience.