Skip to content

Inbound and outbound handler execution order

In Netty's ChannelPipeline, the order in which handlers are executed depends on whether the event is inbound (read) or outbound (write), as well as the specific type of the handler (Inbound vs. Outbound).^[600-developer-big-data-netty-netty-channelpipeline.md]

Handler Registration and Types

When adding handlers to a pipeline, they are appended to the list in the order they are registered using methods like addLast.^[600-developer-big-data-netty-netty-channelpipeline.md] Handlers are generally categorized as ChannelInboundHandler, ChannelOutboundHandler, or a hybrid that implements both.^[600-developer-big-data-netty-netty-channelpipeline.md]

For example, given the following registration sequence^[600-developer-big-data-netty-netty-channelpipeline.md]: 1. InboundHandlerA 2. InboundHandlerB 3. OutboundHandlerA 4. OutboundHandlerB 5. InboundOutboundHandlerX

Execution Logic

The execution flow does not simply follow the registration index (1, 2, 3...) linearly. Instead, the pipeline iterates through the context list and invokes handlers only if they implement the appropriate interface for the current event type^[600-developer-big-data-netty-netty-channelpipeline.md].

Inbound Events (e.g., Read)

For an inbound event, the pipeline traverses the list starting from the "head" (beginning).^[600-developer-big-data-netty-netty-channelpipeline.md]

  • Inbound Handlers: Executed in the order they were added (forward direction).
  • Outbound Handlers: Generally ignored/skipped.

In the example above, an inbound event will trigger 1 (InboundHandlerA), 2 (InboundHandlerB), and 5 (InboundOutboundHandlerX), in that order^[600-developer-big-data-netty-netty-channelpipeline.md]. Note that handlers 3 and 4 are skipped because they are purely outbound.

Outbound Events (e.g., Write)

For an outbound event, the pipeline traverses the list starting from the "tail" (end)^[600-developer-big-data-netty-netty-channelpipeline.md].

  • Outbound Handlers: Executed in reverse order of their addition (backward direction).
  • Inbound Handlers: Generally ignored/skipped.

In the example above, an outbound event will trigger 5 (InboundOutboundHandlerX), 4 (OutboundHandlerB), and 3 (OutboundHandlerA)^[600-developer-big-data-netty-netty-channelpipeline.md]. Note that handlers 2 and 1 are skipped.

Sources

^[600-developer-big-data-netty-netty-channelpipeline.md]