AWS Lambda — All You Need To Know
From the publisher’s feed, collected in the ZeroLabs newsroom.
What Lambda is, How it actually works, When to use it, and Everything you need to know to work with it in practice.This is a pretty long article, so I’ve split it into 4 logical parts — you can read it end to end, or jump straight to the part you need.Part 1 — The Fundamentals — the problem Lambda solves, how it works at a high level, and the building blocks of every Lambda function.Part 2 — Under the Hood — execution environments, cold starts vs warm starts, the golden initialization pattern, and why memory = CPU.Part 3 — Lambda in Practice — building a real function step by step, deploying it (zip, layers, containers), and testing it.Part 4 — Production Knowledge — invocation modes and retries, the hard limits you must know, when to use Lambda (and when not to), and best practices.If Lambda is new to you, I recommend reading it in order — each part builds on the previous one.Part 1 — The FundamentalsThe Problem: Why Does Lambda Exist?Before we talk about Lambda, let’s understand the problem it solves.Imagine you have a small piece of code you need to run — say, a Python function that resizes an image every time someone uploads one. You don’t care where it runs. You just want it to run when needed and give you the result.Before Lambda, to run even something this simple, you had to:Rent a server — for example, an EC2 instance (a virtual machine running in AWS’s data center).Set it up — install the operating system, Python, your libraries.Deploy your code onto it.Keep it running 24/7 — even if your function only runs for 5 seconds, a few times per day.Handle scaling — “scaling” means adjusting the number of servers to match the workload. If 10,000 images arrive at once, you need more servers. At night, when nothing happens, you’re paying for machines that sit idle.Maintain it forever — apply security patches, set up monitoring, handle restarts when it crashes.Notice the problem. You wanted to run a function. You ended up managing a server.What you wanted: What you got:┌──────────────────┐ ┌────────────────────────────┐│ def resize(img): │ │ OS updates ││ ... │ │ Server setup ││ return small │ │ Scaling logic │└──────────────────┘ │ 24/7 costs (even when idle)│ │ Monitoring & restarts │ │ ...and your function │ └────────────────────────────┘AWS Lambda changes this completely. You give AWS only your function and AWS handles everything else (servers, scaling, updates, availability). You pay only for the time your code actually runs, billed per millisecond. When nothing runs, you pay nothing.This model is called serverless. The name confuses everyone, so let’s be clear:Serverless does not mean “no servers”, your code still runs on a server somewhere.Serverless means servers are not your problem. You never see them, never configure them, or pay for their idle time.You’ll also see the term FaaS — Function as a Service. It means your code is organized around a single entry point (“function”) that runs in response to events, rather than being a continuously running application like a web server that stays on 24/7 waiting for requests. Lambda is AWS’s FaaS offering.What Is AWS Lambda?At its core, Lambda is a service that runs your code when “something happens” — and AWS manages all the infrastructure for you. That’s it!The mental model is simple: EVENT LAMBDA RESULT┌────────────────┐ ┌─────────────────┐ ┌───────────────┐│ "A file landed │ │ Your function │ │ "Thumbnail ││ in S3!" │ ───> │ wakes up, runs,│ ───> │ created, ││ │ │ goes to sleep │ │ saved to S3" │└────────────────┘ └─────────────────┘ └───────────────┘Now, to really understand Lambda, you need to know three characteristics that define how it works:Event-driven — your Lambda function does not run constantly. It sleeps. Something must trigger it — a file upload, an HTTP request, a schedule — then it wakes up. No trigger, no execution.Stateless — every run starts fresh, as if the function was called for the very first time. Lambda does not remember anything between runs. No counters, no caches, no variables from the previous execution. If you need to “remember” something, you must save it somewhere external — S3, a database like DynamoDB, etc.Auto-scaling — one running copy of your function is called an instance. Each instance handles one event at a time — it does not process ten events in parallel inside itself. So what happens when many events arrive at the same moment? Lambda starts more instances — one per event, automatically:1 event → Lambda runs 1 instance of your function1,000 events → Lambda runs 1,000 instances, side by side, automatically0 events → nothing runs, and you pay nothingYou don’t configure this (no scaling rules, no capacity planning), Lambda does it automatically. You can set a maximum number of instances if you want to limit it, but by default Lambda just scales to whatever is needed. Lambda also scales down to zero — which is where the cost savings come from (when you don’t run calculations, you don’t pay!).Pricing (high level). You pay for two things: (1) the number of requests, and (2) the compute time (memory size × execution duration, per millisecond).P.S. There is a generous free tier, so you can experiment without worrying about cost.The Building Blocks of a Lambda FunctionA Lambda function has four parts. Once you understand them, working with Lambda becomes straightforward. ┌────────────────────────────────────────────────┐ │ A Lambda Function │ │ │ │ 1. CODE your Python code + handler │ │ 2. CONFIGURATION memory, timeout, env vars │ │ 3. IAM ROLE what it is ALLOWED to do │ │ 4. TRIGGER what makes it run │ └────────────────────────────────────────────────┘Let’s go through each one of them.1. The Code (and the Handler)One thing that confuses beginners:your Lambda code is not just a single function.Let’s clarify what that means. In Python:function is one block of code that does one thing — like def resize(image): ...project is bigger — it's a folder with multiple files, each containing functions, classes, and imports + external libraries your code depends on. A typical project might look like this:my_project/├── handler.py # your main file├── logic.py # helper functions├── config.py # settings└── requirements.txt # external libraries (requests, pandas, etc.)Lambda allows you to upload a whole project — many files, many functions, external libraries. The same kind of Python project you run on your laptop (like in the example above).The reason is simple: real-world code rarely lives in isolation. Your “main function” (the one that resizes images) might need helper functions, utility modules, config files, third-party libraries. Lambda doesn’t limit you to a single file with one function — you can give it your whole project, and it will run it.But out of all that code, one specific function has a special role — it’s the entry point.When an event arrives, Lambda calls that one function.Everything else in your project is just supporting code — it runs only if the entry point function uses (calls) it.This entry point function is called the handler.# === handler.py ===import jsondef clean(text): """A helper function. Lambda never calls this directly - it only runs because the handler below uses it.""" return text.strip()def lambda_handler(event, context): # ← THE HANDLER: the entry point name = clean(event.get("name", "world")) # calls the helper above return {"message": f"Hello, {name}!"}How does Lambda know which function is the handler? You tell it in the configuration → file_name.function_name (we will cover this later). For the code above, this setting is handler.lambda_handler (file handler.py, function lambda_handler).The names don't matter — you could call it main.process_event — as long as the setting matches your code.Now, the handler always receives two parameters: event and context. You will work with these constantly, so let's understand them properly.The event — WHAT happened"event” is a Python dictionary that contains the input dataFor example, if S3 triggered your function because a file was uploaded, the event will contain the bucket name, the file name, and the file size — everything your function needs to know to do its job, like in this example which file to process and where to find it.The important thing to understand: the structure of this event dictionary is different for every trigger. Lambda itself doesn’t decide what’s inside the event — the service that triggered the function does. S3 sends one structure, API Gateway sends a completely different one, SQS sends yet another.Let’s look at two examples.Example 1 — S3 trigger (a file was uploaded):# The event S3 sends. # It answers: WHICH file? WHICH bucket? WHAT happened to it?{ "Records": [ # a list, because S3 can send \ { # several records in one event "eventName": "ObjectCreated:Put", # what happened: a file was uploaded "s3": { "bucket": {"name": "my-data-bucket"}, # where it happened "object": {"key": "raw/2026-07-21.csv", # which file (its path) "size": 52100} # its size in bytes } } ]}# In your handler, you read the values from the nested dictionary:bucket = event["Records"][0]["s3"]["bucket"]["name"] # → "my-data-bucket"key = event["Records"][0]["s3"]["object"]["key"] # → "raw/2026-07-21.csv"Example 2 — API Gateway trigger (someone made an HTTP request):# The event API Gateway sends. # It answers: WHAT request did the user make?{ "httpMethod": "POST", # the HTTP method "path": "/users", # the URL path "headers": {"Content-Type": "application/json"}, "body": '{"name": "Alice"}' # the request body. NOTE: a string!}# In your handler:method = event["httpMethod"] # → "POST"data = json.loads(event["body"]) # body arrives as a string → parse it firstname = data["name"] # → "Alice"Both are event dictionaries, but with completely different content. You don’t need to memorize these formats — AWS documents them all.A classic first debugging step is to log the raw event so you can see what you actually received with logger.info(json.dumps(event)).The context — information about THIS runWhile event gives your function the input data it needs to run its logic (file name, request body, message content, etc.), context tells it about the current run itself — things like a unique ID for this specific execution, or how much time is left before the timeout kills it. In practice, you use it for two things:def lambda_handler(event, context): # 1. A unique ID for this specific run. # Log it. When something fails at 3 AM, this ID lets you # find the exact run in the logs. print(context.aws_request_id) # e.g. "8f5a2b1c-..." # 2. Milliseconds remaining before the timeout kills this run. # Useful in loops: stop cleanly instead of dying mid-work. print(context.get_remaining_time_in_millis()) # e.g. 29850That covers 95% of real-world context usage. context also holds the function name, memory size, and other metadata — good to know it exists, rarely needed in practice.2. The ConfigurationThree settings you’ll touch on every function:Memory — how much RAM the function gets. This also controls CPU speed (more on this later — it’s not obvious).Timeout — the maximum time one run is allowed to take. If exceeded, Lambda kills the run and marks it as failed. For example, if you set the timeout to 30 seconds and your function takes 35, Lambda stops it at 30 — even if it was one line away from finishing.Environment variables — key-value settings your code reads at runtime (bucket names, table names, feature flags). This is how the same code behaves differently in dev and prod environment — you don’t hardcode values, you read them from environment variables, and each environment has its own values.3. The IAM Role — What the Function Is Allowed to DoIAM (Identity and Access Management) is AWS’s permission system. Every Lambda function runs with a role — a set of permissions that define exactly what the function can do inside your AWS account.Think of it like a keycard in an office building. The keycard doesn’t give you access to every room — only the ones you need. A Lambda role works the same way — it lists the specific actions the function is allowed to perform. For example: “this function can read files from the bucket called my-data-bucket, and nothing else."Why does this matter to you? Because it’s the #1 source of beginner errors. Your function reads from S3, but its role doesn’t include S3 read permission → you get AccessDenied. The code is correct. The permissions are not. When a Lambda fails with a permission error, check the role first.The rule to follow is least privilege: give the function only the permissions it actually needs — nothing more. For example, if your function only reads files from one S3 bucket called my-data-bucket, the role should allow read only — not "full access to all of S3." That way, if the function ever has a bug or gets misused, it can't accidentally delete files, access other buckets, or touch any other AWS service. The damage stays small.4. The Trigger — What Makes It RunA trigger is the event source connected to your function — the “something happened” that makes Lambda run your code.A simple example: you configure an S3 bucket as a trigger for your function, with the rule “when a new file is created”. From that moment on, every time someone uploads a file to that bucket, S3 notifies Lambda, Lambda starts your function and passes it the event data. You don’t write any polling logic or scheduling — you set up the trigger once, and it works automatically from that point on.The most common triggers:+-----------------------+----------------------------------------------+-------------------------------+| Trigger | Runs your function when... | Typical use |+-----------------------+----------------------------------------------+-------------------------------+| S3 | A file is created or deleted in a bucket | Process files as they arrive || API Gateway | An HTTP request comes in | Build a serverless API || EventBridge Scheduler | A schedule fires (e.g. "every day at 6 AM") | Replace cron jobs || SQS (queue service) | Messages appear in a queue | Reliable, buffered processing || DynamoDB Streams | A database table changes | React to data changes || Direct call | Other code calls Lambda via the AWS SDK | Chaining, manual runs |+-----------------------+----------------------------------------------+-------------------------------+You can also trigger a function manually from the AWS Console with a test event — very useful for development (will explore later).Part 2 — Under the HoodHow Does Lambda Work Under the Hood?So far we’ve covered what Lambda is and what its building blocks are. Now let’s look at how it actually runs your code — understanding these underlying mechanics will save you from surprises in production (like what is a “cold start”, which we’ll get to in a moment).The Execution EnvironmentYour code can’t run on nothing. It needs hardware, an operating system, and a Python interpreter. Where do those come from?When Lambda needs to run your function, it creates an execution environment — a small, isolated virtual machine built just for your function. You can think of it as a lightweight computer that exists only to run your code.“Isolated” means your code, memory, and disk are completely separated from other customers and even from your other functions.Each environment consist of: ┌──────────────────────────────────────────────────────────┐ │ Execution Environment │ │ │ │ • Operating system (managed by AWS) │ │ • Python runtime (the interpreter) │ │ • YOUR code and libraries │ │ • RAM (the memory size you chose in configuration) │ │ • /tmp (a small temporary disk — explained below) │ └──────────────────────────────────────────────────────────┘# A quick note on /tmp: # RAM is where your code keeps data while it's running # - variables, objects, things in memory. # /tmp is different: # it's actual disk space where your function can save and read files, # just like a folder on your laptop. # # For example, if your function downloads a file from S3, processes it, # and uploads the result — it needs somewhere to put that file in between. # That's what /tmp is for. It starts empty on every new environment, # and anything stored there disappears when the environment is deleted.Now, remember that earlier we said one instance handles one event at a time? This is the moment where “instance” gets a concrete meaning: one instance = one execution environment. Each environment handles exactly one event at a time — never two.So when we say “Lambda runs 1,000 instances”, it physically means AWS creates 1,000 separate execution environments, each handling its own event:3 events arrive at the same time → 3 separate environments ┌────────────┐Event 1 ──> │ Env A │ (instance 1) └────────────┘ ┌────────────┐Event 2 ──> │ Env B │ (instance 2) └────────────┘ ┌────────────┐Event 3 ──> │ Env C │ (instance 3) └────────────┘The number of environments running at the same moment is called “concurrency”.Remember this word — it comes back in the limitations section.Cold Starts vs Warm StartsIn the previous section we learned that an execution environment must exist before your handler can run. But creating one takes time — AWS must download your code, start the Python interpreter, and run your initialization code. Only after all of that the handler can finally run.But this preparation doesn’t happen every time. Sometimes the environment already exists from a previous run. Sometimes it has to be built from scratch. That difference is the entire concept:Cold start — no idle environment is available, so AWS must create one from scratch. This happens, for example, on the first event after a quiet period, or during a traffic spike that requires more environments than currently exist. Your event waits while AWS downloads the code, starts Python, and runs the initialization. Only then does the handler execute.Warm start — an idle environment already exists, so the preparation is skipped entirely. After a run finishes, Lambda doesn’t destroy the environment right away — it keeps it around for a while. If another event arrives in time, Lambda routes it to that existing environment. Code is already loaded, Python is running, initialization is done — as a result, the handler starts right away.COLD START (no ready environment exists):┌──────────────┬───────────────┬───────────────────┬─────────────┐│ Download code│ Start runtime │ Run init code │ Run handler ││ │ (Python boot) │ (outside handler) │ │└──────────────┴───────────────┴───────────────────┴─────────────┘ ◄──────────────── extra delay ───────────────────►WARM START (an idle environment is reused): ┌─────────────┐ │ Run handler │ └─────────────┘ That's it. Fast.How much should you worry about this? Two facts to calibrate:Cold starts add delay, not cost — you’re not billed for the preparation time, but the request waits longer.In production, typically less than 1% of runs are cold starts. But for real-time, user-facing APIs where every millisecond matters, that 1% can be significant.Can you control whether a cold start happens? Not directly — you can’t tell Lambda “keep this environment alive forever.” AWS decides when to create and destroy environments. But you can influence cold start duration (by keeping your code package small and your initialization fast) and for critical functions, you can use Provisioned Concurrency — a feature where you tell AWS “always keep N environments ready for this function”. Those environments stay initialized and waiting, so requests routed to them never hit a cold start. It costs extra (you pay for the environments even when they’re idle), but it guarantees fast starts (we’ll cover both in detail later).Simple rule: for background jobs and data pipelines, ignore cold starts. For user-facing APIs with strict latency requirements, take them seriously.The Golden Pattern: Initialize Outside the HandlerNow that you understand cold starts and warm starts, there’s a practical coding pattern that follows directly from them — and it’s the single most important thing you can do to make your Lambda functions faster.Look at the cold start diagram again. Notice that your code lives in two different places inside your file:import boto3 # ┐ # │ OUTSIDE the handlers3_client = boto3.client("s3") # │ (module-level code: imports, globals) # ┘def lambda_handler(event, context): # ┐ response = s3_client.get_object() # │ INSIDE the handler ... # ┘Here is the key insight: these two places run at different times and at different frequencies.The code outside the handler runs once per environment, during the cold start. When a new environment is created, Python executes your file top to bottom — all your imports, all your global variables, everything at the module level. This happens only once. On every warm run after that, this code is skipped because it already ran.The code inside the handler runs on every single event. Every time Lambda receives an event, it calls your handler function.This means you have a choice about where to put each piece of code — and that choice has real performance consequences:import boto3# === OUTSIDE the handler ===# Runs ONCE per environment, during the cold start.# Every warm run afterwards reuses this object for free.s3_client = boto3.client("s3") # creating a client is slow - do it oncedef lambda_handler(event, context): # === INSIDE the handler === # Runs for EVERY event. Keep it lean: only per-event work here. response = s3_client.get_object(...) # reuses the client ✓ ...Anything expensive and reusable — creating AWS clients, opening database connections, loading config — should live outside the handler. The environment runs that code once during initialization, and every warm run after that reuses it for free.If you create the client inside the handler instead, every single event pays that setup cost again — pure waste.One warning about reuse.Because the environment survives between runs, global variables (the code outside the handler) survive too.A reusable environment is great for performance — but global variables that persist between runs can cause bugs if you’re not careful.Two rules:Never depend on reuse. AWS can destroy any environment at any time without warning. Your code should work correctly whether it gets a fresh environment or a reused one. Treat reuse as a performance bonus, never as a guarantee.Be careful with global variables — they carry over between events. If your handler writes something into a global variable during one event, that value will still be there when the next event arrives in the same environment. The next event sees leftover data from the previous one — that’s a data leak between requests and it can cause bugs.Memory (RAM) = CPU (Non-Obvious but Critical)Most cloud services let you configure CPU and memory separately. Lambda is different — memory is the only setting you control, and it determines everything else, including CPU speed.You can set memory between 128 MB and 10,240 MB. This is RAM (the fast, temporary memory your code uses while it runs — not disk storage). There is no separate CPU setting. CPU power scales proportionally with memory — so if your function is slow because of heavy computation (not network calls), the fix is to give it more memory, even if it’s not running out of RAM.This leads to two consequences that surprise most people:More memory can be cheaper. Your bill = memory × duration. If doubling the memory makes the function finish three times faster, the total cost goes down — and the function is faster too. Counterintuitive, but it happens often.Don’t guess — measure. Run your function at a few memory levels (for example 256 / 512 / 1024 MB) and compare duration and cost. AWS provides an open-source tool called AWS Lambda Power Tuning that does this automatically and shows you the best balance between speed and cost.Part 3 — Lambda in PracticeLambda in Practice: A Real FunctionSo far we’ve covered how Lambda works in theory, now let’s put it all together and build a real function from scratch.The scenario: process a file every time it lands in S3.Step 1: Write the Functionimport jsonimport loggingimport boto3# We use Python's logging module instead of print() because it adds# timestamps, log levels, and structure - which makes debugging# in CloudWatch much easier.logger = logging.getLogger()logger.setLevel(logging.INFO)s3 = boto3.client("s3") # outside the handler: created once, reused (golden pattern!)def lambda_handler(event, context): """Triggered when a file is uploaded to S3. Reads the file, counts the lines, writes a summary back to S3.""" # 1. The S3 event tells us WHICH file triggered us record = event["Records"][0] bucket = record["s3"]["bucket"]["name"] # "my-data-bucket" key = record["s3"]["object"]["key"] # "raw/2026-07-21.csv" logger.info(f"Processing s3://{bucket}/{key} (request: {context.aws_request_id})") # 2. Read the file from S3 obj = s3.get_object(Bucket=bucket, Key=key) lines = obj["Body"].read().decode("utf-8").splitlines() # 3. Write a small summary file back to S3 summary = {"file": key, "line_count": len(lines)} s3.put_object( Bucket=bucket, Key=f"summaries/{key}.json", Body=json.dumps(summary), ) logger.info(f"Done: {summary}") return summaryTwo things to notice:Logging goes to CloudWatch automatically. CloudWatch is AWS’s monitoring and logging service. Everything your function logs — even print() — ends up there. This is your main debugging tool. There is no server you can SSH into.We log aws_request_id — every run gets a unique ID. When something fails at 3 AM, this ID lets you find the exact execution in the logs.Step 2: Configure ItWhere do you set all this up? Two places:AWS Console (the web interface) — inside your function’s page, the Configuration tab is where you set memory, timeout, environment variables, permissions (IAM role), and triggers. It’s also the first place to check when something isn’t working.Infrastructure-as-code (Terraform / SAM / CDK) — lets you define all the same settings as code in your repository. This is what teams use in practice, because it’s version-controlled, reviewable, and repeatable. We’ll cover this in the deployment section.The decisions to make:+------------+----------------------------+--------------------------------+| Setting | What to decide | Good starting point |+------------+----------------------------+--------------------------------+| Memory | RAM (and CPU) | 256–512 MB, then tune || Timeout | Max run time | Typical duration + buffer || IAM Role | What the function can do | Only what it needs / || | | read + write on one S3 bucket |+------------+----------------------------+--------------------------------+Why not set timeout to the maximum (15 minutes)? Because if your function hangs — say, a network call that never responds — you pay for the entire hang. And if Lambda retries it automatically, you pay again. Set it to the realistic worst case plus a safety margin.Step 3: Connect the TriggerAttach the S3 bucket as a trigger: “when a new object is created in bucket X, run this function.” That’s all. No polling loop, no scheduler — S3 pushes the event to Lambda.┌────────┐ file lands ┌───────────────┐ S3 event ┌──────────────┐│ User │ ────────────> │ S3 Bucket │ ───────────> │ Lambda │└────────┘ │ (raw data) │ (trigger) │ function │ └───────────────┘ └──────┬───────┘ ▲ │ │ writes summary │ └────────────────────────────┘ (needs IAM permission!)How to Deploy Lambda CodeSo you’ve written your function. Now you need to get it into Lambda so it can actually run. This is called deploying.There is one important difference between running code on your machine and running it on Lambda. On your machine, when you pip install a library, it stays available — you install it once and your code can use it anytime. Lambda doesn't work that way. Nothing is pre-installed except Python's standard library and boto3 (AWS's SDK). Everything else — requests, pandas, any other library — you must package and upload yourself, together with your code. This section covers the different ways to do that.Option 1: Console Code EditorWrite code directly in the browser, in the Lambda console.Use it for learning and quick experiments.Don’t use it for anything real. There’s no version control, no code review, and no way to include external libraries.Option 2: Zip Package — the Standard ApproachYou package your code plus all its dependencies into a .zip file and upload it. This is the standard approach for most functions.You build this zip on your own machine, using the terminal.In real team projects, this step is usually automated — every time you push code to Git, a tool builds and uploads the zip for you. But when you’re learning, you just do it manually.A typical Lambda project on your machine might look like this:my_project/├── handler.py # your handler function├── logic.py # your business logic└── requirements.txt # list of your dependencies (e.g. requests, pandas)The requirements.txt file lists the external libraries your code needs. For example:requests==2.31.0pandas==2.1.0To turn this into a zip that Lambda can run, you do three things:# 1. Download all the libraries from requirements.txt into a folder called "package"pip install -r requirements.txt -t package/# 2. Copy your own code into the same foldercp handler.py logic.py package/# 3. Zip everything together into one filecd package && zip -r ../function.zip .After step 2, the package folder contains everything Lambda needs — your code and all the library files together in one place:package/├── handler.py # your code├── logic.py # your code├── requests/ # the 'requests' library (downloaded by pip)│ ├── __init__.py│ ├── api.py│ └── ...├── pandas/ # the 'pandas' library (downloaded by pip)│ ├── __init__.py│ ├── core/│ └── ...└── ... # other library filesAs you can see, pip install -t package/ downloads the actual Python files of each library and puts them into the package folder — the same files that normally get installed deep inside your system Python. Here, you collect them in one place so they can be zipped up and shipped to Lambda.The result is a single function.zip that contains your code and all the libraries it needs. You then upload this file to Lambda.Forgot a dependency? You’ll see Lambda’s most common error: Unable to import module 'handler'. Now you know why it happens — the library simply isn't in the zip.Size limits. Lambda limits how big your deployment package (the zip file) can be — 50 MB when zipped, 250 MB when unzipped. It is a hard limit set by AWS and cannot be changed.This is separate from the memory (RAM) limit we discussed earlier. Heavy libraries can exceed this quickly — pandas with its dependencies alone gets close. If you hit this limit, see Option 4.Option 3: Layers — Shared DependenciesA layer is a separate zip file that contains only dependencies — no function code. You upload it once, and then you can attach it to as many functions as you want. A single function can also use multiple layers (up to 5).For example, if ten functions all need the requests library, you don't have to include it in each function's zip. Instead, you put requests in a layer and attach that layer to all ten functions. Each function's own package stays small, and you only maintain the dependency in one place.One thing to note: layers don’t give you extra space. The 250 MB unzipped limit applies to everything combined — your function code plus all attached layers together. Layers help you organize your dependencies, not bypass the size limit.Option 4: Container Images — For Heavy CasesIf your dependencies are too large to fit in a zip file (or you need tools that go beyond Python libraries), there is another option — Docker container images.Think of a container image as a complete package that holds everything your code needs to run — your code, all Python libraries, and even operating-system-level tools. You take all of that, load it into one image, and upload it to AWS so Lambda can use it.The process, at a high level — you build the image on your machine using a template that AWS provides (this base image already knows how to work with Lambda, so you don’t need to configure that yourself), upload it to ECR (a storage service in AWS where container images are kept), and set up your Lambda function to use it as the source.Container images can be up to 10 GB, so the size constraints of zip packages are no longer a problem. The tradeoffs — building and deploying container images take more setup than a simple zip file, and larger images mean slower cold starts, because AWS has to load more data when creating a new environment.Simple rule: start with zip. Move to containers when zip stops fitting.How Teams Actually DeployEverything above — the function, its configuration, IAM role, triggers — can be set up in the AWS console by clicking through the web interface. That’s fine for learning. But in a real team, clicking through a UI to deploy creates problems. If your Lambda breaks, there’s no record of what changed. Another team member can’t review your settings before they go live. And if you need to recreate the same function in a new environment (say, from dev to prod), you have to click through all the same steps again manually.The solution is infrastructure-as-code (IaC). Instead of “clicking”, you define everything — the function, its memory, timeout, IAM role, triggers — in files that live in your Git repository, just like your application code. You get version history, code reviews, and automated deployments. The most common tools are:Terraform — general-purpose, works across cloud providers. Common in data teams.AWS SAM — serverless-focused. Also lets you run functions locally.AWS CDK — define infrastructure in Python or TypeScript.The way they work is simple — you describe the final state you want (for example, “a Lambda function with 512 MB of memory, triggered by this S3 bucket, with this IAM role”), and the tool figures out what operations are needed to get there. You don’t tell it how to create things step by step — you tell it what you want, and it handles the rest.Which one you use is a team decision — they all achieve the same result. Start with the console to learn. Switch to infrastructure-as-code for anything real.How to Test a Lambda FunctionYou might think testing Lambda is complicated because your code runs inside AWS, in execution environments, triggered by events. But here is the thing — a Lambda handler is just a Python function. It takes a dictionary, does some work, and returns a result. That means you can call it yourself, create a dictionary as input, and test it on your own laptop. No AWS needed.That said, there are different things you want to verify — from basic logic (“does my code do what I expect?”) to the full deployed setup (“do the trigger, permissions, and code all work together?”). So let’s walk through three levels of testing, from simplest to most complete.Level 1: Run It Locally with a Fake EventSince the handler takes a dictionary as input, you can write one yourself that imitates what a real trigger would send.# local_test.py - run with: python local_test.pyfrom handler import lambda_handler# A hand-written event that imitates what S3 would sendfake_event = { "Records": [{ "s3": { "bucket": {"name": "my-data-bucket"}, "object": {"key": "raw/test.csv"} } }]}print(lambda_handler(fake_event, context=None))This setup catches most logic bugs before you ever deploy your function into AWS. However, if the code calls real AWS services, you’ll need AWS credentials — or mocking (next level).Unit tests — separating the logic from the eventAbove, we tested the handler by calling it with a fake event dictionary. That works, but it has a problem. Look at what the handler does — it has two jobs mixed together in one function:extracting values from the event dictionary (like digging out the bucket name and file path from the nested S3 structure)and doing the actual work with those values (your business logic)These are two very different responsibilities living in the same place.This creates a testing problem. Every time you want to test your business logic, you also have to build a correctly structured event dictionary just to get to it. That’s tedious, fragile, and if AWS changes the event format, all your tests break even though your logic hasn’t changed.The solution is to separate them.Keep the handler as small as possible — its only job should be to extract values from the event dictionary and pass them to a separate function that does the real work.# handler.py - small adapter: extracts values from the event, delegates the workfrom logic import process_filedef lambda_handler(event, context): record = event["Records"][0] bucket = record["s3"]["bucket"]["name"] key = record["s3"]["object"]["key"] return process_file(bucket, key) # all logic lives elsewhere# logic.py - plain Python, no event parsing, easy to testdef process_file(bucket: str, key: str) -> dict: ...Now you test process_file with normal pytest — just pass it a bucket name and a key as strings. No event dictionaries, no AWS shapes.But what if your function calls AWS services like s3.get_object(...)?You don't want your tests to talk to real AWS — it's slow, costs money, and requires credentials. The standard solution is a library called moto. It simulates AWS services on your local machine, entirely in memory. From your code’s perspective, nothing changes — it calls s3.get_object(...) exactly like it normally would. But instead of going to real AWS, moto intercepts the call and handles it locally. No AWS account needed, no costs, and your code doesn’t know the difference.Level 2: Test Events in the AWS ConsoleThe previous level tests your code on your own machine, before deploying. But once your function is deployed to AWS, you also want to verify that it works there — with real permissions, real configuration, and a realistic event.The Lambda console has a Test button for exactly this. You paste a JSON event (the console even provides ready-made templates for S3, API Gateway, and more), press Test, and immediately see the result and logs right in the browser.Level 3: End-to-EndIn Level 2, you tested the deployed function by manually giving it a fake event. In this level, you test the entire chain — the real trigger, real permissions, real code, real output. Nothing is faked.For our S3 example, this means uploading an actual file to the bucket and watching the CloudWatch logs to confirm that Lambda picked it up, ran your function, and produced the expected result.How do these levels work together in practice? You don’t run all four levels every time. The typical workflow is:run unit tests locally while you developuse a console test event to verify after deployingdo one end-to-end check to confirm the full chainafter that, trust your monitoring to catch issues in productionPart 4 — Production KnowledgeTwo Invocation Modes — and Why They Change EverythingSo far we've talked about triggers — the events that start your function. But there's something we haven't covered yet. Not all triggers call your function in the same way:some wait for a response (“call and wait”)some send the event and walk away (fire and forget)This difference changes how errors and retries work, and it directly affects how you write your code.Synchronous (“call and wait”). The caller sends the event and waits for the response. API Gateway works this way — a user makes an HTTP request, API Gateway calls your Lambda, and it waits until your function returns a result. If the function fails, the error goes back to the caller. Retrying is the caller’s decision.Asynchronous (“fire and forget”). The caller sends the event and moves on without waiting for a response. S3 works this way — when a file is uploaded, S3 sends the event to Lambda and immediately goes back to doing its job. It never checks whether your function succeeded or not. The event goes into an internal lambda queue, and if the function fails, Lambda retries automatically — twice by default (lambda waits one minute before the first retry and two minutes before the second). After that, the event can be sent to a DLQ if you configured one.What’s a DLQ? DLQ stands for Dead Letter Queue = a “box for failed events.”Events that fail all retries go there instead of disappearing silently. You can inspect them later and decide what to do — reprocess them, investigate the bug, or discard them. If your async Lambda does anything important, always configure a DLQ. Otherwise failed events are lost forever with no trace.The automatic retry creates one important consequence.Your function must be idempotent.“Idempotent” means running it twice with the same input produces the same result as running it once.Why? Because retries will happen — after your errors, and occasionally even without them (event systems can sometimes deliver the same event more than once).If your function inserts a database row per event and the event arrives twice, you get duplicate rows. Design for this from the start — use the file name or a unique event ID as a deduplication key, and skip work that’s already been done.Limitations You Must KnowLambda is powerful, but it has boundaries. If you don’t know them before you start building, you’ll discover them in production — and that’s a much more painful way to learn.One distinction first. Some limits are hard (cannot be changed, no matter what), others are soft (AWS can raise them if you ask). Here are the ones that matter most:+------------------------------+---------------------------------------------------------+--------------+| Limit | Value | Type |+------------------------------+---------------------------------------------------------+--------------+| Max execution time | 15 minutes (900 seconds) | Hard || Memory | 128 MB – 10,240 MB | Hard || Payload, synchronous | 6 MB (request and response) | Hard || Payload, asynchronous | 256 KB per event | Hard || Deployment package | 50 MB zipped, 250 MB unzipped (containers: up to 10 GB) | Hard || /tmp temporary disk | 512 MB default, configurable up to 10 GB | Configurable || Concurrency (parallel runs) | 1,000 default, can grow to tens of thousands | Soft |+------------------------------+---------------------------------------------------------+--------------+What each one means in practice:1. The 15-minute wall.If your job takes longer (lambda kills it), you can’t just increase the timeout — 15 minutes is the absolute maximum.The solution is to split the work into multiple functions and chain them together using Step Functions (AWS’s workflow orchestrator).2. Payload limits — and why they differ.“Payload” is the data you send to a Lambda function (the event) and the data it sends back (the response). Lambda limits how big that data can be — but the limit depends on how the function was called.For synchronous calls (where the caller waits for a response), the limit is 6 MB in both directions. There’s a direct connection between the caller and the function, so it can handle more data.For asynchronous calls (where the event goes into a queue first), the limit is just 256 KB. Queues are designed for small messages, so the allowance is much smaller.In either case, if your data is larger, the approach is always the same — write the data to S3 and return just the S3 path.3. Package size matters twice.Every dependency you add makes your deployment package bigger, and there is a hard size limit (50 MB zipped / 250 MB unzipped). But hitting the limit isn’t the only problem — even if you stay under it, bigger packages mean slower cold starts. Remember, every time AWS creates a new execution environment, it has to download and unpack your entire package. The more you put in, the longer that takes. Keep your dependencies minimal.4. Concurrency is shared across your entire account (per region)Remember, concurrency is the number of execution environments running at the same moment.The important thing to understand is that the concurrency limit is not per function — it applies to all your Lambda functions in the account combined.Here is why this matters. Say your account has a limit of 1,000 concurrent runs. You have two functions — one processes payment notifications, the other generates daily reports. If the reporting function suddenly gets a flood of events and scales up to 1,000 parallel runs, it uses the entire limit. Your payment function now can’t run at all. Synchronous callers get a 429 “too many requests” error, and async events get queued for retry.To prevent this, you can reserve concurrency for critical functions. For example, you can reserve 200 for the payment function, which guarantees it always has room to run — no matter what other functions in the account are doing.5. Lambda can scale faster than the systems it talks to.This is a subtle but important one. Lambda happily runs 1,000 instances in parallel, and all 1,000 try to open connections to your database at the same time. If your database can only handle 100 connections, it gets overwhelmed and stops responding — taking down not just your Lambda, but everything else that depends on that database.When Lambda talks to systems that don’t auto-scale (databases especially), either cap the function’s concurrency or put a queue (like SQS) between them as a buffer.6. /tmp is scratch space, not storage.Each execution environment has a small disk space at /tmp (512 MB by default, configurable up to 10 GB). This is separate from the memory (RAM) you assign to the function. RAM holds your variables, objects, and running code. /tmp is actual disk space where you can read and write files — just like a folder on your laptop.A simple example — say your function needs to download a CSV file from S3, modify it, and upload the result back. You can’t edit a file “in S3 directly”. You need to download it somewhere first, work on it, and then upload the new version. That “somewhere” is /tmp:# Download from S3 to /tmps3.download_file("my-bucket", "data.csv", "/tmp/data.csv")# Work with it like a normal file on your computerwith open("/tmp/data.csv", "r") as f: content = f.read()# Upload the result back to S3s3.upload_file("/tmp/result.csv", "my-bucket", "result.csv")But remember how execution environments work — they are temporary, and AWS can destroy them at any time. When the environment is gone, everything in /tmp is gone with it. Never rely on /tmp to keep data between runs. If you need to keep something, write it to S3 or a database.When to Use Lambda — and When to Avoid ItLambda is not the right tool for every job. It is designed for a very specific type of work — short, stateless, event-driven tasks. When your use case fits that profile, Lambda is hard to beat. When it doesn’t, forcing it will cause more problems than it solves.Lambda Is a Great Fit For:Event-driven glue — “when X happens, do Y.” | a file lands in S3 → validate it | a message arrives in a queue → transform it and pass it on… This is exactly what Lambda was built for.Spiky or unpredictable traffic — scales to zero when idle, scales out instantly under load.Scheduled small jobs — replace that old cron server. “Run this cleanup every night at 2 AM.”Simple APIs — API Gateway + Lambda gives you a complete web backend with no servers to manage.Short, stateless data transformations — light ETL steps, event enrichment, notifications, thumbnail generation.Avoid Lambda For:Long-running work. One execution can last at most 15 minutes. Hard limit, no exceptions. If your job needs more time, break it into smaller steps using Step Functions (AWS’s workflow orchestrator that chains multiple Lambdas together, similar to a DAG), or use ECS / AWS Batch (services that run containers without time limits).Heavy, constant 24/7 workloads. Lambda wins when traffic is bursty or mostly idle. If your service runs at full load all day, every day, a fixed server or container is usually cheaper. Compare the costs before deciding.Latency-critical paths where cold starts are unacceptable. Cold starts define the worst case of your p99 latency (the response time experienced by the slowest 1% of requests). If that rare spike matters, you need Provisioned Concurrency or an always-running service.Stateful applications — long-lived connections, in-memory sessions, or local disk that must persist between requests. Lambda environments are temporary and can be destroyed at any time.Moving large data through the function itself. Remember the 6 MB payload limit. If your function needs to work with large datasets, store the data in S3 and pass just the S3 path through the event. The function then reads directly from S3.What Else You Need to KnowDealing with Cold Starts (Only When Necessary)We covered cold starts earlier. Here is the practical question — what can you actually do about them?First, ask yourself whether cold starts actually matter for your use case. Most workloads (async pipelines, scheduled jobs, data processing) are not affected by cold starts in any meaningful way. The latency only matters for user-facing, real-time functions where a slow response is noticeable.If cold starts do matter for your function, here is the toolbox, cheapest option first:Shrink the package and init code. Fewer and smaller dependencies mean faster startup. In Python, heavy imports slow down initialization — so import large libraries only where they are actually needed. This is free and often the highest-impact improvement.SnapStart. Lambda takes a snapshot of the fully initialized environment and creates new environments from that cached snapshot instead of initializing from scratch — skipping the slow initialization step. Cold starts still happen, but they drop to sub-second. It helps most when your initialization is heavy (importing large libraries like pandas or numpy, loading a framework). If your Python function already starts in a few hundred milliseconds, SnapStart won’t save you much — the initialization it skips is already fast. Originally Java-only solution, it now supports Python 3.12+ too. For Python it costs extra (you pay for the cached snapshot and each restore), but typically far less than keeping environments warm around the clock.Provisioned Concurrency. You pay AWS to keep N environments fully warm at all times. This is the most expensive option because you pay for the reserved environments continuously, even when they are idle. Use it when even SnapStart’s sub-second startup is too slow for your users.Error HandlingLambda’s retry behavior (covered earlier) makes error handling especially important. A few rules:Let unexpected exceptions crash the run. A crashed run is retried automatically. But if you catch the exception and return normally, Lambda marks the event as successfully processed — and the event is lost forever.Be idempotent. Worth repeating. Retries are a feature, not a bug, and your code must produce the correct result even if the same event arrives twice.Monitor four CloudWatch metrics — Errors, Throttles, Duration (watch p99, not average), and ConcurrentExecutions. Set alarms on the first two from day one. Don't wait for something to break to find out your function has been failing silently.Configuration and Code HygieneThese are small habits that compound over time. Skip them at the start and you’ll pay for it later:Use env variables for config — bucket names, table names, feature flags. Never hardcode them. For secrets (passwords, API keys), use AWS Secrets Manager or SSM Parameter Store, not plaintext environment variables.Keep the handler small — the handler extracts values from the event, a separate Python function does the work. Testable. Portable. Readable.One function, one job. Resist the “mega-Lambda” that uses if/else to route ten different tasks. Small, single-purpose functions are easier to monitor, secure, and tune.Infrastructure-as-code from day one of any real project.THE ENDOkay, that’s it for this article! I hope I gave you a clear picture of what AWS Lambda is, how it actually works under the hood, and when it’s the right tool for the job.You now have everything you need to start building with Lambda confidently — from writing your first handler to deploying real functions in production.Did this help? If you found this article useful, I’d really appreciate your support: 👏 clap for this story (once or 50!), 🔔 follow for more content, ✍ ️leave a comment telling me what you think!Check out my other articles — I’ve grouped them by category so you can easily find what’s relevant to you: My Articles by Category.I’ll be sharing more material on data and software engineering concepts!You can find me also on LinkedIn.Cheers, see you next time!AWS Lambda — All You Need To Know was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.