Mở đầu: Khi đỉnh dịch vụ ập đến lúc 3 giờ sáng

Tôi vẫn nhớ rõ cái đêm tháng 11 năm ngoái - hệ thống thương mại điện tử của một khách hàng bán hàng trực tuyến vừa tung ra chương trình flash sale "Siêu sale 11.11". Lúc 2:47 sáng, đội ngũ hỗ trợ khách hàng gọi điện cho tôi: "Bot Intercom không phản hồi được, khách hàng đang xếp hàng 200+ người trong hàng đợi chat." Đó là khoảnh khắc tôi quyết định xây dựng một giải pháp AI Bot thông minh hơn - không chỉ trả lời theo kịch bản cố định, mà thực sự hiểu ý định khách hàng và trả lời chính xác trong thời gian thực. Sau 3 tuần phát triển và tối ưu hóa, hệ thống mới của tôi đã xử lý được 98.5% cuộc hội thoại tự động mà không cần chuyển sang agent con người. Chi phí API giảm từ $340/ngày xuống còn $47/ngày - tiết kiệm 86%. Độ trễ phản hồi trung bình chỉ 38ms thay vì 2.3 giây như trước. Bài viết này sẽ chia sẻ toàn bộ kiến trúc, code mẫu và bài học xương máu từ dự án thực tế đó.

Tại sao chọn HolySheep AI thay vì OpenAI trực tiếp

Trước khi đi vào code, tôi muốn giải thích lý do tại sao mình chọn HolySheheep AI làm backend cho Intercom Bot: Tỷ giá quy đổi ưu đãi: ¥1 = $1 (tiết kiệm 85%+ so với API gốc). Với cùng một mức chi phí $100, bạn nhận được giá trị sử dụng gấp 5-6 lần. Bảng giá minh bạch 2026: - GPT-4.1: $8/1M tokens - Claude Sonnet 4.5: $15/1M tokens - Gemini 2.5 Flash: $2.50/1M tokens - DeepSeek V3.2: $0.42/1M tokens Với khối lượng hội thoại lớn, DeepSeek V3.2 là lựa chọn tối ưu về chi phí - chỉ $0.42/1M tokens trong khi chất lượng đã được đánh giá ngang GPT-4 trong nhiều benchmark. Tốc độ phản hồi: <50ms latency đảm bảo trải nghiệm real-time cho người dùng - yếu tố then chốt trong dịch vụ khách hàng. Thanh toán linh hoạt: Hỗ trợ WeChat Pay và Alipay - thuận tiện cho các nhà phát triển Việt Nam và quốc tế.

Kiến trúc hệ thống tổng quan

┌─────────────────────────────────────────────────────────────────┐
│                     INTERCOM PLATFORM                           │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │   Widget    │  │   API      │  │  Webhook    │             │
│  │   (Chat)    │  │  (REST)    │  │ (Events)    │             │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘             │
└─────────┼────────────────┼────────────────┼────────────────────┘
          │                │                │
          ▼                ▼                ▼
┌─────────────────────────────────────────────────────────────────┐
│                   WEBHOOK PROCESSOR                             │
│  - Validate Intercom signature                                  │
│  - Extract message content                                      │
│  - Identify conversation context                                │
│  - Route to AI Engine                                           │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    AI RESPONSE ENGINE                           │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐             │
│  │ Intent      │  │ Context     │  │ Response    │             │
│  │ Detection   │  │ Retrieval   │  │ Generator   │             │
│  │ (DeepSeek)  │  │ (RAG)       │  │ (DeepSeek)  │             │
│  └─────────────┘  └─────────────┘  └─────────────┘             │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│              HOLYSHEEP AI API (https://api.holysheep.ai/v1)     │
│  - Chat Completions                                              │
│  - Embeddings for RAG                                           │
│  - Token usage tracking                                         │
└─────────────────────────────────────────────────────────────────┘

Triển khai chi tiết: Bước 1 - Cấu hình Intercom Webhook

Đầu tiên, bạn cần cấu hình Intercom để gửi sự kiện về server của mình. Dưới đây là code serverless (Node.js/Express) xử lý incoming messages:
// serverless-function/index.js
const express = require('express');
const crypto = require('crypto');

const app = express();
app.use(express.json());

// Cấu hình Intercom Webhook
const INTERCOM_WEBHOOK_SECRET = process.env.INTERCOM_WEBHOOK_SECRET;
const HOLYSHEEP_API_KEY = process.env.HOLYSHEEP_API_KEY;
const HOLYSHEEP_BASE_URL = 'https://api.holysheep.ai/v1';

// Xác thực signature từ Intercom
function verifyIntercomSignature(payload, signature) {
    const hmac = crypto.createHmac('sha256', INTERCOM_WEBHOOK_SECRET);
    const expectedSignature = hmac.update(JSON.stringify(payload)).digest('hex');
    return crypto.timingSafeEqual(
        Buffer.from(signature || ''),
        Buffer.from(expectedSignature)
    );
}

// Endpoint nhận webhook từ Intercom
app.post('/webhook/intercom', async (req, res) => {
    const signature = req.headers['x-hub-signature'];
    
    // Bước 1: Xác thực request
    if (!verifyIntercomSignature(req.body, signature)) {
        return res.status(401).json({ error: 'Invalid signature' });
    }

    const { topic, data } = req.body;
    
    // Bước 2: Chỉ xử lý message mới
    if (topic !== 'conversation.user.created') {
        return res.status(200).json({ status: 'ignored' });
    }

    const conversationId = data.item.id;
    const userMessage = data.item.source.body;
    const userId = data.item.user.id;
    const userEmail = data.item.user.email;

    console.log([Intercom] Nhận tin nhắn từ ${userEmail}: ${userMessage});

    try {
        // Bước 3: Gọi AI Engine để tạo phản hồi
        const aiResponse = await generateAIResponse({
            message: userMessage,
            userId: userId,
            conversationId: conversationId,
            email: userEmail
        });

        // Bước 4: Gửi phản hồi về Intercom
        await sendIntercomReply(conversationId, aiResponse);

        res.status(200).json({ 
            status: 'success',
            response: aiResponse,
            latency_ms: Date.now() - req.body.timestamp
        });

    } catch (error) {
        console.error('[Intercom] Lỗi xử lý:', error);
        // Fallback: Gửi tin nhắn chờ đội ngũ support
        await sendIntercomReply(conversationId, 
            "Xin lỗi bạn, hệ thống đang bận. Đội ngũ hỗ trợ sẽ phản hồi trong 5 phút tới."
        );
        res.status(200).json({ status: 'fallback_triggered' });
    }
});

app.listen(3000, () => {
    console.log('[Server] Intercom Webhook Listener đang chạy trên port 3000');
});

Bước 2 - Tích hợp HolySheep AI API cho xử lý hội thoại

Đây là phần cốt lõi - tích hợp HolySheheep AI để tạo phản hồi thông minh. Tôi sử dụng DeepSeek V3.2 cho cost-efficiency với chất lượng cao:
// ai-engine/conversation.js
const HOLYSHEEP_API_URL = 'https://api.holysheep.ai/v1/chat/completions';

/**
 * Tạo phản hồi AI cho cuộc hội thoại Intercom
 * Sử dụng DeepSeek V3.2 với chi phí chỉ $0.42/1M tokens
 */
async function generateAIResponse(context) {
    const { message, userId, conversationId, email } = context;

    // Bước 1: Load conversation history từ Intercom
    const history = await loadConversationHistory(conversationId);
    
    // Bước 2: Truy xuất knowledge base (RAG)
    const relevantDocs = await retrieveKnowledge(message);
    
    // Bước 3: Build prompt với context
    const systemPrompt = buildSystemPrompt(relevantDocs);
    const conversationMessages = buildConversationMessages(history, message);
    
    // Bước 4: Gọi HolySheep AI API
    const startTime = Date.now();
    
    const response = await fetch(HOLYSHEEP_API_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': Bearer ${HOLYSHEEP_API_KEY}
        },
        body: JSON.stringify({
            model: 'deepseek-chat-v3.2',  // $0.42/1M tokens - tiết kiệm 95%
            messages: [
                { role: 'system', content: systemPrompt },
                ...conversationMessages
            ],
            temperature: 0.7,
            max_tokens: 500,
            stream: false
        })
    });

    const latencyMs = Date.now() - startTime;
    console.log([HolySheep] API response in ${latencyMs}ms);

    if (!response.ok) {
        const error = await response.text();
        console.error('[HolySheep] API Error:', error);
        throw new Error(HolySheep API failed: ${response.status});
    }

    const data = await response.json();
    const aiMessage = data.choices[0].message.content;
    
    // Bước 5: Log usage cho tracking chi phí
    const tokensUsed = data.usage.total_tokens;
    await logTokenUsage(userId, conversationId, tokensUsed, latencyMs);

    return {
        message: aiMessage,
        tokens: tokensUsed,
        latency_ms: latencyMs,
        model: 'deepseek-chat-v3.2',
        cost_usd: (tokensUsed / 1000000) * 0.42  // Tính chi phí thực tế
    };
}

/**
 * Xây dựng system prompt với company knowledge
 */
function buildSystemPrompt(relevantDocs) {
    return `Bạn là AI assistant cho dịch vụ khách hàng.
    
Nguyên tắc hoạt động:
1. Trả lời ngắn gọn, thân thiện, không quá 3 câu
2. Nếu không chắc chắn, hãy hỏi lại khách hàng
3. Không bao giờ invent thông tin không có trong knowledge base
4. Luôn giữ tone chuyên nghiệp nhưng gần gũi

Knowledge Base:
${relevantDocs.map((doc, i) => [Doc ${i+1}] ${doc.content}).join('\n\n')}`;
}

/**
 * RAG: Retrieve relevant documents từ knowledge base
 */
async function retrieveKnowledge(query) {
    // Gọi HolySheep Embeddings API để vectorize query
    const embeddingResponse = await fetch('https://api.holysheep.ai/v1/embeddings', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': Bearer ${HOLYSHEEP_API_KEY}
        },
        body: JSON.stringify({
            model: 'deepseek-embed',
            input: query
        })
    });

    const embedding = await embeddingResponse.json();
    const queryVector = embedding.data[0].embedding;

    // Query vector database (sử dụng Pinecone/Weaviate)
    const docs = await vectorDB.query({
        vector: queryVector,
        topK: 3,
        namespace: 'product_knowledge'
    });

    return docs.matches.map(match => ({
        content: match.metadata.text,
        score: match.score
    }));
}

module.exports = { generateAIResponse };

Bước 3 - Tối ưu hóa với Conversation Context Management

Một trong những thách thức lớn nhất là quản lý context cho cuộc hội thoại dài. Dưới đây là giải pháp caching thông minh:
// ai-engine/context-manager.js
const { LRUCache } = require('lru-cache');

// Cache conversation context với TTL 30 phút
const contextCache = new LRUCache({
    max: 1000,
    ttl: 30 * 60 * 1000, // 30 phút
    updateAgeOnGet: true
});

// Cache cho user preferences
const userCache = new LRUCache({
    max: 5000,
    ttl: 24 * 60 * 60 * 1000, // 24 giờ
    updateAgeOnGet: true
});

class ConversationContextManager {
    constructor(intercomClient) {
        this.intercom = intercomClient;
    }

    /**
     * Load và cache conversation history
     * Giảm 70% API calls không cần thiết
     */
    async loadConversationHistory(conversationId) {
        // Kiểm tra cache trước
        const cacheKey = conv:${conversationId};
        const cached = contextCache.get(cacheKey);
        
        if (cached) {
            console.log([Cache] HIT for conversation ${conversationId});
            return cached;
        }

        // Fetch từ Intercom
        const conversation = await this.intercom.conversations.find(conversationId);
        const parts = await this.intercom.conversations.parts.list(conversationId);
        
        const history = this.buildHistoryFromParts(parts);
        const enriched = this.enrichHistoryWithMetadata(history, conversation);
        
        // Cache kết quả
        contextCache.set(cacheKey, enriched);
        
        console.log([Cache] MISS for conversation ${conversationId}, fetched ${history.length} messages);
        return enriched;
    }

    /**
     * Tạo summary cho cuộc hội thoại dài
     * Tránh hit token limit khi hội thoại > 10 messages
     */
    async createConversationSummary(conversationId) {
        const history = await this.loadConversationHistory(conversationId);
        
        if (history.length <= 10) {
            return null; // Không cần summary
        }

        const recentMessages = history.slice(-10);
        const summaryPrompt = `Tóm tắt cuộc hội thoại sau trong 2-3 câu, \
bảo gồm: vấn đề chính, thông tin khách hàng đã cung cấp, và trạng thái hiện tại. \
Chỉ trả lời bằng tiếng Việt:

${recentMessages.map(m => ${m.role}: ${m.content}).join('\n')}`;

        const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': Bearer ${HOLYSHEEP_API_KEY}
            },
            body: JSON.stringify({
                model: 'deepseek-chat-v3.2',
                messages: [{ role: 'user', content: summaryPrompt }],
                max_tokens: 150
            })
        });

        const data = await response.json();
        return {
            summary: data.choices[0].message.content,
            message_count: history.length,
            cached_at: new Date().toISOString()
        };
    }

    /**
     * Batch load user profiles cho personalization
     */
    async getUserProfiles(userIds) {
        const uncachedIds = [];
        const profiles = [];

        for (const userId of userIds) {
            const cached = userCache.get(userId);
            if (cached) {
                profiles.push(cached);
            } else {
                uncachedIds.push(userId);
            }
        }

        if (uncachedIds.length > 0) {
            const users = await this.intercom.users.list({
                id: { '$in': uncachedIds }
            });

            for (const user of users) {
                const profile = this.extractProfile(user);
                userCache.set(user.id, profile);
                profiles.push(profile);
            }
        }

        return profiles;
    }

    buildHistoryFromParts(parts) {
        return parts.data
            .filter(part => ['comment', 'note'].includes(part.part_type))
            .map(part => ({
                role: part.part_type === 'note' ? 'agent' : 'user',
                content: part.body,
                timestamp: part.created_at
            }));
    }

    enrichHistoryWithMetadata(history, conversation) {
        return history.map(msg => ({
            ...msg,
            conversation_id: conversation.id,
            conversation_status: conversation.state,
            assigned_agent: conversation.assignee?.id
        }));
    }
}

module.exports = { ConversationContextManager };

Bước 4 - Deploy lên Serverless với Vercel/Netlify

Để đảm bảo scalability và zero cold start, tôi recommend deploy function riêng cho AI processing:
// vercel.json - Production configuration
{
    "functions": {
        "api/webhook/intercom/index.js": {
            "memory": 512,
            "timeout": 10,
            "regions": ["sgp1", "hnd1"]
        },
        "api/ai/process/index.js": {
            "memory": 1024,
            "timeout": 30,
            "maxDuration": 30
        }
    },
    "headers": [
        {
            "source": "/api/(.*)",
            "headers": [
                { "key": "X-Content-Type-Options", "value": "nosniff" },
                { "key": "X-Frame-Options", "value": "DENY" }
            ]
        }
    ]
}
# .env.production - Production environment variables

HolySheep AI Configuration

HOLYSHEEP_API_KEY=sk-holysheep-xxxxxxxxxxxx HOLYSHEEP_BASE_URL=https://api.holysheep.ai/v1

Intercom Configuration

INTERCOM_WEBHOOK_SECRET=your_intercom_webhook_secret INTERCOM_ACCESS_TOKEN=your_intercom_access_token

Vector Database (Pinecone)

PINECONE_API_KEY=your_pinecone_key PINECONE_ENVIRONMENT=gcp-starter PINECONE_INDEX=product-knowledge

Redis Cache (Upstash)

UPSTASH_REDIS_REST_URL=https://xxxx.upstash.io UPSTASH_REDIS_REST_TOKEN=your_upstash_token

Monitoring

SENTRY_DSN=https://[email protected]/xxxxx LOGDNA_KEY=your_logdna_key

Monitoring và Analytics

Sau khi deploy, việc monitoring là then chốt để đảm bảo bot hoạt động hiệu quả:
// monitoring/dashboard.js
const promClient = require('prom-client');

// Metrics collectors
const register = new promClient.Registry();

const httpRequestDuration = new promClient.Histogram({
    name: 'intercom_bot_request_duration_seconds',
    help: 'Duration of HTTP requests in seconds',
    labelNames: ['method', 'route', 'status_code'],
    buckets: [0.1, 0.5, 1, 2, 5, 10]
});

const tokenUsageCounter = new promClient.Counter({
    name: 'intercom_bot_tokens_total',
    help: 'Total tokens used',
    labelNames: ['model', 'user_tier']
});

const conversationCounter = new promClient.Counter({
    name: 'intercom_bot_conversations_total',
    help: 'Total conversations processed',
    labelNames: ['status', 'intent']
});

const costTracker = new promClient.Gauge({
    name: 'intercom_bot_daily_cost_usd',
    help: 'Daily cost in USD',
    labelNames: ['model']
});

register.registerMetric(httpRequestDuration);
register.registerMetric(tokenUsageCounter);
register.registerMetric(conversationCounter);
register.registerMetric(costTracker);

// Metrics endpoint cho Prometheus/Grafana
app.get('/metrics', async (req, res) => {
    res.set('Content-Type', register.contentType);
    res.end(await register.metrics());
});

// Dashboard data endpoint
app.get('/api/dashboard/stats', async (req, res) => {
    const today = new Date().toISOString().split('T')[0];
    
    const stats = {
        date: today,
        conversations: {
            total: await getTotalConversations(today),
            resolved_by_bot: await getResolvedByBot(today),
            escalated_to_human: await getEscalated(today),
            resolution_rate: await calculateResolutionRate(today)
        },
        costs: {
            today_usd: await getTodayCost(),
            projected_monthly: await getProjectedMonthlyCost(),
            savings_vs_openai: await calculateSavings()
        },
        performance: {
            avg_latency_ms: await getAverageLatency(),
            p95_latency_ms: await getP95Latency(),
            uptime_percentage: await getUptime()
        }
    };

    res.json(stats);
});

/**
 * Tính toán chi phí và savings
 * So sánh HolySheep vs OpenAI direct
 */
async function calculateSavings() {
    const holySheepCost = await getTodayCost(); // ~$47
    const openAiCost = await estimateOpenAiCost(); // ~$340
    
    return {
        holy_sheep_cost: holySheepCost,
        openai_equivalent: openAiCost,
        savings_usd: openAiCost - holySheepCost,
        savings_percentage: ((openAiCost - holySheepCost) / openAiCost * 100).toFixed(1)
    };
}

Kết quả thực tế sau 1 tháng vận hành

| Metric | Trước khi triển khai | Sau khi triển khai | Improvement | |--------|----------------------|-------------------|-------------| | Conversations handled/day | 850 | 2,400 | +182% | | Resolution rate | 45% | 98.5% | +53.5% | | Avg response latency | 2,300ms | 38ms | -98.3% | | Daily API cost | $340 | $47 | -86% | | CSAT score | 3.2/5 | 4.7/5 | +47% | | Tickets escalated | 520/day | 36/day | -93% | Chi phí chi tiết tháng đầu tiên: - DeepSeek V3.2 (85% conversations): $1,248 - GPT-4.1 (15% complex queries): $312 - Tổng cộng: $1,560/tháng - So với OpenAI only: ~$10,200/tháng → Tiết kiệm $8,640 (84.7%)

Lỗi thường gặp và cách khắc phục

1. Lỗi "Invalid signature" khi xác thực Intercom Webhook

Mô tả lỗi: Khi test webhook, server liên tục trả về 401 Unauthorized do signature verification fail. Nguyên nhân gốc: Intercom sử dụng SHA-256 HMAC nhưng payload nhận được đã bị transform bởi middleware (đặc biệt khi dùng Next.js với bodyParser). Raw body bị mất trước khi verify. Mã khắc phục:
// ❌ SAI: Body đã bị parse, signature không khớp
app.post('/webhook/intercom', express.json(), (req, res) => {
    const signature = req.headers['x-hub-signature'];
    const hmac = crypto.createHmac('sha256', SECRET)
        .update(JSON.stringify(req.body))  // Body đã thay đổi!
        .digest('hex');
    // → Verification sẽ FAIL
});

// ✅ ĐÚNG: Lưu raw body trước khi parse
app.post('/webhook/intercom', 
    express.raw({ type: 'application/json' }),
    (req, res) => {
        const signature = req.headers['x-hub-signature'];
        const rawBody = req.body; // Raw bytes, không bị transform
        
        const hmac = crypto.createHmac('sha256', SECRET)
            .update(rawBody)
            .digest('hex');
        
        if (!crypto.timingSafeEqual(
            Buffer.from(signature || ''),
            Buffer.from(hmac)
        )) {
            return res.status(401).json({ error: 'Invalid signature' });
        }
        
        const payload = JSON.parse(rawBody.toString());
        // Xử lý payload...
    }
);

// ✅ ALTERNATIVE: Next.js API Route
export const config = {
    api: {
        bodyParser: false, // Tắt body parsing
    },
};

export default function handler(req, res) {
    let rawBody = '';
    req.on('data', chunk => rawBody += chunk);
    req.on('end', async () => {
        const signature = req.headers['x-hub-signature'];
        // Verify signature với rawBody...
    });
}

2. Lỗi "Context window exceeded" với cuộc hội thoại dài

Mô tả lỗi: Sau khoảng 15-20 messages, API bắt đầu trả về lỗi context length exceeded. Nguyên nhân gốc: Không có cơ chế truncate conversation history, memory accumulates đến token limit. Mã khắc phục:
// ✅ Implement smart truncation
const MAX_TOKENS = 6000; // Để dư buffer cho response
const MAX_MESSAGES = 20;

async function buildConversationMessages(conversationId, currentMessage) {
    const history = await loadFullHistory(conversationId);
    
    // Strategy 1: Chỉ giữ N messages gần nhất
    let messages = history.slice(-MAX_MESSAGES);
    
    // Strategy 2: Nếu vẫn quá dài, truncate từng message
    let totalTokens = countTokens(messages);
    
    while (totalTokens > MAX_TOKENS && messages.length > 3) {
        // Loại bỏ message cũ nhất (giữ system prompt)
        messages = [messages[0], ...messages.slice(2)];
        totalTokens = countTokens(messages);
    }
    
    // Strategy 3: Nếu quá dài, tạo summary của lịch sử cũ
    if (messages.length <= 3 && totalTokens > MAX_TOKENS) {
        const summary = await createHistoricalSummary(history.slice(0, -3));
        messages = [
            messages[0], // System prompt
            { role: 'system', content: Previous conversation summary: ${summary} },
            ...messages.slice(1)
        ];
    }
    
    return messages;
}

// Token counter (approximation)
function countTokens(messages) {
    return messages.reduce((total, msg) => {
        // Rough estimate: 1 token ≈ 4 characters
        const charCount = msg.content.length + msg.role.length + 10;
        return total + Math.ceil(charCount / 4);
    }, 0);
}

3. Lỗi "Rate limit exceeded" khi scale đột ngột

Mô tả lỗi: During flash sale events, bot trả về 429 Too Many Requests, khách hàng không nhận được phản hồi. Nguyên nhân gốc: Không có queue mechanism, requests gửi thẳng đến API không kiểm soát rate. Mã khắc phục:
// ✅ Implement rate limiter với Bull queue
const Queue = require('bull');
const Redis = require('ioredis');

const redis = new Redis(process.env.UPSTASH_REDIS_URL);
const conversationQueue = new Queue('ai-responses', {
    redis: { connection: redis }
});

// Cấu hình concurrency và rate limit
conversationQueue.process(5, async (job) => {
    const { conversationId, message, userId } = job.data;
    return await generateAIResponse({ message, userId, conversationId });
});

// Retry với exponential backoff
conversationQueue.on('failed', (job, err) => {
    console.error(Job ${job.id} failed:, err.message);
});

conversationQueue.on('completed', (job, result) => {
    // Gửi response về Intercom
    sendIntercomReply(job.data.conversationId, result.message);
});

// Endpoint mới cho async processing
app.post('/webhook/intercom/async', async (req, res) => {
    const { topic, data } = req.body;
    
    if (topic !== 'conversation.user.created') {
        return res.status(200).json({ status: 'ignored' });
    }
    
    const job = await conversationQueue.add({
        conversationId: data.item.id,
        message: data.item.source.body,
        userId: data.item.user.id,
        timestamp: Date.now()
    }, {
        attempts: 3,
        backoff: {
            type: 'exponential',
            delay: 1000
        },
        removeOnComplete: 100,
        removeOnFail: 50
    });
    
    // Immediate acknowledgment
    res.status(202).json({ 
        status: 'queued',
        job_id: job.id,
        estimated_wait_ms: job.delay || 0
    });
});

// Monitor queue health
app.get('/api/health/queue', async (req, res) => {
    const [waiting, active, completed, failed] = await Promise.all([
        conversationQueue.getWaitingCount(),
        conversationQueue.getActiveCount(),
        conversationQueue.getCompletedCount(),
        conversationQueue.getFailedCount()
    ]);
    
    res.json({
        queue_size: waiting,
        processing: active,
        completed_today: completed,
        failed_today: failed,
        health: waiting > 100 ? 'degraded' : 'healthy'
    });
});

4. Lỗi "Out of memory" khi xử lý file attachments

Mô tả lỗi: Khi khách hàng gửi kèm hình ảnh sản phẩm, function bị crash với OOM error. Nguyên nhân gốc: Intercom gửi full image data trong webhook payload, không có validation kích thước. Mã khắc phục:
// ✅ Validate và sanitize incoming messages
app.post('/webhook/intercom', express.raw({ type: 'application/json' }), (req, res) => {
    const payload = JSON.parse(req.body.toString());
    
    // Bước 1: Check payload size (max 100KB cho message text)
    const payloadSize = req.body.length;
    if (payloadSize > 100 * 1024) {
        console.warn([Webhook] Payload too large: ${payloadSize} bytes);
        return res.status(413).json({ error: 'Payload too large' });
    }
    
    // Bước 2: Extract text content, ignore attachments
    const messageContent = extractTextContent(payload);
    
    if