better-sse icon indicating copy to clipboard operation
better-sse copied to clipboard

Event batching

Open MatthewWid opened this issue 2 years ago • 0 comments

Add a mechanism that allows the user to batch events emitted with push over time and then emit them all at once.

This will allow users with more advanced use-cases to optimise their code if they are submitting a large number of events in a short period of time, minimising the number of calls to res.write.

This will also be used in the new history API (#16) to batch the mass number of event emissions when sending missed events back to the client.

There are some options for what this API can look like listed below.


The first is having a stateful tracking of when batching is turned on or off and then disabling the no-oping the dispatch method while it is enabled:

session.beginBatch();
...
session.endBatch();

This is likely the most complex option to implement and may have a negative performance impact as every call to the data-writing methods will now have to check if batching is enabled or not.


The second option is to allow the user to provide a callback and have any method calls made within that callback be batched internally and then flushed upon completion:

session.batch(() => {
    ...
    session.push("Hello world");
    ...
});

The third is adding a new Batched class which stores the original session and provides special versions of all the helper methods (push, stream and iterate). This is accessed via a user-given callback on the Session class.

session.batch((batched) => {
    ...
    batched.push("Hello world");
    ...
});

This is the easiest to implement and likely the most performant, though may be a little confusing when you need to access non-helper methods as Batched won't be a sub-class of Session, so you'll need to use the original session instance instead.

MatthewWid avatar May 30 '22 14:05 MatthewWid