NestJS Enterprise Backend APIs · Lezione

RPC in streaming e backpressure

Gestisca lo streaming lato server, client e bidirezionale con @GrpcStreamMethod e gli observable.

Lezione 3 di 413 passaggi

RPC in streaming e backpressure è una lezione NestJS Enterprise Backend APIs gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento NestJS Enterprise Backend APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso NestJS Enterprise Backend APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 Observable and return an Observable/Promise. NestJS owns the underlying gRPC call object.
  • @GrpcStreamCall — lower level. You receive the raw gRPC call (a Node duplex stream) and drive it with call.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 for call.on('cancelled', ...) and stop your pump.
  • With Observables, the RxJS teardown runs when NestJS unsubscribes on cancel — put cleanup in a finalize operator or the producer's teardown function.
  • Always propagate errors via error() (or throw a RpcException) 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 stream keyword in .proto selects server, client, or bidirectional streaming.
  • @GrpcMethod returning an Observable handles server streaming; @GrpcStreamMethod gives you an inbound Observable for client and bidirectional streams (return a Promise or Subject).
  • RxJS is push-based with no native backpressure — operators like concatMap, sampleTime, and bufferTime shape load but do not pause a hot source.
  • For genuine flow control, drop to @GrpcStreamCall and respect write()'s false return plus the 'drain' event.
  • Handle cancellation and deadlines with cancelled listeners or finalize, and surface failures via error()/RpcException so clients get a real status.
Gratis per iniziare

Impara TypeScript con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
20
Lezioni
76

Domande Frequenti

La lezione «RPC in streaming e backpressure» è gratuita?

Sì — il testo completo di «RPC in streaming e backpressure» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso NestJS Enterprise Backend APIs, passa a CoddyKit PRO. Il corso NestJS Enterprise Backend APIs include 4 lezioni in totale.

Cosa imparerò in «RPC in streaming e backpressure»?

Gestisca lo streaming lato server, client e bidirezionale con @GrpcStreamMethod e gli observable. Eserciti NestJS Enterprise Backend APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare NestJS Enterprise Backend APIs?

Non è richiesta alcuna esperienza precedente. NestJS Enterprise Backend APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «RPC in streaming e backpressure»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione NestJS Enterprise Backend APIs?

Sì. Ogni lezione NestJS Enterprise Backend APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Definizione di servizi e messaggi in Protobuf
  2. Implementazione e consumo dei metodi gRPC
  3. RPC in streaming e backpressure
  4. Evoluzione dei contratti e compatibilità all’indietro
← Torna a NestJS Enterprise Backend APIs