Skip to content
JCJohnny Chung
← All posts

Khi AI Agent Làm Bot Detection Thở Khó: Bài Học Production Về Edge Rate Limiting Và Observability

AI agent hiện đại bypass được WAF truyền thống như thế nào? Chia sẻ thực chiến về edge rate limiting, eBPF observability, và architecture thay đổi khi bot không còn là script đơn giản.

· 5 min read

Hôm qua team on-call bị đánh thức lúc 3 sáng vì alert p99 latency nhảy từ 120ms lên 2.3s. Không phải deployment mới, không phải config drift. Nguyên nhân: một wave traffic từ ASN thuộc về một cloud provider lớn, user-agent Chrome 120 trên Windows 10, behavior pattern gần như không thể phân biệt với user thật. WAF rule set của Cloudflare trả về “allow” cho 94% request. Bot detection score? 0.12 — thấp hơn ngưỡng block.

Thực tế là wave đó do một fleet AI agent điều phối, mỗi agent chạy headless browser thực sự, execute JavaScript, render canvas, solve CAPTCHA nhờ vision model. Chúng không phải script curl hay Python requests nữa. Chúng là browser thật, chạy trên infrastructure thật, với fingerprint thật.

AI agent browser fleet running on cloud infrastructure

Ảnh: Jemimus, BY qua openverse (nguồn)

Vấn đề ở chỗ: mô hình threat modeling của chúng ta đã lỗi thời. Hầu hết rule set WAF, rate limiting, bot detection hiện nay đều giả định attacker dùng automation tool headless hoặc script đơn giản. Khi AI agent có thể điều khiển browser thật, execute full JS stack, mimic human behavior pattern — đường phân chia giữa “bot” và “human” tan biến ở application layer.

Team mình đã phải redesign toàn bộ defense-in-depth strategy trong 2 tuần. Dưới đây là những gì thay đổi, tại sao thay đổi, và lesson learned cho bất kỳ team nào đang vận hành edge infrastructure.

Layer 1: Edge Rate Limiting Chuyển Từ IP-Based Sang Session-Behavior-Based

Cách cũ: rate limit theo IP subnet, ASN, hoặc fingerprint hash. Cách mới: rate limit theo behavioral fingerprint — sequence của actions, timing distribution, entropy của interaction pattern.

Cụ thể: thay vì rate_limit(key="ip", limit=100/min), ta deploy Cloudflare Workers với logic:

export default {
  async fetch(request, env, ctx) {
    const sessionId = request.headers.get('cf-ray') + ':' + 
      await getSessionFingerprint(request);
    
    const behavior = await env.BEHAVIOR_KV.get(sessionId);
    const anomalyScore = calculateAnomalyScore(behavior);
    
    if (anomalyScore > THRESHOLD) {
      return new Response('Challenge required', { status: 429 });
    }
    
    ctx.waitUntil(updateBehaviorKV(sessionId, request));
    return fetch(request);
  }
};

Điểm mấu chốt: getSessionFingerprint không dùng TLS fingerprint hay user-agent. Nó hash kết hợp: mouse movement entropy (nếu có), scroll pattern, click timing variance, DOM interaction sequence, WebGL parameter variation. AI agent hiện tại vẫn chưa mimic được micro-behavior này ở scale — chúng tối ưu cho task completion, không phải cho statistical indistinguishability.

Kết quả: wave attack lúc 3 sáng bị chặn 87% tại edge, chỉ 13% leak xuống origin. So với 94% bypass trước đây.

Layer 2: eBPF Observability Tại Origin — Xem Những Gì Edge Miss

Edge filter được 87% là chưa đủ. Cần visibility tại origin để catch phần còn lại và feed back vào edge rule.

Team mình deploy Cilium + Tetragon trên GKE cluster, hook vào syscall connect, sendto, recvfrom của pod application. Không dùng sidecar proxy — overhead quá lớn cho latency-sensitive path. eBPF program attach kprobe vào tcp_sendmsg, extract HTTP request/response metadata, correlate với pod identity, namespace, deployment version.

SEC("kprobe/tcp_sendmsg")
int trace_tcp_sendmsg(struct pt_regs *ctx) {
    struct sock *sk = (struct sock *)PT_REGS_PARM1(ctx);
    if (!is_target_namespace(sk))
        return 0;
    
    struct http_metadata_t meta = {};
    meta.pod_uid = get_pod_uid(sk);
    meta.timestamp_ns = bpf_ktime_get_ns();
    extract_http_metadata(sk, &meta);
    
    bpf_perf_event_output(ctx, &events, BPF_F_CURRENT_CPU,
                          &meta, sizeof(meta));
    return 0;
}

Data stream vào ClickHouse qua vector agent. Query pattern detection chạy real-time: tìm session có entropy quá thấp trên timing, hoặc request sequence match biết trước (ví dụ: luôn GET /api/v1/product → POST /api/v1/cart → GET /api/v1/checkout trong 2.3s ± 50ms).

eBPF kernel tracing dashboard showing network syscalls

Ảnh: Tirza van Dijk tirzavandijk, CC0 qua wikimedia (nguồn)

Observability này cho phép ta detect “low-and-slow” agent: mỗi IP chỉ 5 req/min, nhưng 10k IP cùng pattern. Edge rate limit theo IP không bắt được. Correlation tại origin bắt được ngay.

Layer 3: Feedback Loop Tự Động Edge ←→ Origin

Điểm quan trọng nhất: không phải human update rule. Pipeline tự động:

  1. Origin detection engine emit ThreatSignature event (Kafka topic)
  2. Cloudflare Workers KV consumer đọc event, update behavior_blocklist namespace
  3. Edge worker check blocklist trước khi forward request
  4. Metrics push lên Grafana, alert nếu block rate > 5% total traffic (false positive guard)
# Argo Workflow cho feedback loop
apiVersion: argoproj.io/v1alpha1
kind: Workflow
metadata:
  name: threat-signature-sync
spec:
  entrypoint: sync-loop
  templates:
  - name: sync-loop
    container:
      image: ghcr.io/our-org/threat-sync:v2.1
      env:
      - name: KAFKA_BROKERS
        value: kafka-cluster:9092
      - name: CF_ACCOUNT_ID
        valueFrom:
          secretKeyRef:
            name: cloudflare-credentials
            key: account-id
      - name: CF_API_TOKEN
        valueFrom:
          secretKeyRef:
            name: cloudflare-credentials
            key: api-token

Sync latency trung bình 12s từ detection đến edge enforcement. Nhanh đủ cho wave attack kéo dài hàng giờ.

Trade-off Và Chi Phí Thực Tế

Không có free lunch. Chi phí team trả:

  • Edge compute cost: Cloudflare Workers Unbound usage tăng 3.2x. Bill tháng trước $2.4k, tháng này $7.8k. Acceptable vì revenue protection.
  • eBPF maintenance burden: Kernel upgrade (GKE node pool upgrade) break Tetragon probe 2 lần trong 3 tháng. Cần dedicated SRE ownership, không phải shared responsibility.
  • False positive rate: 0.8% legitimate traffic bị challenge. Team support phải handle ticket tăng 15%. Mitigation: progressive challenge (turnstile → JS challenge → block) thay vì block ngay.
  • Model drift: Behavioral fingerprint cần retrain hàng tuần. AI agent evolve nhanh. Team ML eng phải maintain feature pipeline, không chỉ deploy once.

Grafana dashboard showing cost vs protection metrics

Ảnh: ProjectManhattan, BY-SA qua openverse (nguồn)

Khi Nào Cách Này Không Cần Thiết

Dùng cho: public API surface, high-value transaction path (checkout, login, signup), content protection (anti-scraping).

Không phù hợp cho: internal service-to-service communication (dùng mTLS + OPA policy), low-traffic admin panel (IP allowlist đủ), static asset CDN (cache hit rate cao, attack surface thấp).

Kết Luận Actionable

  1. Audit bot detection assumption: Nếu WAF rule vẫn dựa trên user-agent, IP reputation, JA3 fingerprint — đã lỗi thời. Test với Playwright + Stealth plugin + vision CAPTCHA solver.
  2. Invest eBPF observability early: Không đợi incident. Deploy Cilium + Tetragon trên staging, build baseline behavioral profile cho service critical.
  3. Automate feedback loop: Human-in-the-loop không scale. Build pipeline detection → signature → edge enforcement < 30s.
  4. Cost monitoring as first-class metric: Set budget alert trên Cloudflare Workers usage, eBPF CPU overhead, false positive rate. Treat as SLO.
  5. Red team định kỳ: Hire external hoặc internal red team simulate AI agent attack hàng quý. Không test thì không biết gap.

Tóm lại: threat landscape đã shift từ “automation script” sang “AI-driven browser fleet”. Defense phải shift từ signature-based sang behavior-based, từ static rule sang adaptive feedback loop, từ edge-only sang edge-origin correlation. Team nào không invest observability layer tại origin + automated edge sync sẽ luôn reactive, không bao giờ proactive.

Lần tới alert 3 sáng reo, hy vọng là vì disk full hoặc config drift — những thứ boring, predictable, fixable. Không phải vì bot detection model đã obsolete.


Bạn đang đối mặt challenge tương tự? Team mình đang open-source behavioral fingerprint library cho Cloudflare Workers. Ping tôi nếu muốn contribute hoặc early access.