스트리밍 RPC와 백프레셔
@GrpcStreamMethod와 옵저버블을 사용해 서버, 클라이언트 및 양방향 스트리밍을 처리합니다.
스트리밍 RPC와 백프레셔은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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.
자주 묻는 질문
“스트리밍 RPC와 백프레셔” 강의는 무료인가요?
네 — “스트리밍 RPC와 백프레셔” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.
“스트리밍 RPC와 백프레셔”에서 뭘 배우나요?
@GrpcStreamMethod와 옵저버블을 사용해 서버, 클라이언트 및 양방향 스트리밍을 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“스트리밍 RPC와 백프레셔” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Protobuf에서 서비스와 메시지 정의
- gRPC 메서드 구현과 사용
- 스트리밍 RPC와 백프레셔
- 계약 진화와 하위 호환성