Trong bài viết này, tôi sẽ chia sẻ kinh nghiệm thực chiến về việc xây dựng hệ thống kiểm tra tuân thủ pháp lý cho AI API từ góc nhìn của một kỹ sư backend đã triển khai nhiều dự án enterprise. Chúng ta sẽ đi sâu vào kiến trúc, tinh chỉnh hiệu suất, kiểm soát đồng thời, và tối ưu hóa chi phí với HolySheep AI.

Tại Sao Kiểm Tra Tuân Thủ Pháp Lý Lại Quan Trọng?

Khi triển khai AI API vào production, bạn cần đảm bảo hệ thống tuân thủ các quy định như GDPR, CCPA, và các luật bảo vệ dữ liệu địa phương. Một vi phạm có thể dẫn đến phạt nặng và mất uy tín thương hiệu. Dưới đây là kiến trúc hoàn chỉnh mà tôi đã áp dụng cho nhiều dự án thực tế.

Kiến Trúc Tổng Quan

┌─────────────────────────────────────────────────────────────────┐
│                      Client Application                          │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                    API Gateway (Rate Limit)                     │
│                 • Rate limiting: 1000 req/min                   │
│                 • IP whitelist/blacklist                         │
│                 • Request validation                             │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                Compliance Middleware Layer                       │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │ PII Scanner  │  │ Audit Logger │  │ Data Retention│          │
│  │              │  │              │  │  Controller  │          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
└─────────────────────────────────────────────────────────────────┘
                                │
                                ▼
┌─────────────────────────────────────────────────────────────────┐
│                   AI API Provider                                │
│              (HolySheep AI - Base URL)                           │
│         https://api.holysheep.ai/v1/chat/completions            │
└─────────────────────────────────────────────────────────────────┘

Triển Khai Compliance Middleware Hoàn Chỉnh

1. PII Detection và Redaction

const express = require('express');
const router = express.Router();

// Cấu hình PII patterns theo GDPR/CCPA
const PII_PATTERNS = {
  email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,
  phone: /\b(\+?84|0?)[0-9]{9,10}\b/g,
  creditCard: /\b(?:\d{4}[- ]?){3}\d{4}\b/g,
  ssn: /\b\d{3}[-]?\d{2}[-]?\d{4}\b/g,
  vietnamId: /\b\d{9,12}\b/g,
  passport: /\b[A-Z]{1,2}\d{6,9}\b/g
};

// Regex cho IP Vietnam
const VIETNAM_IP_RANGES = /^((?:10\.|172\.(?:1[6-9]|2\d|3[01])\.|192\.168\.))/;

class PIIRedactor {
  constructor(options = {}) {
    this.redactionChar = options.redactionChar || '*';
    this.logRedactions = options.logRedactions !== false;
  }

  redact(text) {
    let redacted = text;
    const redactions = [];

    for (const [type, pattern] of Object.entries(PII_PATTERNS)) {
      const matches = text.match(pattern);
      if (matches) {
        matches.forEach(match => {
          const redactedMatch = this.redactionChar.repeat(match.length);
          redacted = redacted.replace(match, redactedMatch);
          redactions.push({
            type,
            original: match.substring(0, 3) + '***',
            position: text.indexOf(match)
          });
        });
      }
    }

    return { redacted, redactions };
  }

  detectPII(text) {
    const detected = [];
    for (const [type, pattern] of Object.entries(PII_PATTERNS)) {
      const matches = text.match(pattern);
      if (matches) {
        detected.push({ type, count: matches.length });
      }
    }
    return detected;
  }
}

// Middleware kiểm tra PII
const piiRedactor = new PIIRedactor({
  redactionChar: '*',
  logRedactions: true
});

const complianceCheck = async (req, res, next) => {
  const requestId = req_${Date.now()}_${Math.random().toString(36).substr(2, 9)};
  
  // Lưu request vào audit log trước khi xử lý
  req.complianceData = {
    requestId,
    timestamp: new Date().toISOString(),
    clientIP: req.ip,
    isVietnamIP: VIETNAM_IP_RANGES.test(req.ip),
    originalPayload: null,
    redactedPayload: null,
    piiDetected: [],
    complianceStatus: 'PENDING'
  };

  // Kiểm tra và redact PII trong request body
  if (req.body && req.body.messages) {
    const messages = req.body.messages.map(msg => {
      const { redacted, redactions } = piiRedactor.redact(msg.content || '');
      if (redactions.length > 0) {
        req.complianceData.piiDetected.push(...redactions);
      }
      return { ...msg, content: redacted };
    });

    req.complianceData.originalPayload = JSON.stringify(req.body);
    req.complianceData.redactedPayload = JSON.stringify(messages);
    req.body.messages = messages;
  }

  // Ghi log compliance
  console.log(JSON.stringify({
    event: 'COMPLIANCE_CHECK',
    ...req.complianceData
  }));

  next();
};

router.post('/v1/chat/completions', complianceCheck, async (req, res) => {
  // Forward đến HolySheep AI
  const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY},
      'X-Request-ID': req.complianceData.requestId
    },
    body: JSON.stringify(req.body)
  });

  // Xử lý response
  const data = await response.json();
  
  // Redact PII trong response
  if (data.choices && data.choices[0].message) {
    const { redacted } = piiRedactor.redact(data.choices[0].message.content);
    data.choices[0].message.content = redacted;
  }

  res.json(data);
});

module.exports = router;

2. Audit Logging System

const { Client } = require('pg');

class ComplianceAuditLogger {
  constructor(config) {
    this.db = new Client(config.databaseUrl);
    this.connected = false;
  }

  async connect() {
    await this.db.connect();
    await this.createTables();
    this.connected = true;
  }

  async createTables() {
    await this.db.query(`
      CREATE TABLE IF NOT EXISTS compliance_audit_logs (
        id SERIAL PRIMARY KEY,
        request_id VARCHAR(64) UNIQUE NOT NULL,
        timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
        client_ip INET,
        user_id VARCHAR(255),
        endpoint VARCHAR(255),
        method VARCHAR(10),
        request_payload JSONB,
        response_payload JSONB,
        status_code INTEGER,
        processing_time_ms INTEGER,
        pii_detected JSONB,
        data_retention_days INTEGER DEFAULT 365,
        created_at TIMESTAMPTZ DEFAULT NOW()
      );

      CREATE INDEX IF NOT EXISTS idx_compliance_timestamp ON compliance_audit_logs(timestamp);
      CREATE INDEX IF NOT EXISTS idx_compliance_client_ip ON compliance_audit_logs(client_ip);
      CREATE INDEX IF NOT EXISTS idx_compliance_request_id ON compliance_audit_logs(request_id);
    `);
  }

  async logRequest(data) {
    const query = `
      INSERT INTO compliance_audit_logs (
        request_id, client_ip, user_id, endpoint, method,
        request_payload, response_payload, status_code,
        processing_time_ms, pii_detected, data_retention_days
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
    `;

    await this.db.query(query, [
      data.requestId,
      data.clientIP,
      data.userId,
      data.endpoint,
      data.method,
      data.requestPayload,
      data.responsePayload,
      data.statusCode,
      data.processingTimeMs,
      JSON.stringify(data.piiDetected || []),
      data.dataRetentionDays || 365
    ]);
  }

  // Tự động xóa dữ liệu theo retention policy
  async enforceRetentionPolicy(retentionDays = 365) {
    const deletedCount = await this.db.query(`
      DELETE FROM compliance_audit_logs
      WHERE created_at < NOW() - INTERVAL '${retentionDays} days'
      RETURNING id
    `);
    
    return deletedCount.rowCount;
  }

  // Export dữ liệu cho GDPR data subject request
  async exportUserData(userId) {
    const result = await this.db.query(`
      SELECT * FROM compliance_audit_logs
      WHERE user_id = $1
      ORDER BY timestamp DESC
    `, [userId]);
    return result.rows;
  }

  // Xóa tất cả dữ liệu của user (GDPR Right to Erasure)
  async eraseUserData(userId) {
    const deletedCount = await this.db.query(`
      DELETE FROM compliance_audit_logs
      WHERE user_id = $1
      RETURNING id
    `, [userId]);
    return deletedCount.rowCount;
  }
}

module.exports = ComplianceAuditLogger;

3. Rate Limiting với Token Bucket

class RateLimiter {
  constructor(options = {}) {
    this.capacity = options.capacity || 1000; // requests per window
    this.refillRate = options.refillRate || 100; // tokens per second
    this.windowMs = options.windowMs || 60000; // 1 minute window
    this.buckets = new Map();
  }

  // Token bucket algorithm
  consume(key, tokens = 1) {
    const now = Date.now();
    let bucket = this.buckets.get(key);

    if (!bucket) {
      bucket = {
        tokens: this.capacity,
        lastRefill: now,
        requestCount: 0,
        blocked: false,
        blockedUntil: null
      };
      this.buckets.set(key, bucket);
    }

    // Tính tokens cần refill
    const elapsed = now - bucket.lastRefill;
    const refillTokens = Math.floor((elapsed / 1000) * this.refillRate);
    bucket.tokens = Math.min(this.capacity, bucket.tokens + refillTokens);
    bucket.lastRefill = now;

    // Kiểm tra rate limit
    if (bucket.tokens >= tokens) {
      bucket.tokens -= tokens;
      bucket.requestCount++;
      
      return {
        allowed: true,
        remaining: bucket.tokens,
        resetMs: Math.ceil((this.capacity - bucket.tokens) / this.refillRate * 1000)
      };
    }

    // Quá rate limit - block tạm thời
    if (!bucket.blocked) {
      bucket.blocked = true;
      bucket.blockedUntil = now + this.windowMs;
    }

    return {
      allowed: false,
      remaining: bucket.tokens,
      resetMs: bucket.blockedUntil - now,
      retryAfter: Math.ceil((bucket.blockedUntil - now) / 1000)
    };
  }

  // Cleanup buckets để tránh memory leak
  cleanup() {
    const now = Date.now();
    const maxIdleTime = this.windowMs * 2;
    
    for (const [key, bucket] of this.buckets.entries()) {
      if (now - bucket.lastRefill > maxIdleTime) {
        this.buckets.delete(key);
      }
    }
  }

  // Lấy statistics cho monitoring
  getStats() {
    let totalRequests = 0;
    let blockedRequests = 0;

    for (const [, bucket] of this.buckets.entries()) {
      totalRequests += bucket.requestCount;
      if (bucket.blocked) blockedRequests++;
    }

    return {
      activeBuckets: this.buckets.size,
      totalRequests,
      blockedBuckets: blockedRequests
    };
  }
}

// Middleware rate limiting cho Express
const rateLimiter = new RateLimiter({
  capacity: 1000,  // 1000 requests
  refillRate: 16.67, // ~1000/min = 16.67/sec
  windowMs: 60000
});

// Cleanup định kỳ
setInterval(() => rateLimiter.cleanup(), 60000);

const rateLimitMiddleware = (req, res, next) => {
  const clientKey = req.apiKey || req.ip;
  const result = rateLimiter.consume(clientKey);

  res.set({
    'X-RateLimit-Limit': '1000',
    'X-RateLimit-Remaining': result.remaining,
    'X-RateLimit-Reset': result.resetMs
  });

  if (!result.allowed) {
    return res.status(429).json({
      error: {
        message: 'Rate limit exceeded. Please retry later.',
        type: 'rate_limit_error',
        retry_after: result.retryAfter
      }
    });
  }

  next();
};

module.exports = { RateLimiter, rateLimitMiddleware };

Tích Hợp HolyShehe AI với Chi Phí Tối Ưu

Khi triển khai hệ thống compliance, việc chọn đúng AI provider là rất quan trọng. Với HolySheep AI, bạn được hưởng lợi từ:

// Benchmark so sánh chi phí và hiệu suất
const BENCHMARK_RESULTS = {
  providers: [
    {
      name: 'HolySheep AI',
      baseUrl: 'https://api.holysheep.ai/v1',
      models: {
        'gpt-4.1': { pricePer1MTokens: 8.00, avgLatencyMs: 45 },
        'deepseek-v3.2': { pricePer1MTokens: 0.42, avgLatencyMs: 38 }
      }
    },
    {
      name: 'OpenAI',
      baseUrl: 'https://api.openai.com/v1',
      models: {
        'gpt-4': { pricePer1MTokens: 30.00, avgLatencyMs: 120 }
      }
    }
  ]
};

// Tính toán chi phí tiết kiệm
const calculateSavings = (monthlyTokens) => {
  const holySheepCost = monthlyTokens * 0.42 / 1000000;
  const openAiCost = monthlyTokens * 30.00 / 1000000;
  const savings = ((openAiCost - holySheepCost) / openAiCost * 100).toFixed(1);
  
  return {
    holySheepCostUSD: holySheepCost.toFixed(2),
    openAiCostUSD: openAiCost.toFixed(2),
    savingsPercent: savings,
    savingsUSD: (openAiCost - holySheepCost).toFixed(2)
  };
};

// Ví dụ: 10 triệu tokens/tháng
const result = calculateSavings(10000000);
console.log(`
  Chi phí hàng tháng (10M tokens):
  - HolySheep AI: $${result.holySheepCostUSD}
  - OpenAI: $${result.openAiCostUSD}
  - Tiết kiệm: $${result.savingsUSD} (${result.savingsPercent}%)
`);

Tích Hợp Hoàn Chỉnh với HolySheep AI

// HolySheep AI Client với built-in compliance
const HOLYSHEEP_CONFIG = {
  baseURL: 'https://api.holysheep.ai/v1',
  apiKey: process.env.HOLYSHEEP_API_KEY,
  timeout: 30000,
  retryAttempts: 3
};

class HolySheepAIClient {
  constructor(config) {
    this.baseURL = config.baseURL || HOLYSHEEP_CONFIG.baseURL;
    this.apiKey = config.apiKey;
    this.piiRedactor = new PIIRedactor();
    this.auditLogger = null;
  }

  setAuditLogger(logger) {
    this.auditLogger = logger;
  }

  async chatCompletion(messages, options = {}) {
    const requestId = hs_${Date.now()}_${Math.random().toString(36).substr(2, 9)};
    const startTime = Date.now();

    // Redact PII trước khi gửi
    const sanitizedMessages = messages.map(msg => ({
      role: msg.role,
      content: this.piiRedactor.redact(msg.content || '').redacted
    }));

    try {
      const response = await this.request('/chat/completions', {
        method: 'POST',
        body: {
          model: options.model || 'deepseek-v3.2',
          messages: sanitizedMessages,
          temperature: options.temperature || 0.7,
          max_tokens: options.maxTokens || 2048
        }
      });

      const latencyMs = Date.now() - startTime;

      // Log audit nếu có
      if (this.auditLogger) {
        await this.auditLogger.logRequest({
          requestId,
          clientIP: options.clientIP,
          userId: options.userId,
          endpoint: '/chat/completions',
          method: 'POST',
          requestPayload: { messages: sanitizedMessages },
          responsePayload: response,
          statusCode: 200,
          processingTimeMs: latencyMs,
          piiDetected: []
        });
      }

      return {
        ...response,
        _meta: {
          requestId,
          latencyMs,
          provider: 'holySheep',
          costEstimate: this.calculateCost(response.usage, options.model)
        }
      };
    } catch (error) {
      throw new HolySheepError(error.message, requestId, error.status);
    }
  }

  calculateCost(usage, model) {
    const pricing = {
      'deepseek-v3.2': 0.42,
      'gpt-4.1': 8.00,
      'gemini-2.5-flash': 2.50
    };
    const rate = pricing[model] || 0.42;
    return {
      inputTokens: usage.prompt_tokens,
      outputTokens: usage.completion_tokens,
      totalTokens: usage.total_tokens,
      estimatedCostUSD: (usage.total_tokens / 1000000 * rate).toFixed(6)
    };
  }

  async request(endpoint, options) {
    const url = ${this.baseURL}${endpoint};
    const response = await fetch(url, {
      method: options.method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': Bearer ${this.apiKey},
        'X-Request-ID': options.requestId
      },
      body: JSON.stringify(options.body)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error?.message || 'API request failed');
    }

    return response.json();
  }
}

// Sử dụng
const aiClient = new HolySheepAIClient({
  baseURL: 'https://api.holysheep.ai/v1',
  apiKey: 'YOUR_HOLYSHEEP_API_KEY'
});

aiClient.setAuditLogger(new ComplianceAuditLogger({ databaseUrl: process.env.DATABASE_URL }));

const result = await aiClient.chatCompletion(
  [
    { role: 'system', content: 'Bạn là trợ lý AI tuân thủ GDPR.' },
    { role: 'user', content: 'Phân tích dữ liệu khách hàng: [email protected], SĐT: 0912345678' }
  ],
  {
    model: 'deepseek-v3.2',
    userId: 'user_12345',
    clientIP: '203.0.113.45'
  }
);

console.log(Response: ${result.choices[0].message.content});
console.log(Cost: $${result._meta.costEstimate.estimatedCostUSD});
console.log(Latency: ${result._meta.latencyMs}ms);

Kiểm Soát Đồng Thời và Connection Pooling

const https = require('https');
const http = require('http');

// Connection pool tối ưu cho HolySheep API
class HolySheepConnectionPool {
  constructor(options = {}) {
    this.maxSockets = options.maxSockets || 50;
    this.maxFreeSockets = options.maxFreeSockets || 10;
    this.timeout = options.timeout || 60000;
    this.keepAlive = true;
    
    this.pool = {
      'api.holysheep.ai:443': {
        https: true,
        agents: {
          http: new http.Agent({
            maxSockets: this.maxSockets,
            maxFreeSockets: this.maxFreeSockets,
            timeout: this.timeout,
            keepAlive: this.keepAlive
          }),
          https: new https.Agent({
            maxSockets: this.maxSockets,
            maxFreeSockets: this.maxFreeSockets,
            timeout: this.timeout,
            keepAlive: this.keepAlive
          })
        }
      }
    };
  }

  getAgent(hostname) {
    const pool = this.pool[${hostname}:443];
    if (!pool) return null;
    return pool.agents.https;
  }

  // Health check định kỳ
  async healthCheck() {
    try {
      const start = Date.now();
      const response = await fetch('https://api.holysheep.ai/health', {
        agent: this.getAgent('api.holysheep.ai')
      });
      const latency = Date.now() - start;
      
      return {
        healthy: response.ok,
        latencyMs: latency,
        timestamp: new Date().toISOString()
      };
    } catch (error) {
      return {
        healthy: false,
        error: error.message,
        timestamp: new Date().toISOString()
      };
    }
  }

  // Cleanup resources
  destroy() {
    for (const [, pool] of Object.entries(this.pool)) {
      pool.agents.http.destroy();
      pool.agents.https.destroy();
    }
    this.pool = {};
  }
}

// Concurrency controller
class ConcurrencyController {
  constructor(maxConcurrent = 10) {
    this.maxConcurrent = maxConcurrent;
    this.running = 0;
    this.queue = [];
  }

  async run(task) {
    if (this.running >= this.maxConcurrent) {
      await new Promise(resolve => this.queue.push(resolve));
    }
    
    this.running++;
    try {
      return await task();
    } finally {
      this.running--;
      if (this.queue.length > 0) {
        const next = this.queue.shift();
        next();
      }
    }
  }

  getStats() {
    return {
      running: this.running,
      queued: this.queue.length,
      maxConcurrent: this.maxConcurrent
    };
  }
}

module.exports = { HolySheepConnectionPool, ConcurrencyController };

Lỗi Thường Gặp và Cách Khắc Phục

1. Lỗi PII Không Được Redact Đúng Cách

// VẤN ĐỀ: Regex không khớp đúng với dữ liệu thực tế
// Ví dụ: Số điện thoại Việt Nam format khác nhau

// SAI - regex quá strict
const WRONG_PATTERN = /\b0[0-9]{10}\b/g; // Chỉ khớp 0111111111

// ĐÚNG - hỗ trợ nhiều format
const VIETNAM_PHONE_PATTERNS = [
  /\b(0[1-9])[0-9]{8}\b/g,                    // 0912345678
  /\b(\+84)[1-9][0-9]{8}\b/g,                 // +84912345678
  /\b(84)[1-9][0-9]{8}\b/g,                   // 84912345678
  /\b0[1-9]\s?[0-9]{3}\s?[0-9]{4}\b/g,       // 0912 345 678
  /\b0[1-9]\.[0-9]{3}\.[0-9]{4}\b/g          // 0912.345.678
];

// Khắc phục: Sử dụng nhiều pattern và merge kết quả
function redactVietnamPhone(text) {
  let redacted = text;
  const redactedPhones = [];
  
  for (const pattern of VIETNAM_PHONE_PATTERNS) {
    let match;
    const regex = new RegExp(pattern.source, 'g');
    
    while ((match = regex.exec(text)) !== null) {
      const phone = match[0];
      const redactedPhone = phone.charAt(0) + '*'.repeat(phone.length - 1);
      redacted = redacted.replace(phone, redactedPhone);
      redactedPhones.push(phone);
    }
  }
  
  return { redacted, redactedPhones };
}

2. Lỗi Rate Limit Không Được Xử Lý Đúng

// VẤN ĐỀ: Retry không có exponential backoff
// Gây overload khi server đang quá tải

// SAI - retry ngay lập tức
async function sendRequest() {
  for (let i = 0; i < 3; i++) {
    try {
      return await fetch('https://api.holysheep.ai/v1/chat/completions', options);
    } catch (error) {
      if (i < 2) continue; // Retry ngay - BAD!
    }
  }
}

// ĐÚNG - exponential backoff với jitter
async function sendRequestWithRetry(options, maxRetries = 3) {
  const baseDelay = 1000; // 1 giây
  const maxDelay = 30000; // 30 giây
  
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
        ...options,
        headers: {
          ...options.headers,
          'X-Retry-Attempt': attempt
        }
      });
      
      if (response.status === 429) {
        const retryAfter = parseInt(response.headers.get('Retry-After') || '1');
        throw new RateLimitError(retryAfter * 1000);
      }
      
      return response;
    } catch (error) {
      if (error instanceof RateLimitError) {
        // Exponential backoff với jitter ngẫu nhiên
        const delay = Math.min(
          baseDelay * Math.pow(2, attempt) + Math.random() * 1000,
          maxDelay
        );
        
        console.log(Rate limited. Waiting ${delay}ms before retry ${attempt + 1}/${maxRetries});
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      
      throw error; // Không phải rate limit error
    }
  }
  
  throw new Error('Max retries exceeded');
}

3. Lỗi Memory Leak từ Connection Pool

// VẤN ĐỀ: Agents không được destroy khi app shutdown

// SAI - memory leak khi restart
const agent = new https.Agent({ keepAlive: true });
// App restart nhưng agent không được cleanup

// ĐÚNG - graceful shutdown
class HolySheepClient {
  constructor() {
    this.agent = new https.Agent({
      keepAlive: true,
      maxSockets: 50,
      maxFreeSockets: 10,
      timeout: 60000
    });
    this.requests = new Set();
  }

  async request(endpoint, options) {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 30000);
    
    try {
      const response = await fetch(https://api.holysheep.ai/v1${endpoint}, {
        ...options,
        signal: controller.signal,
        agent: this.agent
      });
      
      this.requests.add(response);
      return response;
    } finally {
      clearTimeout(timeout);
    }
  }

  // Cleanup khi shutdown
  async destroy() {
    console.log('Cleaning up HolySheep client...');
    
    // Hủy tất cả pending requests
    for (const request of this.requests) {
      request.cancel();
    }
    this.requests.clear();
    
    // Destroy agent
    this.agent.destroy();
    
    console.log('HolySheep client cleaned up');
  }
}

// Sử dụng graceful shutdown
const client = new HolySheepClient();

process.on('SIGTERM', async () => {
  console.log('SIGTERM received, shutting down gracefully...');
  await client.destroy();
  process.exit(0);
});

process.on('SIGINT', async () => {
  console.log('SIGINT received, shutting down gracefully...');
  await client.destroy();
  process.exit(0);
});

4. Lỗi GDPR Data Subject Request Chậm

// VẤN ĐỀ: Export user data không indexed, chậm với large dataset

// SAI - full table scan
async function exportUserDataSlow(userId) {
  const result = await db.query(`
    SELECT * FROM compliance_audit_logs
    WHERE user_id = $1
  `, [userId]);
  return result.rows;
}

// ĐÚNG - sử dụng partition và index
async function exportUserDataOptimized(userId) {
  // Sử dụng partition theo tháng
  const currentMonth = new Date().toISOString().slice(0, 7); // YYYY-MM
  
  // Query với hint sử dụng index
  const result = await db.query(`
    SELECT /*+ IndexScan(compliance_audit_logs idx_compliance_user_month) */
      id, request_id, timestamp, endpoint, method,
      request_payload, response_payload, pii_detected
    FROM compliance_audit_logs
    WHERE user_id = $1
      AND created_at >= $2
      AND created_at < $3
    ORDER BY timestamp DESC
    LIMIT 10000
  , [userId, ${currentMonth}-01, ${currentMonth}-31`]);
  
  return {
    data: result.rows,
    total: result.rows.length,
    hasMore: result.rows.length === 10000
  };
}

// Index tối ưu cho GDPR requests
async function createOptimalIndexes(db) {
  // Composite index cho user queries
  await db.query(`
    CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_compliance_user_month
    ON compliance_audit_logs (user_id, created_at DESC)
  `);
  
  // Partial index cho active data
  await db.query(`
    CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_compliance_recent
    ON compliance_audit_logs (created_at DESC)
    WHERE created_at > NOW() - INTERVAL '90 days'
  `);
}

Monitoring và Alerting

// Prometheus metrics cho compliance monitoring
const { Registry, Counter, Histogram, Gauge } = require('prom-client');

const register = new Registry();

// Compliance metrics
const complianceRequestsTotal = new Counter({
  name: 'compliance_requests_total',
  help: 'Total compliance checked requests',
  labelNames: ['endpoint', 'pii_detected', 'status'],
  registers: [register]
});

const complianceLatency = new Histogram({
  name: 'compliance_latency_seconds',
  help: 'Compliance check latency in seconds',
  buckets: [0.01, 0.05, 0.1, 0.5, 1, 5],
  registers: [register]
});

const activeConnections = new Gauge({
  name: 'holySheep_active_connections',
  help: 'Number of active connections to HolySheep API',
  registers: [register]
});

const apiCostUSD = new Counter({
  name: 'holySheep_api_cost_usd',
  help: 'Total API cost in USD',
  labelNames: ['model'],
  registers: [register]
});

// Middleware ghi metrics
const metricsMiddleware = (req, res, next) => {
  const start = Date.now