Azure Container Apps Dynamic Sessions — Sandbox Hyper-V cho AI Agent chạy code an toàn
Posted on: 4/27/2026 2:10:40 AM
Table of contents
- 1. Bài toán: Chạy code AI-generated ở đâu?
- 2. Kiến trúc tổng quan
- 3. Hai loại Session Pool
- 4. Cơ chế Session Pool và Prewarming
- 5. Bảo mật: Hyper-V Isolation
- 6. Tích hợp MCP — AI Agent gọi trực tiếp
- 7. Hai mô hình host MCP Server trên Container Apps
- 8. Pattern triển khai thực tế
- 9. Cấu hình ARM Template đầy đủ
- 10. So sánh với các giải pháp khác
- 11. Pricing và tối ưu chi phí
- 12. Hạn chế cần lưu ý
- Kết luận
- Nguồn tham khảo
Khi AI Agent có khả năng sinh code và thực thi tự động, câu hỏi lớn nhất không còn là "AI có viết được code không?" mà là "Chạy code đó ở đâu cho an toàn?". Azure Container Apps Dynamic Sessions ra đời để giải quyết chính xác bài toán đó — cung cấp môi trường cách ly Hyper-V, khởi động trong mili-giây, tự scale hàng ngàn session đồng thời, và tích hợp sẵn MCP (Model Context Protocol) để AI agent gọi trực tiếp.
Bài viết này đi sâu vào kiến trúc, cơ chế hoạt động, mô hình bảo mật và các pattern triển khai thực tế của Dynamic Sessions — từ góc nhìn system design cho team đang xây dựng hệ thống AI agent production.
1. Bài toán: Chạy code AI-generated ở đâu?
Hãy hình dung một AI coding assistant nhận yêu cầu: "Phân tích file CSV 500MB và vẽ biểu đồ revenue theo quý". Agent sẽ sinh ra đoạn Python dùng pandas + matplotlib, nhưng code này phải chạy ở đâu đó. Các phương án truyền thống đều có vấn đề:
| Phương án | Vấn đề | Mức độ rủi ro |
|---|---|---|
| Chạy trên server chính (app process) | Code injection, resource exhaustion, crash toàn hệ thống | Rất cao |
| Container riêng (Docker spawn) | Cold start 5-30s, phải tự quản lý lifecycle, không scale tốt | Trung bình |
| Lambda / Cloud Functions | Giới hạn runtime, không có filesystem, payload limit | Thấp nhưng hạn chế |
| VM riêng per request | Chi phí cực cao, boot time phút-level | Thấp nhưng tốn kém |
Dynamic Sessions giải quyết tất cả: Hyper-V cách ly hoàn toàn, prewarmed pool khởi động sub-second, tự quản lý lifecycle, scale tới hàng ngàn session, và tích hợp sẵn với hệ sinh thái AI agent qua MCP.
2. Kiến trúc tổng quan
graph TD
Client["🤖 AI Agent / LLM App"]
MgmtAPI["Management API Endpoint"]
Pool["Session Pool"]
Prewarmed["Prewarmed Sessions
(Hyper-V Isolated)"]
Active1["Session A
identifier: user-123"]
Active2["Session B
identifier: user-456"]
Active3["Session C
identifier: conv-789"]
EntraID["Microsoft Entra ID"]
Client -->|"HTTPS + Bearer Token"| MgmtAPI
EntraID -->|"AuthN/AuthZ"| MgmtAPI
MgmtAPI -->|"Route by identifier"| Pool
Pool --> Prewarmed
Pool --> Active1
Pool --> Active2
Pool --> Active3
style Client fill:#e94560,stroke:#fff,color:#fff
style MgmtAPI fill:#2c3e50,stroke:#fff,color:#fff
style Pool fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style Prewarmed fill:#f8f9fa,stroke:#4CAF50,color:#2c3e50
style Active1 fill:#fff,stroke:#e94560,color:#2c3e50
style Active2 fill:#fff,stroke:#e94560,color:#2c3e50
style Active3 fill:#fff,stroke:#e94560,color:#2c3e50
style EntraID fill:#2c3e50,stroke:#fff,color:#fff
Hình 1: Kiến trúc tổng quan Azure Container Apps Dynamic Sessions
3. Hai loại Session Pool
3.1. Code Interpreter Session Pool
Dùng container platform-managed, cài sẵn Python (NumPy, pandas, matplotlib), Node.js và Shell. Không cần build image — chỉ cần tạo pool là dùng được ngay.
Khi nào chọn Code Interpreter?
AI agent cần chạy code Python/JS/Shell đơn giản: phân tích data, vẽ chart, xử lý file, chạy script. Không cần custom dependency phức tạp. Ưu điểm lớn nhất: zero setup, khởi động nhanh nhất.
3.2. Custom Container Session Pool
Bring-your-own-container — bạn push image lên ACR (Azure Container Registry), cấu hình resource (CPU, RAM), command, env vars. Hoàn toàn tùy biến runtime environment.
Khi nào chọn Custom Container?
Workload cần thư viện đặc thù (TensorFlow, FFmpeg, Puppeteer), cần custom TCP protocol, cần binary proprietarty, hoặc cần environment y hệt production để chạy integration test.
| Tiêu chí | Code Interpreter | Custom Container |
|---|---|---|
| Image requirement | Không cần — dùng platform image | Bắt buộc — push lên ACR |
| Ngôn ngữ | Python, Node.js, Shell | Bất kỳ (tuỳ image) |
| Startup time | Nhanh nhất (prewarmed sẵn) | Nhanh (prewarmed từ custom image) |
| Custom dependency | Hạn chế (thư viện phổ biến) | Không giới hạn |
| MCP support | Có (Python + Shell) | Tự implement nếu cần |
| Use case chính | LLM code execution, data analysis | Custom compute, proprietary tools |
4. Cơ chế Session Pool và Prewarming
Điểm khác biệt cốt lõi của Dynamic Sessions so với việc tự spawn container: Session Pool duy trì một tập session prewarmed — container đã boot xong, OS đã load, runtime đã sẵn sàng, chỉ chờ request đến là allocate ngay.
sequenceDiagram
participant App as AI Agent App
participant API as Management API
participant Pool as Session Pool
participant PW as Prewarmed Session
participant Active as Active Session
App->>API: POST /api/execute?identifier=user-123
API->>API: Validate Entra ID token
API->>Pool: Route by identifier "user-123"
alt Session exists
Pool->>Active: Forward request
Active-->>App: Response (execution result)
else New identifier
Pool->>PW: Allocate from prewarmed pool
PW->>Active: Become active session
Active-->>App: Response (sub-second)
Pool->>Pool: Replenish prewarmed pool
end
Note over Active: Cooldown timer starts
Note over Active: No activity → auto-destroy
Hình 2: Luồng xử lý request và cơ chế prewarming
4.1. Identifier-based Routing
Mỗi request phải kèm ?identifier=<value>. Đây là cách Pool biết request thuộc session nào:
- Nếu identifier đã tồn tại → route tới session đang active
- Nếu identifier chưa có → allocate session mới từ prewarmed pool
- Identifier là free-form string (4-128 ký tự): có thể dùng user ID, conversation ID, hoặc task ID
4.2. Lifecycle và Cooldown
Session tự động bị destroy khi hết cooldown period (cấu hình được, mặc định 600 giây). Điều này đảm bảo resource không bị lãng phí. Bạn có thể query trạng thái session qua endpoint /.management/getSession và liệt kê tất cả session qua /.management/listSessions.
5. Bảo mật: Hyper-V Isolation
Đây là yếu tố quan trọng nhất khi chạy untrusted code. Dynamic Sessions không dùng container isolation thông thường (Linux namespaces/cgroups) — mà dùng Hyper-V isolation, tức mỗi session chạy trong một lightweight VM riêng biệt.
graph LR
subgraph Host["Azure Host Machine"]
subgraph HV1["Hyper-V VM 1"]
S1["Session A
user-123"]
end
subgraph HV2["Hyper-V VM 2"]
S2["Session B
user-456"]
end
subgraph HV3["Hyper-V VM 3"]
S3["Session C
conv-789"]
end
end
S1 -.->|"❌ Không thể truy cập"| S2
S2 -.->|"❌ Không thể truy cập"| S3
style Host fill:#f8f9fa,stroke:#2c3e50,color:#2c3e50
style HV1 fill:#fff,stroke:#e94560,color:#2c3e50
style HV2 fill:#fff,stroke:#e94560,color:#2c3e50
style HV3 fill:#fff,stroke:#e94560,color:#2c3e50
style S1 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style S2 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style S3 fill:#f8f9fa,stroke:#e94560,color:#2c3e50
Hình 3: Mô hình cách ly Hyper-V — mỗi session là một VM riêng biệt
Lưu ý bảo mật quan trọng
Dù session cách ly với nhau, mọi thứ bên trong một session (file, env vars, process) đều accessible bởi code chạy trong session đó. Không nên đưa secret hay credential vào session nếu code chạy bên trong là untrusted. Nếu cần truy cập Azure resource, dùng managed identity với quyền tối thiểu và bật managedIdentitySettings.lifecycle: "Main" cẩn thận.
5.1. Network Security
Mặc định, session không có outbound network access. Đây là defense-in-depth: ngay cả khi attacker escape được application , họ vẫn không gọi ra ngoài được. Bạn có thể mở qua sessionNetworkConfiguration.status: "EgressEnabled" khi cần (ví dụ session cần gọi external API).
5.2. Authentication Flow
Tất cả request tới Management API đều phải có Microsoft Entra ID token với role Azure ContainerApps Session Executor trên session pool resource. Flow xác thực:
// C# - Lấy token từ managed identity hoặc DefaultAzureCredential
using Azure.Identity;
var credential = new DefaultAzureCredential();
var token = credential.GetToken(
new TokenRequestContext(new[] { "https://dynamicsessions.io/.default" })
);
// Gửi kèm header: Authorization: Bearer {token.Token}
# Python - Azure Identity
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
token = credential.get_token("https://dynamicsessions.io/.default")
# Header: Authorization: Bearer {token.token}
6. Tích hợp MCP — AI Agent gọi trực tiếp
Tính năng nổi bật nhất (preview từ tháng 3/2026): bật MCP trên session pool, platform tự expose endpoint /mcp theo chuẩn JSON-RPC 2.0. AI agent (Claude, GitHub Copilot, Azure Foundry) kết nối trực tiếp và gọi tool mà không cần code trung gian.
sequenceDiagram
participant Agent as AI Agent (Claude/Copilot)
participant MCP as /mcp Endpoint
participant Sandbox as Hyper-V Sandbox
Agent->>MCP: initialize (JSON-RPC 2.0)
MCP-->>Agent: capabilities: [launchShell, runShellCommand, runPythonCode]
Agent->>MCP: tools/call → launchShell
MCP->>Sandbox: Create environment
Sandbox-->>MCP: environmentId: "env-abc"
MCP-->>Agent: environmentId
Agent->>MCP: tools/call → runPythonCodeInRemoteEnvironment
Note right of Agent: code: "import pandas as pd
df = pd.read_csv('data.csv')
print(df.describe())"
MCP->>Sandbox: Execute Python code
Sandbox-->>MCP: stdout output
MCP-->>Agent: execution result
Hình 4: Luồng giao tiếp AI Agent → MCP → Sandbox
6.1. Ba tool MCP platform-managed
| Tool | Chức năng | Use case |
|---|---|---|
launchShell | Tạo environment mới, trả về environmentId | Bước đầu tiên trong mọi workflow |
runShellCommandInRemoteEnvironment | Chạy shell command trong environment đã tạo | Install package, quản lý file, chạy script |
runPythonCodeInRemoteEnvironment | Chạy Python code trong environment đã tạo | Data analysis, ML inference, chart generation |
6.2. Cấu hình MCP trên Session Pool
Chỉ cần một property trong ARM/Bicep template:
{
"type": "Microsoft.App/sessionPools",
"apiVersion": "2025-02-02-preview",
"properties": {
"containerType": "PythonLTS",
"poolManagementType": "Dynamic",
"mcpServerSettings": {
"isMCPServerEnabled": true
},
"dynamicPoolConfiguration": {
"executionType": "Timed",
"cooldownPeriodInSeconds": 600
},
"scaleConfiguration": {
"maxConcurrentSessions": 100,
"readySessionInstances": 10
}
}
}
Sau khi deploy, lấy API key qua Azure CLI:
az rest --method POST \
--uri "https://management.azure.com/subscriptions/{subId}/resourceGroups/{rg}/providers/Microsoft.App/sessionPools/{pool}/fetchMCPServerCredentials" \
--uri-parameters api-version=2025-02-02-preview \
--query "apiKey" -o tsv
Agent kết nối bằng endpoint https://{pool}.{envId}.{region}.azurecontainerapps.io/mcp với header x-ms-apikey.
7. Hai mô hình host MCP Server trên Container Apps
Ngoài Dynamic Sessions (platform-managed MCP), bạn còn có thể deploy MCP server riêng dưới dạng standalone container app. Hai mô hình phục vụ mục đích khác nhau:
| Tiêu chí | Standalone Container App | Dynamic Sessions (Managed MCP) |
|---|---|---|
| Custom tool | Tự định nghĩa bất kỳ tool nào | Chỉ 3 tool platform-defined |
| Ngôn ngữ | Bất kỳ (có MCP SDK: .NET, Python, TS, Go, Java) | Python + Shell execution |
| Authentication | Microsoft Entra ID (built-in auth) | API key (x-ms-apikey) |
| Isolation | Container-level | Hyper-V per session |
| Scaling | Revision-based autoscale (scale-to-zero) | Per-session, pool-managed |
| Use case | MCP server với business logic phức tạp | Sandboxed code execution |
Pattern kết hợp hai mô hình
Trong thực tế, nhiều team dùng cả hai: standalone container app làm MCP server chính (expose custom tool: query database, gọi internal API, quản lý workflow), và Dynamic Sessions cho tool "execute_code" — khi agent cần chạy code sinh ra, request được proxy sang session pool. Cách này tận dụng cả custom logic lẫn isolation.
8. Pattern triển khai thực tế
8.1. AI Data Analyst Agent
graph LR
User["Người dùng"]
App["Web App / API"]
LLM["Azure OpenAI / Claude"]
DS["Dynamic Session
(Code Interpreter)"]
Blob["Azure Blob Storage"]
User -->|"Upload CSV + câu hỏi"| App
App -->|"Prompt + context"| LLM
LLM -->|"Generated Python code"| App
App -->|"Execute code
identifier=user-id"| DS
DS -->|"Read/Write file"| DS
DS -->|"Chart image"| Blob
Blob -->|"Chart URL"| App
App -->|"Kết quả + chart"| User
style User fill:#f8f9fa,stroke:#2c3e50,color:#2c3e50
style App fill:#2c3e50,stroke:#fff,color:#fff
style LLM fill:#e94560,stroke:#fff,color:#fff
style DS fill:#f8f9fa,stroke:#e94560,color:#2c3e50
style Blob fill:#f8f9fa,stroke:#2c3e50,color:#2c3e50
Hình 5: Pattern AI Data Analyst với Dynamic Sessions
8.2. Multi-tenant Code Playground
Mỗi tenant có identifier riêng → session cách ly hoàn toàn. Cooldown 15 phút → tự dọn dẹp. Egress disabled → tenant không thể gọi ra ngoài (trừ khi bạn cho phép). Scale tới hàng trăm tenant đồng thời mà không cần manage infrastructure.
8.3. CI/CD Pipeline với Secure Test Execution
Chạy test suite trong Dynamic Sessions thay vì trên build agent. Lợi ích: test không ảnh hưởng lẫn nhau (Hyper-V isolation), không cần clean up build agent, scale tự động theo số PR.
9. Cấu hình ARM Template đầy đủ
{
"type": "Microsoft.App/sessionPools",
"apiVersion": "2024-08-02-preview",
"name": "my-ai-session-pool",
"location": "southeastasia",
"properties": {
"environmentId": "/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.App/managedEnvironments/{env}",
"poolManagementType": "Dynamic",
"containerType": "CustomContainer",
"scaleConfiguration": {
"maxConcurrentSessions": 50,
"readySessionInstances": 5
},
"dynamicPoolConfiguration": {
"executionType": "Timed",
"cooldownPeriodInSeconds": 900
},
"customContainerTemplate": {
"registryCredentials": {
"server": "myregistry.azurecr.io",
"identity": "/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{id}"
},
"containers": [{
"image": "myregistry.azurecr.io/my-:latest",
"name": "",
"resources": { "cpu": 0.5, "memory": "1Gi" },
"env": [
{ "name": "SANDBOX_MODE", "value": "restricted" }
]
}],
"ingress": { "targetPort": 8080 }
},
"sessionNetworkConfiguration": {
"status": "EgressDisabled"
}
}
}
10. So sánh với các giải pháp khác
| Tiêu chí | Dynamic Sessions | AWS Lambda | Google Cloud Run Jobs | Self-managed Docker |
|---|---|---|---|---|
| Cold start | < 1s (prewarmed) | 100ms-10s (tuỳ runtime) | 1-10s | 5-30s |
| Isolation | Hyper-V (VM-level) | Firecracker microVM | gVisor | Linux namespaces |
| Stateful session | Có (cooldown-based) | Không | Không | Tự quản lý |
| MCP tích hợp | Có (native) | Không | Không | Tự implement |
| Max runtime | Tuỳ cooldown | 15 phút | 24 giờ | Không giới hạn |
| Custom container | Có | Có (image) | Có | Có |
| Scale model | Pool-managed auto | Per-invocation | Task-based | Manual/K8s HPA |
11. Pricing và tối ưu chi phí
Dynamic Sessions tính phí dựa trên resource tiêu thụ của session pool (vCPU-second + memory GiB-second). Vài chiến lược tối ưu:
- Giảm
readySessionInstancesngoài giờ cao điểm — prewarmed session vẫn tiêu thụ resource dù chưa được allocate - Cooldown period ngắn hơn cho workload one-shot (ví dụ code execution) — 60-120s thay vì mặc định 600s
- Right-size container resource — code interpreter thường chỉ cần 0.25 vCPU + 0.5Gi RAM trừ khi xử lý data lớn
- Dùng Code Interpreter pool thay vì Custom Container khi có thể — ít overhead quản lý image hơn
12. Hạn chế cần lưu ý
Những điểm cần cân nhắc trước khi adopt
- MCP feature đang preview (API version
2025-02-02-preview) — có thể thay đổi breaking - Session là ephemeral — không có persistent storage. Nếu cần lưu kết quả, phải upload ra external storage (Blob, DB) trước khi session hết cooldown
- Managed identity trong session cho phép code untrusted tạo token — dùng rất cẩn thận, chỉ gán quyền tối thiểu
- Chỉ có Python + Shell cho MCP managed — nếu cần Rust, Go, Java thì dùng Custom Container + standalone MCP
- Outbound network mặc định disabled — cần enable nếu code cần gọi external API (nhưng nên cân nhắc security trade-off)
Kết luận
Azure Container Apps Dynamic Sessions là lời giải chuyên biệt cho bài toán "chạy code AI-generated an toàn ở quy mô lớn". Với Hyper-V isolation, prewarmed pool sub-second, và MCP native support, đây là building block quan trọng cho bất kỳ hệ thống AI agent nào cần code execution capability.
Điểm mạnh nhất nằm ở sự đơn giản vận hành: không cần quản lý container lifecycle, không cần lo clean up, không cần tự build infrastructure. Bạn chỉ cần tạo session pool, gán identity, và AI agent bắt đầu chạy code an toàn.
Với sự tích hợp MCP ngày càng sâu vào hệ sinh thái (Azure Foundry, GitHub Copilot, Claude), Dynamic Sessions đang trở thành cầu nối tiêu chuẩn giữa AI reasoning và real-world code execution.
Nguồn tham khảo
- Dynamic sessions in Azure Container Apps - Microsoft Learn
- Use dynamic sessions in Azure Container Apps - Microsoft Learn
- Host MCP servers on Azure Container Apps - Microsoft Learn
- Even simpler to Safely Execute AI-generated Code with Dynamic Sessions - Microsoft Tech Community
- What's new in Azure Container Apps at Ignite'25 - Microsoft Tech Community
Node.js 24 — TypeScript Native, Permission Model và V8 13.6 thay đổi cách xây dựng Backend
Thiết kế hệ thống News Feed — Fan-out, Caching & Ranking cho hàng triệu người dùng
Disclaimer: The opinions expressed in this blog are solely my own and do not reflect the views or opinions of my employer or any affiliated organizations. The content provided is for informational and educational purposes only and should not be taken as professional advice. While I strive to provide accurate and up-to-date information, I make no warranties or guarantees about the completeness, reliability, or accuracy of the content. Readers are encouraged to verify the information and seek independent advice as needed. I disclaim any liability for decisions or actions taken based on the content of this blog.