Serverless computing has reshaped the way developers think about building and running applications. Instead of provisioning and managing servers, you write code, upload it, and let the cloud provider handle the rest. AWS Lambda is the flagship service in Amazon’s serverless portfolio, and mastering its deployment workflow is a valuable skill for any cloud‑savvy engineer. In this guide we’ll walk you through everything you need to get a simple function from your laptop to a live Lambda, complete with real commands, configuration snippets, and warnings about the pitfalls that trip up many newcomers.
What You’ll Need
- A free or paid AWS account with permissions to create IAM roles, Lambda functions, and API Gateway resources.
- A local development environment (Windows, macOS, or Linux) with
git,node(or Python), and the AWS CLI installed. - The AWS SAM CLI (Serverless Application Model) for local testing and packaging.
- A text editor or IDE you’re comfortable with (VS Code, PyCharm, etc.).
- Basic knowledge of the programming language you’ll use for the function (JavaScript/Node.js is used in examples).
Step 1: Set Up Your AWS CLI and Verify Access
First, install the AWS CLI if you haven’t already. On macOS you can use Homebrew:
brew install awscli On Windows, download the MSI installer from the official site. After installation, configure your credentials:
aws configure
# Enter Access Key ID, Secret Access Key, default region (e.g., us-east-1), and output format (json) Run a quick test to ensure you can list your Lambda functions (you may see an empty list if you have none):
aws lambda list-functions If you receive an AccessDenied error, double‑check that the IAM user or role you used has AWSLambdaFullAccess and IAMFullAccess policies attached.
Step 2: Create a New Project Directory and Initialize SAM
Open a terminal and create a folder for your project:
mkdir lambda-hello-world && cd lambda-hello-world Initialize a SAM starter template. This will scaffold a basic Lambda function and the supporting CloudFormation template:
sam init --runtime nodejs18.x --name hello-world --app-template hello-world The command creates a hello-world sub‑folder containing app.js (the function code) and template.yaml (the infrastructure definition). Navigate into it:
cd hello-world Take a moment to open app.js. You’ll see a simple handler that returns a JSON payload. This is the code we’ll deploy.
Step 3: Write or Refine Your Function Code
Replace the starter logic with something a bit more useful. For example, a function that returns the current time and echoes back any query string parameters:
exports.handler = async (event) => {
const now = new Date().toISOString();
const params = event.queryStringParameters || {};
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
message: "Hello from Lambda!",
timestamp: now,
received: params
})
};
}; Save the file. If you’re using Python, the same logic would live in app.py with a def lambda_handler(event, context): function.
Step 4: Define Permissions and Resources in template.yaml
The SAM template already includes a basic AWS::Serverless::Function resource. Ensure the Runtime, Handler, and Policies sections match your code:
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: app.handler
Runtime: nodejs18.x
Timeout: 10
MemorySize: 128
Policies:
- AWSLambdaBasicExecutionRole If your function needs to read from S3, write to DynamoDB, or call other AWS services, add the appropriate managed policies or inline statements here. Forgetting to grant a needed permission is a common source of runtime AccessDenied errors.
Step 5: Build and Test Locally
Before you push anything to the cloud, let SAM compile your code and run a local simulation:
sam build Now invoke the function locally with a sample event:
sam local invoke "HelloWorldFunction" -e events/event.json Create events/event.json with a simple payload, for example:
{ "queryStringParameters": { "name": "Alice" } } If the output shows a 200 status and the JSON you expect, you’re ready to deploy. If you see errors, inspect the stack trace – missing environment variables or syntax errors are the usual culprits.
Step 6: Deploy to AWS Using SAM
First, create a dedicated S3 bucket that SAM will use to upload your packaged code. Replace my‑sam‑bucket with a globally unique name:
aws s3 mb s3://my-sam-bucket Now run the deployment command. The --guided flag walks you through stack name, region, and IAM role creation:
sam deploy --guided You’ll be prompted for:
- Stack name (e.g.,
lambda-hello-world-stack) - AWS Region (e.g.,
us-east-1) - Confirm changes before deploy (yes)
- Save arguments to a
samconfig.tomlfile for future non‑guided deployments
When the deployment finishes, SAM outputs the function’s ARN and, if you added an API Gateway trigger, the endpoint URL.
Step 7: Verify the Live Function
Copy the API endpoint (or use the Lambda console’s test tab) and make a request with curl:
curl "https://abc123.execute-api.us-east-1.amazonaws.com/Prod/?name=Bob" You should receive a JSON response similar to:
{
"message": "Hello from Lambda!",
"timestamp": "2026-11-22T14:35:12.000Z",
"received": { "name": "Bob" }
} If the request fails with a 403 or 502, double‑check the API Gateway stage settings and the Lambda execution role’s policies.
Step 8: Set Up Continuous Deployment (Optional but Recommended)
For production workloads you’ll want code changes to flow automatically from your Git repository to Lambda. A simple CI/CD pipeline can be built with GitHub Actions:
name: Deploy Lambda
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Node
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install SAM CLI
run: |
curl -Lo sam.zip https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip
unzip sam.zip -d sam-installation
sudo ./sam-installation/install
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v2
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- name: Build and Deploy
run: |
sam build
sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
Store your AWS keys as encrypted GitHub secrets. Once this workflow is in place, every push to main triggers a fresh build and deployment, keeping your Lambda up‑to‑date without manual steps.
Common Mistakes to Avoid
Even experienced developers slip up when moving to serverless. Here are the most frequent errors and how to sidestep them:
- Forgetting to set the handler name correctly. SAM expects
fileName.exportedFunction. A typo will cause aRuntime.MalformedHandlerNameerror. - Undersizing the function timeout or memory. A function that needs more than the default 3 seconds or 128 MiB will be killed abruptly. Monitor CloudWatch logs and adjust
TimeoutandMemorySizeaccordingly. - Missing IAM permissions. If your code accesses S3, DynamoDB, or other services, you must attach the right policies. The error message will usually say
AccessDeniedException. - Deploying from the wrong directory. Run
sam buildandsam deployfrom the folder that containstemplate.yaml. Otherwise SAM can’t locate your resources. - Leaving debugging statements in production. Console logs are fine, but never commit hard‑coded credentials or test data.
Tips and Tricks
Take your Lambda game to the next level with these proven practices:
- Use environment variables for configuration. Store API keys, feature flags, or bucket names in the Lambda console or via SAM
Globalssection, and access them withprocess.env.VAR_NAME. - Leverage Lambda Layers. If you have shared libraries (e.g., a custom SDK), package them as a layer and attach it to multiple functions to keep deployment packages small.
- Enable Provisioned Concurrency for latency‑sensitive workloads. This keeps a set number of execution environments warm, eliminating cold‑start delays.
- Monitor with CloudWatch Insights. Write structured logs (JSON) and use Insights queries to spot errors or performance bottlenecks quickly.
- Keep the deployment package under 50 MB (zipped). Larger packages increase upload time and may hit Lambda limits. Trim dev‑dependencies and use
npm prune --productionbefore building.
Frequently Asked Questions
Can I use a custom domain with my Lambda‑backed API?
Yes. After creating an API Gateway, you can map a custom domain name in the API Gateway console and point a Route 53 alias record to it. Remember to attach an ACM‑issued TLS certificate to the domain.
How do I debug a Lambda function that fails in production?
Enable detailed logging in the function code and inspect the generated CloudWatch log streams. You can also use AWS X‑Ray to trace request flow and pinpoint latency or error hotspots.
What is the difference between a Lambda function and a Lambda layer?
A function contains your business logic and its direct dependencies. A layer is a zip archive that can be shared across functions, typically used for common libraries, runtimes, or native binaries.
Conclusion
Deploying a serverless function on AWS Lambda is a straightforward process once you understand the SAM workflow, IAM permissions, and the importance of testing locally before pushing to the cloud. By following the eight steps outlined above, you’ll have a production‑ready Lambda backed by API Gateway, version‑controlled deployments, and a solid foundation for scaling. Remember to watch out for the common mistakes, apply the tips, and keep iterating—serverless is all about rapid, low‑maintenance delivery. Happy coding!
Photo by Poddar Group of Institutions on Unsplash



