Streaming RPCs and Backpressure
Handle server, client, and bidirectional streaming with @GrpcStreamMethod and observables.
Streaming RPCs and Backpressure is a free NestJS Enterprise Backend APIs lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the NestJS Enterprise Backend APIs learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Four gRPC Call Shapes
gRPC defines four kinds of RPC, distinguished by whether each side sends a single message or a stream:
- Unary — one request, one response. The default; modeled in NestJS with a plain method returning a value or
Observable. - Server streaming — one request, the server emits a stream of responses.
- Client streaming — the client emits a stream of requests, the server replies once.
- Bidirectional — both sides stream independently over the same HTTP/2 connection.
Streaming matters for enterprise APIs: live price feeds, log tailing, file chunk upload, and chat all map naturally onto one of the three streaming shapes instead of polling.
Declaring Streams in Protobuf
The stream keyword in your .proto service definition is what selects the call shape. Put it on the request, the response, or both.
NestJS reads this contract at startup and wires each RPC to a handler. A method whose response is stream must be implemented as an @GrpcStreamMethod (or @GrpcStreamCall), not a plain @GrpcMethod.
syntax = "proto3";
package trading;
service PriceService {
// server streaming: one subscribe, many ticks
rpc Subscribe (SubscribeRequest) returns (stream PriceTick);
// client streaming: many orders, one ack
rpc PlaceOrders (stream Order) returns (OrderAck);
// bidirectional: stream in, stream out
rpc Chat (stream ChatMessage) returns (stream ChatMessage);
}
message SubscribeRequest { string symbol = 1; }
message PriceTick { string symbol = 1; double price = 2; int64 ts = 3; }
message Order { string id = 1; int32 qty = 2; }
message OrderAck { int32 accepted = 1; }
message ChatMessage { string user = 1; string text = 2; }Server Streaming with @GrpcMethod
Server streaming returns many messages for one request. In NestJS you implement it as a normal @GrpcMethod that returns an Observable. Every value the Observable emits is sent as one gRPC message; complete() closes the stream and error() ends it with a status.
Here a price feed pushes a tick every second using RxJS interval and stops after ten ticks.
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';
import { Observable, interval, map, take } from 'rxjs';
interface SubscribeRequest { symbol: string; }
interface PriceTick { symbol: string; price: number; ts: number; }
@Controller()
export class PriceController {
@GrpcMethod('PriceService', 'Subscribe')
subscribe(req: SubscribeRequest): Observable<PriceTick> {
return interval(1000).pipe(
take(10),
map((i) => ({
symbol: req.symbol,
price: 100 + Math.random(),
ts: Date.now() + i,
})),
);
}
}Client Streaming with @GrpcStreamMethod
When the client streams, NestJS hands your handler an Observable of incoming messages. You subscribe to it, aggregate, and resolve a single response once the input stream completes.
The key pattern: return a Promise (or Subject) you resolve inside complete. Use @GrpcStreamMethod so NestJS subscribes the request observable for you.
import { Controller } from '@nestjs/common';
import { GrpcStreamMethod } from '@nestjs/microservices';
import { Observable } from 'rxjs';
interface Order { id: string; qty: number; }
interface OrderAck { accepted: number; }
@Controller()
export class OrderController {
@GrpcStreamMethod('PriceService', 'PlaceOrders')
placeOrders(messages: Observable<Order>): Promise<OrderAck> {
return new Promise((resolve) => {
let accepted = 0;
messages.subscribe({
next: (order) => {
if (order.qty > 0) accepted++;
},
complete: () => resolve({ accepted }),
});
});
}
}Bidirectional Streaming
In bidirectional mode both observables are live at once. NestJS gives you the inbound Observable and expects you to return an outbound Observable (typically a Subject you push into as inbound messages arrive).
This is the echo/chat shape: subscribe to inbound, transform, and next() onto the outbound subject. Call complete() on the outbound subject when inbound completes to close cleanly.
import { Controller } from '@nestjs/common';
import { GrpcStreamMethod } from '@nestjs/microservices';
import { Observable, Subject } from 'rxjs';
interface ChatMessage { user: string; text: string; }
@Controller()
export class ChatController {
@GrpcStreamMethod('PriceService', 'Chat')
chat(messages: Observable<ChatMessage>): Observable<ChatMessage> {
const out = new Subject<ChatMessage>();
messages.subscribe({
next: (m) =>
out.next({ user: 'server', text: `echo: ${m.text}` }),
complete: () => out.complete(),
error: (e) => out.error(e),
});
return out.asObservable();
}
}@GrpcStreamMethod vs @GrpcStreamCall
NestJS exposes two decorators for streaming handlers:
- @GrpcStreamMethod — RxJS-friendly. You receive an
Observableand return anObservable/Promise. NestJS owns the underlying gRPC call object. - @GrpcStreamCall — lower level. You receive the raw gRPC
call(a Node duplex stream) and drive it withcall.on('data'),call.write(),call.end().
Reach for @GrpcStreamCall when you need direct control of the stream — for example to apply backpressure via the duplex's write() return value, which the Observable wrapper hides from you.
What Backpressure Actually Is
Backpressure is the situation where a producer generates data faster than the consumer (or the network) can accept it. Without handling, the surplus is buffered in memory until the process runs out of heap and crashes.
gRPC over HTTP/2 has flow control: each stream has a window, and a slow reader stops advancing it. The Node duplex stream surfaces this through write() returning false when its internal buffer is full, and a 'drain' event when it is safe to resume.
RxJS Observables are push-based and have no native backpressure — an interval will keep emitting regardless of whether the socket can keep up. That is the core tension in streaming RPCs.
Respecting write() Backpressure
With @GrpcStreamCall you get the raw duplex and can honor flow control properly. The rule: when call.write(msg) returns false, stop producing until the 'drain' event fires.
This generator-driven pump pulls the next item only after the previous write is accepted, so memory stays bounded no matter how fast the source could go.
import { Controller } from '@nestjs/common';
import { GrpcStreamCall } from '@nestjs/microservices';
@Controller()
export class FeedController {
@GrpcStreamCall('PriceService', 'Subscribe')
subscribe(call: any) {
let i = 0;
const pump = () => {
let ok = true;
while (ok && i < 100000) {
const tick = { symbol: 'ACME', price: i, ts: Date.now() };
ok = call.write(tick); // false => buffer full
i++;
}
if (i < 100000) {
call.once('drain', pump); // resume when flushed
} else {
call.end();
}
};
pump();
}
}Backpressure-Friendly RxJS Operators
When you stay in the Observable world, you cannot pause a hot source, but you can shape the throughput so the consumer is not overwhelmed:
concatMap— process one inner task fully before the next; preserves order and serializes work.throttleTime/sampleTime— drop intermediate values, emit at most one per window (good for noisy price feeds).bufferTime/bufferCount— batch many emissions into one message, cutting per-message overhead.auditTime— emit the latest value after a quiet window.
These trade completeness or latency for bounded load. mergeMap with no concurrency limit does the opposite — it fans out unboundedly and is a common backpressure footgun.
import { interval, Observable } from 'rxjs';
import { sampleTime, map, take } from 'rxjs';
interface PriceTick { symbol: string; price: number; }
// Raw feed could emit every 1ms; downstream only needs ~10/sec.
function throttledFeed(): Observable<PriceTick> {
return interval(1).pipe(
map((i) => ({ symbol: 'ACME', price: 100 + (i % 50) })),
sampleTime(100), // at most one tick per 100ms
take(20),
);
}Bounded Concurrency with concatMap
A frequent enterprise mistake is mapping each inbound stream item to an async call with mergeMap and unlimited concurrency. Under load, thousands of in-flight promises pile up and exhaust the DB pool.
Prefer concatMap (concurrency 1) or mergeMap(fn, N) with an explicit limit. The snippet below processes inbound orders strictly one at a time, providing natural backpressure on the persistence layer.
import { Observable, from } from 'rxjs';
import { concatMap, toArray } from 'rxjs';
interface Order { id: string; qty: number; }
// Simulate a slow persistence call.
function persist(o: Order): Promise<string> {
return new Promise((res) => setTimeout(() => res(o.id), 5));
}
function processOrders(orders: Observable<Order>): Observable<string[]> {
return orders.pipe(
concatMap((o) => from(persist(o))), // one at a time
toArray(),
);
}Cancellation, Deadlines, and Cleanup
Streams must end cleanly even when the client disconnects or a deadline expires. If you ignore cancellation, your producer keeps emitting into a dead socket and leaks timers and DB cursors.
- With
@GrpcStreamCall, listen forcall.on('cancelled', ...)and stop your pump. - With Observables, the RxJS teardown runs when NestJS unsubscribes on cancel — put cleanup in a
finalizeoperator or the producer's teardown function. - Always propagate errors via
error()(or throw aRpcException) so the client sees a real gRPC status instead of a silently hung stream.
import { Observable, interval } from 'rxjs';
import { map, takeWhile, finalize } from 'rxjs';
interface Tick { price: number; }
function feedWithCleanup(): Observable<Tick> {
return interval(500).pipe(
map((i) => ({ price: 100 + i })),
takeWhile((t) => t.price < 110),
finalize(() => {
// runs on complete, error, OR client cancel/unsubscribe
console.log('feed torn down, releasing resources');
}),
);
}Quick Check: Choosing the Decorator
You are streaming a multi-million-row export to a gRPC client and observe the Node process heap climbing until it OOMs. You suspect the producer outruns the socket.
Recap
You now know how to implement and control streaming RPCs in NestJS:
- The
streamkeyword in.protoselects server, client, or bidirectional streaming. @GrpcMethodreturning anObservablehandles server streaming;@GrpcStreamMethodgives you an inboundObservablefor client and bidirectional streams (return aPromiseorSubject).- RxJS is push-based with no native backpressure — operators like
concatMap,sampleTime, andbufferTimeshape load but do not pause a hot source. - For genuine flow control, drop to
@GrpcStreamCalland respectwrite()'sfalsereturn plus the'drain'event. - Handle cancellation and deadlines with
cancelledlisteners orfinalize, and surface failures viaerror()/RpcExceptionso clients get a real status.
Frequently asked questions
Is the “Streaming RPCs and Backpressure” lesson free?
Yes — the full text of “Streaming RPCs and Backpressure” is free to read here on the web, and the NestJS Enterprise Backend APIs course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the NestJS Enterprise Backend APIs course, upgrade to CoddyKit PRO.
What will I learn in “Streaming RPCs and Backpressure”?
Handle server, client, and bidirectional streaming with @GrpcStreamMethod and observables. You practise NestJS Enterprise Backend APIs with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start NestJS Enterprise Backend APIs?
No prior experience is required. NestJS Enterprise Backend APIs on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Streaming RPCs and Backpressure” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this NestJS Enterprise Backend APIs lesson?
Yes. Every NestJS Enterprise Backend APIs lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.