0Pricing
Elixir & Phoenix: Scalable Backend Development · Lezione

Pipeline GenStage e backpressure

Costruisca pipeline di dati guidate dalla domanda con GenStage, in cui i consumer controllano il flusso tramite backpressure per evitare il sovraccarico nei sistemi distribuiti.

Pipeline GenStage e backpressure è una lezione Elixir & Phoenix: Scalable Backend Development gratuita su CoddyKit. Questa è la lezione 4 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 Elixir & Phoenix: Scalable Backend Development, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.

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

The Overload Problem

When a fast producer feeds a slow consumer, messages pile up and memory explodes. Backpressure solves this: consumers signal how much work they can handle, and producers send only that much.

What is GenStage?

GenStage is an Elixir behaviour for building staged, demand-driven pipelines. Data flows from producers to consumers, with optional producer-consumer stages in between.

The Three Stage Types

Every GenStage process plays one role:

  • Producer: emits events on demand
  • ProducerConsumer: receives, transforms, and re-emits
  • Consumer: receives and processes events

Defining a Producer

A producer implements init/1 and handle_demand/2. It returns events only when consumers ask for them.

defmodule Counter do
  use GenStage
  def init(start), do: {:producer, start}
  def handle_demand(demand, state) do
    events = Enum.to_list(state..(state + demand - 1))
    {:noreply, events, state + demand}
  end
end

Defining a Consumer

A consumer implements handle_events/3. It returns no events itself, only acknowledging the demand it processed.

defmodule Printer do
  use GenStage
  def init(_), do: {:consumer, :ok}
  def handle_events(events, _from, state) do
    for e <- events, do: IO.inspect(e)
    {:noreply, [], state}
  end
end

Subscribing Stages

Connect a consumer to a producer with GenStage.sync_subscribe/2. The max_demand option caps how many events flow at once.

{:ok, prod} = GenStage.start_link(Counter, 0)
{:ok, cons} = GenStage.start_link(Printer, :ok)
GenStage.sync_subscribe(cons, to: prod, max_demand: 10)

How Backpressure Works

The consumer requests up to max_demand events. The producer can never send more than was requested, so a slow consumer naturally throttles a fast producer. No buffering blowup.

Producer-Consumer Stages

A middle stage transforms data. It implements handle_events/3 but returns transformed events for the next stage.

def handle_events(events, _from, state) do
  doubled = Enum.map(events, &(&1 * 2))
  {:noreply, doubled, state}
end

ConsumerSupervisor

For concurrent processing, ConsumerSupervisor spawns a short-lived child process per event, bounded by demand. This parallelizes work while keeping backpressure intact.

Flow for Parallel Pipelines

The Flow library builds on GenStage to offer map/reduce-style parallel data processing with partitioning — ideal for crunching large collections across cores.

File.stream!("big.csv")
|> Flow.from_enumerable()
|> Flow.map(&parse_line/1)
|> Flow.partition()
|> Enum.to_list()

When to Reach for GenStage

Use GenStage when you have:

  • A rate mismatch between data source and processing
  • Streaming data that must not overwhelm memory
  • Multi-stage transformation pipelines

Quick Check

Test your GenStage knowledge.

Recap

You learned demand-driven pipelines:

  • GenStage has producers, producer-consumers, and consumers
  • Consumers request bounded demand for backpressure
  • Subscribe stages with sync_subscribe and max_demand
  • ConsumerSupervisor parallelizes per-event work
  • Flow builds parallel map/reduce pipelines on top

Backpressure keeps distributed systems stable under load.

Domande Frequenti

La lezione «Pipeline GenStage e backpressure» è gratuita?

Sì — il testo completo di «Pipeline GenStage 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 Elixir & Phoenix: Scalable Backend Development, passa a CoddyKit PRO. Il corso Elixir & Phoenix: Scalable Backend Development include 4 lezioni in totale.

Cosa imparerò in «Pipeline GenStage e backpressure»?

Costruisca pipeline di dati guidate dalla domanda con GenStage, in cui i consumer controllano il flusso tramite backpressure per evitare il sovraccarico nei sistemi distribuiti. Eserciti Elixir & Phoenix: Scalable Backend Development 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 Elixir & Phoenix: Scalable Backend Development?

Non è richiesta alcuna esperienza precedente. Elixir & Phoenix: Scalable Backend Development su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Pipeline GenStage 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 Elixir & Phoenix: Scalable Backend Development?

Sì. Ogni lezione Elixir & Phoenix: Scalable Backend Development 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. Elixir distribuito e clustering
  2. Strategie avanzate dei supervisor
  3. Supervisor dinamici e Registry
  4. Pipeline GenStage e backpressure
← Torna a Elixir & Phoenix: Scalable Backend Development