-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
feat(batch-queue): two-level tenant dispatch for fair queue #3133
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ericallam
merged 9 commits into
main
from
feature/tri-7082-batch-queue-fair-queue-architecture-change
Feb 26, 2026
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6aa8954
feat: two-level tenant dispatch for fair queue (TRI-7082)
ericallam e1604f7
safer legacy master queue draining
ericallam a7c1b4a
fix: update visibility manager release/reclaim to use dispatch indexes
ericallam 8d0a826
test: add release/reclaim dispatch index tests and legacy migration t…
ericallam d79ca44
fix: fallback dispatch scheduler was reading empty master queue
ericallam 4a62c4b
typecheck fixes
ericallam b855e48
Better DRR efficiency and making sure selection is fair
ericallam af54cdf
fix: dispatch index shard must be tenant-based, not queue-based
ericallam 321b462
chore: add server changes file for dispatch shard fix
ericallam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| import { createRedisClient, type Redis, type RedisOptions } from "@internal/redis"; | ||
| import { jumpHash } from "@trigger.dev/core/v3/serverOnly"; | ||
| import type { FairQueueKeyProducer, QueueWithScore } from "./types.js"; | ||
|
|
||
| export interface TenantDispatchOptions { | ||
| redis: RedisOptions; | ||
| keys: FairQueueKeyProducer; | ||
| shardCount: number; | ||
| } | ||
|
|
||
| export interface TenantWithScore { | ||
| tenantId: string; | ||
| score: number; | ||
| } | ||
|
|
||
| /** | ||
| * TenantDispatch manages the two-level tenant dispatch index. | ||
| * | ||
| * Level 1 - Dispatch Index (per shard): | ||
| * Key: {prefix}:dispatch:{shardId} | ||
| * ZSET of tenantIds scored by oldest message timestamp across their queues. | ||
| * Only tenants with queues containing messages appear here. | ||
| * | ||
| * Level 2 - Per-Tenant Queue Index: | ||
| * Key: {prefix}:tenantq:{tenantId} | ||
| * ZSET of queueIds scored by oldest message timestamp in that queue. | ||
| * | ||
| * This replaces the flat master queue for new enqueues, isolating each tenant's | ||
| * queue backlog so the scheduler iterates tenants (not queues) at Level 1. | ||
| */ | ||
| export class TenantDispatch { | ||
| private redis: Redis; | ||
| private keys: FairQueueKeyProducer; | ||
| private shardCount: number; | ||
|
|
||
| constructor(private options: TenantDispatchOptions) { | ||
| this.redis = createRedisClient(options.redis); | ||
| this.keys = options.keys; | ||
| this.shardCount = Math.max(1, options.shardCount); | ||
| } | ||
|
|
||
| /** | ||
| * Get the shard ID for a queue. | ||
| * Uses the same jump consistent hash as MasterQueue for consistency. | ||
| */ | ||
| getShardForQueue(queueId: string): number { | ||
| return jumpHash(queueId, this.shardCount); | ||
| } | ||
|
|
||
| /** | ||
| * Get eligible tenants from a dispatch shard (Level 1). | ||
| * Returns tenants ordered by oldest message (lowest score first). | ||
| */ | ||
| async getTenantsFromShard( | ||
| shardId: number, | ||
| limit: number = 1000, | ||
| maxScore?: number | ||
| ): Promise<TenantWithScore[]> { | ||
| const dispatchKey = this.keys.dispatchKey(shardId); | ||
| const score = maxScore ?? Date.now(); | ||
|
|
||
| const results = await this.redis.zrangebyscore( | ||
| dispatchKey, | ||
| "-inf", | ||
| score, | ||
| "WITHSCORES", | ||
| "LIMIT", | ||
| 0, | ||
| limit | ||
| ); | ||
|
|
||
| const tenants: TenantWithScore[] = []; | ||
| for (let i = 0; i < results.length; i += 2) { | ||
| const tenantId = results[i]; | ||
| const scoreStr = results[i + 1]; | ||
| if (tenantId && scoreStr) { | ||
| tenants.push({ | ||
| tenantId, | ||
| score: parseFloat(scoreStr), | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return tenants; | ||
| } | ||
|
|
||
| /** | ||
| * Get queues for a specific tenant (Level 2). | ||
| * Returns queues ordered by oldest message (lowest score first). | ||
| */ | ||
| async getQueuesForTenant( | ||
| tenantId: string, | ||
| limit: number = 1000, | ||
| maxScore?: number | ||
| ): Promise<QueueWithScore[]> { | ||
| const tenantQueueKey = this.keys.tenantQueueIndexKey(tenantId); | ||
| const score = maxScore ?? Date.now(); | ||
|
|
||
| const results = await this.redis.zrangebyscore( | ||
| tenantQueueKey, | ||
| "-inf", | ||
| score, | ||
| "WITHSCORES", | ||
| "LIMIT", | ||
| 0, | ||
| limit | ||
| ); | ||
|
|
||
| const queues: QueueWithScore[] = []; | ||
| for (let i = 0; i < results.length; i += 2) { | ||
| const queueId = results[i]; | ||
| const scoreStr = results[i + 1]; | ||
| if (queueId && scoreStr) { | ||
| queues.push({ | ||
| queueId, | ||
| score: parseFloat(scoreStr), | ||
| tenantId, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return queues; | ||
| } | ||
|
|
||
| /** | ||
| * Get the number of tenants in a dispatch shard. | ||
| */ | ||
| async getShardTenantCount(shardId: number): Promise<number> { | ||
| const dispatchKey = this.keys.dispatchKey(shardId); | ||
| return await this.redis.zcard(dispatchKey); | ||
| } | ||
|
|
||
| /** | ||
| * Get total tenant count across all dispatch shards. | ||
| * Note: tenants may appear in multiple shards, so this may overcount. | ||
| */ | ||
| async getTotalTenantCount(): Promise<number> { | ||
| const counts = await Promise.all( | ||
| Array.from({ length: this.shardCount }, (_, i) => this.getShardTenantCount(i)) | ||
| ); | ||
| return counts.reduce((sum, count) => sum + count, 0); | ||
| } | ||
ericallam marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Get the number of queues for a tenant. | ||
| */ | ||
| async getTenantQueueCount(tenantId: string): Promise<number> { | ||
| const tenantQueueKey = this.keys.tenantQueueIndexKey(tenantId); | ||
| return await this.redis.zcard(tenantQueueKey); | ||
| } | ||
|
|
||
| /** | ||
| * Remove a tenant from a specific dispatch shard. | ||
| */ | ||
| async removeTenantFromShard(shardId: number, tenantId: string): Promise<void> { | ||
| const dispatchKey = this.keys.dispatchKey(shardId); | ||
| await this.redis.zrem(dispatchKey, tenantId); | ||
| } | ||
|
|
||
| /** | ||
| * Add a tenant to a dispatch shard with the given score. | ||
| */ | ||
| async addTenantToShard(shardId: number, tenantId: string, score: number): Promise<void> { | ||
| const dispatchKey = this.keys.dispatchKey(shardId); | ||
| await this.redis.zadd(dispatchKey, score, tenantId); | ||
| } | ||
|
|
||
| /** | ||
| * Remove a queue from a tenant's queue index. | ||
| */ | ||
| async removeQueueFromTenant(tenantId: string, queueId: string): Promise<void> { | ||
| const tenantQueueKey = this.keys.tenantQueueIndexKey(tenantId); | ||
| await this.redis.zrem(tenantQueueKey, queueId); | ||
| } | ||
|
|
||
| /** | ||
| * Close the Redis connection. | ||
| */ | ||
| async close(): Promise<void> { | ||
| await this.redis.quit(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.