
AWS Lambda Explained: The Event-Driven Model
How AWS Lambda actually works: execution environments, cold starts, concurrency, and the security decisions that matter in production.
Your code ran, billed you for 847 milliseconds, and the server it ran on never existed.
That is not a magic trick. It is the logical endpoint of a specific architectural idea that AWS turned into a service in 2014 and called Lambda. Before Lambda, handling unpredictable traffic meant one of two things: over-provision and pay for capacity you were not using, or build autoscaling logic that was always slightly behind the actual traffic curve. Lambda collapses both problems into a single model, run code when something happens, pay for exactly the time it runs, and let AWS handle every physical concern below the function boundary.
This is not just a different way to run code. It is a different way to think about what compute is for.
The Event-Driven Mental Model
Most compute runs on a pull model. A server starts, opens a port, and waits. Requests arrive. The server handles them. Traffic drops. The server keeps waiting. You keep paying.
Lambda runs on a push model. Something happens: an HTTP request arrives at API Gateway, a file lands in S3, a record is written to DynamoDB, a scheduled rule fires in EventBridge, and that event triggers your function. The function runs, finishes, and the execution environment is reclaimed. Nothing idles. Nothing waits.
The architectural implication is significant. An event-driven system is not a web application with the server removed. It is a fundamentally different decomposition of work, where each discrete thing that happens in your system can trigger a specific, isolated piece of code with a defined input and a defined output. The Getting Started with Serverless AWS Educate course introduces this at a conceptual level, but the real payoff comes when you stop thinking in services and start thinking in events.
What Actually Happens When Lambda Runs Your Code
Lambda runs your function inside a managed execution environment, a lightweight micro-VM based on Firecracker, AWS's open-source virtualization technology. When a function is invoked for the first time (or after a period of inactivity), Lambda provisions this environment, initializes the runtime, loads your deployment package, and runs your initialisation code. That sequence is a cold start. On subsequent rapid invocations, Lambda reuses the warm environment and skips straight to running your handler. That is why you see the occasional slow first invocation in any Lambda function with real traffic.
The configuration decisions that matter most are:
- Memory. Lambda allocates CPU proportionally to memory. A function set to 128 MB gets roughly one-eighth the CPU of a function set to 1024 MB. Counterintuitively, increasing memory allocation often reduces total cost because the function completes faster and duration billing is the primary cost driver. Profile your functions.
- Timeout. Default is 3 seconds. Maximum is 15 minutes. Set this to the realistic worst case for your function, not the maximum. A misconfigured timeout on an async function that keeps getting retried is one of the fastest ways to generate an unexpected AWS bill.
- Concurrency. By default, Lambda scales by running more parallel instances of your function - up to 1,000 concurrent executions per account per region, shared across all functions. Reserved concurrency sets a hard ceiling on a specific function. Provisioned concurrency pre-warms execution environments to eliminate cold starts for latency-sensitive workloads.
- Invocation type. Synchronous invocations (API Gateway, ALB) wait for a response. Asynchronous invocations (S3 events, SNS) return immediately and Lambda handles retries internally - up to two retries on failure, which means your function can execute three times for a single event if it keeps failing. That retry behavior is the source of most Lambda cost surprises.
A Real Architecture: Payment Webhooks at a Fintech Startup
A payment provider sends a webhook POST when a transaction completes. The architecture to handle this reliably at scale looks like this:
API Gateway receives the POST and invokes a Lambda function synchronously. The function validates the webhook signature, parses the payload, and writes the transaction record to DynamoDB. A DynamoDB Stream captures that write and triggers a second Lambda function asynchronously. That function updates the ledger, sends a confirmation email through SES, and writes a structured audit log to CloudWatch Logs.
None of this requires a server. There is no process to monitor, no port to open, no capacity to plan for. The system handles one transaction per day and ten thousand transactions per hour identically, and costs nothing when it is not processing anything.
The architecture that emerged from the VPC design covered in Post 07 connects here directly, Lambda functions processing sensitive financial data should run inside a private VPC with no public internet access, reaching DynamoDB and SES through VPC endpoints rather than the public internet.
The Security Angle
Every Lambda function assumes an IAM execution role when it runs. That role defines exactly what AWS resources and actions the function can access. This is where most production security problems with Lambda originate.
The pattern goes like this: engineer needs Lambda to access S3, DynamoDB, and SES. Rather than writing three scoped policy statements, they attach
AmazonS3FullAccess , AmazonDynamoDBFullAccess , and AmazonSESFullAccess . The function works. The ticket closes. Nobody revisits it.That function can now read, write, and delete every S3 bucket in the account, every DynamoDB table, and send email as any identity in SES. If that function has a code vulnerability, or if its event trigger is misconfigured to accept untrusted input, the blast radius is the entire account.
The minimum secure configuration: one function, one role, one policy with the specific actions and resource ARNs that function actually needs. Not the managed policies. Not wildcards. The actual operations on the actual resources.
The second common security failure is environment variables. Lambda environment variables are visible to anyone with access to the function configuration. Secrets: database passwords, API keys, third-party tokens, do not belong there. They belong in AWS Secrets Manager or SSM Parameter Store, fetched at runtime using the execution role's permissions. That one change makes a compromised function significantly less useful to an attacker.
A Working Configuration
# Create a scoped execution role for Lambda
aws iam create-role \
--role-name payment-webhook-lambda-role \
--assume-role-policy-document file://lambda-trust-policy.json
# Attach a scoped inline policy (not a managed wildcard policy)
aws iam put-role-policy \
--role-name payment-webhook-lambda-role \
--policy-name PaymentWebhookPolicy \
--policy-document file://payment-webhook-policy.json
# Deploy the function with the scoped role
aws lambda create-function \
--function-name payment-webhook-processor \
--runtime python3.12 \
--role arn:aws:iam::ACCOUNT_ID:role/payment-webhook-lambda-role \
--handler handler.lambda_handler \
--zip-file fileb://function.zip \
--timeout 10 \
--memory-size 256This creates a function with a 10-second timeout, 256 MB memory allocation, and a role scoped to exactly what that function needs, not a wildcard policy attached because it was convenient.
What Lambda Actually Costs
Lambda pricing has two components: request count and duration. Request pricing is $0.20 per million invocations. Duration pricing is calculated in 1ms increments, billed at a rate that depends on memory allocation. The free tier covers one million requests and 400,000 GB-seconds of compute per month, every month, permanently.
For most workloads, Lambda is extraordinarily cheap. A function processing 10 million events per month at 200ms average duration with 256 MB memory costs roughly $4. The cost model only becomes expensive at very high throughput with high memory allocation and long durations.
The cost trap is async retry behavior. A function that fails consistently on async invocations gets retried twice automatically, tripling your effective execution count. Add a dead-letter queue, monitor failed invocations in CloudWatch, and fix failures rather than absorbing their cost silently.
The Thing That Catches Everyone
Lambda execution environments are stateless and ephemeral. The environment that runs your function this invocation is not guaranteed to be the environment that runs it next invocation. This seems obvious until you build something that depends on it not being true.
The classic mistake: opening a database connection at the top of your handler function, expecting connection pooling behaviour. In a traditional server, one process opens one connection and reuses it across thousands of requests. In Lambda, each execution environment opens its own connection when it initializes. At high concurrency, a hundred simultaneous Lambda invocations means a hundred simultaneous database connections, which exceeds the connection limit of most RDS instances and causes your database to reject connections exactly when traffic is highest.
The fix is RDS Proxy, which maintains a connection pool between Lambda and RDS and multiplexes Lambda's connections into a manageable number of real database connections. But the mistake comes from not understanding what the execution environment actually is before building on top of it.
Lambda is not a feature. It is a different mental model for what compute means, and using it correctly requires understanding the execution environment, not just the code you put inside it.
Next up: IAM, Policies, and the Principle of Least Privilege Explained.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article