Serverless: functions, queues and events
Serverless means you write code and the cloud runs it on demand: no servers to choose, patch or scale. A function runs when something happens (an HTTP request, a file upload, a message in a queue, a schedule), scales from zero to thousands of copies automatically, and you pay only for the milliseconds it runs. Combined with queues and events, it's a powerful way to build systems where parts react to each other instead of calling each other directly.
| AWS | Google Cloud | Azure | |
|---|---|---|---|
| Functions | Lambda | Cloud Run functions | Azure Functions |
| Serverless containers | Fargate, App Runner | Cloud Run | Container Apps |
| Queue | SQS | Pub/Sub (pull), Cloud Tasks | Service Bus, Queue Storage |
| Publish/subscribe | SNS | Pub/Sub | Service Bus topics, Event Grid |
| Event bus / routing | EventBridge | Eventarc | Event Grid |
| HTTP front door | API Gateway, Lambda function URLs | Cloud Run URLs, API Gateway | API Management |
| Scheduler | EventBridge Scheduler | Cloud Scheduler | Timer triggers |
A function
A Lambda function is a handler that receives an event (a JSON object describing what happened) and returns a result:
import json
def handler(event, context):
"""Triggered by an HTTP request (Lambda function URL or API Gateway)."""
name = (event.get("queryStringParameters") or {}).get("name", "world")
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": json.dumps({"message": f"Hello, {name}!"}),
}Let's call it locally with a sample event, the way you'd test it before deploying:
python3 -c '
import json, handler
event = {"queryStringParameters": {"name": "Asha"}}
print(json.dumps(handler.handler(event, None), indent=2))
'{
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": "{\"message\": \"Hello, Asha!\"}"
}Deploying it is a zip file and one command (plus a role giving the function permission to write logs):
cat > trust.json <<'EOF'
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}
EOF
role=$(aws iam create-role --role-name hello-fn-role --assume-role-policy-document file://trust.json --query Role.Arn --output text)
aws iam attach-role-policy --role-name hello-fn-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
zip -q function.zip handler.py
aws lambda create-function --function-name hello --runtime python3.13 --architectures arm64 \
--handler handler.handler --role "$role" --zip-file fileb://function.zip --memory-size 256 --timeout 10 \
--query "[FunctionName, Runtime, Handler, MemorySize, Timeout]" --output text
aws lambda list-functions --query "Functions[].FunctionName" --output texthello python3.13 handler.handler 256 10 hello
On a real account, aws lambda create-function-url-config --function-name hello --auth-type NONE gives it a public HTTPS address, or you can put it behind API Gateway. Then:
$ aws lambda invoke --function-name hello --payload '{"queryStringParameters":{"name":"Ravi"}}' --cli-binary-format raw-in-base64-out out.json && cat out.json
{"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": "{\"message\": \"Hello, Ravi!\"}"}| Setting | Notes |
|---|---|
| Memory | 128 MB – 10 GB; CPU grows with memory, so more memory can make it cheaper (it finishes faster) |
| Timeout | Up to 15 minutes; longer jobs belong in containers |
| Cold start | The first call after idle time loads your code (typically 100 ms – 1 s). Keep packages small; use provisioned concurrency if it matters |
| Concurrency | Each concurrent request gets its own copy; set a limit so a traffic spike can't overwhelm your database |
| Environment variables / secrets | Configuration; secrets from Secrets Manager or Parameter Store |
The other clouds deploy similarly:
gcloud functions deploy hello --gen2 --runtime=python313 --region=asia-south1 \
--source=. --entry-point=handler --trigger-http --allow-unauthenticated
func azure functionapp publish my-function-app # with Azure Functions Core ToolsQueues: decouple the slow parts
When a user places an order, the web request shouldn't wait while you send emails, generate an invoice PDF and update the warehouse. Put a message on a queue and return immediately; workers (functions or containers) process messages at their own pace:
Web app ──send──▶ [ orders queue ] ──▶ worker (Lambda) ──▶ email, invoice, warehouse
│ failed 3 times
▼
[ dead-letter queue ] → alert a humandlq=$(aws sqs create-queue --queue-name orders-dlq --query QueueUrl --output text)
dlq_arn=$(aws sqs get-queue-attributes --queue-url "$dlq" --attribute-names QueueArn --query Attributes.QueueArn --output text)
q=$(aws sqs create-queue --queue-name orders --attributes '{
"VisibilityTimeout": "60",
"RedrivePolicy": "{\"deadLetterTargetArn\":\"'"$dlq_arn"'\",\"maxReceiveCount\":\"3\"}"
}' --query QueueUrl --output text)
for id in 1001 1002 1003; do
aws sqs send-message --queue-url "$q" --message-body "{\"order_id\": $id, \"total\": 499}" --query MessageId --output text > /dev/null
done
aws sqs get-queue-attributes --queue-url "$q" --attribute-names ApproximateNumberOfMessages --query Attributes --output text
echo "--- a worker receives a batch:"
aws sqs receive-message --queue-url "$q" --max-number-of-messages 10 --wait-time-seconds 1 > batch.json
jq -r '.Messages[].Body' batch.json
echo "--- and deletes each one after processing it successfully:"
jq -r '.Messages[].ReceiptHandle' batch.json | while read -r h; do aws sqs delete-message --queue-url "$q" --receipt-handle "$h"; done
aws sqs get-queue-attributes --queue-url "$q" --attribute-names ApproximateNumberOfMessages --query Attributes --output text3
--- a worker receives a batch:
{"order_id": 1001, "total": 499}
{"order_id": 1002, "total": 499}
{"order_id": 1003, "total": 499}
--- and deletes each one after processing it successfully:
0Key ideas:
- A received message becomes invisible for the visibility timeout (60 s here). If the worker crashes before deleting it, the message reappears and another worker retries.
- After
maxReceiveCountfailures, the message moves to the dead-letter queue instead of retrying forever. Alert on messages arriving there. - Delivery is at least once: very rarely a message is delivered twice, so make processing idempotent (processing order 1001 twice must not charge the customer twice).
- Connecting SQS to Lambda (
aws lambda create-event-source-mapping) lets Lambda poll the queue and call your function with batches automatically.
Pub/sub: one event, many listeners
With SNS (AWS), Pub/Sub (Google Cloud) or Event Grid/Service Bus topics (Azure), a publisher sends a message to a topic, and every subscriber gets a copy. The order service doesn't need to know who's interested:
topic=$(aws sns create-topic --name order-placed --query TopicArn --output text)
for name in email-service warehouse-service; do
url=$(aws sqs create-queue --queue-name "$name" --query QueueUrl --output text)
arn=$(aws sqs get-queue-attributes --queue-url "$url" --attribute-names QueueArn --query Attributes.QueueArn --output text)
aws sns subscribe --topic-arn "$topic" --protocol sqs --notification-endpoint "$arn" --attributes RawMessageDelivery=true > /dev/null
done
aws sns publish --topic-arn "$topic" --message '{"order_id": 1001, "customer": "asha"}' --query MessageId --output text > /dev/null
for name in email-service warehouse-service; do
url=$(aws sqs get-queue-url --queue-name "$name" --query QueueUrl --output text)
echo "$name received: $(aws sqs receive-message --queue-url "$url" --query 'Messages[0].Body' --output text)"
doneemail-service received: {"order_id": 1001, "customer": "asha"}
warehouse-service received: {"order_id": 1001, "customer": "asha"}This fan-out pattern (SNS → several SQS queues) lets each service process the event independently, at its own speed, with its own retries. Adding an analytics service later means adding one more subscription, without touching the order service.
Events: react to what happens in your account
EventBridge (AWS), Eventarc (Google Cloud) and Event Grid (Azure) route events from cloud services, SaaS apps and your own code to targets, filtered by content. They also run schedules:
aws events put-rule --name nightly-report --schedule-expression "cron(30 20 * * ? *)" --query RuleArn --output text
aws events put-rule --name big-orders --event-pattern '{
"source": ["shop.orders"],
"detail-type": ["OrderPlaced"],
"detail": { "total": [{ "numeric": [">=", 10000] }] }
}' --query RuleArn --output text
aws events list-rules --query "Rules[].[Name, ScheduleExpression || 'event pattern']" --output textarn:aws:events:ap-south-1:123456789012:rule/nightly-report arn:aws:events:ap-south-1:123456789012:rule/big-orders nightly-report cron(30 20 * * ? *) big-orders event pattern
cron(30 20 * * ? *)runs daily at 20:30 UTC (02:00 in India). EventBridge cron has 6 fields, including year.- The
big-ordersrule matches onlyOrderPlacedevents with a total of 10,000 or more; add a target (a Lambda function, a queue, an SNS topic for alerts) withaws events put-targets.
When serverless fits, and when it doesn't
| Great for | Less suited to |
|---|---|
| APIs with spiky or low traffic | Steady, high, 24/7 traffic (containers or VMs are cheaper) |
| Glue code: react to uploads, queue messages, schedules | Jobs longer than 15 minutes |
| Prototypes and side projects (often free) | Very latency-sensitive paths where cold starts hurt |
| Event-driven and asynchronous processing | Software that needs special OS setup or GPUs |
Cloud Run (and AWS App Runner / Azure Container Apps) is a popular middle ground: you deploy a container, it scales to zero like a function, but it can run any language, framework and long requests. That's the next lesson.
Clean up
aws lambda delete-function --function-name hello > /dev/null && echo "function deleted"
for name in orders orders-dlq email-service warehouse-service; do
aws sqs delete-queue --queue-url "$(aws sqs get-queue-url --queue-name $name --query QueueUrl --output text)"
done
aws sqs list-queues --query "length(QueueUrls || \`[]\`)"function deleted 0
Practice
- Write a handler that reads
bodyfrom an HTTP event, parses JSON, and returns400ifemailis missing. - Create a queue with a dead-letter queue and
maxReceiveCount2. Explain what happens to a message whose processing always fails. - Design the events and subscribers for: "when a user signs up, send a welcome email, create a CRM record, and add them to analytics".
- Write an EventBridge schedule that runs every weekday at 09:00 India time.
1.What do you pay for with a serverless function?
2.A worker crashes after receiving an SQS message but before deleting it. What happens?
3.Why must queue processing be idempotent?
4.What does SNS → several SQS queues ("fan-out") achieve?