Repository navigation
Description
Problem to Solve
MethodStreamMessage.buildMessage (serverpod_serialization/lib/src/websocket_messages.dart:483-499) wraps the value with wrapWithClassName ({'className': 'String', 'data': value}, serialization.dart:274-286, :162-163) and encodes the envelope with SerializationManager.encodeForProtocol (websocket_messages.dart:8-16). The server builds this message for every value of every stream (onOutputStreamValue, serverpod/lib/src/server/websocket_request_handlers/method_websocket_request_handler.dart:227-240) and sends it as text with tryAdd (:549-555); sendBytes is never used for stream messages. On the client, client_method_stream_manager.dart:527 parses the envelope, then MethodStreamMessage decodes the object (websocket_messages.dart:471-479), and the app parses the string a second time.
Two consequences for fan-out servers:
- A value that is already serialized, e.g. a
Stream<String>carrying JSON (a common way to keep a versioned wire format), is embedded as a JSON string: every quote is escaped again, and the client parses twice. - The same value sent to N subscribers is encoded N times, because the envelope (endpoint, method, connectionId) differs per stream.
There is no way to hand over pre-encoded bytes, and stream messages always go out as text frames.
Proposal
For discussion:
- Encode the
datapart once per value and splice it into per-stream envelopes (the envelope is small and fixed-shape), or let an endpoint yield aPreEncoded/RawJsonvalue that is inserted verbatim. - Allow
Stream<ByteData>/Uint8Listvalues to go out as binary frames with a small binary envelope, without base64 (todayByteDatabecomes a base64 string,serialization.dart:312). - If the
className/datawrapper is reworked for #4234, consider dropping it forStringvalues as well.
Use Case
A sync stream (Stream<String> with its own versioned envelope) that sends one event to many subscribers: a 5 KB event to 500 subscribers is 2.5 MB of escaping and writing on one isolate, estimated at 10 to 30 ms during which every RPC on that isolate waits (estimated, not measured).
Alternatives
What we do today: batch events per channel and tick (20 to 50 ms) or up to 64 KiB into one message, keep payloads slim, and run the fan-out in time slices. A separate WebSocket path next to method streams only if a measurement demands it. Batching reduces the cost but not the double encoding or the per-subscriber encoding.
Additional context
- Checked against
serverpod 4.1.0andserverpod_serialization 4.1.0; unchanged in 4.1.1. - Related: #4234 (open; redundant
className/datawrapping next to__className__in streaming messages), #5903 (open; JSON-RPC 2.0 for streaming).
How experienced are you with this library?
Expert - Experienced and comfortable with using this library in complex projects
Are you interested in working on a PR for this?
- I want to work on this
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsInbox 📫
Activity