Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 129/ 160
07. Deployment

Serverless Functions

Event-driven functions for light AI glue code with cold-start trade-offs.

IntermediateCold Start · Events3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A serverless function runs your small piece of code only when something triggers it, and you pay only for the moments it runs.

Think of it like…

A taxi versus owning a car: you pay per trip and never worry about parking or maintenance, which is great for occasional journeys, but if you drive all day, or need a very specific vehicle, ownership is cheaper and more flexible.

Where you’ve seen it

A webhook endpoint receives support tickets, calls an LLM API to classify and summarise each one (about 2 seconds, mostly waiting) and writes the result to a database. On Lambda with 512 MB (0.5 GB), 1,000,000 requests a month cost 1,000,000 × $0.20 / 1M = $0.20 for requests plus 1,000,000 × 0.5 GB × 2 s = 1,000,000 GB-seconds × $0.0000166667 = $16.67 for compute: $16.87 a month, about $0.0000169 per request. An always-on small container service handling the same load costs roughly $30 a month, so the function wins below 30 / 0.0000169 ≈ 1.78 million requests a month and loses above it, particularly because the function bills the 2 seconds spent waiting on the provider while one container can multiplex many concurrent requests with async I/O. Cold starts: a slim Python function with a few small libraries starts in roughly 150 to 400 ms, but bundling a heavy ML library can add multiple seconds, so the team keeps the dependency set small, initialises clients outside the handler, and uses provisioned concurrency for the one latency-sensitive endpoint. The handler is idempotent (events can be delivered at least once), long jobs are handed to a queue and a worker instead of running inside the function, and an API gateway in front adds authentication and rate limits.

Words you’ll hear

Cold start
Extra latency when the platform creates a new execution environment.
GB-second
Billing unit: memory in GB × execution seconds.
Provisioned concurrency
Pre-warmed instances kept ready to avoid cold starts, at an extra cost.
At-least-once invocation
Events may be delivered more than once, so handlers must be idempotent.

Visual diagram

Loading interactive diagram

Theory & deep dive

Strengths, limits and cost model

Strengths: no servers to manage, automatic scaling from zero to hundreds of concurrent executions, event integrations (queues, storage, schedules, gateways) and pay-per-use pricing that makes spiky or low-volume workloads very cheap. Limits (check the current numbers for your provider): maximum execution time (for example 15 minutes on Lambda; gateways in front often cut synchronous requests at about 30 seconds), memory and package size (container-image functions allow larger bundles), request and response payload limits (a few megabytes for synchronous invocations), concurrency quotas (a default account limit in the low thousands) and no GPUs in typical function platforms. Ephemeral execution means no local state between invocations beyond what you cache in the warm environment.

Cost model: Lambda-style billing is requests (about $0.20 per million) plus GB-seconds (about $0.0000166667 each). One million requests of 2 seconds at 0.5 GB use 1,000,000 GB-seconds, $16.67, so $16.87 in total. Because time is billed even while waiting on an LLM provider, long-latency calls make functions less efficient than a container that handles many concurrent requests on one vCPU with async I/O. Compare with an always-on service: at about $30 a month the break-even is about 1.78 million requests a month in this example; above that, containers or a managed container platform (Cloud Run, Fargate) are cheaper, and they also support streaming and longer runs more naturally.

Cost per request

512 MB = 0.5 GB × 2 s = 1 GB-second per request × $0.0000166667 = $0.0000167, plus $0.0000002 for the request = $0.0000169. At 1M requests: $16.87. At 10M: $168.70, more than a $30 container, which can serve this I/O-bound load.

Key takeaway: Functions are cheap at low or spiky volume, but billed waiting time and limits make containers better at high, I/O-heavy volume.

Designing AI functions: cold starts, idempotency and hand-off

Cold starts: keep packages small (avoid bundling PyTorch or large SDKs; use provider HTTP APIs and lightweight clients), initialise SDK clients and load config outside the handler so warm invocations reuse them, choose enough memory (CPU scales with memory on many platforms, so more memory can lower duration and sometimes cost), use faster runtimes for latency-critical paths, and apply provisioned concurrency or minimum instances for the few endpoints that need consistent latency. For streaming LLM responses use platforms that support response streaming, or put a streaming service behind a long-lived connection (see streaming lessons) rather than a short-lived function.

Reliability: invocations from queues and events are typically at-least-once, so handlers must be idempotent (idempotency keys, conditional writes); set timeouts below the platform maximum and retry with backoff only for transient errors; configure dead-letter queues for failures; apply reserved concurrency to protect downstream providers and databases from stampedes and to respect rate limits. Hand off long-running work: a function should validate, enqueue and return, while a container worker or workflow engine (Step Functions, Temporal) executes multi-minute agent runs, embeddings backfills and batch jobs. Secure functions with least-privilege roles, secrets from the secret manager (cached across warm invocations), input validation at the gateway and structured logs with request ids. Use serverless where it fits (webhooks, light tool backends, scheduled evals, event glue) and containers where it doesn't.

Hand-off pattern

POST /ingest → function validates the payload, writes a job row and enqueues a message (about 40 ms, $0.000002) and returns 202. A container worker consumes the queue, calls the LLM, retries safely using the idempotency key and updates the job status.

Key takeaway: Keep functions small and idempotent, mitigate cold starts and hand long or heavy work to queues and workers.

How it works, step by step

Step 1 of 4
Architect

1. Decide if serverless fits

Check duration, payload, concurrency and GPU needs and estimate cost against an always-on service.

break-even ≈ 1.78M requests/month
Key numbers at this step
Waiting
time is billed

When to use it & trade-offs

What it is

Serverless functions (AWS Lambda, Google Cloud Functions and Cloud Run functions, Azure Functions, Cloudflare Workers) run your code in response to events (an HTTP request, a queue message, a file upload, a schedule) without you managing servers. The platform provisions an execution environment on demand, scales to zero when idle and bills by requests and execution time × memory. For AI applications they suit light glue code: webhooks, calling an LLM API and returning a result, triggering ingestion when a file lands in a bucket, scheduled evals and tool backends. Trade-offs include cold starts, time, memory and payload limits, concurrency quotas and, because execution time is billed, paying for time spent waiting on slow LLM responses.

Why it matters: Serverless removes operations work and makes low or spiky traffic cheap: you pay nothing when idle. But AI workloads stress its weak points: model calls take seconds, heavy dependencies (PyTorch, large SDKs) inflate cold starts, long agent runs exceed time limits and GPUs aren't generally available. Knowing where functions fit (and where a container service or queue worker is better) avoids both over-engineering and surprise bills or timeouts.

When to reach for it

  • Webhooks and event glue around LLM APIs
  • Triggering ingestion on file uploads
  • Scheduled lightweight evals and reports

When to avoid or be careful

  • Running multi-minute agent loops inside a function
  • Bundling heavy ML libraries in latency-critical functions
  • Non-idempotent handlers behind at-least-once triggers

Where to run code

Serverless functions
Best for: Spiky or low-volume event-driven glue

Strengths: No servers; scales to zero; pay per use.

Watch out: Limits, cold starts and billed waiting time.

Managed container service (Cloud Run, Fargate)
Best for: HTTP services with streaming and moderate scale

Strengths: Container flexibility; autoscaling; concurrency per instance.

Watch out: Some cost when idle on certain platforms.

Kubernetes workers
Best for: Long jobs, GPUs and complex systems

Strengths: Full control; GPUs; long runs.

Watch out: More operations.

Interview signals & numbers to know

When this topic comes up

  • “Lambda cold starts hurt”
  • GB-seconds pricing
  • Provisioned concurrency
  • Dead-letter queues
  • Event-driven glue

Benchmarks & rules of thumb

$16.87 -
monthly cost of 1M two-second 512 MB invocations
≈ 1.78M requests -
break-even versus a $30 container
150–400 ms -
typical cold start for a slim Python function

Common mistakes & follow-ups

Common interview mistakes

  • Ignoring that waiting for the LLM is billed time.
  • Loading models or large SDKs inside the handler on every invocation.
  • Letting functions scale without a cap and overwhelming a provider quota.

Likely interviewer follow-ups

  • When would you choose serverless over containers for an AI endpoint?
  • How do you reduce cold starts?
  • Why must function handlers be idempotent?
Interview tip: Compute cost per request and the break-even against a container. It's a convincing, quantitative way to choose.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Serverless Functions with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Infrastructure as Code
Next topic
GPU Instances