Skip to content

fix(load-balancing): avoid panic when all weighted backends have zero weight#891

Open
elysia090 wants to merge 1 commit into
cloudflare:mainfrom
elysia090:fix-load-balancing-zero-weight-panic
Open

fix(load-balancing): avoid panic when all weighted backends have zero weight#891
elysia090 wants to merge 1 commit into
cloudflare:mainfrom
elysia090:fix-load-balancing-zero-weight-panic

Conversation

@elysia090
Copy link
Copy Markdown

@elysia090 elysia090 commented May 28, 2026

Summary

This fixes a panic in the weighted backend selector when the backend set is non-empty but every backend has weight 0.

No issue is filed for this small, self-contained bug fix.

Weighted::build() builds the weighted index list by pushing each backend index weight times. If all backend weights are zero, self.backend.backends is non-empty but self.backend.weighted is empty.

The first call to WeightedIterator::next() only checks whether the backend list is empty, then uses self.backend.weighted.len() as the modulo divisor. When that length is zero, this panics.

Fix

Return None from the initial weighted selection path when the weighted index list is empty.

This keeps the change limited to the all-zero-weight panic case. It does not change fallback behavior for mixed weight = 0 / weight > 0 backend sets, and it does not reject weight = 0 in Backend::new_with_weight().

Test

Added a regression test covering two backends created with Backend::new_with_weight(..., 0).

Before this change, the test panics with:

attempt to calculate the remainder with a divisor of zero

After this change, selection returns None, and repeated calls on the same iterator continue returning None.

cargo test -p pingora-load-balancing weighted_all_zero_weight_returns_none_instead_of_panicking

Result:

test selection::weighted::test::weighted_all_zero_weight_returns_none_instead_of_panicking ... ok

@elysia090 elysia090 force-pushed the fix-load-balancing-zero-weight-panic branch from 2812244 to 636b087 Compare May 28, 2026 15:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant