Product knowledge · Advanced · Realtime sessions

Realtime không biến session dài thành tài nguyên vô hạn.

Chọn response stream cho byte tuần tự, SSE cho event một chiều và WebSocket cho session hai chiều. Cả ba vẫn cần admission, authorization, pressure, cancellation và finite shutdown.

01 · Choose the interaction

Chọn theo hướng dữ liệu và lifecycle

ShapeContractDùng khi
Response streamMột HTTP response, server → client, bounded chunks và optional trailers.Byte tuần tự, export hoặc generation incremental rồi kết thúc.
SSEMột HTTP event stream, server → client, event fields có kiểu.Notification/feed mà client không cần gửi message trên cùng channel.
WebSocketHTTP handshake rồi upgraded bidirectional session với typed frames.Client và server cùng cần gửi message trong một session.

API hiện diện không chứng minh target đã bật provider. Đọc effective capability từ exact package đã load trước khi quảng bá endpoint realtime.

02 · SSE lifecycle

SSE là event stream có kiểu, không phải chuỗi text tự nối

1

Admit + authorize

Request đi qua route, limits và application authorization trước khi feed bắt đầu.

2

Start SSE response

Dùng helper/value của connector; Core sở hữu HTTP framing và transport state.

3

Produce events

Chỉ submit event có bound khi writable; producer và source queue vẫn do application sở hữu.

4

Finish/cancel

Normal end, disconnect, timeout hoặc drain đều dừng producer và release retained state.

03 · SSE event fields

Mỗi field có một ý nghĩa, không có field nào tự bảo đảm replay

data
Payload event; nhiều dòng vẫn là một typed event theo helper contract. Application chọn codec và schema.
event
Optional event type cho client dispatch; không thay application authorization hoặc payload versioning.
id
Optional application cursor/identity có thể dùng trong resume protocol; Core không tự giữ event history vì có ID.
retry
Optional reconnect-delay hint cho client; không phải server retry, delivery guarantee hay unbounded reconnect loop.

04 · WebSocket lifecycle

Authorize trước upgrade; sau upgrade vẫn còn owner và terminal

1

Handshake request

Validate route, origin/credential theo application policy và requested subprotocol. Plain GET không phải WebSocket client.

2

Accept upgrade

Chỉ sau accepted upgrade mới có session. Transport authentication vẫn không thay business authorization.

3

Read/write frames

Consume/copy borrowed payload trong connector lifetime; keep pending output, handler tasks và app queues hữu hạn.

4

Close/abort

Close handshake, peer abort, cancel và service drain đều hội tụ về một idempotent cleanup owner.

05 · Frames and messages

Frame kind không thay business contract

Text

Coi decoded text là application input chưa tin cậy; text không tự là JSON hoặc một schema hợp lệ.

Binary

Bytes có media/schema do application định nghĩa; borrowed payload phải copy trước khi giữ.

Ping / pong

Control/progress evidence của session; không thay fresh business liveness hoặc authorization.

Close

Protocol close intent và reason; application vẫn dọn task, subscription và retained state do application sở hữu.

06 · Bounds and pressure

Session dài vẫn phải có budget hữu hạn

BoundaryKhi đầy/chậm
Concurrent sessionsRefuse/shed admission; không spawn owner hoặc subscription vô hạn.
Frame/message bytesReject/close theo typed limit outcome; không collect vượt ceiling.
Pending outputWait bounded writability, coalesce/drop chỉ khi business semantics cho phép, hoặc close.
Application source queueApplication chọn finite capacity và overflow law; Core pressure không bound queue này thay app.
Progress/idle/drain timeUse monotonic finite deadline; timeout không chứng minh peer đã xử lý hay cleanup hoàn tất.

07 · Reconnect and resume

Kết nối mới không mặc nhiên tiếp tục kết nối cũ

SSE reconnect

Client reconnect theo bounded policy. Application có thể dùng event ID/cursor để đọc lại từ store riêng; nếu không có replay store, feed chỉ tiếp tục từ policy hiện tại.

WebSocket reconnect

Handshake mới tạo session mới. Resume token, sequence, dedupe và subscription restore là application protocol, không phải transport guarantee.

Ambiguous delivery

Disconnect không chứng minh event/message cuối chưa tới. Command có side effect cần idempotency hoặc reconciliation trước retry.

Backoff

Bound attempts, total time và jitter ở client/application; server không biến reconnect storm thành unbounded admission.

08 · Finite drain

Graceful không có nghĩa chờ realtime session vô hạn

remove instance from new-traffic selection
  → stop new realtime admission
  → stop or quiesce application producers
  → request bounded SSE finish / WebSocket close
  → wait for terminals within monotonic drain deadline
  → close service only after owned readers/tasks converge

deadline/refusal → report failure → keep owner reachable → operator escalation

Load balancer removal chỉ ngăn selection mới; keep-alive, SSE và WebSocket cũ vẫn có thể sống. Deployment cần spare capacity, reconnect policy và outer stop budget.

09 · Failure law

Giữ handshake, session và lifecycle failure tách biệt

FailureOwner action
Capability unavailableFail closed/disable route for that target; không silently downgrade thành một contract khác.
Handshake/auth/subprotocol refusalApplication trả public-safe HTTP refusal trước upgrade; không tạo fake session.
Session/frame/output limitRefuse, shed hoặc close với typed evidence; không che bằng hidden queue.
Peer disconnect/abortCancel producers/subscriptions, release borrowed/retained state; business delivery có thể ambiguous.
Drain/close timeoutGiữ service và application owner còn reachable; timeout không cho phép free live state.

10 · Integration checklist

Trước khi chọn API ngôn ngữ