Home AWSAWS Lambda Basics: Your First Serverless Function Guide

AWS Lambda Basics: Your First Serverless Function Guide

by Knowledge Base Linux
aws lambda serverless function triggered by a cloud event

Running a small task on a server you manage means paying for idle time, patching an operating system, and scaling capacity by hand. AWS Lambda removes all of that: you upload code, define what triggers it, and AWS runs it on demand and bills you only for the milliseconds it executes. In this guide you will create your first Lambda function, wire it to a real trigger, grant it least-privilege permissions, and learn the limits that shape good serverless design.

Lambda fits event-driven work beautifully: processing uploaded files, responding to HTTP requests through API Gateway, running scheduled jobs, and reacting to database changes. It fits poorly for long-running processes, workloads that need persistent local state, or tasks that run continuously. Knowing that boundary before you build saves you a painful rewrite later.

aws lambda function processing events and writing results to storage

How AWS Lambda Works

A Lambda function is a piece of code plus configuration: a runtime (Python, Node.js, Java, and others), a handler that receives an event object, a memory setting that also scales CPU proportionally, and a timeout that caps execution at 15 minutes. When a trigger fires, Lambda provisions an execution environment, runs your handler, and freezes the environment for reuse. That reuse is why the first invocation after idle time feels slow, the well-known cold start, and why subsequent invocations are fast.

You never manage servers, but you do manage permissions, concurrency, and cost. Every function needs an IAM execution role, and that role should grant only the services the function actually calls. Concurrency defaults to 1,000 simultaneous executions per region, which protects your account from runaway loops but can also throttle a legitimate traffic spike if you do not plan for it.

Prerequisites

  • An AWS account with access to the Lambda console.
  • AWS CLI v2 installed and configured, for the deployment steps.
  • Basic Python knowledge; the examples use Python 3.12.
  • An S3 bucket you own, used as the trigger example.

Step 1: Create Your First AWS Lambda Function

Create a function in the console first, so you can see every setting, then reproduce it with the CLI. The handler below logs the incoming event and returns a greeting:

import json

def lambda_handler(event, context):
    print("Received event:", json.dumps(event))
    return {
        "statusCode": 200,
        "body": json.dumps({"message": "Hello from Lambda!"})
    }

Deploy it from the terminal by zipping the file and updating the function code:

zip function.zip lambda_function.py
aws lambda update-function-code   --function-name hello-world   --zip-file fileb://function.zip

Test it in the console with a test event, then check CloudWatch Logs to see your printed output. If the log group is empty, the execution role is missing permission to write logs, which is the most common first-run failure.

Step 2: Add a Trigger and Least-Privilege Permissions

A function without a trigger only runs when you invoke it manually. Attach an S3 trigger so every object upload runs your code, and scope the execution role to read that bucket and write logs only:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["s3:GetObject"],
      "Resource": "arn:aws:s3:::my-uploads-bucket/*"
    },
    {
      "Effect": "Allow",
      "Action": ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
      "Resource": "arn:aws:logs:*:*:*"
    }
  ]
}

Attach the policy to the function’s execution role and test by uploading a file. Never use the managed AWSLambdaFullAccess policy in production: a compromised function with broad permissions becomes a foothold into your whole account.

Step 3: Configure Memory, Timeout, and Environment Variables

Memory and timeout are performance knobs, not guesses. Start with 512 MB and a 30-second timeout, measure the actual duration in CloudWatch, then tune: raising memory also raises CPU, so a CPU-bound function often gets cheaper per invocation at higher memory despite the higher per-millisecond rate. Store configuration such as bucket names and table names in environment variables, and store real secrets in AWS Secrets Manager or Parameter Store, never in code or plain environment variables.

Troubleshooting AWS Lambda

Function times out. Check CloudWatch for the actual duration, then raise the timeout or reduce the work per invocation. A timeout near the 15-minute ceiling usually means the design needs splitting, for example with Step Functions.

Permission denied errors. Read the CloudWatch error message: it names the exact action and resource that was denied. Add that one permission and retest, rather than widening the policy blindly.

Cold starts hurt latency. Keep functions small, avoid heavy imports at module load, and use provisioned concurrency only for latency-critical paths, since it costs money even when idle.

Trigger fires twice. Lambda offers at-least-once delivery for many event sources. Make your handler idempotent, for example by checking a processed marker before writing results.

Conclusion

Your first AWS Lambda function is a template for everything serverless: small code, an event trigger, least-privilege permissions, and observability through CloudWatch. Use it for event-driven tasks, keep functions short and idempotent, and reserve always-on servers for workloads that genuinely run all the time. For more AWS practice, see our guides on AWS IAM best practices and monitoring EC2 with CloudWatch alarms. The official reference is AWS Lambda documentation.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.