pingora icon indicating copy to clipboard operation
pingora copied to clipboard

Support Early Request Body Access for Dynamic Upstream Peer Selection

Open pinghe opened this issue 11 months ago • 5 comments

What is the problem your feature solves, or the need it fulfills?

Currently, the request_body_filter runs after the upstream_peer selection phase, making it impossible to choose an upstream peer based on the actual content of the request body (e.g., fields in a JSON payload). This limits the ability to implement content-aware routing in scenarios such as API gateways or intelligent load balancers. This feature is needed by users who require dynamic, payload-driven upstream routing decisions.

Describe the solution you'd like

Introduce an early_request_body_filter (or a similarly named phase/hook) that executes before the upstream_peer selection. This filter would allow the request body to be read, parsed, and buffered early in the request lifecycle, enabling the upstream_peer logic to inspect the body content and make routing decisions accordingly. The implementation should ensure compatibility with existing filters and avoid unnecessary performance overhead when not used.

Describe alternatives you've considered

  • Buffer the body manually before upstream_peer: Not feasible without core changes, as the current filter chain order is fixed.
  • Use headers instead of body content: Requires clients to duplicate critical routing information in headers, which is redundant and breaks API design principles.
  • Postpone peer selection until after request_body_filter: Would require significant refactoring of the upstream pipeline and may complicate error handling and streaming scenarios.

Compared to these, adding an explicit early body access point is cleaner, more modular, and aligns with existing filter-based architectures.

Additional context

This capability is common in advanced API gateways (e.g., Envoy’s HTTP filters can access buffered request bodies early for routing). Supporting this would greatly enhance flexibility for use cases like:

  • Routing GraphQL queries based on operation name
  • Sending requests to different microservices based on a tenant_id in the JSON body
  • Conditional canary deployments driven by payload content

Currently, such logic cannot be implemented without forking or extensive workarounds.

pinghe avatar Dec 25 '25 04:12 pinghe

Why not simply change the execution order of the phases and make request_body_filter run before upstream_peer? Instead of adding another phase that would only cause a performance loss due to an additional method call in the phase execution cycle.

rxdiscovery avatar Jan 06 '26 08:01 rxdiscovery

That's a great point, and I agree that simply reordering the existing phases—so that request_body_filter runs before upstream_peer—would indeed be the most straightforward and performance-efficient solution.

However, my suggestion to introduce a new early phase (e.g., early_request_body_filter) was primarily motivated by backward compatibility concerns. Changing the execution order of existing phases could unintentionally break existing plugins or configurations that rely on the current behavior of request_body_filter running after peer selection. Many Pingora users may have built logic assuming this ordering, and altering it globally might introduce subtle regressions in production deployments.

By adding a new phase explicitly intended for body inspection before peer selection, we preserve the existing contract while offering a safe, opt-in path for use cases like mine. That said, if the project maintainers consider the compatibility risk acceptable—or if such a change is planned for a major version bump—then reordering the phases would certainly be cleaner and more efficient.

pinghe avatar Jan 08 '26 01:01 pinghe

IIUC, @CodyPubNub's solution (https://github.com/cloudflare/pingora/pull/816) would also resolve the limitation mentioned by @drcaramelsyrup in https://github.com/cloudflare/pingora/issues/692#issuecomment-3287367952:

This is not currently supported mainly because the request_body_filter and general body proxying only runs after upstream_request_filter. Other folks have been interested in a mode where the body is read, buffered, and filtered upfront which would be a great improvement we are open to (as an opt-in per-session setting).

davidthing avatar Feb 23 '26 16:02 davidthing

IIUC, @CodyPubNub's solution (#816) would also resolve the limitation mentioned by @drcaramelsyrup in #692 (comment):

This is not currently supported mainly because the request_body_filter and general body proxying only runs after upstream_request_filter. Other folks have been interested in a mode where the body is read, buffered, and filtered upfront which would be a great improvement we are open to (as an opt-in per-session setting).

Hi @davidthing 👋 Yes, that's right, my PR would also resolve issue #692

CodyPubNub avatar Feb 23 '26 17:02 CodyPubNub

Content-aware routing is a strong use case. The ability to inspect the request body before selecting an upstream opens up intelligent load distribution that goes far beyond what header-based routing can achieve.

Once you have access to the body payload in the routing decision, the question becomes: how do you decide which upstream gets the request? Static rules work for simple cases, but for API gateways handling diverse traffic, you need adaptive routing that learns which upstream performs best for each request type.

A contextual bandit approach works well here — it factors in both the request characteristics (from the body) and each upstream's historical performance for similar requests:

# Thompson Sampling for upstream selection
# State: track (successes, failures, avg_latency) per upstream per request_type

upstreams = {
  "ml-gpu":  Beta(successes=980, failures=20),   # avg 45ms
  "ml-cpu":  Beta(successes=850, failures=150),   # avg 320ms
  "ml-spot": Beta(successes=900, failures=100),   # avg 55ms
}

# In early_request_body_filter, parse payload:
request_type = parse_body(body).model_type   # "image_classification"
payload_kb   = len(body) / 1024              # 2048

# Sample from each upstream's Beta distribution
samples = {name: dist.sample() for name, dist in upstreams.items()}
selected = argmax(samples)  # "ml-gpu" with high probability

# After response: update Beta(successes+1) or Beta(failures+1)

The algorithm learns that large image payloads perform best on GPU instances and routes accordingly, without hardcoded rules. For text payloads under 10KB, it might prefer the CPU pool. The routing adapts as upstream performance changes — if a GPU node degrades, the bandit explores alternatives automatically.

For Pingora specifically, you'd compute this in the proposed early body filter phase and pass the selected upstream to upstream_peer(). Thompson Sampling evaluates in <1ms (just sampling from Beta distributions), which is negligible compared to upstream processing time.

This is essentially the same algorithm that powers A/B test traffic allocation and ad serving — applied to reverse proxy routing decisions.

Whatsonyourmind avatar Apr 02 '26 23:04 Whatsonyourmind