VeloxAI
Quay lại Blog
Engineering· 11 phút đọc

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.

Nguyen Son Everestt
Nguyen Son EveresttFounder & Engineering Lead, VeloxAI
#streaming#sse#chat
Hướng dẫn Streaming SSE
Hướng dẫn Streaming SSE

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(); }
  }
}
SSE parser với buffer management

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.