Xây streaming chat UI production: SSE, cancellation và error recovery
Hướng dẫn đầy đủ về Server-Sent Events cho AI chat — buffer management, AbortController, reconnection và [DONE] contract.
Streaming không phải performance optimization — mà là UX requirement. Users cảm nhận response 'nhanh' khi token đầu xuất hiện dưới 500ms, dù full response mất 10 giây. Non-streaming 4 giây có cảm giác chậm hơn streaming 6 giây hiện từ đầu tiên ngay lập tức.
SSE contract
Mỗi chunk là data: line chứa JSON. Stream kết thúc bằng data: [DONE]. Parser phải xử lý partial chunks split qua TCP frames, empty keepalive lines và termination signal. Không assume một data: line là một JSON object hoàn chỉnh.
class SSEParser {
buffer = ""; decoder = new TextDecoder();
async *parse(response: Response): AsyncGenerator<SSEEvent> {
const reader = response.body!.getReader();
try {
while (true) {
const { value, done } = await reader.read();
if (done) break;
this.buffer += this.decoder.decode(value, { stream: true });
const lines = this.buffer.split("\n");
this.buffer = lines.pop() || "";
for (const line of lines) {
if (!line) continue;
if (line === "data: [DONE]") return;
if (line.startsWith("data: ")) {
yield { type: "chunk", data: JSON.parse(line.slice(6)) };
}
}
}
} finally { reader.releaseLock(); }
}
}Nút Stop với AbortController
Mọi streaming UI cần nút Stop. Không có, users trả tiền cho tokens không muốn. Dùng AbortController — tạo trước fetch, pass signal, abort() khi Stop. Điều này đóng TCP connection và dừng sinh tokens. Cũng xử lý: connection không thiết lập (hiện error + retry), mid-stream drop (hiện partial + error), server error sau chunks (hiện những gì đã có, đánh dấu incomplete).
Cập nhật:
Sẵn sàng dựng sản phẩm AI của bạn?
Bắt đầu free, route nhiều provider, đo chi phí và readiness trung thực ngay từ ngày đầu.
Bài viết liên quan
- Product
VeloxAI: control plane multi-model cho đội sản phẩm
Vì sao đội sản phẩm cần một API cho models, agents, RAG, billing, analytics và readiness thay vì thêm một proxy mỏng.
- Models
Cách chọn AI model phù hợp cho từng workflow sản phẩm
Framework chọn model được kiểm chứng thực tế, bao gồm cost, latency, context window, tool calling, vision, reasoning — kèm số liệu thật và ma trận quyết định.
- Knowledge Base
Xây hệ thống RAG production không nói dối users
Pipeline RAG production-grade cần ingestion state, chunk metadata, vector isolation, citations, queue-based indexing và honest failure modes.