Serverless · Freelance

Container-Image Lambdas for Audio Segmentation and Sentiment

Docker-based Lambdas process uploaded audio with a TensorFlow speech segmenter and score text with several sentiment lexicons.

  • Lambda containers
  • ECR
  • S3
  • SAM
  • TensorFlow
  • ffmpeg
  • Python

// Why this matters

If you want to run a TensorFlow audio model on AWS Lambda container images, the motivation is usually economic and operational. Audio analysis arrives in bursts, uploads from users or batch drops, and keeping a GPU-less server running around the clock for a few minutes of work an hour is wasteful. Lambda charges per invocation and scales to zero.

The blocker used to be size. A zip deployment is capped at 250 MB unzipped, and TensorFlow alone is bigger than that, before you add ffmpeg and a speech segmentation library. People worked around it with layers and aggressive pruning, which is fragile and slow to build. Container image support removes the problem: you ship the same image you tested locally.

This article covers a concrete pipeline: speech, music and noise segmentation of uploaded audio, written as a CSV of labelled time ranges, plus a sentiment-scoring function built the same way. It also covers the less obvious operational details: recursion, memory sizing, cold starts and event shapes.

// The problem

The heavy part of audio ML is the toolchain. You need a decoder (ffmpeg) to read arbitrary uploads, a numerical stack (TensorFlow, numpy), and a model package, all with compatible versions. Zip packaging with layers hits size limits and drifts between your laptop and the cloud. Building in a matching Linux environment is slow and error-prone.

Processing is also slow relative to a typical web request: decoding and running a neural segmenter over several minutes of audio takes tens of seconds to minutes and needs gigabytes of memory. That is fine for Lambda only if you size memory and timeout correctly and make sure the first invocation is not punished by loading the model every time.

Finally the trigger needs to be safe. An S3-triggered function that writes its output into the same bucket can trigger itself if the filter is sloppy, and that loop will run until someone notices the bill. Event shapes also differ between direct tests, API calls and real S3 notifications, which makes local testing misleading.

// The solution

We package the function as a container image built from the AWS Lambda Python base image, which already contains the runtime interface client, so no custom entrypoint is needed. On top we install ffmpeg as a static binary and pip install the model library with its TensorFlow dependency. The image runs as a non-root user and is pushed to a private ECR repository.

A SAM template deploys the function with an ImageUri parameter, 2 GB or more of memory and a 15 minute timeout, plus an S3 bucket whose notifications invoke it. Notifications cover both simple puts and multipart-complete uploads, because large files uploaded by SDKs arrive as the latter. They are filtered to an input prefix and to the audio suffixes the handler supports, and the function writes only to an output prefix.

The handler accepts both direct-invocation and S3 event shapes (a body wrapper for API-style tests, the Records list for real notifications), validates the extension against an allow-list, downloads to /tmp (the only writable path), runs the segmenter, and uploads the CSV. The segmenter is created once at import time so warm containers reuse the loaded models.

Alternatives we considered: SageMaker batch transform (better for large GPU workloads, but heavier to run for sporadic small files), AWS Batch or Fargate (no 15 minute ceiling, a good move if files grow), and zip plus layers (rejected on size and build fragility). The sentiment function stays a separate image because its dependencies are tiny and it should not carry TensorFlow; keeping them separate also keeps cold starts short.

How it flows flow1. S3 upload → 2. S3 notification → 3. Container Lambda → 4. Format gate → 5. Segmentation → 6. Result → 7. Sentiment Lambda → 8. Delivery01S3 upload02S3 notification03Container Lambda04 · GATEFormat gate05Segmentation06Result07Sentiment Lambda08Delivery
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. S3 uploadaudio placed under a media prefix
  2. S3 notificationput and multipart-complete events invoke the function
  3. Container LambdaECR image, 2048 MB, 900 s timeout
  4. Format gate gateaccepts wav, mp3 and m4a only
  5. Segmentationdownload, segment, write CSV
  6. ResultCSV written under a separate prefix
  7. Sentiment Lambdasequenced text in, per-lexicon scores out
  8. DeliveryDocker build, ECR push, SAM deploy with image URI parameter
UploaderS3Lambda containerModelput object under media/ObjectCreated event filtered by prefix and suffixdownload to /tmpsegment speech, music and noisewrite csv under results/
Upload to CSV result. Input and output prefixes keep the trigger from looping.
Handler decision flow flow1. Parse event → 2. Read key → 3. Format gate → 4. Download → 5. Segment → 6. Export → 7. Upload → 8. Cleanup01Parse event02Read key03 · GATEFormat gate04Download05Segment06Export07Upload08Cleanup
Handler decision flow. Cheap checks before expensive work.
  1. Parse eventRecords list or body wrapper
  2. Read keysplit path, name and extension
  3. Format gate gatewav, mp3 or m4a only
  4. Downloadobject to /tmp
  5. Segmentmodel created once at import
  6. Exportlabelled ranges to CSV
  7. Uploadwrite under the results prefix
  8. Cleanupremove /tmp files

// Before you start

  • Docker with permission to build linux/amd64 images (use buildx on Apple silicon), the AWS CLI v2 and the SAM CLI.
  • An AWS account and permissions for ECR, Lambda, S3, IAM and CloudFormation.
  • A few sample audio files in wav, mp3 and m4a, including one that is several minutes long.
  • Python 3.10 or 3.11 for local testing; familiarity with S3 event notification JSON.
  • Awareness that Lambda has no GPU: the model must run acceptably on CPU.

// Step-by-step implementation

  1. 01 Build the image from the Lambda base with ffmpeg and the model library

    Start from the official Lambda Python base image rather than a general TensorFlow image. It is smaller, already speaks the Lambda runtime API and tracks supported Python versions. Install ffmpeg as a static build so you do not drag in a package manager world, and pin the Python packages.

    TensorFlow wheels are large. Install the CPU build explicitly. There is no GPU on Lambda, and GPU wheels only add hundreds of megabytes to pull on every cold start.

  2. 02 Write the handler: tolerant event parsing, allow-listed formats, warm model

    Create the segmenter at module scope. That single choice moves model loading out of the per-request path: only the cold start pays for it. Everything written must go under /tmp.

    The event parsing tolerates the shapes you will meet: a direct test event with Records, an API-style event whose body is a JSON string containing Records, and real S3 notifications (where keys are URL-encoded, so decode them). Unsupported extensions return cleanly instead of raising, which keeps S3 from retrying uselessly.

  3. 03 Test the image locally with a synthetic S3 event

    The base image ships a runtime interface emulator, so you can invoke the exact image locally with curl. Use a real-shaped S3 event, not a simplified one, otherwise you never exercise the key decoding. Mount your AWS credentials read-only or point the code at a local stub bucket.

  4. 04 Create the ECR repository and push the image

    Create the repository with scan-on-push and a lifecycle rule so old images do not accumulate. Tag by commit and keep the digest: Lambda resolves the tag to a digest at deploy time, so re-pushing the same tag does not update a running function until you redeploy.

  5. 05 Deploy with SAM: image function, bucket and safe notifications

    The template takes the image URI as a parameter, so a deploy is one command with a new tag. Memory of 2048 MB or more also buys proportional CPU, which matters for neural inference; test 3008 and 4096 because a bigger setting can be cheaper if it finishes proportionally sooner.

    S3 notifications in CloudFormation have a circular dependency trap: the bucket needs the permission resource and the permission needs the bucket. Break it by giving the bucket a fixed name or by creating the permission first with DependsOn, as below. Subscribe to both Put and CompleteMultipartUpload.

  6. 06 Add the sentiment sibling as a second, tiny image

    Text scoring needs no TensorFlow, so give it its own image and function. It takes sequenced text (for example transcript segments) and returns per-lexicon scores: a rule-based social-media lexicon, a word-list valence score and a pattern-based polarity score. Returning every score side by side lets the caller pick or ensemble instead of trusting one lexicon, which have well-known blind spots for sarcasm and domain vocabulary.

    The build and deploy steps are identical: Dockerfile from the Lambda base, push to ECR, SAM template with its own ImageUri parameter.

  7. 07 Deploy and invoke end to end

    Run the deploy with the image URI from the push step, upload a sample file under media/, and watch the log group. The first invocation includes the cold start (image pull plus model load), so judge steady state from the second one.

// How to verify it works

  • After uploading to media/, aws s3 ls s3://<bucket>/results/ shows a CSV with the same stem within the function duration.
  • The CSV contains rows labelled speech, music, noise (or silence) with increasing start and stop times.
  • Upload a .txt file under media/: the log shows "skipping unsupported format" and no CSV appears.
  • aws lambda get-function-configuration reports PackageType Image, the memory and timeout you set, and the image digest.
  • CloudWatch shows Init Duration only on cold starts; a second upload within a few minutes shows none.

// Design decisions and trade-offs

  • Container images bypass zip size limits; non-root user in the image.
  • Prefix-filtered notifications avoid recursive triggers.
  • One handler tolerates API-style and S3-style event shapes; local test events included.

// Pitfalls and lessons learned

  • Writing results under the trigger prefix creates an invocation loop. Keep input and output prefixes disjoint and filter by prefix.
  • S3 notification keys are URL-encoded; plus signs for spaces break downloads unless you unquote them.
  • Large uploads arrive as CompleteMultipartUpload, not Put. Subscribe to both or big files never trigger.
  • Building the image on Apple silicon without --platform linux/amd64 produces an image that fails with an exec format error on the default architecture.
  • Loading the model inside the handler makes every request pay seconds of initialisation. Do it at import time.
  • Re-pushing the same tag does not update a deployed function. Deploy with a new tag or digest.
  • The 15 minute Lambda limit is hard. If audio length is unbounded, split the files or move to a container service.
  • GPU TensorFlow wheels bloat the image and slow cold starts for no benefit on Lambda.

// Frequently asked questions

How do I run TensorFlow on AWS Lambda?

Package the function as a container image (up to 10 GB) based on the Lambda base image, install the CPU TensorFlow wheel, and create the model at import time. This article shows the complete build.

Can I use ffmpeg in Lambda?

Yes. Add a static ffmpeg binary to the container image, or use a layer for zip functions. Containers are simpler for decoders plus ML.

How much memory should an audio model function get?

Start at 2 to 3 GB and measure. CPU scales with memory, so more memory can lower both duration and cost.

How do I stop an S3 trigger from looping?

Write outputs under a different prefix than the notification filter, and confirm with a test upload. Never trigger on the whole bucket.

What should I use if files exceed 15 minutes of processing?

Move to a container task on Fargate or Batch. See Auto-scaled Containerised API on ECS Fargate for the Fargate foundations and Event-driven Call-Recording Transcoding and Transcription for the upstream audio pipeline.

// The outcome

ML-grade processing on a serverless footprint.

// Where to take it next

// Keep reading