Skip to content

The open alternative to Salesforce, designed for AI.

feat(usage-limit) - quota engine (#25278)

Etienneb4ab19b6dcb1
diff --git a/packages/twenty-server/src/database/clickhouse/clickhouse.exception.ts b/packages/twenty-server/src/database/clickhouse/clickhouse.exception.ts
new file mode 100644
index 00000000000..3ee408f7b18
--- /dev/null
+++ b/packages/twenty-server/src/database/clickhouse/clickhouse.exception.ts
@@ -0,0 +1,15 @@
+import { msg } from '@lingui/core/macro';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+export enum ClickHouseExceptionCode {
+ CLIENT_NOT_AVAILABLE = 'CLIENT_NOT_AVAILABLE',
+}
+
+export class ClickHouseException extends CustomException<ClickHouseExceptionCode> {
+ constructor(message: string, code: ClickHouseExceptionCode) {
+ super(message, code, {
+ userFriendlyMessage: msg`An unexpected error occurred.`,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/database/clickhouse/clickhouse.service.ts b/packages/twenty-server/src/database/clickhouse/clickhouse.service.ts
index 839603f3a7e..0944983a947 100644
--- a/packages/twenty-server/src/database/clickhouse/clickhouse.service.ts
+++ b/packages/twenty-server/src/database/clickhouse/clickhouse.service.ts
@@ -11,6 +11,10 @@ import {
createClient,
} from '@clickhouse/client';
+import {
+ ClickHouseException,
+ ClickHouseExceptionCode,
+} from 'src/database/clickhouse/clickhouse.exception';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
export type ClickHouseInsertOptions = {
@@ -206,6 +210,29 @@ export class ClickHouseService implements OnModuleInit, OnModuleDestroy {
}
}
+ public async selectOrThrow<T>(
+ query: string,
+ // oxlint-disable-next-line typescript/no-explicit-any
+ params?: Record<string, any>,
+ ): Promise<T[]> {
+ if (!this.mainClient) {
+ throw new ClickHouseException(
+ 'ClickHouse client is not available',
+ ClickHouseExceptionCode.CLIENT_NOT_AVAILABLE,
+ );
+ }
+
+ const resultSet = await this.mainClient.query({
+ query,
+ format: 'JSONEachRow',
+ query_params: params,
+ });
+
+ const result = await resultSet.json<T>();
+
+ return Array.isArray(result) ? result : [];
+ }
+
public async createDatabase(databaseName: string): Promise<boolean> {
try {
if (!this.mainClient) {
diff --git a/packages/twenty-server/src/database/clickhouse/migrations/008-add-consumption-by-scope-daily-projection.sql b/packages/twenty-server/src/database/clickhouse/migrations/008-add-consumption-by-scope-daily-projection.sql
new file mode 100644
index 00000000000..b4c704d7982
--- /dev/null
+++ b/packages/twenty-server/src/database/clickhouse/migrations/008-add-consumption-by-scope-daily-projection.sql
@@ -0,0 +1,19 @@
+ALTER TABLE usageEvent DROP PROJECTION IF EXISTS consumption_by_scope;
+
+ALTER TABLE usageEvent ADD PROJECTION IF NOT EXISTS consumption_by_scope (
+ SELECT
+ workspaceId,
+ resourceType,
+ toStartOfDay(timestamp, 'UTC'),
+ operationType,
+ userWorkspaceId,
+ apiKeyId,
+ applicationId,
+ agentId,
+ workflowId,
+ logicFunctionId,
+ sum(creditsUsedMicro) AS creditsUsedMicro,
+ sum(quantity) AS quantity
+ GROUP BY
+ workspaceId, resourceType, toStartOfDay(timestamp, 'UTC'), operationType, userWorkspaceId, apiKeyId, applicationId, agentId, workflowId, logicFunctionId
+);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/constants/consume-quota-counters-script.constant.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/consume-quota-counters-script.constant.ts
new file mode 100644
index 00000000000..3386cb839ac
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/constants/consume-quota-counters-script.constant.ts
@@ -0,0 +1,21 @@
+import { type CacheScript } from 'src/engine/core-modules/cache-storage/types/cache-script.type';
+
+export const CONSUME_QUOTA_COUNTERS_SCRIPT: CacheScript = {
+ name: 'usage-limit:consume-quota-counters',
+ source: `
+local costs = cjson.decode(ARGV[1])
+local result = {}
+
+for i = 1, #KEYS do
+ if redis.call('EXISTS', KEYS[i]) == 1 then
+ result[2 * i - 1] = 1
+ result[2 * i] = redis.call('DECRBY', KEYS[i], costs[i])
+ else
+ result[2 * i - 1] = 0
+ result[2 * i] = 0
+ end
+end
+
+return result
+`,
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
new file mode 100644
index 00000000000..3d5af75882f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service.ts
@@ -0,0 +1,15 @@
+import { Injectable } from '@nestjs/common';
+
+import { type CreditAllowance } from 'src/engine/core-modules/usage-limit/types/credit-allowance.type';
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+
+@Injectable()
+export abstract class CreditAllowanceProvider {
+ abstract getCreditAllowancePeriod(
+ workspaceId: string,
+ ): Promise<UsagePeriod | null>;
+
+ abstract getCreditAllowance(
+ workspaceId: string,
+ ): Promise<CreditAllowance | null>;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
new file mode 100644
index 00000000000..270df7178a9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/__tests__/usage-limit-quota.service.spec.ts
@@ -0,0 +1,423 @@
+import { DiscoveryService } from '@nestjs/core';
+import { Test, type TestingModule } from '@nestjs/testing';
+
+import { ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import {
+ CacheLockException,
+ CacheLockExceptionCode,
+} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';
+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type UsageLimitCounterScope } from 'src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type';
+import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
+import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
+import { buildQuotaWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const MONTH_PERIOD = {
+ periodStart: new Date('2026-08-01T00:00:00.000Z'),
+ periodEnd: new Date('2100-09-01T00:00:00.000Z'),
+};
+
+const WEEK_PERIOD = {
+ periodStart: new Date('2026-08-24T00:00:00.000Z'),
+ periodEnd: new Date('2100-08-31T00:00:00.000Z'),
+};
+
+const ALLOWANCE_PERIOD = {
+ periodStart: new Date('2026-08-15T09:00:00.000Z'),
+ periodEnd: new Date('2100-09-15T09:00:00.000Z'),
+};
+
+class TestCreditAllowanceProvider extends CreditAllowanceProvider {
+ getCreditAllowancePeriod = jest.fn().mockResolvedValue(null);
+ getCreditAllowance = jest.fn().mockResolvedValue(null);
+}
+
+const buildLimitCounterScope = (
+ overrides: Partial<UsageLimitCounterScope> = {},
+): UsageLimitCounterScope => ({
+ workspaceId: 'workspace-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: '',
+ limitKind: 'quota',
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ ...overrides,
+});
+
+const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+ id: 'limit-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: '',
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ limitValue: 1_000,
+ burstValue: null,
+ ...overrides,
+});
+
+describe('UsageLimitQuotaService', () => {
+ let service: UsageLimitQuotaService;
+ let creditAllowanceProvider: TestCreditAllowanceProvider;
+
+ const cacheStorage = {
+ mget: jest.fn().mockResolvedValue([]),
+ mset: jest.fn().mockResolvedValue(undefined),
+ runScript: jest.fn().mockResolvedValue([]),
+ del: jest.fn().mockResolvedValue(undefined),
+ };
+
+ const workspaceCacheService = {
+ getOrRecompute: jest
+ .fn()
+ .mockResolvedValue({ usageLimits: { byResourceType: {} } }),
+ };
+
+ const cacheLockService = {
+ withLock: jest.fn((fn: () => Promise<unknown>) => fn()),
+ };
+
+ const clickHouseService = {
+ selectOrThrow: jest.fn().mockResolvedValue([]),
+ };
+
+ const usagePeriodService = {
+ getCurrentPeriod: jest.fn(),
+ };
+
+ const setLimits = (limits: FlatUsageLimit[]) => {
+ workspaceCacheService.getOrRecompute.mockResolvedValue({
+ usageLimits: {
+ byResourceType: { [UsageResourceType.AI]: limits },
+ },
+ });
+ };
+
+ const setAllowance = (allowanceMicro: number | null) => {
+ creditAllowanceProvider.getCreditAllowancePeriod.mockResolvedValue(
+ ALLOWANCE_PERIOD,
+ );
+ creditAllowanceProvider.getCreditAllowance.mockResolvedValue(
+ allowanceMicro === null ? null : { ...ALLOWANCE_PERIOD, allowanceMicro },
+ );
+ };
+
+ const assertQuotaNotExhausted = () =>
+ service.assertQuotaNotExhausted({
+ workspaceId: 'workspace-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenders: { userWorkspaceId: 'user-1' },
+ });
+
+ const consumeQuota = (creditsUsedMicro: number, quantity = 0) =>
+ service.consumeQuota({
+ workspaceId: 'workspace-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenders: { userWorkspaceId: 'user-1' },
+ cost: { creditsUsedMicro, quantity },
+ });
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ creditAllowanceProvider = new TestCreditAllowanceProvider();
+ cacheStorage.mget.mockResolvedValue([]);
+ cacheStorage.runScript.mockResolvedValue([]);
+ clickHouseService.selectOrThrow.mockResolvedValue([]);
+ usagePeriodService.getCurrentPeriod.mockImplementation(
+ (periodUnit: string) =>
+ periodUnit === 'week' ? WEEK_PERIOD : MONTH_PERIOD,
+ );
+ workspaceCacheService.getOrRecompute.mockResolvedValue({
+ usageLimits: { byResourceType: {} },
+ });
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ UsageLimitQuotaService,
+ {
+ provide: CacheStorageNamespace.EngineUsageLimit,
+ useValue: cacheStorage,
+ },
+ { provide: WorkspaceCacheService, useValue: workspaceCacheService },
+ { provide: CacheLockService, useValue: cacheLockService },
+ { provide: ClickHouseService, useValue: clickHouseService },
+ { provide: UsagePeriodService, useValue: usagePeriodService },
+ {
+ provide: DiscoveryService,
+ useValue: {
+ getProviders: () => [{ instance: creditAllowanceProvider }],
+ },
+ },
+ ],
+ }).compile();
+
+ service = module.get<UsageLimitQuotaService>(UsageLimitQuotaService);
+ service.onModuleInit();
+ });
+
+ it('admits on a warm counter with budget left', async () => {
+ setLimits([buildLimit({})]);
+ cacheStorage.mget.mockResolvedValue([250]);
+
+ await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
+ expect(clickHouseService.selectOrThrow).not.toHaveBeenCalled();
+ });
+
+ it('denies on an exhausted warm counter', async () => {
+ setLimits([buildLimit({})]);
+ cacheStorage.mget.mockResolvedValue([0]);
+
+ await expect(assertQuotaNotExhausted()).rejects.toMatchObject({
+ code: UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ exhaustedScope: expect.objectContaining({
+ spenderType: 'workspace',
+ limitKind: 'quota',
+ exhaustedKind: 'limit',
+ }),
+ });
+ });
+
+ it('warms limit counters over UTC day buckets', async () => {
+ setLimits([buildLimit({})]);
+ cacheStorage.mget.mockResolvedValue([undefined]);
+
+ await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
+ expect(clickHouseService.selectOrThrow).toHaveBeenCalledWith(
+ expect.stringContaining(
+ "toStartOfDay(timestamp, 'UTC') >= {periodStart:DateTime64(3)}",
+ ),
+ expect.anything(),
+ );
+ });
+
+ it('runs one warm query per distinct period', async () => {
+ setLimits([
+ buildLimit({ id: 'monthly' }),
+ buildLimit({ id: 'weekly', periodUnit: 'week' }),
+ ]);
+ cacheStorage.mget.mockResolvedValue([undefined, undefined]);
+
+ await assertQuotaNotExhausted();
+
+ expect(clickHouseService.selectOrThrow).toHaveBeenCalledTimes(2);
+ });
+
+ it('warms a cold allowance counter from the live allowance minus the stamped consumption', async () => {
+ setAllowance(100);
+ cacheStorage.mget.mockResolvedValue([undefined]);
+ clickHouseService.selectOrThrow.mockResolvedValue([{ total: '150' }]);
+
+ await expect(assertQuotaNotExhausted()).rejects.toThrow(
+ UsageLimitException,
+ );
+ expect(clickHouseService.selectOrThrow).toHaveBeenCalledWith(
+ expect.stringContaining('periodStart = {periodStart:DateTime64(3)}'),
+ expect.anything(),
+ );
+ expect(cacheStorage.mset).toHaveBeenCalledWith([
+ expect.objectContaining({ value: -50 }),
+ ]);
+ });
+
+ it('scopes a spent allowance counter over the live allowance', async () => {
+ setAllowance(2_000_000);
+ cacheStorage.mget.mockResolvedValue([0]);
+
+ await expect(assertQuotaNotExhausted()).rejects.toMatchObject({
+ exhaustedScope: expect.objectContaining({
+ exhaustedKind: 'allowance',
+ limitValue: 2_000_000,
+ }),
+ });
+ });
+
+ it('reports an exhausted limit over the exhausted allowance', async () => {
+ setLimits([buildLimit({})]);
+ setAllowance(2_000_000);
+ cacheStorage.mget.mockResolvedValue([0, 0]);
+
+ await expect(assertQuotaNotExhausted()).rejects.toMatchObject({
+ exhaustedScope: expect.objectContaining({ exhaustedKind: 'limit' }),
+ });
+ });
+
+ it('skips warming an allowance whose period rolled over since the read', async () => {
+ creditAllowanceProvider.getCreditAllowancePeriod.mockResolvedValue(
+ ALLOWANCE_PERIOD,
+ );
+ creditAllowanceProvider.getCreditAllowance.mockResolvedValue({
+ allowanceMicro: 100,
+ periodStart: new Date('2026-09-15T09:00:00.000Z'),
+ periodEnd: new Date('2100-10-15T09:00:00.000Z'),
+ });
+ cacheStorage.mget.mockResolvedValue([undefined]);
+
+ await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
+ expect(cacheStorage.mset).toHaveBeenCalledWith([]);
+ });
+
+ it('admits when the counters cannot be read', async () => {
+ setLimits([buildLimit({})]);
+ cacheStorage.mget.mockRejectedValue(new Error('Socket closed'));
+
+ await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
+ });
+
+ it('admits when the warm query fails instead of granting a fresh budget', async () => {
+ setLimits([buildLimit({})]);
+ cacheStorage.mget.mockResolvedValue([undefined]);
+ clickHouseService.selectOrThrow.mockRejectedValue(
+ new Error('clickhouse unreachable'),
+ );
+
+ await expect(assertQuotaNotExhausted()).resolves.toBeUndefined();
+ expect(cacheStorage.mset).not.toHaveBeenCalled();
+ });
+
+ it('debits each counter in its own meter on consume', async () => {
+ setLimits([
+ buildLimit({ id: 'credits' }),
+ buildLimit({ id: 'tokens', meter: 'quantity' }),
+ ]);
+ cacheStorage.runScript.mockResolvedValue([1, 500, 1, 900]);
+
+ const { exhausted } = await consumeQuota(50, 7);
+
+ expect(cacheStorage.runScript).toHaveBeenCalledWith(
+ expect.objectContaining({ args: ['[50,7]'] }),
+ );
+ expect(exhausted).toBeNull();
+ });
+
+ it('debits the allowance counter with the credit cost on consume', async () => {
+ setLimits([buildLimit({ meter: 'quantity' })]);
+ setAllowance(2_000_000);
+ cacheStorage.runScript.mockResolvedValue([1, 500, 1, -5]);
+
+ const { exhausted } = await consumeQuota(50, 7);
+
+ expect(cacheStorage.runScript).toHaveBeenCalledWith(
+ expect.objectContaining({ args: ['[7,50]'] }),
+ );
+ expect(exhausted).toMatchObject({ exhaustedKind: 'allowance' });
+ });
+
+ it('warms a cold counter before consuming it', async () => {
+ setLimits([buildLimit({})]);
+ cacheStorage.mget.mockResolvedValue([undefined]);
+ cacheStorage.runScript.mockResolvedValue([1, 950]);
+
+ const { exhausted } = await consumeQuota(50);
+
+ expect(cacheStorage.mset).toHaveBeenCalledWith([
+ expect.objectContaining({ value: 1_000 }),
+ ]);
+ expect(cacheStorage.runScript).toHaveBeenCalledWith(
+ expect.objectContaining({ args: ['[50]'] }),
+ );
+ expect(exhausted).toBeNull();
+ });
+
+ describe('dropAllowanceCounter', () => {
+ it('drops the counter keyed by the current period', async () => {
+ setAllowance(2_000_000);
+
+ await service.dropAllowanceCounter('workspace-1');
+
+ expect(cacheStorage.del).toHaveBeenCalledWith(
+ buildAllowanceCounterKey({
+ workspaceId: 'workspace-1',
+ periodStart: ALLOWANCE_PERIOD.periodStart,
+ }),
+ );
+ });
+
+ it('does nothing when no allowance exists', async () => {
+ await service.dropAllowanceCounter('workspace-1');
+
+ expect(cacheStorage.del).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('dropLimitCounter', () => {
+ it('drops the counter keyed by the current period under the warm lock', async () => {
+ await service.dropLimitCounter(buildLimitCounterScope());
+
+ expect(cacheLockService.withLock).toHaveBeenCalledWith(
+ expect.any(Function),
+ buildQuotaWarmLockKey('workspace-1'),
+ expect.anything(),
+ );
+ expect(cacheStorage.del).toHaveBeenCalledWith(
+ buildQuotaCounterKey({
+ workspaceId: 'workspace-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: '',
+ meter: 'creditsUsedMicro',
+ periodUnit: 'month',
+ periodStart: MONTH_PERIOD.periodStart,
+ }),
+ );
+ });
+
+ it('ignores a speed limit', async () => {
+ await service.dropLimitCounter(
+ buildLimitCounterScope({ limitKind: 'speed', periodUnit: 'second' }),
+ );
+
+ expect(cacheStorage.del).not.toHaveBeenCalled();
+ });
+
+ it('dels without the lock when acquiring it times out', async () => {
+ cacheLockService.withLock.mockRejectedValueOnce(
+ new CacheLockException(
+ 'timed out',
+ CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT,
+ ),
+ );
+
+ await service.dropLimitCounter(buildLimitCounterScope());
+
+ expect(cacheStorage.del).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('getAllowanceRemainingMicro', () => {
+ it('reads the warm allowance counter', async () => {
+ setAllowance(2_000_000);
+ cacheStorage.mget.mockResolvedValue([1_500]);
+
+ await expect(
+ service.getAllowanceRemainingMicro('workspace-1'),
+ ).resolves.toBe(1_500);
+ });
+
+ it('answers null when no allowance exists', async () => {
+ await expect(
+ service.getAllowanceRemainingMicro('workspace-1'),
+ ).resolves.toBeNull();
+ expect(cacheStorage.mget).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
new file mode 100644
index 00000000000..38c153caaff
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit-quota.service.ts
@@ -0,0 +1,655 @@
+import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';
+import { DiscoveryService } from '@nestjs/core';
+
+import { msg } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ClickHouseService } from 'src/database/clickhouse/clickhouse.service';
+import { formatDateTimeForClickHouse } from 'src/database/clickhouse/utils/format-date-time-for-clickhouse.util';
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import {
+ CacheLockException,
+ CacheLockExceptionCode,
+} from 'src/engine/core-modules/cache-lock/exceptions/cache-lock.exception';
+import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
+import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { CONSUME_QUOTA_COUNTERS_SCRIPT } from 'src/engine/core-modules/usage-limit/constants/consume-quota-counters-script.constant';
+import {
+ UsageLimitException,
+ UsageLimitExceptionCode,
+} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';
+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type AnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/types/anchored-period-unit.type';
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { type QuotaCost } from 'src/engine/core-modules/usage-limit/types/quota-cost.type';
+import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+import { type UsageLimitCounterScope } from 'src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type';
+import { buildAllowanceCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util';
+import { buildLimitWarmedEntries } from 'src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util';
+import { buildPeriodGroupKey } from 'src/engine/core-modules/usage-limit/utils/build-period-group-key.util';
+import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
+import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/build-quota-counters.util';
+import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util';
+import { buildQuotaWarmLockKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util';
+import { findCreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util';
+import { findExhaustedCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util';
+import { findUsageLimitDefinition } from 'src/engine/core-modules/usage-limit/utils/find-usage-limit-definition.util';
+import { fromConsumeResultsToRemainings } from 'src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+import { WorkspaceCacheException } from 'src/engine/workspace-cache/exceptions/workspace-cache.exception';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const QUOTA_WARM_LOCK_OPTIONS = { ms: 50, maxRetries: 20, ttl: 10_000 };
+
+type AllowanceSumRow = {
+ total: string | number | null;
+};
+
+type QuotaConsumeArgs = {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenders: UsageSpenders;
+};
+
+@Injectable()
+export class UsageLimitQuotaService implements OnModuleInit {
+ private readonly logger = new Logger(UsageLimitQuotaService.name);
+
+ private creditAllowanceProvider: CreditAllowanceProvider | null = null;
+
+ constructor(
+ @InjectCacheStorage(CacheStorageNamespace.EngineUsageLimit)
+ private readonly cacheStorage: CacheStorageService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly cacheLockService: CacheLockService,
+ private readonly clickHouseService: ClickHouseService,
+ private readonly usagePeriodService: UsagePeriodService,
+ private readonly discoveryService: DiscoveryService,
+ ) {}
+
+ onModuleInit() {
+ this.creditAllowanceProvider = findCreditAllowanceProvider(
+ this.discoveryService,
+ );
+ }
+
+ async assertQuotaNotExhausted(args: QuotaConsumeArgs): Promise<void> {
+ const exhaustedScope =
+ await this.findExhaustedScopeAdmittingOnFailure(args);
+
+ if (isDefined(exhaustedScope)) {
+ this.throwQuotaExhausted(exhaustedScope);
+ }
+ }
+
+ async consumeQuota({
+ cost,
+ ...args
+ }: QuotaConsumeArgs & { cost: QuotaCost }): Promise<{
+ exhausted: ExhaustedScope | null;
+ }> {
+ return {
+ exhausted: await this.consumeCountersAdmittingOnFailure({
+ ...args,
+ cost,
+ }),
+ };
+ }
+
+ async dropAllowanceCounter(workspaceId: string): Promise<void> {
+ const period =
+ await this.creditAllowanceProvider?.getCreditAllowancePeriod(workspaceId);
+
+ if (!isDefined(period)) {
+ return;
+ }
+
+ await this.delUnderWarmLock({
+ workspaceId,
+ key: buildAllowanceCounterKey({
+ workspaceId,
+ periodStart: period.periodStart,
+ }),
+ });
+ }
+
+ async dropLimitCounter(usageLimit: UsageLimitCounterScope): Promise<void> {
+ if (
+ usageLimit.limitKind !== 'quota' ||
+ usageLimit.periodUnit === 'second'
+ ) {
+ return;
+ }
+
+ const period = this.usagePeriodService.getCurrentPeriod(
+ usageLimit.periodUnit,
+ );
+
+ await this.delUnderWarmLock({
+ workspaceId: usageLimit.workspaceId,
+ key: buildQuotaCounterKey({
+ workspaceId: usageLimit.workspaceId,
+ resourceType: usageLimit.resourceType,
+ operationType: usageLimit.operationType,
+ spenderType: usageLimit.spenderType,
+ spenderId: usageLimit.spenderId,
+ meter: usageLimit.meter,
+ periodUnit: usageLimit.periodUnit,
+ periodStart: period.periodStart,
+ }),
+ });
+ }
+
+ async getAllowanceRemainingMicro(
+ workspaceId: string,
+ ): Promise<number | null> {
+ try {
+ const allowanceCounter = await this.buildAllowanceCounter(workspaceId);
+
+ if (!isDefined(allowanceCounter)) {
+ return null;
+ }
+
+ const [remaining] = await this.readRemainings({
+ workspaceId,
+ counters: [allowanceCounter],
+ });
+
+ return remaining;
+ } catch (error) {
+ return this.admitOnFailure({ error, workspaceId });
+ }
+ }
+
+ private async delUnderWarmLock({
+ workspaceId,
+ key,
+ }: {
+ workspaceId: string;
+ key: string;
+ }): Promise<void> {
+ try {
+ await this.cacheLockService.withLock(
+ () => this.cacheStorage.del(key),
+ buildQuotaWarmLockKey(workspaceId),
+ QUOTA_WARM_LOCK_OPTIONS,
+ );
+ } catch (error) {
+ if (
+ !(error instanceof CacheLockException) ||
+ error.code !== CacheLockExceptionCode.LOCK_ACQUISITION_TIMEOUT
+ ) {
+ throw error;
+ }
+
+ this.logger.warn(
+ `Dropping quota counter ${key} without the warm lock: ${error.message}`,
+ );
+
+ await this.cacheStorage.del(key);
+ }
+ }
+
+ private async findExhaustedScopeAdmittingOnFailure(
+ args: QuotaConsumeArgs,
+ ): Promise<ExhaustedScope | null> {
+ try {
+ const counters = await this.buildCounters(args);
+
+ if (counters.length === 0) {
+ return null;
+ }
+
+ const remainings = await this.readRemainings({
+ workspaceId: args.workspaceId,
+ counters,
+ });
+
+ return await this.buildExhaustedScope({
+ args,
+ counters,
+ remainings,
+ });
+ } catch (error) {
+ return this.admitOnFailure({ error, workspaceId: args.workspaceId });
+ }
+ }
+
+ private async consumeCountersAdmittingOnFailure({
+ cost,
+ ...args
+ }: QuotaConsumeArgs & { cost: QuotaCost }): Promise<ExhaustedScope | null> {
+ try {
+ const counters = await this.buildCounters(args);
+
+ if (counters.length === 0) {
+ return null;
+ }
+
+ // The consume script only debits keys that exist: warm cold counters
+ // first so a consume-only caller (workflow, logic function) is metered
+ // from its first call instead of waiting for an assert to warm the key.
+ await this.readRemainings({ workspaceId: args.workspaceId, counters });
+
+ const consumeResults = await this.cacheStorage.runScript<number[]>({
+ script: CONSUME_QUOTA_COUNTERS_SCRIPT,
+ keys: counters.map((counter) => counter.key),
+ args: [JSON.stringify(counters.map((counter) => cost[counter.meter]))],
+ });
+
+ const remainings = fromConsumeResultsToRemainings(consumeResults);
+
+ return await this.buildExhaustedScope({
+ args,
+ counters,
+ remainings,
+ });
+ } catch (error) {
+ return this.admitOnFailure({ error, workspaceId: args.workspaceId });
+ }
+ }
+
+ private async buildExhaustedScope({
+ args,
+ counters,
+ remainings,
+ }: {
+ args: QuotaConsumeArgs;
+ counters: QuotaCounter[];
+ remainings: (number | null)[];
+ }): Promise<ExhaustedScope | null> {
+ const exhaustedCounter = findExhaustedCounter({ counters, remainings });
+
+ if (!isDefined(exhaustedCounter)) {
+ return null;
+ }
+
+ const allowance =
+ exhaustedCounter.kind === 'allowance'
+ ? ((await this.creditAllowanceProvider?.getCreditAllowance(
+ args.workspaceId,
+ )) ?? null)
+ : null;
+
+ return buildQuotaExhaustedScope({
+ resourceType: args.resourceType,
+ counter: exhaustedCounter,
+ allowance,
+ });
+ }
+
+ private throwQuotaExhausted(exhaustedScope: ExhaustedScope): never {
+ if (exhaustedScope.exhaustedKind === 'allowance') {
+ throw new UsageLimitException(
+ 'Credit allowance exhausted for this billing period',
+ UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ {
+ userFriendlyMessage: msg`Credit allowance exhausted for this billing period.`,
+ exhaustedScope,
+ },
+ );
+ }
+
+ throw new UsageLimitException(
+ `Usage limit reached for ${exhaustedScope.spenderType}`,
+ UsageLimitExceptionCode.QUOTA_EXHAUSTED,
+ { exhaustedScope },
+ );
+ }
+
+ private admitOnFailure({
+ error,
+ workspaceId,
+ }: {
+ error: unknown;
+ workspaceId: string;
+ }): null {
+ if (
+ error instanceof WorkspaceCacheException ||
+ error instanceof UsageLimitException
+ ) {
+ throw error;
+ }
+
+ this.logger.error(
+ `Usage quota enforcement degraded for workspace ${workspaceId}: ${error instanceof Error ? error.message : 'unknown error'}`,
+ );
+
+ return null;
+ }
+
+ private async buildCounters(args: QuotaConsumeArgs): Promise<QuotaCounter[]> {
+ const [limitCounters, allowanceCounter] = await Promise.all([
+ this.buildLimitCounters(args),
+ this.buildAllowanceCounter(args.workspaceId),
+ ]);
+
+ return isDefined(allowanceCounter)
+ ? [...limitCounters, allowanceCounter]
+ : limitCounters;
+ }
+
+ private async buildLimitCounters({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenders,
+ }: QuotaConsumeArgs): Promise<LimitQuotaCounter[]> {
+ const definition = findUsageLimitDefinition({
+ resourceType,
+ limitKind: 'quota',
+ });
+
+ if (!isDefined(definition)) {
+ return [];
+ }
+
+ const quotaLimits = await this.findQuotaLimits({
+ workspaceId,
+ resourceType,
+ });
+
+ if (quotaLimits.length === 0) {
+ return [];
+ }
+
+ return buildQuotaCounters({
+ limits: quotaLimits,
+ usageSpenders: spenders,
+ workspaceId,
+ resourceType,
+ operationType,
+ periodByUnit: this.getCurrentPeriodsByUnit(quotaLimits),
+ });
+ }
+
+ private async buildAllowanceCounter(
+ workspaceId: string,
+ ): Promise<AllowanceQuotaCounter | null> {
+ const period =
+ await this.creditAllowanceProvider?.getCreditAllowancePeriod(workspaceId);
+
+ if (!isDefined(period)) {
+ return null;
+ }
+
+ return {
+ kind: 'allowance',
+ key: buildAllowanceCounterKey({
+ workspaceId,
+ periodStart: period.periodStart,
+ }),
+ meter: 'creditsUsedMicro',
+ periodStart: period.periodStart,
+ periodEnd: period.periodEnd,
+ };
+ }
+
+ private getCurrentPeriodsByUnit(
+ quotaLimits: FlatUsageLimit[],
+ ): Partial<Record<PeriodUnit, UsagePeriod>> {
+ const periodUnits = [
+ ...new Set(
+ quotaLimits
+ .map((limit) => limit.periodUnit)
+ .filter(
+ (periodUnit): periodUnit is AnchoredPeriodUnit =>
+ periodUnit !== 'second',
+ ),
+ ),
+ ];
+
+ return Object.fromEntries(
+ periodUnits.map((periodUnit) => [
+ periodUnit,
+ this.usagePeriodService.getCurrentPeriod(periodUnit),
+ ]),
+ );
+ }
+
+ private async findQuotaLimits({
+ workspaceId,
+ resourceType,
+ }: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ }): Promise<FlatUsageLimit[]> {
+ const { usageLimits } = await this.workspaceCacheService.getOrRecompute(
+ workspaceId,
+ ['usageLimits'],
+ );
+
+ return (usageLimits.byResourceType[resourceType] ?? []).filter(
+ (limit) => limit.limitKind === 'quota',
+ );
+ }
+
+ private async readRemainings({
+ workspaceId,
+ counters,
+ }: {
+ workspaceId: string;
+ counters: QuotaCounter[];
+ }): Promise<(number | null)[]> {
+ const remainings = await this.cacheStorage.mget<number>(
+ counters.map((counter) => counter.key),
+ );
+
+ const warmRemainings = remainings.filter(isDefined);
+
+ if (warmRemainings.length === remainings.length) {
+ return warmRemainings;
+ }
+
+ return this.warmColdCounters({ workspaceId, counters });
+ }
+
+ private async warmColdCounters({
+ workspaceId,
+ counters,
+ }: {
+ workspaceId: string;
+ counters: QuotaCounter[];
+ }): Promise<(number | null)[]> {
+ return this.cacheLockService.withLock(
+ async () => {
+ const remainings = await this.cacheStorage.mget<number>(
+ counters.map((counter) => counter.key),
+ );
+
+ const warmRemainings = remainings.filter(isDefined);
+
+ if (warmRemainings.length === remainings.length) {
+ return warmRemainings;
+ }
+
+ const coldCounters = counters.filter(
+ (_, index) => !isDefined(remainings[index]),
+ );
+
+ const warmedEntries = await this.buildWarmedEntries({
+ workspaceId,
+ coldCounters,
+ });
+
+ await this.cacheStorage.mset(warmedEntries);
+
+ const warmedValueByKey = new Map(
+ warmedEntries.map((entry) => [entry.key, entry.value]),
+ );
+
+ return counters.map(
+ (counter, index) =>
+ remainings[index] ?? warmedValueByKey.get(counter.key) ?? null,
+ );
+ },
+ buildQuotaWarmLockKey(workspaceId),
+ QUOTA_WARM_LOCK_OPTIONS,
+ );
+ }
+
+ private async buildWarmedEntries({
+ workspaceId,
+ coldCounters,
+ }: {
+ workspaceId: string;
+ coldCounters: QuotaCounter[];
+ }): Promise<{ key: string; value: number; ttl: number }[]> {
+ const coldLimitCounters = coldCounters.filter(
+ (counter): counter is LimitQuotaCounter => counter.kind === 'limit',
+ );
+ const coldAllowanceCounter = coldCounters.find(
+ (counter): counter is AllowanceQuotaCounter =>
+ counter.kind === 'allowance',
+ );
+
+ const now = Date.now();
+
+ const [rowsByPeriod, allowanceEntries] = await Promise.all([
+ this.fetchConsumptionRowsByPeriod({
+ workspaceId,
+ coldLimitCounters,
+ }),
+ this.buildAllowanceWarmedEntry({
+ workspaceId,
+ counter: coldAllowanceCounter,
+ now,
+ }),
+ ]);
+
+ return [
+ ...buildLimitWarmedEntries({ coldLimitCounters, rowsByPeriod, now }),
+ ...allowanceEntries,
+ ];
+ }
+
+ private async buildAllowanceWarmedEntry({
+ workspaceId,
+ counter,
+ now,
+ }: {
+ workspaceId: string;
+ counter: AllowanceQuotaCounter | undefined;
+ now: number;
+ }): Promise<{ key: string; value: number; ttl: number }[]> {
+ if (!isDefined(counter)) {
+ return [];
+ }
+
+ const ttl = counter.periodEnd.getTime() - now;
+
+ if (ttl <= 0) {
+ return [];
+ }
+
+ const allowance =
+ await this.creditAllowanceProvider?.getCreditAllowance(workspaceId);
+
+ if (
+ !isDefined(allowance) ||
+ allowance.periodStart.getTime() !== counter.periodStart.getTime()
+ ) {
+ return [];
+ }
+
+ const consumedMicro = await this.fetchAllowanceConsumedMicro({
+ workspaceId,
+ periodStart: counter.periodStart,
+ });
+
+ return [
+ {
+ key: counter.key,
+ value: allowance.allowanceMicro - consumedMicro,
+ ttl,
+ },
+ ];
+ }
+
+ private async fetchAllowanceConsumedMicro({
+ workspaceId,
+ periodStart,
+ }: {
+ workspaceId: string;
+ periodStart: Date;
+ }): Promise<number> {
+ const rows = await this.clickHouseService.selectOrThrow<AllowanceSumRow>(
+ `SELECT sum(creditsUsedMicro) AS total
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND periodStart = {periodStart:DateTime64(3)}`,
+ {
+ workspaceId,
+ periodStart: formatDateTimeForClickHouse(periodStart),
+ },
+ );
+
+ return Number(rows[0]?.total ?? 0);
+ }
+
+ private async fetchConsumptionRowsByPeriod({
+ workspaceId,
+ coldLimitCounters,
+ }: {
+ workspaceId: string;
+ coldLimitCounters: LimitQuotaCounter[];
+ }): Promise<Map<string, QuotaConsumptionRow[]>> {
+ const countersByPeriod = new Map<string, LimitQuotaCounter>();
+
+ for (const counter of coldLimitCounters) {
+ countersByPeriod.set(buildPeriodGroupKey(counter), counter);
+ }
+
+ const rowsByPeriod = new Map<string, QuotaConsumptionRow[]>();
+
+ await Promise.all(
+ [...countersByPeriod.entries()].map(async ([periodGroupKey, counter]) => {
+ rowsByPeriod.set(
+ periodGroupKey,
+ await this.fetchConsumptionRows({ workspaceId, counter }),
+ );
+ }),
+ );
+
+ return rowsByPeriod;
+ }
+
+ private async fetchConsumptionRows({
+ workspaceId,
+ counter,
+ }: {
+ workspaceId: string;
+ counter: LimitQuotaCounter;
+ }): Promise<QuotaConsumptionRow[]> {
+ return this.clickHouseService.selectOrThrow<QuotaConsumptionRow>(
+ `SELECT operationType, userWorkspaceId, apiKeyId, applicationId, agentId,
+ workflowId, logicFunctionId,
+ sum(creditsUsedMicro) AS creditsUsedMicro,
+ sum(quantity) AS quantity
+ FROM usageEvent
+ WHERE workspaceId = {workspaceId:String}
+ AND resourceType = {resourceType:String}
+ AND toStartOfDay(timestamp, 'UTC') >= {periodStart:DateTime64(3)}
+ AND toStartOfDay(timestamp, 'UTC') < {periodEnd:DateTime64(3)}
+ GROUP BY operationType, userWorkspaceId, apiKeyId, applicationId, agentId,
+ workflowId, logicFunctionId`,
+ {
+ workspaceId,
+ resourceType: counter.resourceType,
+ periodStart: formatDateTimeForClickHouse(counter.periodStart),
+ periodEnd: formatDateTimeForClickHouse(counter.periodEnd),
+ },
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
index 26231945cc8..0d25816f9d0 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-limit.service.ts
@@ -10,6 +10,7 @@ import {
UsageLimitException,
UsageLimitExceptionCode,
} from 'src/engine/core-modules/usage-limit/exceptions/usage-limit.exception';
+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
import { UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
import { validateUsageLimitAgainstDefinition } from 'src/engine/core-modules/usage-limit/utils/validate-usage-limit-against-definition.util';
@@ -36,6 +37,7 @@ export class UsageLimitService {
@InjectWorkspaceScopedRepository(LogicFunctionEntity)
private readonly logicFunctionRepository: WorkspaceScopedRepository<LogicFunctionEntity>,
private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly usageLimitQuotaService: UsageLimitQuotaService,
) {}
async findAll(workspaceId: string): Promise<UsageLimitEntity[]> {
@@ -85,9 +87,16 @@ export class UsageLimitService {
'usageLimits',
]);
- return this.usageLimitRepository.findOneOrFail(workspaceId, {
- where: scope,
- });
+ const usageLimit = await this.usageLimitRepository.findOneOrFail(
+ workspaceId,
+ {
+ where: scope,
+ },
+ );
+
+ await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
+
+ return usageLimit;
}
async delete({
@@ -97,6 +106,14 @@ export class UsageLimitService {
workspaceId: string;
usageLimitId: string;
}): Promise<boolean> {
+ const usageLimit = await this.usageLimitRepository.findOne(workspaceId, {
+ where: { id: usageLimitId },
+ });
+
+ if (!isDefined(usageLimit)) {
+ return false;
+ }
+
const { affected } = await this.usageLimitRepository.delete(workspaceId, {
id: usageLimitId,
});
@@ -109,6 +126,8 @@ export class UsageLimitService {
'usageLimits',
]);
+ await this.usageLimitQuotaService.dropLimitCounter(usageLimit);
+
return true;
}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts
new file mode 100644
index 00000000000..80a44883494
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/services/usage-period.service.ts
@@ -0,0 +1,32 @@
+/* @license Enterprise */
+
+import { Injectable } from '@nestjs/common';
+
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { type AnchoredPeriodUnit } from 'src/engine/core-modules/usage-limit/types/anchored-period-unit.type';
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+import { getCalendarDayPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-day-period.util';
+import { getCalendarMonthPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-month-period.util';
+import { getCalendarWeekPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-week-period.util';
+
+@Injectable()
+export class UsagePeriodService {
+ getCurrentPeriod(periodUnit: AnchoredPeriodUnit): UsagePeriod {
+ const now = new Date();
+
+ switch (periodUnit) {
+ case 'day':
+ return getCalendarDayPeriod(now);
+ case 'week':
+ return getCalendarWeekPeriod(now);
+ case 'month':
+ return getCalendarMonthPeriod(now);
+ default:
+ return assertUnreachable(
+ periodUnit,
+ `Unknown period unit ${periodUnit}`,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts
new file mode 100644
index 00000000000..07ef21e8636
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/allowance-quota-counter.type.ts
@@ -0,0 +1,7 @@
+export type AllowanceQuotaCounter = {
+ kind: 'allowance';
+ key: string;
+ meter: 'creditsUsedMicro';
+ periodStart: Date;
+ periodEnd: Date;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/credit-allowance.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/credit-allowance.type.ts
new file mode 100644
index 00000000000..8f98e0b8402
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/credit-allowance.type.ts
@@ -0,0 +1,5 @@
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+
+export type CreditAllowance = UsagePeriod & {
+ allowanceMicro: number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
new file mode 100644
index 00000000000..22e616dd3c8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/limit-quota-counter.type.ts
@@ -0,0 +1,19 @@
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export type LimitQuotaCounter = {
+ kind: 'limit';
+ key: string;
+ limitValue: number;
+ meter: UsageMeter;
+ resourceType: UsageResourceType;
+ periodUnit: PeriodUnit;
+ periodStart: Date;
+ periodEnd: Date;
+ spenderType: SpenderType;
+ spenderId: string | null;
+ operationType: UsageOperationType;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-consumption-row.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-consumption-row.type.ts
new file mode 100644
index 00000000000..ca036cdc2dd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-consumption-row.type.ts
@@ -0,0 +1,11 @@
+export type QuotaConsumptionRow = {
+ operationType: string;
+ userWorkspaceId: string;
+ apiKeyId: string;
+ applicationId: string;
+ agentId: string;
+ workflowId: string;
+ logicFunctionId: string;
+ creditsUsedMicro: string | number;
+ quantity: string | number;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
new file mode 100644
index 00000000000..32592dc9c76
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-cost.type.ts
@@ -0,0 +1,3 @@
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+
+export type QuotaCost = Record<UsageMeter, number>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-counter.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-counter.type.ts
new file mode 100644
index 00000000000..5a2db6706cf
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/quota-counter.type.ts
@@ -0,0 +1,4 @@
+import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+
+export type QuotaCounter = LimitQuotaCounter | AllowanceQuotaCounter;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type.ts
new file mode 100644
index 00000000000..967c31e1c79
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-limit-counter-scope.type.ts
@@ -0,0 +1,13 @@
+import { type UsageLimitEntity } from 'src/engine/core-modules/usage-limit/usage-limit.entity';
+
+export type UsageLimitCounterScope = Pick<
+ UsageLimitEntity,
+ | 'workspaceId'
+ | 'resourceType'
+ | 'operationType'
+ | 'spenderType'
+ | 'spenderId'
+ | 'limitKind'
+ | 'periodUnit'
+ | 'meter'
+>;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-period.type.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-period.type.ts
new file mode 100644
index 00000000000..8cf6c4ea2a8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/types/usage-period.type.ts
@@ -0,0 +1,6 @@
+/* @license Enterprise */
+
+export type UsagePeriod = {
+ periodStart: Date;
+ periodEnd: Date;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
index da85a70df88..db5528130d1 100644
--- a/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/usage-limit.module.ts
@@ -1,7 +1,13 @@
import { Module } from '@nestjs/common';
+import { DiscoveryModule } from '@nestjs/core';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { ClickHouseModule } from 'src/database/clickhouse/clickhouse.module';
import { ApiKeyEntity } from 'src/engine/core-modules/api-key/api-key.entity';
+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
+import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
+import { UsagePeriodService } from 'src/engine/core-modules/usage-limit/services/usage-period.service';
+import { UsageModule } from 'src/engine/core-modules/usage/usage.module';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
@@ -27,10 +33,16 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
]),
WorkspaceCacheModule,
PermissionsModule,
+ DiscoveryModule,
+ CacheLockModule,
+ ClickHouseModule,
+ UsageModule,
],
providers: [
+ UsageLimitQuotaService,
UsageLimitSpeedService,
UsageLimitsCacheService,
+ UsagePeriodService,
UsageLimitService,
UsageLimitResolver,
provideWorkspaceScopedRepository(UsageLimitEntity),
@@ -40,6 +52,10 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache
provideWorkspaceScopedRepository(AgentEntity),
provideWorkspaceScopedRepository(LogicFunctionEntity),
],
- exports: [UsageLimitSpeedService, UsageLimitsCacheService],
+ exports: [
+ UsageLimitQuotaService,
+ UsageLimitSpeedService,
+ UsageLimitsCacheService,
+ ],
})
export class UsageLimitModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-limit-warmed-entries.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-limit-warmed-entries.util.spec.ts
new file mode 100644
index 00000000000..5edfe115321
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-limit-warmed-entries.util.spec.ts
@@ -0,0 +1,110 @@
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { buildLimitWarmedEntries } from 'src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util';
+import { buildPeriodGroupKey } from 'src/engine/core-modules/usage-limit/utils/build-period-group-key.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const NOW = new Date('2026-08-20T00:00:00.000Z').getTime();
+
+const buildCounter = (
+ overrides: Partial<LimitQuotaCounter> = {},
+): LimitQuotaCounter => ({
+ kind: 'limit',
+ key: 'counter-key',
+ limitValue: 1_000,
+ meter: 'creditsUsedMicro',
+ resourceType: UsageResourceType.AI,
+ periodUnit: 'month',
+ periodStart: new Date('2026-08-01T00:00:00.000Z'),
+ periodEnd: new Date('2026-09-01T00:00:00.000Z'),
+ spenderType: 'workspace',
+ spenderId: null,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ ...overrides,
+});
+
+const buildRow = (
+ overrides: Partial<QuotaConsumptionRow> = {},
+): QuotaConsumptionRow => ({
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ userWorkspaceId: 'user-1',
+ apiKeyId: '',
+ applicationId: '',
+ agentId: '',
+ workflowId: '',
+ logicFunctionId: '',
+ creditsUsedMicro: '0',
+ quantity: '0',
+ ...overrides,
+});
+
+const buildRowsByPeriod = (
+ counter: LimitQuotaCounter,
+ rows: QuotaConsumptionRow[],
+) => new Map([[buildPeriodGroupKey(counter), rows]]);
+
+describe('buildLimitWarmedEntries', () => {
+ it('seeds the counter with its budget minus the stamped consumption', () => {
+ const counter = buildCounter();
+
+ expect(
+ buildLimitWarmedEntries({
+ coldLimitCounters: [counter],
+ rowsByPeriod: buildRowsByPeriod(counter, [
+ buildRow({ creditsUsedMicro: '150' }),
+ buildRow({ userWorkspaceId: 'user-2', creditsUsedMicro: '100' }),
+ ]),
+ now: NOW,
+ }),
+ ).toEqual([
+ {
+ key: 'counter-key',
+ value: 750,
+ ttl: counter.periodEnd.getTime() - NOW,
+ },
+ ]);
+ });
+
+ it('counts only the rows the counter spender stamped', () => {
+ const counter = buildCounter({
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ });
+
+ expect(
+ buildLimitWarmedEntries({
+ coldLimitCounters: [counter],
+ rowsByPeriod: buildRowsByPeriod(counter, [
+ buildRow({ creditsUsedMicro: '150' }),
+ buildRow({ userWorkspaceId: 'user-2', creditsUsedMicro: '100' }),
+ ]),
+ now: NOW,
+ }),
+ ).toMatchObject([{ value: 850 }]);
+ });
+
+ it('skips a counter whose period already ended', () => {
+ const counter = buildCounter({
+ periodEnd: new Date('2026-08-10T00:00:00.000Z'),
+ });
+
+ expect(
+ buildLimitWarmedEntries({
+ coldLimitCounters: [counter],
+ rowsByPeriod: buildRowsByPeriod(counter, [buildRow({})]),
+ now: NOW,
+ }),
+ ).toEqual([]);
+ });
+
+ it('skips a counter whose consumption was not fetched', () => {
+ expect(
+ buildLimitWarmedEntries({
+ coldLimitCounters: [buildCounter()],
+ rowsByPeriod: new Map(),
+ now: NOW,
+ }),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
new file mode 100644
index 00000000000..1b6f91a140d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-counters.util.spec.ts
@@ -0,0 +1,135 @@
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { buildQuotaCounters } from 'src/engine/core-modules/usage-limit/utils/build-quota-counters.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const MONTH_PERIOD = {
+ periodStart: new Date('2026-08-01T00:00:00.000Z'),
+ periodEnd: new Date('2026-09-01T00:00:00.000Z'),
+};
+
+const WEEK_PERIOD = {
+ periodStart: new Date('2026-08-24T00:00:00.000Z'),
+ periodEnd: new Date('2026-08-31T00:00:00.000Z'),
+};
+
+const buildLimit = (overrides: Partial<FlatUsageLimit>): FlatUsageLimit => ({
+ id: 'limit-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenderType: 'workspace',
+ spenderId: '',
+ limitKind: 'quota',
+ periodCount: 1,
+ periodUnit: 'month',
+ meter: 'creditsUsedMicro',
+ limitValue: 1_000_000,
+ burstValue: null,
+ ...overrides,
+});
+
+const buildCounters = ({ limits }: { limits: FlatUsageLimit[] }) =>
+ buildQuotaCounters({
+ limits,
+ usageSpenders: { userWorkspaceId: 'user-1' },
+ workspaceId: 'workspace-1',
+ resourceType: UsageResourceType.AI,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ periodByUnit: { month: MONTH_PERIOD, week: WEEK_PERIOD },
+ });
+
+describe('buildQuotaCounters', () => {
+ it('builds one counter per matching limit with a period-scoped key', () => {
+ const counters = buildCounters({
+ limits: [buildLimit({ spenderType: 'workspace' })],
+ });
+
+ expect(counters).toEqual([
+ {
+ kind: 'limit',
+ key: `{workspace-1}:quota:AI:AI_CHAT_TOKEN:workspace:-:creditsUsedMicro:month:${MONTH_PERIOD.periodStart.getTime()}`,
+ limitValue: 1_000_000,
+ meter: 'creditsUsedMicro',
+ resourceType: UsageResourceType.AI,
+ periodUnit: 'month',
+ periodStart: MONTH_PERIOD.periodStart,
+ periodEnd: MONTH_PERIOD.periodEnd,
+ spenderType: 'workspace',
+ spenderId: null,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ },
+ ]);
+ });
+
+ it('anchors each counter to its own period unit', () => {
+ const counters = buildCounters({
+ limits: [
+ buildLimit({ id: 'monthly' }),
+ buildLimit({ id: 'weekly', periodUnit: 'week' }),
+ ],
+ });
+
+ expect(counters.map((counter) => counter.periodStart)).toEqual([
+ MONTH_PERIOD.periodStart,
+ WEEK_PERIOD.periodStart,
+ ]);
+ });
+
+ it('ignores limits for spenders absent from the call', () => {
+ const counters = buildCounters({
+ limits: [buildLimit({ spenderType: 'apiKey', spenderId: 'key-1' })],
+ });
+
+ expect(counters).toEqual([]);
+ });
+
+ it('applies a wildcard-operation limit alongside the operation-scoped one', () => {
+ const counters = buildCounters({
+ limits: [
+ buildLimit({ id: 'all', operationType: UsageOperationType.ALL }),
+ buildLimit({ id: 'chat' }),
+ ],
+ });
+
+ expect(counters.map((counter) => counter.operationType)).toEqual([
+ UsageOperationType.AI_CHAT_TOKEN,
+ UsageOperationType.ALL,
+ ]);
+ });
+
+ it('ranks a named user counter before workspace counters', () => {
+ const counters = buildCounters({
+ limits: [
+ buildLimit({ spenderType: 'workspace' }),
+ buildLimit({
+ id: 'limit-2',
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ }),
+ ],
+ });
+
+ expect(counters.map((counter) => counter.spenderType)).toEqual([
+ 'userWorkspace',
+ 'workspace',
+ ]);
+ });
+
+ it('skips a limit whose period was not resolved', () => {
+ const counters = buildCounters({
+ limits: [buildLimit({ periodUnit: 'day' })],
+ });
+
+ expect(counters).toEqual([]);
+ });
+
+ it('does not match a limit for another operation', () => {
+ const counters = buildCounters({
+ limits: [
+ buildLimit({ operationType: UsageOperationType.AI_WORKFLOW_TOKEN }),
+ ],
+ });
+
+ expect(counters).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
new file mode 100644
index 00000000000..d3707c0d829
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/build-quota-exhausted-scope.util.spec.ts
@@ -0,0 +1,114 @@
+import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { buildQuotaExhaustedScope } from 'src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const NOW = new Date('2026-08-20T00:00:00.000Z');
+const PERIOD_START = new Date('2026-08-01T00:00:00.000Z');
+const PERIOD_END = new Date('2026-09-01T00:00:00.000Z');
+
+const buildLimitCounter = (
+ overrides: Partial<LimitQuotaCounter> = {},
+): LimitQuotaCounter => ({
+ kind: 'limit',
+ key: 'counter-key',
+ limitValue: 1_000,
+ meter: 'creditsUsedMicro',
+ resourceType: UsageResourceType.AI,
+ periodUnit: 'month',
+ periodStart: PERIOD_START,
+ periodEnd: PERIOD_END,
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ ...overrides,
+});
+
+const allowanceCounter: AllowanceQuotaCounter = {
+ kind: 'allowance',
+ key: 'allowance-key',
+ meter: 'creditsUsedMicro',
+ periodStart: PERIOD_START,
+ periodEnd: PERIOD_END,
+};
+
+describe('buildQuotaExhaustedScope', () => {
+ beforeAll(() => {
+ jest.useFakeTimers().setSystemTime(NOW);
+ });
+
+ afterAll(() => {
+ jest.useRealTimers();
+ });
+
+ it('scopes an exhausted limit counter to its spender', () => {
+ expect(
+ buildQuotaExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ counter: buildLimitCounter(),
+ allowance: null,
+ }),
+ ).toEqual({
+ resourceType: UsageResourceType.AI,
+ limitKind: 'quota',
+ exhaustedKind: 'limit',
+ spenderType: 'userWorkspace',
+ spenderId: 'user-1',
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ limitValue: 1_000,
+ remaining: 0,
+ periodCount: 1,
+ periodUnit: 'month',
+ retryAfterMs: PERIOD_END.getTime() - NOW.getTime(),
+ });
+ });
+
+ it('scopes an exhausted allowance counter to the whole workspace', () => {
+ expect(
+ buildQuotaExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ counter: allowanceCounter,
+ allowance: {
+ periodStart: PERIOD_START,
+ periodEnd: PERIOD_END,
+ allowanceMicro: 2_000_000,
+ },
+ }),
+ ).toEqual({
+ resourceType: UsageResourceType.AI,
+ limitKind: 'quota',
+ exhaustedKind: 'allowance',
+ spenderType: 'workspace',
+ spenderId: null,
+ operationType: UsageOperationType.ALL,
+ limitValue: 2_000_000,
+ remaining: 0,
+ periodCount: null,
+ periodUnit: null,
+ retryAfterMs: PERIOD_END.getTime() - NOW.getTime(),
+ });
+ });
+
+ it('reports a zero allowance when it is gone since the counter was read', () => {
+ expect(
+ buildQuotaExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ counter: allowanceCounter,
+ allowance: null,
+ }),
+ ).toMatchObject({ exhaustedKind: 'allowance', limitValue: 0 });
+ });
+
+ it('clamps the retry delay to zero once the period has ended', () => {
+ expect(
+ buildQuotaExhaustedScope({
+ resourceType: UsageResourceType.AI,
+ counter: buildLimitCounter({
+ periodEnd: new Date('2026-08-10T00:00:00.000Z'),
+ }),
+ allowance: null,
+ }),
+ ).toMatchObject({ retryAfterMs: 0 });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
new file mode 100644
index 00000000000..f56d5195689
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/compute-quota-consumed.util.spec.ts
@@ -0,0 +1,136 @@
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const buildRow = (
+ overrides: Partial<QuotaConsumptionRow>,
+): QuotaConsumptionRow => ({
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ userWorkspaceId: 'user-1',
+ apiKeyId: '',
+ applicationId: '',
+ agentId: '',
+ workflowId: '',
+ logicFunctionId: '',
+ creditsUsedMicro: '100',
+ quantity: '10',
+ ...overrides,
+});
+
+const buildCounter = (
+ overrides: Partial<LimitQuotaCounter>,
+): LimitQuotaCounter => ({
+ kind: 'limit',
+ key: 'counter-key',
+ limitValue: 1_000,
+ meter: 'creditsUsedMicro',
+ resourceType: UsageResourceType.AI,
+ periodUnit: 'month',
+ periodStart: new Date('2026-08-01T00:00:00.000Z'),
+ periodEnd: new Date('2026-09-01T00:00:00.000Z'),
+ spenderType: 'workspace',
+ spenderId: null,
+ operationType: UsageOperationType.ALL,
+ ...overrides,
+});
+
+const rows = [
+ buildRow({ agentId: 'agent-1' }),
+ buildRow({
+ userWorkspaceId: 'user-2',
+ logicFunctionId: 'logic-function-1',
+ creditsUsedMicro: '40',
+ }),
+ buildRow({
+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,
+ userWorkspaceId: '',
+ workflowId: 'workflow-1',
+ creditsUsedMicro: '7',
+ quantity: '3',
+ }),
+];
+
+describe('computeQuotaConsumed', () => {
+ it('sums every row for a workspace counter with no operation', () => {
+ expect(computeQuotaConsumed({ rows, counter: buildCounter({}) })).toBe(147);
+ });
+
+ it('cuts by operation when the counter names one', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ counter: buildCounter({
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ }),
+ }),
+ ).toBe(140);
+ });
+
+ it('matches a named spender on its own column', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ counter: buildCounter({
+ spenderType: 'userWorkspace',
+ spenderId: 'user-2',
+ }),
+ }),
+ ).toBe(40);
+ });
+
+ it('sums every attributed row for a shared spender counter', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ counter: buildCounter({
+ spenderType: 'userWorkspace',
+ spenderId: null,
+ }),
+ }),
+ ).toBe(140);
+ });
+
+ it('sums the quantity column when the counter meters on it', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ counter: buildCounter({ meter: 'quantity' }),
+ }),
+ ).toBe(23);
+ });
+
+ it('matches a named agent on its own column', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ counter: buildCounter({ spenderType: 'agent', spenderId: 'agent-1' }),
+ }),
+ ).toBe(100);
+ });
+
+ it('matches a named workflow on its own column', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ counter: buildCounter({
+ spenderType: 'workflow',
+ spenderId: 'workflow-1',
+ }),
+ }),
+ ).toBe(7);
+ });
+
+ it('matches a named logic function on its own column', () => {
+ expect(
+ computeQuotaConsumed({
+ rows,
+ counter: buildCounter({
+ spenderType: 'logicFunction',
+ spenderId: 'logic-function-1',
+ }),
+ }),
+ ).toBe(40);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counter.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counter.util.spec.ts
new file mode 100644
index 00000000000..cb645000eaa
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/find-exhausted-counter.util.spec.ts
@@ -0,0 +1,57 @@
+import { type AllowanceQuotaCounter } from 'src/engine/core-modules/usage-limit/types/allowance-quota-counter.type';
+import { findExhaustedCounter } from 'src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util';
+
+const buildCounter = (key: string): AllowanceQuotaCounter => ({
+ kind: 'allowance',
+ key,
+ meter: 'creditsUsedMicro',
+ periodStart: new Date('2026-08-01T00:00:00.000Z'),
+ periodEnd: new Date('2026-09-01T00:00:00.000Z'),
+});
+
+describe('findExhaustedCounter', () => {
+ it('answers null when every counter has budget left', () => {
+ expect(
+ findExhaustedCounter({
+ counters: [buildCounter('first'), buildCounter('second')],
+ remainings: [250, 1],
+ }),
+ ).toBeNull();
+ });
+
+ it('picks the first counter whose budget is gone', () => {
+ expect(
+ findExhaustedCounter({
+ counters: [buildCounter('first'), buildCounter('second')],
+ remainings: [100, 0],
+ }),
+ ).toMatchObject({ key: 'second' });
+ });
+
+ it('counts an overdrawn counter as exhausted', () => {
+ expect(
+ findExhaustedCounter({
+ counters: [buildCounter('first')],
+ remainings: [-10],
+ }),
+ ).toMatchObject({ key: 'first' });
+ });
+
+ it('skips cold counters', () => {
+ expect(
+ findExhaustedCounter({
+ counters: [buildCounter('first'), buildCounter('second')],
+ remainings: [null, 0],
+ }),
+ ).toMatchObject({ key: 'second' });
+ });
+
+ it('answers null when every counter is cold', () => {
+ expect(
+ findExhaustedCounter({
+ counters: [buildCounter('first')],
+ remainings: [null],
+ }),
+ ).toBeNull();
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-consume-results-to-remainings.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-consume-results-to-remainings.util.spec.ts
new file mode 100644
index 00000000000..6bf2cc1a552
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/from-consume-results-to-remainings.util.spec.ts
@@ -0,0 +1,17 @@
+import { fromConsumeResultsToRemainings } from 'src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util';
+
+describe('fromConsumeResultsToRemainings', () => {
+ it('reads one remaining per debited counter', () => {
+ expect(fromConsumeResultsToRemainings([1, 500, 1, -10])).toEqual([
+ 500, -10,
+ ]);
+ });
+
+ it('leaves a counter the script did not find cold', () => {
+ expect(fromConsumeResultsToRemainings([1, 500, 0, 0])).toEqual([500, null]);
+ });
+
+ it('answers nothing for no results', () => {
+ expect(fromConsumeResultsToRemainings([])).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-day-period.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-day-period.util.spec.ts
new file mode 100644
index 00000000000..e876b155601
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-day-period.util.spec.ts
@@ -0,0 +1,21 @@
+import { getCalendarDayPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-day-period.util';
+
+describe('getCalendarDayPeriod', () => {
+ it('returns the enclosing UTC day', () => {
+ const { periodStart, periodEnd } = getCalendarDayPeriod(
+ new Date('2026-08-27T15:30:00.000Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-27T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2026-08-28T00:00:00.000Z');
+ });
+
+ it('rolls the end over a month boundary', () => {
+ const { periodStart, periodEnd } = getCalendarDayPeriod(
+ new Date('2026-08-31T23:59:59.999Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-31T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2026-09-01T00:00:00.000Z');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-month-period.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-month-period.util.spec.ts
new file mode 100644
index 00000000000..d47b24088e5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-month-period.util.spec.ts
@@ -0,0 +1,30 @@
+import { getCalendarMonthPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-month-period.util';
+
+describe('getCalendarMonthPeriod', () => {
+ it('returns the enclosing UTC calendar month', () => {
+ const { periodStart, periodEnd } = getCalendarMonthPeriod(
+ new Date('2026-08-27T15:30:00.000Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-01T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2026-09-01T00:00:00.000Z');
+ });
+
+ it('rolls the end over a year boundary', () => {
+ const { periodStart, periodEnd } = getCalendarMonthPeriod(
+ new Date('2026-12-31T23:59:59.999Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-12-01T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2027-01-01T00:00:00.000Z');
+ });
+
+ it('keeps a first-instant date inside its own month', () => {
+ const { periodStart, periodEnd } = getCalendarMonthPeriod(
+ new Date('2026-08-01T00:00:00.000Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-01T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2026-09-01T00:00:00.000Z');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-week-period.util.spec.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-week-period.util.spec.ts
new file mode 100644
index 00000000000..9c0562f57cc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/__tests__/get-calendar-week-period.util.spec.ts
@@ -0,0 +1,38 @@
+import { getCalendarWeekPeriod } from 'src/engine/core-modules/usage-limit/utils/get-calendar-week-period.util';
+
+describe('getCalendarWeekPeriod', () => {
+ it('anchors to the enclosing Monday-started UTC week', () => {
+ const { periodStart, periodEnd } = getCalendarWeekPeriod(
+ new Date('2026-08-27T15:30:00.000Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-24T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2026-08-31T00:00:00.000Z');
+ });
+
+ it('keeps a Monday inside its own week', () => {
+ const { periodStart } = getCalendarWeekPeriod(
+ new Date('2026-08-24T00:00:00.000Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-24T00:00:00.000Z');
+ });
+
+ it('puts a Sunday at the end of the running week', () => {
+ const { periodStart, periodEnd } = getCalendarWeekPeriod(
+ new Date('2026-08-30T23:59:59.999Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-24T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2026-08-31T00:00:00.000Z');
+ });
+
+ it('rolls over a month boundary', () => {
+ const { periodStart, periodEnd } = getCalendarWeekPeriod(
+ new Date('2026-09-01T00:00:00.000Z'),
+ );
+
+ expect(periodStart.toISOString()).toBe('2026-08-31T00:00:00.000Z');
+ expect(periodEnd.toISOString()).toBe('2026-09-07T00:00:00.000Z');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util.ts
new file mode 100644
index 00000000000..29d8dcda3cb
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-allowance-counter-key.util.ts
@@ -0,0 +1,7 @@
+export const buildAllowanceCounterKey = ({
+ workspaceId,
+ periodStart,
+}: {
+ workspaceId: string;
+ periodStart: Date;
+}): string => `{${workspaceId}}:quota:allowance:${periodStart.getTime()}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util.ts
new file mode 100644
index 00000000000..baf609fbefe
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-limit-warmed-entries.util.ts
@@ -0,0 +1,32 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+import { buildPeriodGroupKey } from 'src/engine/core-modules/usage-limit/utils/build-period-group-key.util';
+import { computeQuotaConsumed } from 'src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util';
+
+export const buildLimitWarmedEntries = ({
+ coldLimitCounters,
+ rowsByPeriod,
+ now,
+}: {
+ coldLimitCounters: LimitQuotaCounter[];
+ rowsByPeriod: Map<string, QuotaConsumptionRow[]>;
+ now: number;
+}): { key: string; value: number; ttl: number }[] =>
+ coldLimitCounters.flatMap((counter) => {
+ const ttl = counter.periodEnd.getTime() - now;
+ const rows = rowsByPeriod.get(buildPeriodGroupKey(counter));
+
+ if (ttl <= 0 || !isDefined(rows)) {
+ return [];
+ }
+
+ return [
+ {
+ key: counter.key,
+ value: counter.limitValue - computeQuotaConsumed({ rows, counter }),
+ ttl,
+ },
+ ];
+ });
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-period-group-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-period-group-key.util.ts
new file mode 100644
index 00000000000..39cbeaf4ef7
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-period-group-key.util.ts
@@ -0,0 +1,4 @@
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+
+export const buildPeriodGroupKey = (counter: LimitQuotaCounter): string =>
+ `${counter.resourceType}:${counter.periodUnit}:${counter.periodStart.getTime()}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
new file mode 100644
index 00000000000..46bf252da5d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util.ts
@@ -0,0 +1,30 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type SpenderType } from 'src/engine/core-modules/usage-limit/types/spender-type.type';
+import { type UsageMeter } from 'src/engine/core-modules/usage-limit/types/usage-meter.type';
+import { type UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+const ABSENT = '-';
+
+export const buildQuotaCounterKey = ({
+ workspaceId,
+ resourceType,
+ operationType,
+ spenderType,
+ spenderId,
+ meter,
+ periodUnit,
+ periodStart,
+}: {
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ spenderType: SpenderType;
+ spenderId?: string | null;
+ meter: UsageMeter;
+ periodUnit: PeriodUnit;
+ periodStart: Date;
+}): string =>
+ `{${workspaceId}}:quota:${resourceType}:${operationType}:${spenderType}:${isNonEmptyString(spenderId) ? spenderId : ABSENT}:${meter}:${periodUnit}:${periodStart.getTime()}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
new file mode 100644
index 00000000000..2786698c9fe
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-counters.util.ts
@@ -0,0 +1,76 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { SPENDER_TYPE_SPECIFICITY } from 'src/engine/core-modules/usage-limit/constants/spender-type-specificity.constant';
+import { type FlatUsageLimit } from 'src/engine/core-modules/usage-limit/types/flat-usage-limit.type';
+import { type PeriodUnit } from 'src/engine/core-modules/usage-limit/types/period-unit.type';
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { buildQuotaCounterKey } from 'src/engine/core-modules/usage-limit/utils/build-quota-counter-key.util';
+import { buildSpendersFromUsageSpenders } from 'src/engine/core-modules/usage-limit/utils/build-spenders-from-usage-spenders.util';
+import { findLimitsForSpender } from 'src/engine/core-modules/usage-limit/utils/find-limits-for-spender.util';
+import { normalizeSpenderId } from 'src/engine/core-modules/usage-limit/utils/normalize-spender-id.util';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+import { type UsageSpenders } from 'src/engine/core-modules/usage/types/usage-spenders.type';
+
+const counterSpecificity = (counter: LimitQuotaCounter): number =>
+ SPENDER_TYPE_SPECIFICITY[counter.spenderType] * 4 +
+ (isDefined(counter.spenderId) ? 0 : 2) +
+ (counter.operationType === UsageOperationType.ALL ? 1 : 0);
+
+export const buildQuotaCounters = ({
+ limits,
+ usageSpenders,
+ workspaceId,
+ resourceType,
+ operationType,
+ periodByUnit,
+}: {
+ limits: FlatUsageLimit[];
+ usageSpenders: UsageSpenders;
+ workspaceId: string;
+ resourceType: UsageResourceType;
+ operationType: UsageOperationType;
+ periodByUnit: Partial<Record<PeriodUnit, UsagePeriod>>;
+}): LimitQuotaCounter[] => {
+ const spenders = buildSpendersFromUsageSpenders(usageSpenders);
+
+ const counters = spenders.flatMap((spender) =>
+ findLimitsForSpender({ limits, spender, operationType }).flatMap(
+ (limit) => {
+ const period = periodByUnit[limit.periodUnit];
+
+ if (!isDefined(period)) {
+ return [];
+ }
+
+ return [
+ {
+ kind: 'limit' as const,
+ key: buildQuotaCounterKey({
+ workspaceId,
+ resourceType,
+ operationType: limit.operationType,
+ spenderType: limit.spenderType,
+ spenderId: limit.spenderId,
+ meter: limit.meter,
+ periodUnit: limit.periodUnit,
+ periodStart: period.periodStart,
+ }),
+ limitValue: limit.limitValue,
+ meter: limit.meter,
+ resourceType,
+ periodUnit: limit.periodUnit,
+ periodStart: period.periodStart,
+ periodEnd: period.periodEnd,
+ spenderType: limit.spenderType,
+ spenderId: normalizeSpenderId(limit.spenderId),
+ operationType: limit.operationType,
+ },
+ ];
+ },
+ ),
+ );
+
+ return counters.sort((a, b) => counterSpecificity(a) - counterSpecificity(b));
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
new file mode 100644
index 00000000000..1b6c475fe5f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-exhausted-scope.util.ts
@@ -0,0 +1,47 @@
+import { type CreditAllowance } from 'src/engine/core-modules/usage-limit/types/credit-allowance.type';
+import { type ExhaustedScope } from 'src/engine/core-modules/usage-limit/types/exhausted-scope.type';
+import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type UsageResourceType } from 'src/engine/core-modules/usage/enums/usage-resource-type.enum';
+
+export const buildQuotaExhaustedScope = ({
+ resourceType,
+ counter,
+ allowance,
+}: {
+ resourceType: UsageResourceType;
+ counter: QuotaCounter;
+ allowance: CreditAllowance | null;
+}): ExhaustedScope => {
+ const retryAfterMs = Math.max(counter.periodEnd.getTime() - Date.now(), 0);
+
+ if (counter.kind === 'limit') {
+ return {
+ resourceType,
+ limitKind: 'quota',
+ exhaustedKind: 'limit',
+ spenderType: counter.spenderType,
+ spenderId: counter.spenderId,
+ operationType: counter.operationType,
+ limitValue: counter.limitValue,
+ remaining: 0,
+ periodCount: 1,
+ periodUnit: counter.periodUnit,
+ retryAfterMs,
+ };
+ }
+
+ return {
+ resourceType,
+ limitKind: 'quota',
+ exhaustedKind: 'allowance',
+ spenderType: 'workspace',
+ spenderId: null,
+ operationType: UsageOperationType.ALL,
+ limitValue: allowance?.allowanceMicro ?? 0,
+ remaining: 0,
+ periodCount: null,
+ periodUnit: null,
+ retryAfterMs,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util.ts
new file mode 100644
index 00000000000..f36d476de10
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/build-quota-warm-lock-key.util.ts
@@ -0,0 +1,2 @@
+export const buildQuotaWarmLockKey = (workspaceId: string): string =>
+ `usage-quota-warm:${workspaceId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
new file mode 100644
index 00000000000..6f5888a440b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/compute-quota-consumed.util.ts
@@ -0,0 +1,53 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+
+import { type LimitQuotaCounter } from 'src/engine/core-modules/usage-limit/types/limit-quota-counter.type';
+import { type QuotaConsumptionRow } from 'src/engine/core-modules/usage-limit/types/quota-consumption-row.type';
+
+const spenderColumnMatches = (
+ rowValue: string,
+ spenderId: string | null,
+): boolean =>
+ isDefined(spenderId) ? rowValue === spenderId : isNonEmptyString(rowValue);
+
+const rowMatchesCounter = (
+ row: QuotaConsumptionRow,
+ counter: LimitQuotaCounter,
+): boolean => {
+ if (
+ counter.operationType !== UsageOperationType.ALL &&
+ row.operationType !== counter.operationType
+ ) {
+ return false;
+ }
+
+ switch (counter.spenderType) {
+ case 'workspace':
+ return true;
+ case 'userWorkspace':
+ return spenderColumnMatches(row.userWorkspaceId, counter.spenderId);
+ case 'apiKey':
+ return spenderColumnMatches(row.apiKeyId, counter.spenderId);
+ case 'application':
+ return spenderColumnMatches(row.applicationId, counter.spenderId);
+ case 'agent':
+ return spenderColumnMatches(row.agentId, counter.spenderId);
+ case 'workflow':
+ return spenderColumnMatches(row.workflowId, counter.spenderId);
+ case 'logicFunction':
+ return spenderColumnMatches(row.logicFunctionId, counter.spenderId);
+ }
+};
+
+export const computeQuotaConsumed = ({
+ rows,
+ counter,
+}: {
+ rows: QuotaConsumptionRow[];
+ counter: LimitQuotaCounter;
+}): number =>
+ rows
+ .filter((row) => rowMatchesCounter(row, counter))
+ .reduce((total, row) => total + Number(row[counter.meter]), 0);
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util.ts
new file mode 100644
index 00000000000..f9edbbf376d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-credit-allowance-provider.util.ts
@@ -0,0 +1,19 @@
+import { type DiscoveryService } from '@nestjs/core';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { CreditAllowanceProvider } from 'src/engine/core-modules/usage-limit/interfaces/credit-allowance-provider.service';
+
+export const findCreditAllowanceProvider = (
+ discoveryService: DiscoveryService,
+): CreditAllowanceProvider | null => {
+ for (const wrapper of discoveryService.getProviders()) {
+ const { instance } = wrapper;
+
+ if (isDefined(instance) && instance instanceof CreditAllowanceProvider) {
+ return instance;
+ }
+ }
+
+ return null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util.ts
new file mode 100644
index 00000000000..dc9f320acfd
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/find-exhausted-counter.util.ts
@@ -0,0 +1,17 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type QuotaCounter } from 'src/engine/core-modules/usage-limit/types/quota-counter.type';
+
+export const findExhaustedCounter = ({
+ counters,
+ remainings,
+}: {
+ counters: QuotaCounter[];
+ remainings: (number | null)[];
+}): QuotaCounter | null => {
+ const exhaustedIndex = remainings.findIndex(
+ (remaining) => isDefined(remaining) && remaining <= 0,
+ );
+
+ return exhaustedIndex === -1 ? null : counters[exhaustedIndex];
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util.ts
new file mode 100644
index 00000000000..d0608170191
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/from-consume-results-to-remainings.util.ts
@@ -0,0 +1,8 @@
+// The consume script answers [existed, remaining] pairs, one per counter key;
+// a counter that did not exist was not debited and stays cold (null).
+export const fromConsumeResultsToRemainings = (
+ consumeResults: number[],
+): (number | null)[] =>
+ Array.from({ length: consumeResults.length / 2 }, (_, index) =>
+ consumeResults[2 * index] === 1 ? consumeResults[2 * index + 1] : null,
+ );
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-day-period.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-day-period.util.ts
new file mode 100644
index 00000000000..378cd2da1f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-day-period.util.ts
@@ -0,0 +1,12 @@
+/* @license Enterprise */
+
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+
+export const getCalendarDayPeriod = (now: Date): UsagePeriod => ({
+ periodStart: new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()),
+ ),
+ periodEnd: new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1),
+ ),
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-month-period.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-month-period.util.ts
new file mode 100644
index 00000000000..ed570b86ce7
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-month-period.util.ts
@@ -0,0 +1,8 @@
+/* @license Enterprise */
+
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+
+export const getCalendarMonthPeriod = (now: Date): UsagePeriod => ({
+ periodStart: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)),
+ periodEnd: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)),
+});
diff --git a/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-week-period.util.ts b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-week-period.util.ts
new file mode 100644
index 00000000000..dd6d027b42f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/usage-limit/utils/get-calendar-week-period.util.ts
@@ -0,0 +1,24 @@
+/* @license Enterprise */
+
+import { type UsagePeriod } from 'src/engine/core-modules/usage-limit/types/usage-period.type';
+
+export const getCalendarWeekPeriod = (now: Date): UsagePeriod => {
+ const daysSinceMonday = (now.getUTCDay() + 6) % 7;
+
+ return {
+ periodStart: new Date(
+ Date.UTC(
+ now.getUTCFullYear(),
+ now.getUTCMonth(),
+ now.getUTCDate() - daysSinceMonday,
+ ),
+ ),
+ periodEnd: new Date(
+ Date.UTC(
+ now.getUTCFullYear(),
+ now.getUTCMonth(),
+ now.getUTCDate() - daysSinceMonday + 7,
+ ),
+ ),
+ };
+};