Skip to content

fix(router): delays in finding worker slots when event ordering is disabled - #6930

Merged
atzoum merged 1 commit into
masterfrom
fix.wbPerf
May 12, 2026
Merged

atzoum merged 1 commit into
masterfrom
fix.wbPerf

Conversation

@atzoum

@atzoum atzoum commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

🔒 Scanned for secrets using gitleaks 8.30.1

Description

Observed problem

When event ordering is disabled, Handle.findWorkerSlot becomes unexpectedly slow at high worker counts. With 512 workers per partition and the experimental buffer-size calculator enabled, each call to find a worker slot took ~47 µs locally — meaning a single pickup batch of 6 000 events spent ~280 ms of CPU just resolving which worker to assign each job to, before any actual processing happened. Latency is even worse on production machines.

Root causes

The slow path is the event-ordering-disabled branch in findWorkerSlot:

availableWorkers := lo.Filter(workers, func(w *worker, _ int) bool { return w.AvailableSlots() > 0 })
if len(availableWorkers) == 0 { return nil, types.ErrWorkerNoSlot }
slot := availableWorkers[rand.Intn(len(availableWorkers))].ReserveSlot()

Two compounding problems:

  1. AvailableSlots() recomputes the buffer's target capacity on every call. Inside workerBuffer.currentCapacity(), the calculator closure runs (for the experimental calculator: a SimpleMovingAverage.Load, multiple ValueLoader.Loads, and math.Max/math.Ceil), plus the stats OnceEvery.Do check fires — and this happens 513 times per call (once per worker for the filter, then once more on the chosen worker's ReserveSlot). With stats wired up, this path costs ~47 µs/call.

  2. Filter-then-pick is structurally redundant and racy. lo.Filter allocates a ~5 KB survivor slice, takes 512 RLocks just to ask "do you have a slot?", then we take a write Lock on the chosen worker to actually reserve. The first 512 reads are throwaway work, and there's a (currently benign, single-threaded) race window between the filter and the reservation.

What we're doing

1. Cache the buffer capacity, refresh it from a 1 s sampler.

  • workerBuffer gains a cachedCapacity atomic.Int64 field (initialized in the constructor).
  • availableSlots() reads the cached value with an atomic load instead of invoking the calculator.
  • partitionWorker runs a single sampler goroutine that ticks once per second and calls refreshCapacity() on every worker buffer it owns. The sampler is cancelled cleanly from Stop().
  • Since the calculator inputs (config values, throughput SMA) move slowly, a 1 s lag is harmless — production already throttles the corresponding stats observation to every 5 s via OnceEvery.

2. Replace filter+pick with shuffle-and-try.

  • New helper reserveAnyWorkerSlot(workers) picks a random starting offset and walks the workers slice with wrap-around, calling ReserveSlot until one succeeds.
  • ReserveSlot is the atomic decision point — no pre-filter step, no race window, no allocation for the survivor slice.
  • The random start gives uniform worker selection (in expectation) just like the old rand.Intn over the filter result.

3. New observability stat for slot-resolution latency.

  • router_pickup_find_worker_slot_time (TimerType, tags: destType, partition) — total wall-clock time spent inside findWorkerSlot across a single pickup loop. Published once per pickup. Lets us catch regressions in the future, alert on pathological saturation (when buffers run dry and findWorkerSlot keeps failing fast across all workers), and confirm the impact of this change in production.

Benchmark results

Added BenchmarkFindWorkerSlot in router/find_worker_slot_bench_test.go. It exercises 512 workers across all three production buffer modes (simple, dynamic/standard, dynamic/experimental) and five fill scenarios. Numbers below are from an Apple M1 Pro at 2 s/case for the worst production mode (dynamic/experimental — switcher with enableExperimental=true, full workerBufferStats wired up).

scenario before + cached capacity + shuffleTry (this PR)
typical (slots widely available) ~47 µs/op, 4 872 B/op ~6.7 µs/op, 4 872 B/op ~45 ns/op, 8 B/op
50% of workers full ~47 µs/op ~6.7 µs/op ~1.1 µs/op
99% of workers full ~47 µs/op ~6.7 µs/op ~4.3 µs/op
99.8% of workers full ~47 µs/op ~6.4 µs/op ~4.4 µs/op

Even in the catastrophic 99.8%-full case, the new path wins — and allocations drop from ~5 KB/call to 8 B/call (boxed int from rand.Intn).

Extrapolated to a 6 000-event pickup batch, in the typical case:

  • Before: ~280 ms of CPU just resolving worker slots.
  • After: ~0.27 ms — roughly 1 000× lower CPU cost on the hot path.

Linear Ticket

resolves PIPE-2949

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

@atzoum
atzoum force-pushed the fix.wbPerf branch 3 times, most recently from b9e8133 to 4db66e1 Compare April 30, 2026 08:05
@atzoum
atzoum marked this pull request as ready for review April 30, 2026 08:19
@codecov

codecov Bot commented Apr 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.28571% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.05%. Comparing base (73d3bbe) to head (e863c8b).

Files with missing lines Patch % Lines
router/handle.go 87.50% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6930      +/-   ##
==========================================
- Coverage   80.06%   80.05%   -0.02%     
==========================================
  Files         565      565              
  Lines       63412    63436      +24     
==========================================
+ Hits        50772    50781       +9     
+ Misses       9646     9645       -1     
- Partials     2994     3010      +16     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…sabled

🔒 Scanned for secrets using gitleaks 8.30.1

@fracasula fracasula left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, disregard the comment 👍

Comment thread router/handle.go
}
start := rand.Intn(n)
for i := range n {
if slot := workers[(start+i)%n].ReserveSlot(); slot != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's say we have a workers slice, say of 10 workers.
0 is free, all others are taken.
Then you get 1 as the index and iterate over all of them, then return nil.
Shouldn't you do a second loop in that case and go from 0 to n, which in the above case would return the worker at 0?

@fracasula fracasula May 11, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read this wrong, nevermind. I didn't notice the %n and I was under the impression that you started from n and kept going ahead until the end of the slice 👍

@atzoum
atzoum merged commit a7389f8 into master May 12, 2026
73 checks passed
@atzoum
atzoum deleted the fix.wbPerf branch May 12, 2026 09:34
This was referenced May 12, 2026
itsmihir pushed a commit that referenced this pull request May 12, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.75.0-rc.1](v1.74.0...v1.75.0-rc.1)
(2026-05-12)


### Features

* snowpipe batch status
([#6926](#6926))
([f00dd89](f00dd89))
* support clickhouse day week month partitions
([#6931](#6931))
([00ff494](00ff494))
* support concurrency during partition migration flushing
([#6929](#6929))
([dd2f658](dd2f658))


### Bug Fixes

* **router:** delays in finding worker slots when event ordering is
disabled
([#6930](#6930))
([a7389f8](a7389f8))
* rsources failed keys batch fails to be inserted with postgres error
21000 ([#6940](#6940))
([3c7a1ec](3c7a1ec))
* salesforce bulk upload null and numeric CSV formatting
([#6923](#6923))
([5e67a45](5e67a45))


### Miscellaneous

* debug snowpipe streaming importing job size
([#6941](#6941))
([73d3bbe](73d3bbe))
* filtering overflow events for snowpipe streaming above 16MB
([#6921](#6921))
([2e5192b](2e5192b))
* pyt managed session
([#6910](#6910))
([c7aa7c4](c7aa7c4))
* remove deprecated fetch-tables endpoint
([#6944](#6944))
([fdb2649](fdb2649))
* sync release v1.74.0 to main branch
([#6920](#6920))
([e844f82](e844f82))
* workflow cleanup
([#6924](#6924))
([da7161d](da7161d))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.com>
itsmihir pushed a commit that referenced this pull request May 14, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.75.0](v1.74.0...v1.75.0)
(2026-05-12)


### Features

* snowpipe batch status
([#6926](#6926))
([f00dd89](f00dd89))
* support clickhouse day week month partitions
([#6931](#6931))
([00ff494](00ff494))
* support concurrency during partition migration flushing
([#6929](#6929))
([dd2f658](dd2f658))


### Bug Fixes

* **router:** delays in finding worker slots when event ordering is
disabled
([#6930](#6930))
([a7389f8](a7389f8))
* rsources failed keys batch fails to be inserted with postgres error
21000 ([#6940](#6940))
([3c7a1ec](3c7a1ec))
* salesforce bulk upload null and numeric CSV formatting
([#6923](#6923))
([5e67a45](5e67a45))


### Miscellaneous

* debug snowpipe streaming importing job size
([#6941](#6941))
([73d3bbe](73d3bbe))
* filtering overflow events for snowpipe streaming above 16MB
([#6921](#6921))
([2e5192b](2e5192b))
* pyt managed session
([#6910](#6910))
([c7aa7c4](c7aa7c4))
* remove deprecated fetch-tables endpoint
([#6944](#6944))
([fdb2649](fdb2649))
* sync release v1.74.0 to main branch
([#6920](#6920))
([e844f82](e844f82))
* workflow cleanup
([#6924](#6924))
([da7161d](da7161d))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.com>
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.

3 participants