Skip to content

The open alternative to Salesforce, designed for AI.

Bill logic function executions for duration like AWS Lambda (#24938)

martmull80af0155c304
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 1bb51c453ba..c8e7cd56387 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -79,6 +79,10 @@ yarn twenty dev:function:logs
```
</Note>
+<Note>
+On the cloud, each run consumes workspace credits: a flat charge per invocation plus a per-millisecond charge for the time the function runs, so keeping `timeoutSeconds` tight and code fast keeps costs down. See [Credits](/user-guide/billing/capabilities/credits) for the rates.
+</Note>
+
#### Route trigger payload
When a route trigger invokes your logic function, it receives a `RoutePayload` object that follows the
diff --git a/packages/twenty-docs/user-guide/billing/capabilities/credits.mdx b/packages/twenty-docs/user-guide/billing/capabilities/credits.mdx
index 0a3ec86a7c2..7cddb85a51d 100644
--- a/packages/twenty-docs/user-guide/billing/capabilities/credits.mdx
+++ b/packages/twenty-docs/user-guide/billing/capabilities/credits.mdx
@@ -15,7 +15,8 @@ Cost scales with the work. Everyday automation and quick AI messages cost a tiny
| What you do | Roughly costs | What that means |
|-------------|---------------|-----------------|
-| Run a standard workflow step (search, create, or update records) or trigger an app's logic function | $0.0001 | **10,000 runs per credit** |
+| Run a standard workflow step (search, create, or update records) | $0.0001 | **10,000 runs per credit** |
+| Trigger an app's logic function | $0.0001 + $0.0001 per second of runtime | **Thousands of runs per credit** |
| Call an external API or run a code node | A small fraction of a credit | Thousands per credit |
| Send a quick AI chat message or simple AI step | A fraction of a cent | Hundreds per credit |
| Run a large AI agent task (e.g. "configure 10 workspace objects") | Can run to **~$1 or more** | A few per credit |
@@ -29,6 +30,15 @@ For most teams, standard automations are effectively free — you'll only make a
Not every app charges for its runs. Call Recorder and Last Contact react to every email and calendar event imported into your workspace, so their logic function runs are free. You are still charged for the metered work they do, such as recorded call minutes.
</Note>
+## How logic function runs are metered
+
+Logic function pricing mirrors AWS Lambda: a flat charge per invocation plus a duration charge for the time your code actually runs, billed per millisecond.
+
+- **Per invocation**: $0.0001
+- **Per duration**: $0.0001 per second of runtime ($0.0000001 per millisecond)
+
+A typical function that finishes in under a second costs at most double the flat invocation charge. Long-running functions pay for the compute they use: a function running for a full minute adds $0.006, and one hitting the 15-minute timeout adds $0.09. A function that times out is billed for its full elapsed time, just like on AWS.
+
## How AI usage is metered
When an action calls an AI model, we measure the exact tokens used and price them at **the model provider's published rates**, then convert that dollar amount straight into credits — so what you spend tracks the real cost of the work, not a marked-up internal rate. A short chat message costs a fraction of a cent. A large agent task — say, configuring 10 workspace objects — makes many model calls over a growing context, so it can add up to a dollar or more. You're billed for what you actually use, down to the token.
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts
index f482c7edf59..79972f7d00c 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda.driver.ts
@@ -202,7 +202,7 @@ export class LambdaDriver implements LogicFunctionDriver {
const result = await lambdaClient.send(command, {
abortSignal: AbortSignal.timeout(timeoutMs),
});
- const invokeSendMs = Date.now() - invokeStart;
+ const invokeDurationMs = Date.now() - invokeStart;
const parsedResult = result.Payload
? JSON.parse(result.Payload.transformToString())
@@ -211,7 +211,7 @@ export class LambdaDriver implements LogicFunctionDriver {
const {
logs,
initDurationMs,
- billedDurationMs,
+ billedDurationMs: awsBilledDurationMs,
reportDurationMs,
coldStart,
} = parseLambdaLogResult(result.LogResult);
@@ -219,13 +219,14 @@ export class LambdaDriver implements LogicFunctionDriver {
const duration = Date.now() - invokeFlowStart;
this.logger.log(
- `[lambda-timing] fnId=${flatLogicFunction.id} executionMode=${executionMode} totalMs=${Date.now() - buildStart} buildExecutorMs=${buildExecutorMs} getBuiltCodeMs=${getBuiltCodeMs} payloadBytes=${Buffer.byteLength(payloadString, 'utf8')} invokeSendMs=${invokeSendMs} reportDurationMs=${reportDurationMs ?? 'n/a'} billedMs=${billedDurationMs ?? 'n/a'} initDurationMs=${initDurationMs ?? 'n/a'} coldStart=${coldStart}`,
+ `[lambda-timing] fnId=${flatLogicFunction.id} executionMode=${executionMode} totalMs=${Date.now() - buildStart} buildExecutorMs=${buildExecutorMs} getBuiltCodeMs=${getBuiltCodeMs} payloadBytes=${Buffer.byteLength(payloadString, 'utf8')} invokeDurationMs=${invokeDurationMs} reportDurationMs=${reportDurationMs ?? 'n/a'} awsBilledDurationMs=${awsBilledDurationMs ?? 'n/a'} initDurationMs=${initDurationMs ?? 'n/a'} coldStart=${coldStart}`,
);
if (result.FunctionError) {
return {
data: null,
duration,
+ billedDurationMs: invokeDurationMs,
status: LogicFunctionExecutionStatus.ERROR,
error: parsedResult,
logs,
@@ -236,6 +237,7 @@ export class LambdaDriver implements LogicFunctionDriver {
data: parsedResult,
logs,
duration,
+ billedDurationMs: invokeDurationMs,
status: LogicFunctionExecutionStatus.SUCCESS,
};
} catch (error) {
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/utils/build-logic-function-timeout-result.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/utils/build-logic-function-timeout-result.util.ts
index 79b48699ea1..4d5d9541391 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/utils/build-logic-function-timeout-result.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/utils/build-logic-function-timeout-result.util.ts
@@ -7,6 +7,7 @@ export const buildLogicFunctionTimeoutResult = (
data: null,
logs: '',
duration: timeoutMs,
+ billedDurationMs: timeoutMs,
status: LogicFunctionExecutionStatus.ERROR,
error: {
errorType: 'TimeoutError',
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts
index 12a99d85b2a..2ab284d4006 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/drivers/local.driver.ts
@@ -230,6 +230,7 @@ export class LocalDriver implements LogicFunctionDriver {
data: (result ?? null) as object | null,
logs,
duration,
+ billedDurationMs: duration,
status: LogicFunctionExecutionStatus.SUCCESS,
};
}
@@ -238,6 +239,7 @@ export class LocalDriver implements LogicFunctionDriver {
data: null,
logs,
duration,
+ billedDurationMs: duration,
error: {
errorType: errorType ?? 'UnhandledError',
errorMessage: error || 'Unknown error',
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts
index fce5ffabecd..a4da7c3e760 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface.ts
@@ -14,6 +14,7 @@ export type LogicFunctionExecuteError = {
export type LogicFunctionExecuteResult = {
data: object | null;
duration: number;
+ billedDurationMs: number;
logs: string;
status: LogicFunctionExecutionStatus;
error?: LogicFunctionExecuteError;
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/constants/logic-function-billing.constant.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/constants/logic-function-billing.constant.ts
new file mode 100644
index 00000000000..d59364e39c3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/constants/logic-function-billing.constant.ts
@@ -0,0 +1,5 @@
+// Flat charge per invocation: $0.0001 (1 micro credit = $0.000001).
+export const LOGIC_FUNCTION_INVOCATION_CREDITS_MICRO = 100;
+
+// Charge per seconds: $0.0001
+export const LOGIC_FUNCTION_DURATION_CREDITS_MICRO_PER_MS = 0.1;
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index 8ac5f74c827..b9a7221d502 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -41,6 +41,7 @@ import { BillingService } from 'src/engine/core-modules/billing/services/billing
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { LogicFunctionDriverFactory } from 'src/engine/core-modules/logic-function/logic-function-drivers/logic-function-driver.factory';
+import { computeLogicFunctionExecutionCreditsMicro } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
@@ -598,14 +599,18 @@ export class LogicFunctionExecutorService {
// Billing-exempt apps (first-party maintenance apps whose per-record
// triggers fire during mailbox/calendar import) do not consume the
- // workspace's credits for the invocation itself. Explicit chargeCredits
+ // workspace's credits for the execution itself. Explicit chargeCredits
// calls and AI token usage from within the function are billed separately
// and stay untouched.
- const creditsUsedMicro = isBillingExemptApplication(
- flatApplication.universalIdentifier,
- )
- ? 0
- : 100;
+ const { invocationCreditsMicro, durationCreditsMicro, billedDurationMs } =
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: result.billedDurationMs,
+ isBillingExempt: isBillingExemptApplication(
+ flatApplication.universalIdentifier,
+ ),
+ });
+
+ const totalCreditsMicro = invocationCreditsMicro + durationCreditsMicro;
let periodStart: Date | undefined;
@@ -618,10 +623,10 @@ export class LogicFunctionExecutorService {
if (currentBillingSubscription !== NO_BILLING_SUBSCRIPTION) {
periodStart = currentBillingSubscription.currentPeriodStart;
- if (creditsUsedMicro > 0) {
+ if (totalCreditsMicro > 0) {
await this.billingUsageService.decrementAvailableCreditsInCache({
workspaceId,
- usedCredits: creditsUsedMicro,
+ usedCredits: totalCreditsMicro,
});
}
}
@@ -633,12 +638,21 @@ export class LogicFunctionExecutorService {
{
resourceType: UsageResourceType.LOGIC_FUNCTION,
operationType: UsageOperationType.CODE_EXECUTION,
- creditsUsedMicro,
+ creditsUsedMicro: invocationCreditsMicro,
quantity: 1,
unit: UsageUnit.INVOCATION,
resourceId: flatLogicFunction.id,
periodStart,
},
+ {
+ resourceType: UsageResourceType.LOGIC_FUNCTION,
+ operationType: UsageOperationType.CODE_EXECUTION,
+ creditsUsedMicro: durationCreditsMicro,
+ quantity: billedDurationMs,
+ unit: UsageUnit.MILLISECOND,
+ resourceId: flatLogicFunction.id,
+ periodStart,
+ },
],
workspaceId,
);
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/compute-logic-function-execution-credits-micro.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/compute-logic-function-execution-credits-micro.util.spec.ts
new file mode 100644
index 00000000000..2c480f0f39f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/compute-logic-function-execution-credits-micro.util.spec.ts
@@ -0,0 +1,90 @@
+import { computeLogicFunctionExecutionCreditsMicro } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util';
+
+describe('computeLogicFunctionExecutionCreditsMicro', () => {
+ it('charges the flat invocation fee plus duration', () => {
+ expect(
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: 1_000,
+ isBillingExempt: false,
+ }),
+ ).toEqual({
+ invocationCreditsMicro: 100,
+ durationCreditsMicro: 100,
+ billedDurationMs: 1_000,
+ });
+ });
+
+ it('rounds duration credits down to the previous micro credit', () => {
+ expect(
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: 9,
+ isBillingExempt: false,
+ }),
+ ).toEqual({
+ invocationCreditsMicro: 100,
+ durationCreditsMicro: 0,
+ billedDurationMs: 9,
+ });
+
+ expect(
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: 155,
+ isBillingExempt: false,
+ }),
+ ).toEqual({
+ invocationCreditsMicro: 100,
+ durationCreditsMicro: 15,
+ billedDurationMs: 155,
+ });
+ });
+
+ it('charges no duration credits for a zero or negative duration', () => {
+ expect(
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: 0,
+ isBillingExempt: false,
+ }),
+ ).toEqual({
+ invocationCreditsMicro: 100,
+ durationCreditsMicro: 0,
+ billedDurationMs: 0,
+ });
+
+ expect(
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: -5,
+ isBillingExempt: false,
+ }),
+ ).toEqual({
+ invocationCreditsMicro: 100,
+ durationCreditsMicro: 0,
+ billedDurationMs: 0,
+ });
+ });
+
+ it('bills the full timeout duration of a timed out execution', () => {
+ expect(
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: 900_000,
+ isBillingExempt: false,
+ }),
+ ).toEqual({
+ invocationCreditsMicro: 100,
+ durationCreditsMicro: 90_000,
+ billedDurationMs: 900_000,
+ });
+ });
+
+ it('charges nothing for billing-exempt applications', () => {
+ expect(
+ computeLogicFunctionExecutionCreditsMicro({
+ durationMs: 5_000,
+ isBillingExempt: true,
+ }),
+ ).toEqual({
+ invocationCreditsMicro: 0,
+ durationCreditsMicro: 0,
+ billedDurationMs: 0,
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util.ts
new file mode 100644
index 00000000000..7a2cabe4958
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/compute-logic-function-execution-credits-micro.util.ts
@@ -0,0 +1,34 @@
+import {
+ LOGIC_FUNCTION_DURATION_CREDITS_MICRO_PER_MS,
+ LOGIC_FUNCTION_INVOCATION_CREDITS_MICRO,
+} from 'src/engine/core-modules/logic-function/logic-function-executor/constants/logic-function-billing.constant';
+
+export const computeLogicFunctionExecutionCreditsMicro = ({
+ durationMs,
+ isBillingExempt,
+}: {
+ durationMs: number;
+ isBillingExempt: boolean;
+}): {
+ invocationCreditsMicro: number;
+ durationCreditsMicro: number;
+ billedDurationMs: number;
+} => {
+ if (isBillingExempt) {
+ return {
+ invocationCreditsMicro: 0,
+ durationCreditsMicro: 0,
+ billedDurationMs: 0,
+ };
+ }
+
+ const billedDurationMs = Math.max(Math.floor(durationMs), 0);
+
+ return {
+ invocationCreditsMicro: LOGIC_FUNCTION_INVOCATION_CREDITS_MICRO,
+ durationCreditsMicro: Math.floor(
+ billedDurationMs * LOGIC_FUNCTION_DURATION_CREDITS_MICRO_PER_MS,
+ ),
+ billedDurationMs,
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
index 4df51c8349f..b5014726067 100644
--- a/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/usage/enums/usage-unit.enum.ts
@@ -5,6 +5,7 @@ export enum UsageUnit {
TOKEN = 'TOKEN',
INVOCATION = 'INVOCATION',
MINUTE = 'MINUTE',
+ MILLISECOND = 'MILLISECOND',
BYTE = 'BYTE',
REQUEST = 'REQUEST',
}
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/application-uninstall-retry.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/application-uninstall-retry.integration-spec.ts
index cb86deaa09e..c7e9e2ba763 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/application-uninstall-retry.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/application-uninstall-retry.integration-spec.ts
@@ -28,6 +28,7 @@ type InstalledApplication = {
const SUCCESSFUL_EXECUTION_RESULT = {
data: {},
duration: 1,
+ billedDurationMs: 1,
logs: '',
status: LogicFunctionExecutionStatus.SUCCESS,
};
@@ -35,6 +36,7 @@ const SUCCESSFUL_EXECUTION_RESULT = {
const FAILED_EXECUTION_RESULT = {
data: null,
duration: 1,
+ billedDurationMs: 1,
logs: '',
status: LogicFunctionExecutionStatus.ERROR,
error: {
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts
index 59cb5a612ec..4639421449f 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-uninstall-application-logic-function-hook.integration-spec.ts
@@ -113,6 +113,7 @@ describe('Uninstall application logic function hook', () => {
.mockResolvedValue({
data: {},
duration: 1,
+ billedDurationMs: 1,
logs: '',
status: LogicFunctionExecutionStatus.SUCCESS,
});
@@ -241,6 +242,7 @@ describe('Uninstall application logic function hook', () => {
executeSpy.mockResolvedValue({
data: null,
duration: 1,
+ billedDurationMs: 1,
logs: '',
status: LogicFunctionExecutionStatus.ERROR,
error: {
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/workspace-deletion-runs-uninstall-hooks.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/workspace-deletion-runs-uninstall-hooks.integration-spec.ts
index 3d271f58278..15ffad7347d 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/workspace-deletion-runs-uninstall-hooks.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/workspace-deletion-runs-uninstall-hooks.integration-spec.ts
@@ -83,6 +83,7 @@ describe('Workspace deletion runs application uninstall hooks', () => {
.mockResolvedValue({
data: {},
duration: 1,
+ billedDurationMs: 1,
logs: '',
status: LogicFunctionExecutionStatus.SUCCESS,
});