Batching with event buffers
While SSE is already performant and bandwidth-efficient, sending many events at a time by repeatedly calling Session#push
can be wasteful as every call will initiate a full TCP round trip where the client must send acknowledgement packets back for every event it receives.
Event buffers improve this process by allowing you to batch and send multiple events in a single network transmission, greatly improving performance and lowering overall bandwidth usage.
Using the batch
method
To batch and send multiple events at a time, simply invoke Session#batch
method and pass a callback that takes an event buffer as its first argument:
You can use the same helper methods as you would with the session itself (push
, stream
and iterate
) with the buffer.
When the callback finishes execution - or resolves if it returns a promise - every event created with the buffer will be sent to the client all at once in a single network transmission.
Create your own event buffer
You can also create an event buffer outside of the context of a single session and then write its contents to one or many sessions later on. To do so, create an event buffer and then pass it directly to the batch
method:
Or send the buffer contents to every session on a channel, for example:
Send individual event fields
For users needing more fine-grained control over the exact data being sent over the wire, event buffers also allow you to write raw spec-compliant SSE fields into a string that can be read and sent over the wire as-is.
This is an advanced use-case. For most users, you should still stick with using Session
by default.