💧 Elixir Advanced

What is GenStage in Elixir?

Answer

GenStage is a specification for building back-pressure-aware data pipelines in Elixir. It extends GenServer with demand-driven flow — producers only produce what consumers request. Three roles: :producer (generates data), :consumer (processes data), :producer_consumer (both — a transformation stage). Key mechanism: consumers send demand to producers; producers respond with events. handle_demand(demand, state): produce up to demand events. handle_events(events, _from, state): process received events. Back-pressure: if a consumer is slow, it simply doesn't request more events — the pressure propagates upstream automatically. Dispatch strategies: GenStage.BroadcastDispatcher (all consumers get all events), GenStage.DemandDispatcher (distribute based on demand), GenStage.PartitionDispatcher (route to specific consumers by key). GenStage is the foundation of Broadway and provides the primitives for building custom streaming data systems.