# Remotion Lambda

> ---

- Skill: `dinaf2026-web/remotion-lambda` (Agent Skill)
- Install (CLI): `npx get-skill add dinaf2026-web/remotion-lambda`
- Raw SKILL.md: https://api.skillmd.com/api/skills/dinaf2026-web/remotion-lambda/raw
- Safety review: pending (external: skill-scanner PASS, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: dinaf2026-web (https://skillmd.com/u/dinaf2026-web)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/dinaf2026-web/remotion-lambda

---

---
name: remotion-lambda
description: Production video rendering with Remotion Lambda — AWS setup, deploy, render at scale, progress tracking, S3 output, cost estimation, and CI/CD integration.
origin: community
tags: [remotion, lambda, aws, rendering, production, s3, serverless]
---

# remotion-lambda

Production video rendering with Remotion Lambda. Covers AWS setup, function deployment, render triggering, progress polling, S3 output retrieval, cost estimation, webhook patterns, CI/CD integration, error handling, and cleanup.

---

## 1. When to Use Lambda vs Local Rendering

| Factor | Local (`renderMedia`) | Lambda (`renderMediaOnLambda`) |
|---|---|---|
| Video length | < 2 min | Any length |
| Concurrency needed | 1 render at a time | Hundreds in parallel |
| Server infra | Required (long-running) | None (serverless) |
| Cold start latency | None | ~3-8 s first render |
| Cost model | Fixed server cost | Pay-per-second |
| CI/CD rendering | Slow, blocks pipeline | Fast, async |
| Development/preview | Best choice | Overkill |
| Frame count > 500 | Possible but slow | Recommended |
| Budget per render | Free (your CPU) | ~$0.003-$0.05 typical |

**Decision rule:**
- Local for dev, previews, and short clips in non-concurrent environments.
- Lambda for production, user-triggered renders, batch jobs, and anything requiring horizontal scale.

---

## 2. AWS Setup

### 2.1 Install CLI and SDK

```bash
npm install @remotion/lambda
npx remotion lambda policies validate   # prints required IAM JSON
```

### 2.2 IAM User for Remotion CLI

Create an IAM user (`remotion-cli`) with **programmatic access** only. Attach the following inline policy (generated by `npx remotion lambda policies print`):

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "0",
      "Effect": "Allow",
      "Action": ["s3:*"],
      "Resource": [
        "arn:aws:s3:::remotionlambda-*",
        "arn:aws:s3:::remotionlambda-*/*"
      ]
    },
    {
      "Sid": "1",
      "Effect": "Allow",
      "Action": [
        "lambda:CreateFunction",
        "lambda:ListFunctions",
        "lambda:InvokeFunction",
        "lambda:GetFunction",
        "lambda:DeleteFunction",
        "lambda:UpdateFunctionCode",
        "lambda:UpdateFunctionConfiguration",
        "lambda:PutFunctionEventInvokeConfig"
      ],
      "Resource": ["arn:aws:lambda:*:*:function:remotion-render-*"]
    },
    {
      "Sid": "2",
      "Effect": "Allow",
      "Action": [
        "iam:GetRole",
        "iam:PassRole",
        "iam:CreateRole",
        "iam:AttachRolePolicy",
        "iam:PutRolePolicy"
      ],
      "Resource": ["arn:aws:iam::*:role/remotion-lambda-role"]
    },
    {
      "Sid": "3",
      "Effect": "Allow",
      "Action": ["logs:*"],
      "Resource": ["arn:aws:logs:*:*:log-group:/aws/lambda/remotion-render-*"]
    }
  ]
}
```

### 2.3 Lambda Execution Role

The Lambda function itself needs a role with:

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::remotionlambda-*",
        "arn:aws:s3:::remotionlambda-*/*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": ["lambda:InvokeFunction"],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "*"
    }
  ]
}
```

Create this role automatically:

```bash
npx remotion lambda roles create
```

### 2.4 Region Selection

```bash
# Prefer regions with lowest Lambda + S3 pricing:
# us-east-1, us-west-2, eu-west-1

export AWS_REGION=us-east-1
export AWS_ACCESS_KEY_ID=your_key
export AWS_SECRET_ACCESS_KEY=your_secret
```

Store in `.env` (never commit):

```bash
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=AKIA...
AWS_SECRET_ACCESS_KEY=...
REMOTION_LAMBDA_FUNCTION_NAME=remotion-render-4-0-272-mem3000mb-disk2048mb-240sec
REMOTION_SERVE_URL=https://remotionlambda-xxxx.s3.us-east-1.amazonaws.com/sites/my-site/index.html
```

---

## 3. Lambda Function Deploy

```typescript
// scripts/deploy-lambda.ts
import {
  deployFunction,
  getOrCreateBucket,
  deploySite,
  getSites,
} from "@remotion/lambda";
import { bundle } from "@remotion/bundler";
import path from "path";

const REGION = process.env.AWS_REGION ?? "us-east-1";

async function deploy() {
  const { bucketName } = await getOrCreateBucket({ region: REGION });
  console.log("Bucket:", bucketName);

  const { functionName, alreadyExisted } = await deployFunction({
    region: REGION,
    timeoutInSeconds: 240,
    memorySizeInMb: 3009,
    diskSizeInMb: 10240,
    createCloudWatchLogGroup: true,
  });

  console.log(
    alreadyExisted ? "Function already deployed:" : "Deployed function:",
    functionName
  );

  const bundleLocation = await bundle({
    entryPoint: path.resolve("./src/index.ts"),
    webpackOverride: (config) => config,
  });

  const { serveUrl } = await deploySite({
    bucketName,
    entryPoint: bundleLocation,
    region: REGION,
    siteName: "my-site",
  });

  console.log("Serve URL:", serveUrl);

  const { sites } = await getSites({ region: REGION, bucketName });
  console.log("All sites:", sites.map((s) => ({ id: s.id, serveUrl: s.serveUrl })));

  return { functionName, serveUrl };
}

deploy().catch(console.error);
```

---

## 4. Triggering a Render

```typescript
// src/render/trigger.ts
import { renderMediaOnLambda, RenderMediaOnLambdaInput } from "@remotion/lambda";

interface RenderOptions {
  compositionId: string;
  inputProps: Record<string, unknown>;
  durationInFrames?: number;
  fps?: number;
  width?: number;
  height?: number;
}

export async function triggerRender({
  compositionId,
  inputProps,
  durationInFrames = 300,
  fps = 30,
  width = 1920,
  height = 1080,
}: RenderOptions) {
  const region = process.env.AWS_REGION ?? "us-east-1";
  const functionName = process.env.REMOTION_LAMBDA_FUNCTION_NAME;
  const serveUrl = process.env.REMOTION_SERVE_URL;

  if (!functionName || !serveUrl) {
    throw new Error("REMOTION_LAMBDA_FUNCTION_NAME and REMOTION_SERVE_URL must be set");
  }

  const params: RenderMediaOnLambdaInput = {
    region,
    functionName,
    serveUrl,
    composition: compositionId,
    inputProps,
    codec: "h264",
    imageFormat: "jpeg",
    durationInFrames,
    fps,
    width,
    height,
    outName: `output-${Date.now()}.mp4`,
    timeoutInSeconds: 240,
    memorySizeInMb: 3009,
    concurrencyPerLambda: 1,
    maxRetries: 1,
    logLevel: "warn",
  };

  const { renderId, bucketName } = await renderMediaOnLambda(params);
  console.log("Render started:", { renderId, bucketName });
  return { renderId, bucketName, region };
}
```

---

## 5. Progress Tracking

```typescript
// src/render/progress.ts
import { getRenderProgress, RenderProgress } from "@remotion/lambda";

interface PollOptions {
  renderId: string;
  bucketName: string;
  region: string;
  pollIntervalMs?: number;
  onProgress?: (progress: RenderProgress) => void;
}

export async function pollUntilDone({
  renderId,
  bucketName,
  region,
  pollIntervalMs = 3000,
  onProgress,
}: PollOptions): Promise<RenderProgress> {
  const functionName = process.env.REMOTION_LAMBDA_FUNCTION_NAME!;

  while (true) {
    const progress = await getRenderProgress({ renderId, bucketName, functionName, region });

    onProgress?.(progress);

    if (progress.fatalErrorEncountered) {
      const error = progress.errors[0];
      throw new Error(`Render failed: ${error?.message ?? "unknown error"}\n${error?.stack ?? ""}`);
    }

    if (progress.done) {
      console.log("Render complete:", progress.outputFile);
      return progress;
    }

    const pct = Math.round(progress.overallProgress * 100);
    console.log(`[${pct}%] ${progress.framesRendered}/${progress.totalFrames} frames`);

    await new Promise((r) => setTimeout(r, pollIntervalMs));
  }
}
```

### Progress Object Key Fields

```typescript
interface RenderProgress {
  overallProgress: number;       // 0-1
  framesRendered: number;
  totalFrames: number;
  lambdasInvoked: number;
  done: boolean;
  fatalErrorEncountered: boolean;
  errors: Array<{ message: string; stack: string }>;
  outputFile: string | null;     // S3 URL when done
  outputSizeInBytes: number | null;
  timeToFinish: number | null;   // ms
  costs: {
    currency: string;
    disclaimer: string;
    estimatedCost: number;
    estimatedDisplayCost: string;
  };
}
```

---

## 6. Downloading Output

### 6.1 Use the S3 URL Directly (public bucket)

```typescript
const videoUrl = result.outputFile;
// "https://remotionlambda-xxxx.s3.us-east-1.amazonaws.com/renders/abc123/output.mp4"
```

### 6.2 Download to Local Disk

```typescript
import { downloadMedia } from "@remotion/lambda";
import path from "path";

async function downloadRender(renderId: string, bucketName: string, region: string) {
  const { outputPath, sizeInBytes } = await downloadMedia({
    bucketName,
    region,
    renderId,
    outPath: path.join(process.cwd(), "output", `${renderId}.mp4`),
  });
  console.log(`Downloaded ${sizeInBytes} bytes to ${outputPath}`);
  return outputPath;
}
```

### 6.3 Presigned URL for Clients (private bucket)

```typescript
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

async function getPresignedUrl(s3Url: string, expiresInSeconds = 3600): Promise<string> {
  const url = new URL(s3Url);
  const bucketName = url.hostname.split(".")[0];
  const key = url.pathname.slice(1);
  const client = new S3Client({ region: process.env.AWS_REGION ?? "us-east-1" });
  const command = new GetObjectCommand({ Bucket: bucketName, Key: key });
  return getSignedUrl(client, command, { expiresIn: expiresInSeconds });
}
```

---

## 7. Cost Estimation

```typescript
import { calculatePrice } from "@remotion/lambda";

function estimateCost({
  durationInSeconds,
  memorySizeInMb = 3009,
  lambdasInvoked,
  region = "us-east-1",
}: {
  durationInSeconds: number;
  memorySizeInMb?: number;
  lambdasInvoked: number;
  region?: string;
}) {
  return calculatePrice({
    region,
    durationInMilliseconds: durationInSeconds * 1000,
    memorySizeInMb,
    lambdasInvoked,
  });
}
```

### Typical Costs Table

| Video Length | Resolution | Lambdas | Approx Cost |
|---|---|---|---|
| 10 s | 720p | 5 | ~$0.0008 |
| 30 s | 1080p | 10 | ~$0.002 |
| 60 s | 1080p | 20 | ~$0.004 |
| 5 min | 1080p | 100 | ~$0.02 |
| 30 min | 1080p | 600 | ~$0.12 |
| 10 s | 4K | 10 | ~$0.005 |

---

## 8. Webhook Pattern

### 8.1 Trigger with Webhook

```typescript
const { renderId } = await renderMediaOnLambda({
  region, functionName, serveUrl,
  composition: "MyVideo",
  inputProps: { title: "Hello" },
  codec: "h264",
  webhook: {
    url: "https://api.yourapp.com/webhooks/remotion",
    secret: process.env.REMOTION_WEBHOOK_SECRET!,
    customData: { userId: "user_123", jobId: "job_456" },
  },
});
```

### 8.2 Webhook Receiver (Express)

```typescript
import express from "express";
import crypto from "crypto";

function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean {
  const expected = crypto.createHmac("sha512", secret).update(payload).digest("hex");
  return crypto.timingSafeEqual(
    Buffer.from(`sha512=${expected}`),
    Buffer.from(signature)
  );
}

router.post("/remotion", express.raw({ type: "application/json" }), async (req, res) => {
  const signature = req.headers["x-remotion-signature"] as string;
  if (!verifyWebhookSignature(req.body.toString(), signature, process.env.REMOTION_WEBHOOK_SECRET!)) {
    return res.status(401).json({ error: "Invalid signature" });
  }

  const event = JSON.parse(req.body.toString());
  switch (event.type) {
    case "success":
      await markRenderComplete({ renderId: event.renderId, outputUrl: event.outputUrl, ...event.customData });
      break;
    case "error":
    case "timeout":
      await markRenderFailed({ renderId: event.renderId, errors: event.errors ?? ["timeout"], ...event.customData });
      break;
  }

  res.json({ received: true });
});
```

---

## 9. CI/CD Integration (GitHub Actions)

```yaml
# .github/workflows/render.yml
name: Render Video
on:
  push:
    branches: [main]
    paths: ["src/**", "public/**"]

jobs:
  render:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: "20", cache: "npm" }
      - run: npm ci
      - name: Deploy Lambda function and site
        env:
          AWS_REGION: ${{ secrets.AWS_REGION }}
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        run: npx ts-node scripts/deploy-lambda.ts
      - name: Trigger render and wait
        env:
          AWS_REGION: ${{ secrets.AWS_REGION }}
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          REMOTION_LAMBDA_FUNCTION_NAME: ${{ secrets.REMOTION_LAMBDA_FUNCTION_NAME }}
          REMOTION_SERVE_URL: ${{ secrets.REMOTION_SERVE_URL }}
        run: npx ts-node scripts/render.ts
      - uses: actions/upload-artifact@v4
        with:
          name: rendered-video
          path: output/*.mp4
          retention-days: 7
```

---

## 10. Error Handling

### Timeout sizing

```typescript
// Rule: set Lambda timeout to at least 2x the video duration, max 900 s
const timeoutInSeconds = Math.min(Math.max((durationInFrames / fps) * 2, 60), 900);
```

### Memory sizing

```typescript
function getMemoryForResolution(width: number, height: number): number {
  const pixels = width * height;
  if (pixels <= 921600)  return 1769;  // 720p
  if (pixels <= 2073600) return 3009;  // 1080p sweet spot
  return 10240;                         // 4K
}
```

### Retry with exponential backoff

```typescript
async function renderWithRetry(options: RenderOptions, maxAttempts = 3) {
  let lastError: Error | undefined;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      const { renderId, bucketName, region } = await triggerRender(options);
      return await pollUntilDone({ renderId, bucketName, region });
    } catch (err: unknown) {
      lastError = err instanceof Error ? err : new Error(String(err));
      if (attempt < maxAttempts) {
        await new Promise((r) => setTimeout(r, Math.min(1000 * 2 ** attempt, 30000)));
      }
    }
  }
  throw new Error(`All ${maxAttempts} render attempts failed. Last: ${lastError?.message}`);
}
```

---

## 11. Cleanup

```typescript
import { deleteRender, deleteSite, getSites } from "@remotion/lambda";

// Delete a specific render's S3 artifacts
await deleteRender({ renderId, bucketName, region });

// Delete old deployed sites (keep current)
const { sites } = await getSites({ region, bucketName });
for (const site of sites) {
  if (site.id !== keepSiteId) {
    await deleteSite({ region, bucketName, siteId: site.id });
  }
}
```

---

## 12. Anti-Patterns

### Do not set `timeoutInSeconds` too low
Lambda kills the function mid-render. Scale with video duration, cap at 900.

### Do not use 512 MB memory for 1080p+
Causes OOM crashes. Use 3009 MB for 1080p; 10240 MB for 4K.

### Do not leave renders in S3 indefinitely
At 50 MB each, 1000 renders = 50 GB = ~$1.15/month. Call `deleteRender` after delivering output.

### Do not redeploy the site on every render
`deploySite` adds 10-60 s per request. Deploy once in CI/CD; read `REMOTION_SERVE_URL` from env at render time.

### Do not ignore `fatalErrorEncountered` during polling
Check it on every poll cycle or the loop runs forever if the render crashes silently.

### Do not set `concurrencyPerLambda > 1` without profiling
High concurrency on memory-heavy compositions causes OOM inside Lambda. Leave at default (1) unless tested.

