TROISINH
Phát triển AgentScheduling & Automation

Event-driven Agents: Trigger agent từ webhook, email, file change — Tự động hóa không chờ đợi

Event-driven Agents kích hoạt AI từ webhook, email, file change thay vì polling. Giảm 90% latency, tiết kiệm compute, phản ứng real-time với sự kiện business.

Event-driven Agents là kiến trúc cho phép AI Agent "ngủ đông" cho đến khi được đánh thức bởi sự kiện bên ngoài — có thể là webhook HTTP từ Stripe/GitHub, email mới qua IMAP, hoặc file vừa upload lên S3 — thay vì liên tục polling hoặc chờ người dùng khởi động. Đây là bước chuyển từ "agent như công cụ" sang "agent như nhân viên tự chủ", phản ứng tức thì với business events mà không tốn compute khi rảnh rỗi.

Định nghĩa

Event-driven Agents là pattern thiết kế cho phép agent nhận signal kích hoạt từ external systems thông qua webhook, email triggers, hoặc file system events, thay vì chủ động poll hoặc maintain persistent connection. Agent chỉ "thức dậy" khi có việc thực sự, xử lý xong thì trở về trạng thái nghỉ, tiết kiệm token và compute resources.

Giải thích chi tiết

Webhook Trigger: Từ HTTP POST đến Queue

Webhook là cơ chế phổ biến nhất: Stripe báo "có thanh toán mới", GitHub báo "có push code", Zapier báo "có trigger mới". Tuy nhiên, lỗi chết người là xử lý LLM call trực tiếp bên trong webhook handler.

Tại sao? Webhook providers sử dụng "at-least-once delivery" với timeout chặt chẽ (thường 5–20 giây). Nếu agent cần 8–12 giây để suy nghĩ (GPT-4o) và provider retry sau 5 giây, bạn sẽ xử lý cùng một đơn hàng hai lần — gây duplicate processing, thực tế từng có case mất $340 vì thiếu idempotency check.

Quy trình đúng là tách receipt khỏi cognition:

  1. Ingress Layer: Webhook handler nhận HTTP POST → validate HMAC signature → push vào queue (Redis/BullMQ/AWS SQS) với jobId (ví dụ Stripe event.id) → return HTTP 200 ngay lập tức
  2. Deduplication: Queue tự động loại bỏ retry duplicates dựa trên event ID
  3. Agent Worker: Consumer lấy job từ queue → hydrate context từ MEMORY.md → execute tools → emit kết quả ra channel (Zalo, Slack, Email)
// webhook-handler.ts — Lễ tân nhận thư, không đọc thư
app.post('/webhook/stripe', async (req, res) => {
  const sig = req.headers['stripe-signature'];
  const event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
  
  // Đẩy vào queue, không xử lý logic ở đây
  await redis.lpush('agent:queue', JSON.stringify({
    type: 'payment_intent.succeeded',
    id: event.id, // Idempotency key
    data: event.data
  }));
  
  res.status(200).send('Received'); // Stripe dừng retry
});

Email & File Triggers: Khi legacy gặp AI

Không phải hệ thống nào cũng có webhook hiện đại. Email IMAPFile system events (S3 triggers, Dropbox webhooks) là cầu nối với legacy systems.

Email Trigger: Kết hợp Gmail Pub/Sub webhook với IMAP fetch. Agent nhận signal "có email mới" → fetch nội dung qua MCP tool → classify intent (invoice, support request, approval) → route đến agent chuyên môn. Phù hợp cho helpdesk tự động hoặc approval workflows qua email mà không cần refactor hệ thống cũ.

File Change: S3 Event Notifications kích hoạt agent khi file upload xong. Pattern "file drop integration" — sales upload Excel vào thư mục chia sẻ → Agent tự động parse → update ERP → gửi xác nhận Zalo. Không cần API phức tạp, chỉ cần folder permissions.

Async Architecture: Queue như Circuit Breaker

Queue đóng vai trò circuit breakerload balancer tự nhiên. Khi flash sale gây burst traffic (1000 orders/giây), queue absorb shock thay vì overwhelm agent. Agent xử lý với tốc độ ổn định (backpressure), không bị crash hoặc drop events.

Với OpenClaw, cấu hình điển hình dùng Redis làm message bus giữa webhook ingress và agent runtime, cho phép scale worker instances độc lập với webhook receivers.

Ví dụ thực tế

Ví dụ 1: E-commerce Order Pipeline (Stripe → Zalo) Khi Stripe gửi payment_intent.succeeded, webhook handler ghi event vào Redis. Agent wake up: (1) Verify fraud patterns qua ML model, (2) Query inventory via MCP tool, (3) Gửi ZNS (Zalo Notification Service) cho khách hàng "Đơn hàng đã thanh toán", (4) Tạo đơn nội bộ trên MongoDB. Toàn bộ xảy ra trong dưới 3 giây, zero human intervention.

Ví dụ 2: DevOps Auto-Review (GitHub → Merge) GitHub push event → webhook → agent trigger. Agent: (1) Checkout code qua Git MCP, (2) Chạy static analysis và security scan, (3) Nếu phát hiện SQL injection pattern, post comment vào PR block merge; nếu clean, approve và gửi Slack thông báo. Đây là "quality gate" tự động chạy 24/7, thay thế manual code review cho trivial changes.

Ví dụ 3: Document Processing (S3 → Notion) Sales team upload contract PDF vào S3 bucket. S3 Event Notification trigger Lambda → đẩy message vào SQS. Agent: (1) OCR extract text qua Vision tool, (2) RAG search template contracts để compare terms, (3) Highlight rủi ro pháp lý (liability cap, termination clauses), (4) Lưu summary vào Notion và gửi Telegram alert cho legal team.

Ứng dụng

Developer / DevOps Engineer Xây dựng webhook handlers resilient: idempotency keys, HMAC validation, dead letter queues cho poisoned messages. Dùng ngrok cho local testing webhook mà không cần deploy liên tục. Tích hợp vào CI/CD để agent tự động review code, chạy test, và quyết định merge dựa trên kết quả.

Startup Founder / Product Manager Tiết kiệm 70–90% compute cost so với polling infrastructure. Thay vì maintain server chạy 24/7 chỉ để check API mỗi 5 phút, agent chỉ "sống" khi có việc thực sự, giảm cloud bill cho early-stage startup. Phù hợp cho automated onboarding, fraud detection real-time, hoặc content moderation khi có upload mới.

Enterprise / IT Operations Kết nối agent với legacy ERP qua "file drop" hoặc email integration — không cần refactor hệ thống cũ chạy trên COBOL hoặc Oracle. Xây dựng workflow automation nối giữa các department: HR upload Excel danh sách nhân viên mới → Agent tự động tạo account AD, gửi welcome email qua Outlook MCP, đặt lịch orientation qua Google Calendar.

So sánh

DimensionEvent-drivenPolling (Cron)Synchronous API
LatencyDưới 1 giây (real-time)30 giây–5 phút (tùy interval)Tức thì nhưng block connection
Compute CostZero idle (pay per use)Tuyến tính với tần suất (lãng phí)Cao (always-on connection)
InfrastructureQueue + Webhook endpointSimple schedulerLoad balancer + sticky sessions
ReliabilityAt-least-once delivery (cần dedup)Rủi ro miss events giữa các lần pollTimeout risk nếu LLM chậm
DebuggingKhó (async tracing cần correlation ID)Dễ (sequential logs)Dễ
Phù hợpReal-time business eventsBatch processing, daily reportsInteractive apps (chat)

Kết luận: Event-driven thắng khi cần phản ứng tức thì với external state changes và tiết kiệm operational cost. Polling vẫn phù hợp cho scheduled tasks (daily report lúc 8h sáng). Synchronous chỉ dùng khi human chờ đợi trực tiếp và timeout rủi ro thấp.

Bài viết liên quan

Cùng cụm (Scheduling & Automation):

Cron Jobs cho Agent: Tự động chạy theo lịch

So sánh event-driven với scheduled automation — khi nào dùng cron thay vì webhook?

HEARTBEAT.md: Agent tự kiểm tra sức khỏe

Self-monitoring pattern để agent không "ngủ quên" khi event quá hiếm

Workflow Automation: Nối agent vào quy trình business

Nối event-driven agent vào chuỗi quy trình business (A2A protocol, n8n)

Đọc tiếp:

Channels & Integration

Cách agent nhận và gửi message qua REST, WebSocket, Telegram, Zalo OA

Use Cases thực chiến

Xem event-driven agents hoạt động trong support, sales, và internal ops

Production Deployment

Deploy webhook handlers và queue workers production-ready với Docker Compose

Tài liệu tham khảo mở rộng:

  • Stripe Documentation: "Best practices for using webhooks" — idempotency và signature verification
  • AWS S3 Event Notifications — trigger Lambda từ file upload
  • n8n Workflow Automation — nối webhook với 400+ services no-code
  • Maritime.sh Blog: "Webhook-Driven Agent Architecture" — case study $340 duplicate processing loss

On this page