Skip to content

🎥 Make videos programmatically with React

Fix Lambda cost estimate (#9005)

Jonny Burgerf1a07cd16458
diff --git a/packages/serverless-client/src/calculate-billing-duration.ts b/packages/serverless-client/src/calculate-billing-duration.ts
new file mode 100644
index 0000000000..c5a13e1c20
--- /dev/null
+++ b/packages/serverless-client/src/calculate-billing-duration.ts
@@ -0,0 +1,20 @@
+import {OVERHEAD_TIME_PER_LAMBDA} from './most-expensive-chunks';
+import type {ParsedTiming} from './types';
+
+export const calculateBillingDuration = ({
+ timings,
+ functionsInvoked,
+ elapsedTimeOfUnfinishedChunks,
+}: {
+ timings: ParsedTiming[];
+ functionsInvoked: number;
+ elapsedTimeOfUnfinishedChunks: number;
+}) => {
+ const completedChunksDuration = timings
+ .map((p) => Math.max(0, p.rendered - p.start) + OVERHEAD_TIME_PER_LAMBDA)
+ .reduce((a, b) => a + b, 0);
+
+ const unfinished = Math.max(0, functionsInvoked - timings.length);
+
+ return completedChunksDuration + unfinished * elapsedTimeOfUnfinishedChunks;
+};
diff --git a/packages/serverless-client/src/estimate-price-from-bucket.ts b/packages/serverless-client/src/estimate-price-from-bucket.ts
index 0550ad85a4..73e82a053b 100644
--- a/packages/serverless-client/src/estimate-price-from-bucket.ts
+++ b/packages/serverless-client/src/estimate-price-from-bucket.ts
@@ -1,4 +1,4 @@
-import {calculateChunkTimes} from './calculate-chunk-times';
+import {calculateBillingDuration} from './calculate-billing-duration';
import type {ProviderSpecifics} from './provider-implementation';
import type {RenderMetadata} from './render-metadata';
import type {CloudProvider, ParsedTiming} from './types';
@@ -28,20 +28,12 @@ export const estimatePriceFromMetadata = <Provider extends CloudProvider>({
const now = fatalErrorTimestamp ?? Date.now();
const elapsedTime = Math.max(0, now - (renderMetadata?.startedDate ?? 0));
- const unfinished = Math.max(
- 0,
- (renderMetadata?.totalChunks ?? 0) - timings.length,
- );
- const timeElapsedOfUnfinished = new Array(unfinished)
- .fill(true)
- .map(() => elapsedTime)
- .reduce((a, b) => a + b, 0);
- const estimatedBillingDurationInMilliseconds =
- calculateChunkTimes({
- type: 'combined-time-for-cost-calculation',
- timings,
- }) + timeElapsedOfUnfinished;
+ const estimatedBillingDurationInMilliseconds = calculateBillingDuration({
+ timings,
+ functionsInvoked,
+ elapsedTimeOfUnfinishedChunks: elapsedTime,
+ });
const accruedSoFar = Number(
providerSpecifics
diff --git a/packages/serverless-client/src/index.ts b/packages/serverless-client/src/index.ts
index a4c165c55c..7c919e893c 100644
--- a/packages/serverless-client/src/index.ts
+++ b/packages/serverless-client/src/index.ts
@@ -55,6 +55,7 @@ export type {_InternalTypes} from 'remotion';
export type {DownloadBehavior, VideoConfig} from 'remotion/no-react';
export {VERSION} from 'remotion/version';
export {Await} from './await';
+export {calculateBillingDuration} from './calculate-billing-duration';
export {calculateChunkTimes} from './calculate-chunk-times';
export {
compressInputProps,
diff --git a/packages/serverless-client/src/progress.ts b/packages/serverless-client/src/progress.ts
index cabd89bef9..87dfc665f5 100644
--- a/packages/serverless-client/src/progress.ts
+++ b/packages/serverless-client/src/progress.ts
@@ -205,7 +205,7 @@ export const getProgress = async <Provider extends CloudProvider>({
memorySizeInMb:
providerSpecifics.parseFunctionName(renderMetadata.rendererFunctionName)
?.memorySizeInMb ?? memorySizeInMb,
- functionsInvoked: renderMetadata.estimatedRenderLambdaInvokations ?? 0,
+ functionsInvoked: overallProgress.lambdasInvoked ?? 0,
diskSizeInMb: providerSpecifics.getEphemeralStorageForPriceCalculation(),
timings: overallProgress.timings ?? [],
region,
diff --git a/packages/serverless-client/src/test/calculate-billing-duration.test.ts b/packages/serverless-client/src/test/calculate-billing-duration.test.ts
new file mode 100644
index 0000000000..45dcc8e3bb
--- /dev/null
+++ b/packages/serverless-client/src/test/calculate-billing-duration.test.ts
@@ -0,0 +1,36 @@
+import {expect, test} from 'bun:test';
+import {calculateBillingDuration} from '../calculate-billing-duration';
+import {OVERHEAD_TIME_PER_LAMBDA} from '../most-expensive-chunks';
+
+test('calculates billing duration for completed chunks with lambda overhead', () => {
+ expect(
+ calculateBillingDuration({
+ timings: [
+ {chunk: 0, start: 1000, rendered: 1500},
+ {chunk: 1, start: 1200, rendered: 2000},
+ ],
+ functionsInvoked: 2,
+ elapsedTimeOfUnfinishedChunks: 10000,
+ }),
+ ).toBe(500 + OVERHEAD_TIME_PER_LAMBDA + 800 + OVERHEAD_TIME_PER_LAMBDA);
+});
+
+test('only estimates unfinished duration for lambdas that have been invoked', () => {
+ expect(
+ calculateBillingDuration({
+ timings: [{chunk: 0, start: 1000, rendered: 1500}],
+ functionsInvoked: 2,
+ elapsedTimeOfUnfinishedChunks: 10000,
+ }),
+ ).toBe(500 + OVERHEAD_TIME_PER_LAMBDA + 10000);
+});
+
+test('does not charge for chunks that have not been invoked yet', () => {
+ expect(
+ calculateBillingDuration({
+ timings: [],
+ functionsInvoked: 1,
+ elapsedTimeOfUnfinishedChunks: 10000,
+ }),
+ ).toBe(10000);
+});
diff --git a/packages/serverless-client/src/test/progress.test.ts b/packages/serverless-client/src/test/progress.test.ts
index e9eafe3de2..073295df53 100644
--- a/packages/serverless-client/src/test/progress.test.ts
+++ b/packages/serverless-client/src/test/progress.test.ts
@@ -4,7 +4,10 @@ import {overallProgressKey} from '../constants';
import {getExpectedOutName} from '../expected-out-name';
import type {OverallRenderProgress} from '../overall-render-progress';
import {getProgress} from '../progress';
-import type {ProviderSpecifics} from '../provider-implementation';
+import type {
+ EstimatePriceInput,
+ ProviderSpecifics,
+} from '../provider-implementation';
import type {RenderMetadata} from '../render-metadata';
import type {CloudProvider} from '../types';
@@ -88,8 +91,10 @@ const progress: OverallRenderProgress<MockProvider> = {
};
const makeProviderSpecifics = ({
+ onEstimatePrice,
onHeadFile,
}: {
+ onEstimatePrice?: (input: EstimatePriceInput<MockProvider>) => number;
onHeadFile: ProviderSpecifics<MockProvider>['headFile'];
}): ProviderSpecifics<MockProvider> => {
return {
@@ -103,7 +108,7 @@ const makeProviderSpecifics = ({
createBucket: () => Promise.resolve(),
deleteFile: () => Promise.resolve(),
deleteFunction: () => Promise.resolve(),
- estimatePrice: () => 0.01,
+ estimatePrice: (input) => onEstimatePrice?.(input) ?? 0.01,
getAccountId: () => Promise.resolve('123456789012'),
getBucketPrefix: () => 'remotionlambda-',
getBuckets: () => Promise.resolve([]),
@@ -186,3 +191,48 @@ test('getProgress treats an existing output file as finished if postRenderData w
expect(renderProgress.outputSizeInBytes).toBe(1234);
expect(renderProgress.errors).toEqual([]);
});
+
+test('getProgress estimates costs from invoked lambdas only', async () => {
+ const priceInputs: EstimatePriceInput<MockProvider>[] = [];
+ const originalTimings = progress.timings;
+ const originalChunks = progress.chunks;
+ const originalLambdasInvoked = progress.lambdasInvoked;
+
+ try {
+ progress.timings = [];
+ progress.chunks = [];
+ progress.lambdasInvoked = 1;
+
+ const providerSpecifics = makeProviderSpecifics({
+ onEstimatePrice: (input) => {
+ priceInputs.push(input);
+ return input.durationInMilliseconds;
+ },
+ onHeadFile: () => Promise.resolve({ContentLength: 0}),
+ });
+
+ const renderProgress = await getProgress({
+ bucketName,
+ customCredentials: null,
+ expectedBucketOwner: null,
+ forcePathStyle: false,
+ functionName: renderMetadata.functionName,
+ memorySizeInMb: 2048,
+ providerSpecifics,
+ region: 'eu-central-1',
+ renderId,
+ requestHandler: null,
+ timeoutInMilliseconds: 120000,
+ });
+
+ expect(priceInputs).toHaveLength(1);
+ expect(priceInputs[0].lambdasInvoked).toBe(1);
+ expect(renderProgress.estimatedBillingDurationInMilliseconds).toBeLessThan(
+ 60000,
+ );
+ } finally {
+ progress.timings = originalTimings;
+ progress.chunks = originalChunks;
+ progress.lambdasInvoked = originalLambdasInvoked;
+ }
+});
diff --git a/packages/serverless/src/create-post-render-data.ts b/packages/serverless/src/create-post-render-data.ts
index dc838e8621..5e3e2d7957 100644
--- a/packages/serverless/src/create-post-render-data.ts
+++ b/packages/serverless/src/create-post-render-data.ts
@@ -7,9 +7,9 @@ import type {
RenderMetadata,
} from '@remotion/serverless-client';
import {
+ calculateBillingDuration,
calculateChunkTimes,
getMostExpensiveChunks,
- OVERHEAD_TIME_PER_LAMBDA,
} from '@remotion/serverless-client';
import type {OutputFileMetadata} from './find-output-file-in-bucket';
@@ -40,9 +40,11 @@ export const createPostRenderData = <Provider extends CloudProvider>({
}): PostRenderData<Provider> => {
const parsedTimings = overallProgress.timings;
- const estimatedBillingDurationInMilliseconds = parsedTimings
- .map((p) => p.rendered - p.start + OVERHEAD_TIME_PER_LAMBDA)
- .reduce((a, b) => a + b);
+ const estimatedBillingDurationInMilliseconds = calculateBillingDuration({
+ timings: parsedTimings,
+ functionsInvoked: parsedTimings.length,
+ elapsedTimeOfUnfinishedChunks: 0,
+ });
const cost = providerSpecifics.estimatePrice({
durationInMilliseconds: estimatedBillingDurationInMilliseconds,