Strumieniowanie RPC i kontrola przeciążenia
Obsługuj strumieniowanie serwerowe, klienckie i dwukierunkowe za pomocą @GrpcStreamMethod oraz obserwabli.
Strumieniowanie RPC i kontrola przeciążenia to bezpłatna lekcja NestJS Enterprise Backend APIs na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej NestJS Enterprise Backend APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs NestJS Enterprise Backend APIs zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Ucz się TypeScript dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 20
- Lekcje
- 76
Często zadawane pytania
Czy lekcja „Strumieniowanie RPC i kontrola przeciążenia” jest bezpłatna?
Tak — pełny tekst „Strumieniowanie RPC i kontrola przeciążenia” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu NestJS Enterprise Backend APIs, przejdź na CoddyKit PRO. Kurs NestJS Enterprise Backend APIs zawiera 4 lekcji w sumie.
Co nauczysz się w „Strumieniowanie RPC i kontrola przeciążenia”?
Obsługuj strumieniowanie serwerowe, klienckie i dwukierunkowe za pomocą @GrpcStreamMethod oraz obserwabli. Ćwiczysz NestJS Enterprise Backend APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć NestJS Enterprise Backend APIs?
Nie wymagamy żadnego doświadczenia. NestJS Enterprise Backend APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.
Ile czasu zajmuje lekcja „Strumieniowanie RPC i kontrola przeciążenia”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji NestJS Enterprise Backend APIs?
Tak. Każda lekcja NestJS Enterprise Backend APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Definiowanie usług i komunikatów w Protobuf
- Implementowanie i wywoływanie metod gRPC
- Strumieniowanie RPC i kontrola przeciążenia
- Ewolucja kontraktów i zgodność wsteczna