Skip to content

feat(batchrouter): introduce isolation levels and concurrency limiters - #3248

Merged
atzoum merged 3 commits into
masterfrom
refactor.batchrouterWorkers
May 11, 2023
Merged

atzoum merged 3 commits into
masterfrom
refactor.batchrouterWorkers

Conversation

@atzoum

@atzoum atzoum commented Apr 26, 2023 •

Copy link
Copy Markdown
Contributor

Description

Introducing isolation strategies in batchrouter, following the pattern we are already using in processor.

Batchrouter Isolation

The following isolation modes are now supported in batchrouter:

  1. none - a single worker retrieves and processes jobs for all workspaces & destinations
  2. workspace - using a separate worker per workspace (default mode in multi-tenant deployments)
  3. destination - using a separate worker per destination (default mode in non-multi-tenant deployments)

To avoid proliferation of busy goroutines, we are introducing 3 limiters:

  1. read - for reading jobs from jobsdb (limit: 20 goroutines/destType)
  2. process - for controlling concurrency while processing jobs grouped by destination (limit: 20 goroutines/destType)
  3. upload - for controlling concurrency while uploading files grouped by source & destination (limit: 50 goroutines/destType)

Upload frequency adaptations

In the new design, upload frequency is still honoured, but only as long as jobsdb's read limits are not being reached (limited by the number of events and/or total payload size). If a worker detects that jobsdb's limits are reached, it disregards upload frequency restrictions, until the backlog is flushed.

Side-effects of upload frequency adaptations in the context of isolation modes:

  • none: destinations with sparse jobs will be processed more frequently when limits are reached for any other destination.
  • workspace: destinations with sparse jobs will be processed more frequently when limits are reached for any other destination beloning to the same workspace.
  • destination: none, only destinations with large backlog will be processed more frequently when limits are reached.

Performance

Similarly to what has already been observed in processor, both isolation modes (workspace & destination) perform equally well with none up to a cardinality of 200. After that, throughput starts deteriorating, which is an acceptable toll to pay, taking into consideration the other advantages associated with isolation (i.e. one customer/destination not affecting the other).

The relevant benchmark can be found inside batchrouter_isolation_test.go and a visualisation of one execution of this benchmark is available here.

Other notable changes

  • Extracted worker pool & worker lifecycle management logic to a common utility package, dubbed workerpool, so that it can be shared between processor and batchrouter.
  • Reorganised package's code in separate, logically-grouped files, trying to make it easier to read and follow.
  • Removed global variables and Init function from the package.
  • Introduced the db utility function unionjobsdbmetadata which is a faster version of unionjobsdb, since it doesn't include the payloads in the resultsets.

Notion Ticket

Link

Security

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

@codecov

codecov Bot commented Apr 26, 2023 •

Copy link
Copy Markdown

Codecov Report

Patch coverage: 51.43% and project coverage change: +0.50 🎉

Comparison is base (19ceebb) 52.03% compared to head (ef91440) 52.53%.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3248      +/-   ##
==========================================
+ Coverage   52.03%   52.53%   +0.50%     
==========================================
  Files         321      327       +6     
  Lines       53191    53242      +51     
==========================================
+ Hits        27677    27970     +293     
+ Misses      23864    23634     -230     
+ Partials     1650     1638      -12     
Impacted Files Coverage Δ
jobsdb/internal/cache/cache.go 97.00% <0.00%> (ø)
runner/runner.go 67.72% <ø> (-0.13%) ⬇️
warehouse/integrations/testhelper/setup.go 0.47% <0.00%> (-0.01%) ⬇️
warehouse/utils/utils.go 75.31% <ø> (+0.26%) ⬆️
router/batchrouter/handle_async.go 1.82% <1.82%> (ø)
router/batchrouter/util.go 53.12% <53.12%> (ø)
router/batchrouter/worker.go 62.00% <62.00%> (ø)
router/batchrouter/handle.go 63.18% <63.18%> (ø)
jobsdb/jobsdb.go 73.52% <63.88%> (+0.50%) ⬆️
router/batchrouter/handle_lifecycle.go 73.60% <73.60%> (ø)
... and 14 more

... and 12 files with indirect coverage changes

☔ View full report in Codecov by Sentry.
📢 Do you have feedback about the report comment? Let us know in this issue.

@atzoum
atzoum force-pushed the refactor.batchrouterWorkers branch from dd1df6f to a65b5b9 Compare April 26, 2023 11:28
@atzoum
atzoum force-pushed the refactor.batchrouterWorkers branch 9 times, most recently from 8306547 to cfd5163 Compare May 3, 2023 18:23
@atzoum atzoum changed the title [WIP] chore(batchrouter): refactor [WIP] feat(batchrouter): introduce isolation levels and concurrency limiters May 4, 2023
@atzoum
atzoum force-pushed the refactor.batchrouterWorkers branch from cfd5163 to 1cc9965 Compare May 4, 2023 07:26
@atzoum atzoum changed the title [WIP] feat(batchrouter): introduce isolation levels and concurrency limiters feat(batchrouter): introduce isolation levels and concurrency limiters May 4, 2023
@atzoum
atzoum force-pushed the refactor.batchrouterWorkers branch 3 times, most recently from 0653460 to 3a783ef Compare May 5, 2023 11:17
@atzoum
atzoum force-pushed the refactor.batchrouterWorkers branch from 0779771 to 74f0771 Compare May 10, 2023 05:44
@atzoum
atzoum force-pushed the refactor.batchrouterWorkers branch 8 times, most recently from e933141 to 3b182e2 Compare May 11, 2023 07:00
@atzoum
atzoum force-pushed the refactor.batchrouterWorkers branch from 3b182e2 to ef91440 Compare May 11, 2023 07:01
@atzoum
atzoum merged commit d90ea68 into master May 11, 2023
@atzoum
atzoum deleted the refactor.batchrouterWorkers branch May 11, 2023 08:42
achettyiitr added a commit that referenced this pull request Sep 24, 2026
There were no tests for warehouseServiceFailedTime, warehouseServiceMaxRetryTime
or updateJobStatus, which is how the zero-timestamp abort survived since #3248.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012YX6Cdjs6iKeJCtzm9udju
achettyiitr added a commit that referenced this pull request Sep 29, 2026
…tamp (#7426)

Linear:
[INT-7231](https://linear.app/rudderstack/issue/INT-7231/batch-router-aborts-warehouse-jobs-with-410-on-a-zero-failure)

## Problem

`warehouseServiceFailedTime` gates whether jobs waiting on a failing
warehouse service are retried or aborted with `410`. It is meant to give
them `BatchRouter.warehouseServiceMaxRetryTime` (default 3h) before
giving up. In practice it can abort them on their first attempt.

Three things combine (`router/batchrouter/handle.go`):

1. **The field is shared.** `Factory.New(destType)` creates one `Handle`
per destType, so a single `warehouseServiceFailedTime` describes "is the
warehouse service failing" for every destination of that destType in the
process.
2. **Any success zeroes it.** The `else if isWarehouse` arm resets it to
`time.Time{}` on every warehouse batch that is not a ping failure —
including all the successful ones.
3. **The check re-read the shared field** after setting it, rather than
using the value it had just written. `updateJobStatus` runs under
`BatchRouter.Limiter.upload.limit` (default **200**) concurrent
goroutines on the same `Handle`, so a concurrent success can zero the
field between the write and the read.

`time.Since(time.Time{})` is roughly 2,025 years, which exceeds any
retry window, so the guard aborts unconditionally when it reads a zero.

## Production impact

`entusmtprod` / `enterprise-rudder`, 2026-09-23. A workspace migration
edited `Warehouse.degradedWorkspaceIDs` three times in 40 minutes. That
key is read with the non-reloadable getter and the operator sets
`shutdownOnNonReloadableConfigChange: true`, so the shared warehouse
service restarted three times.

`pingWarehouse` POSTs to `/v1/process` failed during the restarts:

```
dial tcp 172.20.230.47:80: connect: connection refused
context deadline exceeded (Client.Timeout exceeded while awaiting headers)
```

- **173 destinations across 108 workspaces**, 210,301 events, got `500`,
retried, and delivered once the service returned — the whole cycle took
about two minutes.
- **4 destinations lost 1,499 events** to terminal `410` aborts. The
sampled reporting row shows `firstAttemptedAt 2026-09-23T20:02:37.175Z`,
and the abort counter reads its final value by `20:03:00Z` — **aborted
23 seconds after the job's first attempt**, on attempt one.

Neither retry policy can produce that. `retryLimitReached` needs
`AttemptNum >= 128` **and** `time.Since(firstAttemptedAt) >
retryTimeWindow` (24h on this cluster), and it is gated on
`!notifyWarehouseErr` so it was never evaluated. The warehouse branch
needs 3 hours. The only way to get 23 seconds is a comparison against
the zero time.

During the failing two-minute window `generate_staging_files` shows
~2,576 batch completions in `entusmtprod` — roughly 20 calls per second
into this code path, most of them successes zeroing the field.

## Change

Capture the failure start under the same lock that sets it, and check
that local copy:

```go
var warehouseServiceFailedSince time.Time
if isWarehouse && notifyWarehouseErr {
    brt.warehouseServiceFailedTimeMu.Lock()
    if brt.warehouseServiceFailedTime.IsZero() {
        brt.warehouseServiceFailedTime = time.Now()
    }
    warehouseServiceFailedSince = brt.warehouseServiceFailedTime
    brt.warehouseServiceFailedTimeMu.Unlock()
}
```

and move the decision into a named method that refuses to abort on a
zero:

```go
func (brt *Handle) warehouseServiceRetryLimitReached(failedSince time.Time) bool {
	if failedSince.IsZero() {
		return false
	}
	return time.Since(failedSince) > brt.warehouseServiceMaxRetryTime.Load()
}
```

The zero check is deliberately belt-and-braces: with the capture in
place the guard should never see a zero, but if it ever does the safe
direction is to retry, not to discard customer data.

## Verification

```
go test ./router/batchrouter/ -run TestWarehouseServiceRetryLimitReached -race -count=1
ok  github.com/rudderlabs/rudder-server/router/batchrouter
```

The test fails without the fix — removing the `IsZero` guard produces:

```
--- FAIL: TestWarehouseServiceRetryLimitReached/zero_failedSince_never_aborts
    Should be false
    a zero failure start must not abort: it is year 1 and exceeds every retry window
```

`go build ./router/...` and `go vet ./router/batchrouter/` are clean.

There were **no existing tests** for `warehouseServiceFailedTime`,
`warehouseServiceMaxRetryTime` or `updateJobStatus`, which is how this
survived since #3248 (May 2023).

## Deliberately not in this PR

The field is still shared across every destination of a destType, so one
destination's success still clears the failure clock for the others.
That means the 3-hour window can struggle to accumulate on a busy shared
namespace and the guard will under-abort. That is the safe direction,
and fixing it properly means keying the state by destination — a larger
change worth doing separately.

## Not proven

The exact interleaving for those four destinations is deduced, not
observed: nothing logs or counts the reset. It is the only remaining
mechanism after ruling out `retryLimitReached` (arithmetically
impossible at 23s), a configuration override (no override in the
operator or devops repos), the drainer path (emits `drained_events`,
which is absent for these destinations), and `degradedWorkspaceIDs`
(only filters config; the degraded workspace itself had zero aborts, and
none of the four was ever on the list).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_012YX6Cdjs6iKeJCtzm9udju

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants