Skip to content

The open alternative to Salesforce, designed for AI.

Replace per-queue job priorities with a shared default (#28924)

martmull3a9965452558
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/constants/default-job-priority.constant.ts b/packages/twenty-server/src/engine/core-modules/message-queue/constants/default-job-priority.constant.ts
new file mode 100644
index 00000000000..f92a8429bb3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/constants/default-job-priority.constant.ts
@@ -0,0 +1 @@
+export const DEFAULT_JOB_PRIORITY = 5;
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/__tests__/bullmq.driver.spec.ts b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/__tests__/bullmq.driver.spec.ts
index e4730d53597..9c0a6bca4dc 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/__tests__/bullmq.driver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/__tests__/bullmq.driver.spec.ts
@@ -1,5 +1,6 @@
import { type Job, Worker } from 'bullmq';
+import { DEFAULT_JOB_PRIORITY } from 'src/engine/core-modules/message-queue/constants/default-job-priority.constant';
import { QUEUE_JOB_CHANGED_EVENT } from 'src/engine/core-modules/message-queue/constants/queue-job-changed-event.constant';
import { BullMQDriver } from 'src/engine/core-modules/message-queue/drivers/bullmq.driver';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
@@ -55,6 +56,32 @@ describe('BullMQDriver deduplication', () => {
);
});
+ describe.each([undefined, 0, 2])('job priority %s', (priority) => {
+ it('uses the caller priority or the shared default to add', async () => {
+ await driver.add(MessageQueue.workspaceQueue, 'job', {}, { priority });
+
+ expect(mockAdd).toHaveBeenCalledWith(
+ 'job',
+ {},
+ expect.objectContaining({ priority: priority ?? DEFAULT_JOB_PRIORITY }),
+ );
+ });
+
+ it('uses the caller priority or the shared default to bulkAdd', async () => {
+ await driver.bulkAdd(MessageQueue.workspaceQueue, 'job', [{ data: {} }], {
+ priority,
+ });
+
+ expect(mockAddBulk).toHaveBeenCalledWith([
+ expect.objectContaining({
+ opts: expect.objectContaining({
+ priority: priority ?? DEFAULT_JOB_PRIORITY,
+ }),
+ }),
+ ]);
+ });
+ });
+
describe('add', () => {
it('skips a job whose id prefix is already waiting', async () => {
const jobId = await driver.add(
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
index d737c631708..11e43dc6260 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/drivers/bullmq.driver.ts
@@ -36,9 +36,9 @@ import {
} from 'src/engine/core-modules/message-queue/interfaces/message-queue-job.interface';
import { type MessageQueueWorkerOptions } from 'src/engine/core-modules/message-queue/interfaces/message-queue-worker-options.interface';
+import { DEFAULT_JOB_PRIORITY } from 'src/engine/core-modules/message-queue/constants/default-job-priority.constant';
import { QUEUE_JOB_CHANGED_EVENT } from 'src/engine/core-modules/message-queue/constants/queue-job-changed-event.constant';
import { QUEUE_RETENTION } from 'src/engine/core-modules/message-queue/constants/queue-retention.constants';
-import { MESSAGE_QUEUE_WORKER_CONFIG } from 'src/engine/core-modules/message-queue/message-queue-worker-config.constant';
import { type MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { type QueueJobChangedEvent } from 'src/engine/core-modules/message-queue/types/queue-job-changed-event.type';
import { getJobKey } from 'src/engine/core-modules/message-queue/utils/get-job-key.util';
@@ -457,19 +457,12 @@ export class BullMQDriver
return broadcastTo;
}
- private buildJobsOptions({
- queueName,
- options,
- }: {
- queueName: MessageQueue;
- options?: QueueJobOptions;
- }): BullMQJobsOptions {
+ private buildJobsOptions(options?: QueueJobOptions): BullMQJobsOptions {
return {
jobId: options?.id
? buildQueueJobIdWithSuffix({ jobIdPrefix: options.id, suffix: v4() })
: undefined,
- priority:
- options?.priority ?? MESSAGE_QUEUE_WORKER_CONFIG[queueName].priority,
+ priority: options?.priority ?? DEFAULT_JOB_PRIORITY,
attempts: 1 + (options?.retryLimit || 0),
backoff: options?.backoff
? {
@@ -514,7 +507,7 @@ export class BullMQDriver
}
}
- const queueOptions = this.buildJobsOptions({ queueName, options });
+ const queueOptions = this.buildJobsOptions(options);
const job = await this.queueMap[queueName].add(jobName, data, queueOptions);
@@ -566,7 +559,7 @@ export class BullMQDriver
return [];
}
- const queueOptions = this.buildJobsOptions({ queueName, options });
+ const queueOptions = this.buildJobsOptions(options);
const addedJobs = await this.queueMap[queueName].addBulk(
jobsToAdd.map(({ data, jobId }, index) => ({
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts
index b8e50c726ed..c07edfb5ecd 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/message-queue-worker-config.constant.ts
@@ -6,7 +6,6 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
// its full configuration is a compile error, and no queue silently relies on
// implicit BullMQ defaults.
//
-// priority: applied when enqueuing, lower value is processed first
// concurrency: max jobs processed in parallel per worker process
// globalConcurrency: optional, max jobs processed in parallel across all
// worker processes
@@ -17,7 +16,6 @@ import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queu
// AI_STREAM_SHUTDOWN_DRAIN_MS instead of waiting for them to finish
export type MessageQueueWorkerConfig = {
- priority: number;
workerOptions: Required<
Omit<MessageQueueWorkerOptions, 'globalConcurrency' | 'rateLimit'>
> &
@@ -29,7 +27,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
MessageQueueWorkerConfig
> = {
[MessageQueue.recordExportQueue]: {
- priority: 7,
workerOptions: {
concurrency: 1,
globalConcurrency: 2,
@@ -39,7 +36,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.workspaceDataExportQueue]: {
- priority: 7,
workerOptions: {
concurrency: 1,
globalConcurrency: 1,
@@ -49,7 +45,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.taskAssignedQueue]: {
- priority: 4,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -58,7 +53,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.messagingQueue]: {
- priority: 2,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -67,7 +61,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.webhookQueue]: {
- priority: 2,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -76,7 +69,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.cronQueue]: {
- priority: 7,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -85,7 +77,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.emailQueue]: {
- priority: 1,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -94,7 +85,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.campaignQueue]: {
- priority: 6,
workerOptions: {
concurrency: 10,
lockDuration: 30_000,
@@ -103,7 +93,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.campaignSendQueue]: {
- priority: 6,
workerOptions: {
concurrency: 10,
lockDuration: 30_000,
@@ -112,7 +101,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.campaignEngagementQueue]: {
- priority: 8,
workerOptions: {
concurrency: 50,
lockDuration: 30_000,
@@ -121,7 +109,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.calendarQueue]: {
- priority: 4,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -130,7 +117,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.connectedAccountSyncWebhookQueue]: {
- priority: 1,
workerOptions: {
concurrency: 5,
lockDuration: 30_000,
@@ -139,7 +125,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.contactCreationQueue]: {
- priority: 4,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -148,7 +133,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.billingQueue]: {
- priority: 1,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -157,7 +141,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.workspaceQueue]: {
- priority: 5,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -166,7 +149,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.workspaceDestroyQueue]: {
- priority: 5,
workerOptions: {
concurrency: 1,
globalConcurrency: 1,
@@ -176,7 +158,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.entityEventsToDbQueue]: {
- priority: 1,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -185,7 +166,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.eventLogQueue]: {
- priority: 1,
workerOptions: {
concurrency: 3,
lockDuration: 30_000,
@@ -194,7 +174,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.workflowQueue]: {
- priority: 2,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -203,7 +182,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.delayedJobsQueue]: {
- priority: 3,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -212,7 +190,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.deleteCascadeQueue]: {
- priority: 6,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -221,7 +198,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.logicFunctionQueue]: {
- priority: 4,
workerOptions: {
concurrency: 20,
lockDuration: 30_000,
@@ -230,7 +206,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.lambdaManagementQueue]: {
- priority: 6,
workerOptions: {
concurrency: 2,
rateLimit: { max: 2, durationMs: 1_000 },
@@ -240,7 +215,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.applicationLifecycleHookQueue]: {
- priority: 4,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -249,7 +223,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.applicationUpgradeQueue]: {
- priority: 6,
workerOptions: {
concurrency: 2,
lockDuration: 60_000,
@@ -258,7 +231,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.triggerQueue]: {
- priority: 5,
workerOptions: {
concurrency: 1,
lockDuration: 30_000,
@@ -267,7 +239,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.aiQueue]: {
- priority: 5,
workerOptions: {
// agent runs wait on the model and their tools most of the time, so several share a worker
concurrency: 10,
@@ -277,7 +248,6 @@ export const MESSAGE_QUEUE_WORKER_CONFIG: Record<
},
},
[MessageQueue.aiStreamQueue]: {
- priority: 2,
workerOptions: {
concurrency: 20,
// 10 minutes: a stream job holds its lock for the whole stream duration
diff --git a/packages/twenty-server/test/integration/message-queue/bullmq-queue-order.integration-spec.ts b/packages/twenty-server/test/integration/message-queue/bullmq-queue-order.integration-spec.ts
new file mode 100644
index 00000000000..cc49fab5c86
--- /dev/null
+++ b/packages/twenty-server/test/integration/message-queue/bullmq-queue-order.integration-spec.ts
@@ -0,0 +1,109 @@
+import { MESSAGE_QUEUE_WORKER_CONFIG } from 'src/engine/core-modules/message-queue/message-queue-worker-config.constant';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+
+import { createQueueOrderSignal } from 'test/integration/message-queue/utils/create-queue-order-signal.util';
+import { withQueueOrderTestContext } from 'test/integration/message-queue/utils/with-queue-order-test-context.util';
+
+const queue1 = MessageQueue.workflowQueue;
+const queue2 = MessageQueue.delayedJobsQueue;
+
+describe('BullMQDriver queue ordering (integration)', () => {
+ it('preserves FIFO within a queue while another queue progresses independently', async () => {
+ const jobs = [
+ { queue: queue1, name: 'job-queue1-1', priority: 1 },
+ { queue: queue2, name: 'job-queue2-1', priority: 0 },
+ { queue: queue1, name: 'job-queue1-2', priority: 1 },
+ { queue: queue1, name: 'job-queue1-3', priority: 1 },
+ ];
+ const expectedOrder = [
+ 'job-queue1-1',
+ 'job-queue2-1',
+ 'job-queue1-2',
+ 'job-queue1-3',
+ ];
+ const actualOrder: string[] = [];
+ const firstStarted = createQueueOrderSignal();
+ const releaseFirst = createQueueOrderSignal();
+ const queue2Started = createQueueOrderSignal();
+ const queue1Done = createQueueOrderSignal();
+
+ await withQueueOrderTestContext(async (driver) => {
+ for (const job of jobs) {
+ await driver.add(job.queue, job.name, {}, { priority: job.priority });
+ }
+
+ try {
+ driver.work(
+ queue1,
+ async (job) => {
+ actualOrder.push(job.name);
+ if (job.name === 'job-queue1-1') {
+ firstStarted.resolve();
+ await releaseFirst.promise;
+ }
+ if (job.name === 'job-queue1-3') {
+ queue1Done.resolve();
+ }
+ },
+ MESSAGE_QUEUE_WORKER_CONFIG[queue1].workerOptions,
+ );
+
+ await firstStarted.promise;
+ driver.work(
+ queue2,
+ async (job) => {
+ actualOrder.push(job.name);
+ queue2Started.resolve();
+ },
+ MESSAGE_QUEUE_WORKER_CONFIG[queue2].workerOptions,
+ );
+
+ await queue2Started.promise;
+ expect(actualOrder).toEqual(expectedOrder.slice(0, 2));
+ releaseFirst.resolve();
+ await queue1Done.promise;
+ expect(actualOrder).toEqual(expectedOrder);
+ } finally {
+ releaseFirst.resolve();
+ }
+ });
+ });
+
+ it('orders jobs by priority within one queue and uses FIFO for equal default priorities', async () => {
+ const jobs = [
+ { name: 'application-job', priority: 10 },
+ { name: 'ordinary-job-1', priority: undefined },
+ { name: 'urgent-job', priority: 1 },
+ { name: 'ordinary-job-2', priority: undefined },
+ { name: 'zero-priority-job', priority: 0 },
+ ];
+ const expectedOrder = [
+ 'zero-priority-job',
+ 'urgent-job',
+ 'ordinary-job-1',
+ 'ordinary-job-2',
+ 'application-job',
+ ];
+ const actualOrder: string[] = [];
+ const done = createQueueOrderSignal();
+
+ await withQueueOrderTestContext(async (driver) => {
+ for (const job of jobs) {
+ await driver.add(queue1, job.name, {}, { priority: job.priority });
+ }
+ driver.work(
+ queue1,
+ async (job) => {
+ actualOrder.push(job.name);
+ if (actualOrder.length === jobs.length) {
+ done.resolve();
+ }
+ },
+ MESSAGE_QUEUE_WORKER_CONFIG[queue1].workerOptions,
+ );
+
+ await done.promise;
+ expect(actualOrder).toEqual(expectedOrder);
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/message-queue/utils/create-queue-order-signal.util.ts b/packages/twenty-server/test/integration/message-queue/utils/create-queue-order-signal.util.ts
new file mode 100644
index 00000000000..d7809d337e3
--- /dev/null
+++ b/packages/twenty-server/test/integration/message-queue/utils/create-queue-order-signal.util.ts
@@ -0,0 +1,8 @@
+export const createQueueOrderSignal = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+
+ return { promise, resolve };
+};
diff --git a/packages/twenty-server/test/integration/message-queue/utils/with-queue-order-test-context.util.ts b/packages/twenty-server/test/integration/message-queue/utils/with-queue-order-test-context.util.ts
new file mode 100644
index 00000000000..35ca123a0e7
--- /dev/null
+++ b/packages/twenty-server/test/integration/message-queue/utils/with-queue-order-test-context.util.ts
@@ -0,0 +1,61 @@
+import { EventEmitter2 } from '@nestjs/event-emitter';
+import { Test } from '@nestjs/testing';
+import { Queue } from 'bullmq';
+import IORedis from 'ioredis';
+import { v4 as generateUuid } from 'uuid';
+
+import { BullMQDriver } from 'src/engine/core-modules/message-queue/drivers/bullmq.driver';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+export const withQueueOrderTestContext = async (
+ run: (driver: BullMQDriver) => Promise<void>,
+) => {
+ const connection = new IORedis(
+ process.env.REDIS_QUEUE_URL ??
+ process.env.REDIS_URL ??
+ 'redis://localhost:6379',
+ { maxRetriesPerRequest: null },
+ );
+ const options = { connection, prefix: `queue-order-${generateUuid()}` };
+ const queues = [MessageQueue.workflowQueue, MessageQueue.delayedJobsQueue];
+ const inspectionQueues = queues.map((name) => new Queue(name, options));
+ const module = await Test.createTestingModule({
+ providers: [
+ {
+ provide: MetricsService,
+ useValue: {
+ recordHistogram: jest.fn(),
+ incrementCounterForEvent: jest.fn(),
+ },
+ },
+ { provide: TwentyConfigService, useValue: {} },
+ { provide: EventEmitter2, useValue: new EventEmitter2() },
+ {
+ provide: BullMQDriver,
+ useFactory: (
+ metrics: MetricsService,
+ config: TwentyConfigService,
+ events: EventEmitter2,
+ ) => new BullMQDriver(options, metrics, config, events),
+ inject: [MetricsService, TwentyConfigService, EventEmitter2],
+ },
+ ],
+ }).compile();
+ const driver = module.get(BullMQDriver);
+
+ queues.forEach((queue) => driver.register(queue));
+
+ try {
+ await run(driver);
+ } finally {
+ await driver.onModuleDestroy();
+ for (const queue of inspectionQueues) {
+ await queue.obliterate({ force: true });
+ await queue.close();
+ }
+ await connection.quit();
+ await module.close();
+ }
+};