Skip to content

Streams

Oleksandr Geronime edited this page Jun 27, 2026 · 1 revision

Streams

SERP supports two streaming call patterns — client streaming and server streaming — for cases where a single request/response cycle is not sufficient.


Client Streaming

The caller opens a write stream and pushes data incrementally. The service receives each chunk as it arrives and produces a single reply when the stream is closed.

Use for:

  • Uploading a sequence of records or chunks
  • Feeding input data incrementally to a processing pipeline
  • Aggregating multiple inputs into one result

Pattern:

// Caller side
auto stream = myService->openDataStream([](Result result) {
    // called once when stream is closed and service replies
    process(result);
});

stream->write("chunk 1");
stream->write("chunk 2");
stream->write("chunk 3");
stream->close();  // triggers the reply callback
// Service side — receives each write, produces one reply
void MyServiceImpl::onDataChunk(std::string chunk, StreamContext& ctx) {
    buffer_ += chunk;
}

void MyServiceImpl::onDataStreamClosed(StreamContext& ctx) {
    ctx.reply(process(buffer_));
}

See client_stream/ in serp-demo for a complete working example.


Server Streaming

The service opens a write stream and pushes data incrementally to the caller. The caller receives each item as it arrives and can cancel the stream at any time.

Use for:

  • Pushing live updates or events to a caller
  • Streaming sensor data, log lines, or progress notifications
  • Serving large datasets incrementally

Pattern:

// Caller side
auto sub = myService->streamData([](int value) {
    // called for each item pushed by the service
    display(value);
});

// Cancel after some condition:
sub->cancel();
// Service side — pushes items on its own schedule
void MyServiceImpl::startStreaming(ServerStream<int> stream) {
    timer_ = serp::Timer::create(loop_, std::chrono::milliseconds(500), [stream]() mutable {
        if (stream.cancelled()) { return; }
        stream.write(nextValue_++);
    });
    timer_->start();
}

See server_stream/ in serp-demo for a complete working example.


Streams vs Notifications

Server Stream Notification
Initiated by Caller requests a stream Service fires at will
Cancellable Yes, caller calls cancel() No, subscriber disconnects
Multiple subscribers No — one stream per call Yes — any number
Backpressure Possible (stream is stateful) None

Use server streaming when the caller explicitly requests a data feed and needs to control its lifetime. Use Notifications when the service broadcasts events to any interested subscriber without a prior request.


See Also

Clone this wiki locally