System Design

Reverse Proxy va API Gateway

Reverse Proxy va API Gateway — client va backend serverlar o’rtasidagi “vositachi” layer.

Forward Proxy vs Reverse Proxy

Forward Proxy (Client tomonda)

Client → Proxy → Internet

User bitta proxy orqali turli saytlarga kiradi

Misol: VPN, corporate proxy

Maqsad:

Reverse Proxy (Server tomonda)

Client → Reverse Proxy → Backend Servers

Foydalanuvchi proxy bilan gaplashadi, 
backend serverlarni ko'rmaydi

Maqsad:

Reverse Proxy nima qiladi?

1. Load Balancing

              ┌─────────────┐
Client ──────▶│   Nginx     │
              │(Rev. Proxy) │
              └──────┬──────┘

         ┌───────────┼───────────┐
         ▼           ▼           ▼
     ┌──────┐   ┌──────┐   ┌──────┐
     │App 1 │   │App 2 │   │App 3 │
     └──────┘   └──────┘   └──────┘

Traffic taqsimlash (oldingi darsda ko’rdik).

2. SSL Termination

Client (HTTPS) → Reverse Proxy (decrypt) → Backend (HTTP)

Foyda:

Nginx config:

server {
    listen 443 ssl;
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    location / {
        proxy_pass http://backend;  # HTTP (SSL yo'q)
    }
}

3. Caching

Client → Reverse Proxy

         ├─ Cache Hit? → Return cached

         └─ Cache Miss → Backend → Cache → Client

Nginx caching:

proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m;

server {
    location /api/ {
        proxy_cache my_cache;
        proxy_cache_valid 200 10m;
        proxy_pass http://backend;
    }
}

API response 10 minut cache’lanadi.

4. Compression

Backend → Large JSON (1MB)

Reverse Proxy (gzip)

Client ← Compressed (100KB) 

Nginx gzip:

gzip on;
gzip_types text/plain application/json;
gzip_min_length 1000;

5. Static file serving

/static/* → Nginx (to'g'ridan-to'g'ri)
/api/*    → Backend server

Nginx static:

location /static/ {
    root /var/www;
    expires 1y;
    add_header Cache-Control "public, immutable";
}

location /api/ {
    proxy_pass http://backend;
}

Backend static file serve qilmaydi → performance ++

6. Security

Reverse Proxy:
- Rate limiting
- IP whitelist/blacklist
- Request filtering (SQL injection, XSS)
- Hide backend topology

Nginx rate limit:

limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

location /api/ {
    limit_req zone=api burst=20;
    proxy_pass http://backend;
}

10 req/sec, burst 20 gacha.

API Gateway

API Gateway = Reverse Proxy + API management features.

Reverse Proxy vs API Gateway

FeatureReverse ProxyAPI Gateway
Load balancing
SSL termination
Caching
Rate limiting
AuthenticationBasicAdvanced
API versioning
Request transformationLimited
Analytics
Developer portal

Xulosa: API Gateway = Reverse Proxy + ko’proq features.

API Gateway features

1. Authentication & Authorization

Client → API Gateway → Verify JWT → Backend

                  401 (invalid token)

Kong config:

plugins:
  - name: jwt
    config:
      secret_is_base64: false
      key_claim_name: iss

AWS API Gateway:

authorizer:
  type: JWT
  identitySource: $request.header.Authorization
  issuerUrl: https://cognito.amazonaws.com

2. Request/Response Transformation

Client Request:
POST /users
{ "firstName": "John", "lastName": "Doe" }

API Gateway Transform:
POST /api/v2/create-user
{ "full_name": "John Doe", "timestamp": 1234567890 }

Kong transform:

plugins:
  - name: request-transformer
    config:
      add:
        headers:
          - X-Service-Version:2.0
      rename:
        body:
          - firstName:full_name

3. API Versioning

Client → /v1/users → Backend v1
Client → /v2/users → Backend v2

Nginx:

location /v1/ {
    proxy_pass http://backend-v1;
}

location /v2/ {
    proxy_pass http://backend-v2;
}

4. Rate Limiting (Advanced)

Free tier:    100 req/hour
Premium tier: 10,000 req/hour

Kong rate limiting per API key:

plugins:
  - name: rate-limiting
    config:
      minute: 100
      policy: local
      limit_by: credential

5. Request Aggregation

Client bitta request → API Gateway
                       ├─ Service A
                       ├─ Service B
                       └─ Service C

Client ← Combined response

Misol: Mobile app bitta requestda profile + posts + notifications olishi kerak.

GraphQL Gateway:

query {
  user(id: 123) {
    profile     # Service A
    posts       # Service B  
    notifications # Service C
  }
}

6. Analytics & Monitoring

API Gateway logs:
- Request count
- Latency (p50, p95, p99)
- Error rate
- Top endpoints
- Top consumers

AWS API Gateway: CloudWatch metrics
Kong: Prometheus + Grafana

1. Nginx (Reverse Proxy)

Juda tez
Bepul, open-source
Battle-tested
Advanced API features kam

Qachon: Oddiy load balancing, SSL termination.

2. Kong

Open-source + Enterprise
Plugin ecosystem (OAuth, JWT, rate limiting)
Kubernetes-native
 Enterprise: $$$

Qachon: Microservices, Kubernetes.

3. AWS API Gateway

Fully managed
AWS ecosystem integration
Serverless (Lambda)
 $3.50 per million requests

Qachon: AWS infrastructure, serverless.

4. Traefik

Container-native
Auto-discovery
Let's Encrypt automatic SSL
Kubernetes, Docker Swarm

Qachon: Docker/Kubernetes environments.

5. Apollo Gateway (GraphQL)

GraphQL federation
Schema stitching
Subgraph routing

Qachon: GraphQL microservices.

Nginx real-world config

upstream backend {
    least_conn;
    server 10.0.1.10:8080 weight=3;
    server 10.0.1.11:8080 weight=2;
    server 10.0.1.12:8080 weight=1;
}

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=api_cache:10m max_size=1g;

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/m;

server {
    listen 443 ssl http2;
    server_name api.example.com;
    
    # SSL
    ssl_certificate /etc/ssl/cert.pem;
    ssl_certificate_key /etc/ssl/key.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    
    # Compression
    gzip on;
    gzip_types application/json;
    
    # Static files
    location /static/ {
        root /var/www;
        expires 1y;
    }
    
    # API endpoints
    location /api/ {
        # Rate limit
        limit_req zone=api_limit burst=50;
        
        # Cache
        proxy_cache api_cache;
        proxy_cache_valid 200 5m;
        proxy_cache_key "$request_uri";
        
        # Proxy headers
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # Timeouts
        proxy_connect_timeout 5s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
        
        # Backend
        proxy_pass http://backend;
    }
    
    # Health check endpoint
    location /health {
        access_log off;
        return 200 "OK\n";
        add_header Content-Type text/plain;
    }
}

API Gateway patterns

1. Backend for Frontend (BFF)

┌─────────┐           ┌──────────────┐
│Web App  │──────────▶│ Web Gateway  │
└─────────┘           └──────┬───────┘

┌─────────┐           ┌──────▼───────┐
│Mobile   │──────────▶│Mobile Gateway│
└─────────┘           └──────┬───────┘

                    ┌────────┴────────┐
                    ▼                 ▼
              ┌──────────┐      ┌──────────┐
              │Service A │      │Service B │
              └──────────┘      └──────────┘

Har bir client uchun alohida gateway.

Foyda:

2. API Composition

Client → API Gateway
         ├─ GET /users/{id}      (User Service)
         ├─ GET /orders?user={id} (Order Service)
         └─ GET /reviews?user={id} (Review Service)

Client ← Combined JSON

3. Service Mesh vs API Gateway

API Gateway: Edge (external clients)
Service Mesh: Internal (service-to-service)

External Client

  API Gateway (Kong)

  ┌────────────────┐
  │ Service Mesh   │
  │ (Istio/Linkerd)│
  │  ┌───┐  ┌───┐  │
  │  │ A │→ │ B │  │
  │  └───┘  └─┬─┘  │
  │          ↓     │
  │         ┌───┐  │
  │         │ C │  │
  │         └───┘  │
  └────────────────┘

Best Practices

  1. SSL termination at gateway

    • Backend’da SSL overhead yo’q
  2. Cache aggressively

    • API responses cache qiling
    • Static content CDN’da
  3. Rate limiting per client

    • API key or JWT bilan
  4. Monitoring & alerts

    • Latency, error rate
    • Alert on anomalies
  5. Health checks

    • Unhealthy serverlarni o’chirish
  6. Timeouts

    • Connection, read, write timeouts
    • Hang qilgan requestlarni kesish
  7. Security headers

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";
    

Xulosa

Reverse Proxy:

API Gateway:

Tanlash:

Keyingi dars: ACID xususiyatlari va database consistency.