Serverless · Freelance

Serverless Video-on-Demand with MediaConvert, CloudFront and Cognito

Serverless Framework stack that transcodes uploads to HLS and MP4 with thumbnails and serves them through a Cognito-protected API and signed CloudFront URLs.

  • S3
  • Lambda
  • MediaConvert
  • EventBridge
  • DynamoDB
  • API Gateway
  • Cognito
  • CloudFront
  • Serverless Framework

// Why this matters

If you need serverless video on demand on AWS, the temptation is to start with an EC2 box running FFmpeg. It works on day one and becomes a queue, a fleet and a patching problem by month three. MediaConvert, Lambda and CloudFront let you pay per minute of video processed and per request, and there is nothing to scale or patch.

The second motivation is access control. Training and member-only video is usually commercially sensitive, so a public bucket with guessable keys is not acceptable. The pipeline below keeps every object private and makes the API the only place that can mint a playback URL.

This is the pattern I used for a freelance client who wanted a managed way to ingest, catalogue and securely stream videos with role-based access. It generalises well to any asset pipeline where an upload must become several derived renditions with a trackable status.

// The problem

A raw upload is not playable everywhere. Phones on a weak connection need a low bitrate HLS rendition, desktop browsers want a high one, and the catalogue UI needs a poster image. Producing those renditions is slow and bursty, which is exactly the wrong workload for a Lambda that has a 15 minute ceiling and no GPU or codec licensing.

The pipeline is also asynchronous. The user uploads, the API returns, and minutes later the video becomes playable. Without an explicit status field the front end cannot tell a video that is still transcoding from one that failed, so support tickets pile up. You need a durable record per video and an event path that updates it.

Finally, delivery. If the output bucket is public, a leaked link is a permanent leak. If you proxy video through Lambda you hit payload limits and pay for compute to move bytes. The goal is a private origin, short-lived signed URLs, and two roles with different blast radius.

// The solution

The design is event driven end to end. The input bucket notifies a conversion Lambda; that Lambda copies the original into the output bucket (so the original is also deliverable), loads a job template, patches the input and destination paths, and calls MediaConvert. The job carries the video id in UserMetadata, which comes back untouched in the completion event. That one detail removes any need for polling.

Status tracking uses an EventBridge rule on the MediaConvert Job State Change event with COMPLETE and ERROR states. A small Lambda finds the record and sets Ready or Error. The reference implementation I read located the record with a table scan on the job id; for any real catalogue use the video id from UserMetadata as the key so it is a single GetItem, and keep the job id as a plain attribute.

Delivery uses CloudFront in front of a private output bucket. CloudFront reads the bucket through an origin access identity (or origin access control on a new build), and the cache behaviours for media extensions require a trusted key group, so unsigned requests get a 403 at the edge. A tiny signer function returns a signed URL for a given object key. I looked at serving through pre-signed S3 URLs instead and rejected it, because HLS playlists reference segments by relative path and S3 signatures do not carry over to those child requests, while CloudFront signed cookies or a signed playlist URL with a wildcard policy do.

Authorisation uses two Cognito user pools, one for all signed-in users and one for admins, each wired as a separate API Gateway authorizer. List and get use the broad authorizer; upload, edit and delete use the admin one. Two pools is blunter than a single pool with groups, but it makes the least-privilege boundary visible in the template and impossible to misconfigure through a token claim. If you prefer one pool, see the FAQ. Related patterns: Event-driven Call-Recording Transcoding and Transcription covers the audio equivalent, and Presigned-Upload Document Parsing API shows the direct-to-S3 upload approach used for the ingest step.

How it flows flow1. Input bucket → 2. MediaConvert job → 3. Outputs → 4. Status events → 5. DynamoDB → 6. REST API → 7. Auth → 8. Delivery01Input bucket02MediaConvert job03Outputs04Status events05DynamoDB06REST API07 · GATEAuth08Delivery
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Input bucketupload event triggers the conversion Lambda
  2. MediaConvert jobsettings updated per object
  3. OutputsMP4, adaptive HLS and thumbnails
  4. Status eventsjob state change invokes a status Lambda
  5. DynamoDBmetadata and status, Ready on completion
  6. REST APIAPI Gateway and Lambda per endpoint
  7. Auth gatetwo Cognito pools, users versus admins
  8. DeliveryCloudFront with origin access to a private bucket, signed URLs
ClientInput bucketConvert LambdaMediaConvertStatus LambdaDynamoDBPUT video via presigned URLObjectCreated eventSet status Transcoding, store job idcreate_job with UserMetadata = video idEventBridge: COMPLETE or ERRORSet status Ready or ErrorGET video (via API) shows Ready
Upload to playback. What happens between a file landing in S3 and a signed URL being returned to the player.
EdgeCloudFrontKey groupOrigin access identityAPIAPI GatewayUser pool authorizerAdmin pool authorizerComputeConvert LambdaStatus LambdaSigner LambdaCRUD LambdasMediaMediaConvertJob templateOutput groupsStorageInput bucketOutput bucketDynamoDB table
Deployment layers. Each layer has one job and its own IAM boundary.

// Before you start

  • An AWS account with permission to create IAM roles, MediaConvert jobs, CloudFront distributions, Cognito pools and API Gateway APIs.
  • Node 18+ and the Serverless Framework 3.x (npm i -g serverless), plus Python 3.11 for the Lambda code.
  • AWS CLI v2 configured with a named profile, in a region where MediaConvert is available.
  • An RSA key pair for CloudFront signing, generated locally; the public key is uploaded to a CloudFront key group and the private key goes into Secrets Manager. Never commit it.
  • Working knowledge of IAM trust policies and S3 bucket policies.

// Step-by-step implementation

  1. 01 Project layout and a single config file

    Everything environment specific lives in one config.json so the same code deploys to dev and prod. Bucket names are globally unique, so derive them from a prefix you own. Keep the file out of version control if it will ever hold anything beyond names.

    The Python Lambdas read the same file at runtime through a tiny helper, which means a config change is a redeploy and never a code edit.

  2. 02 Create the buckets, table and two IAM roles

    Declare the storage in the resources block of serverless.yml. The output bucket has no public access and a CORS rule so a browser player can fetch playlists and segments. The table is keyed on the video id only.

    Use two roles. The API role can read the output bucket, touch the table and invoke functions. The job role is the one MediaConvert passes through: it needs read on the input bucket and write on the output bucket and nothing else. Splitting them is cheap and means a bug in the CRUD code cannot create transcoding jobs.

  3. 03 Describe the MediaConvert job once, patch it per upload

    MediaConvert jobs are plain JSON. The reliable workflow is to build one job in the console, export the settings, and keep that file as a template in the repo. The Lambda only replaces three things: the input file URL and the destination of each output group.

    Three output groups give you everything the player needs. A file group writes the MP4 rendition. An HLS group writes a three-rung ladder plus the master playlist. A frame-capture group writes JPEG thumbnails. Keep the template trimmed to what you actually serve; every rung you add costs transcoding minutes.

  4. 04 The conversion Lambda: copy the source, patch the job, submit it

    The handler receives the S3 event, reads the pre-created DynamoDB row (the upload API wrote it with status Uploading), copies the original to the output bucket, and submits the job. Two details matter. First, describe_endpoints returns the account-specific MediaConvert endpoint, and you should cache it rather than call it per upload. Second, UserMetadata is how the video id survives the round trip.

    Use the output-group name when patching destinations and wrap the submit in a try block that writes Error to the row on failure, otherwise a bad input leaves the video stuck in Uploading forever.

  5. 05 Wire the triggers and the EventBridge status handler

    The S3 trigger is declared on the function. Because the bucket is created in the same stack as plain CloudFormation, use the existing: true form so the framework attaches the notification instead of trying to create a second bucket. The status function subscribes to MediaConvert state changes through EventBridge.

    In the status handler, read the id from detail.userMetadata.assetID. That turns the update into a single keyed write and removes the table scan.

  6. 06 Serve through CloudFront with a private origin and a key group

    Generate a key pair locally, upload only the public half to CloudFront as a public key, put it in a key group, and reference the key group from every cache behaviour that serves media. Anything without a valid signature is rejected at the edge before it touches S3.

    The bucket policy then trusts only the CloudFront identity. On a fresh build prefer origin access control; the older origin access identity still works and is what the original stack used.

  7. 07 A signer Lambda that returns short-lived URLs

    The signer takes an object key, validates that the caller is authorised to see that video, and returns a signed URL. For HLS use a custom policy with a wildcard resource covering the whole rendition folder, otherwise the player can fetch the master playlist but every segment request gets a 403.

    Keep the TTL short for single plays and longer for downloads. Reading the private key from Secrets Manager at cold start, and caching it in the execution environment, keeps the key out of environment variables and out of the repo.

  8. 08 Two Cognito pools and two authorizers on the API

    Create a user pool for everyone and a second one for administrators. In the API, GET endpoints reference the first authorizer and the mutating endpoints reference the second. A token from the user pool cannot satisfy the admin authorizer because the issuer differs, so there is no claim parsing to get wrong.

    The CRUD handlers are ordinary Lambdas. The only rule worth enforcing in code is that the upload endpoint writes the DynamoDB row with status Uploading before returning the upload URL, which is what the conversion Lambda later reads.

  9. 09 Deploy and push a first video through

    Deploy with one command, then upload a short test clip with the AWS CLI. Watch the status field move from Transcoding to Ready and open the master playlist through a signed URL.

// How to verify it works

  • After the upload, aws mediaconvert list-jobs --max-results 1 shows a job in PROGRESSING and then COMPLETE; the DynamoDB status reads Transcoding and then Ready.
  • aws s3 ls s3://<prefix>-vod-output/demo.mp4/ --recursive lists an MP4, hls/master.m3u8 with rendition playlists, and four JPEG thumbnails.
  • A direct curl -I https://cdn.example.com/demo.mp4/hls/master.m3u8 returns 403 Missing Key-Pair-Id; the signed URL from the play endpoint returns 200.
  • Calling DELETE /videos/{id} with a user-pool token returns 401, and with an admin-pool token returns 200.
  • CloudWatch logs for the status Lambda show one invocation per finished job and no table scans.

// Design decisions and trade-offs

  • Separate admin and user pools for least privilege on write and delete.
  • Private origin bucket with signed URLs.
  • Per-function IAM roles and single-command deploy.

// Pitfalls and lessons learned

  • S3 event keys are URL encoded. A filename with a space arrives as a plus sign, and the table lookup silently misses unless you unquote_plus the key.
  • Indexing OutputGroups by position in the template is brittle. Match by group name so editing the template cannot send an HLS playlist to the thumbnails folder.
  • Scanning the table by job id works at ten videos and times out at ten thousand. Carry the id in UserMetadata and key every update on it.
  • HLS needs the signature to cover child requests. A single-object signed URL plays the playlist and then fails on every segment.
  • Never ship the private signing key in the deployment package or a config file; store it in Secrets Manager and load it once per cold start.
  • The job role and the Lambda role are different roles. Passing the Lambda role to MediaConvert fails with an opaque permissions error, and the Lambda also needs iam:PassRole on the job role.

// Frequently asked questions

How do I build serverless video on demand on AWS without managing FFmpeg servers?

Trigger a Lambda from the S3 upload event, have it submit an AWS Elemental MediaConvert job from a JSON template, and use an EventBridge rule on the job state change to update your catalogue. CloudFront in front of a private bucket handles delivery.

Why not serve HLS with pre-signed S3 URLs?

A pre-signed URL covers one object. HLS playlists reference segments by relative path, so the segment requests carry no signature. CloudFront signed URLs with a wildcard custom policy, or signed cookies, cover the whole rendition.

Do I need two Cognito user pools?

No. One pool with an admin group works if you check the group claim in the authorizer or Lambda. Two pools trade a little duplication for a boundary that is visible in the template and cannot be bypassed by a mis-set claim.

How much does MediaConvert cost compared with running FFmpeg?

MediaConvert bills per output minute by resolution and feature tier, so cost scales with usage and idle time is free. An always-on FFmpeg fleet is cheaper only at sustained high utilisation; measure with your own catalogue before assuming either way.

How does the player know the video is ready?

The record in DynamoDB carries a status. The front end polls the GET endpoint, or you add a WebSocket or push notification fired from the status Lambda.

// The outcome

Upload to adaptive, access-controlled playback with no servers to run.

// Where to take it next

  • Replace polling with a push notification from the status Lambda when a video becomes Ready.
  • Add a MediaConvert accelerated-transcoding or per-title quality setting once you know your content mix.
  • Add signed cookies for the web player so HLS rendition requests need no per-segment URL.
  • Compare the audio-only variant in Container-Image Lambdas for Audio Segmentation and Sentiment if your catalogue includes podcasts.

// Keep reading