Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

CL
Cloud (AWS, GCP, Azure)
0/12 completed
Beginner
What is cloud computing?AWS, Google Cloud and Azure comparedAccounts, billing alerts and the CLI
Intermediate
Identity and access (IAM)Virtual machinesObject storageNetworking: VPCs, subnets and load balancersManaged databases
Advanced
Serverless: functions, queues and eventsContainers in the cloud
Pro
Infrastructure as codeCost control, security and reliability
Tracks / Cloud (AWS, GCP, Azure) / Advanced

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:

handler.py
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:

bash
python3 -c '
import json, handler
event = {"queryStringParameters": {"name": "Asha"}}
print(json.dumps(handler.handler(event, None), indent=2))
'
Output
{
  "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):

bash
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 text
Output
hello	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:

bash
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 Tools

Queues: 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 human
bash
dlq=$(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 text
Output
3
--- 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:
0

Key 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 maxReceiveCount failures, 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:

bash
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)"
done
Output
email-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:

bash
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 text
Output
arn: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-orders rule matches only OrderPlaced events with a total of 10,000 or more; add a target (a Lambda function, a queue, an SNS topic for alerts) with aws 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

bash
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 || \`[]\`)"
Output
function deleted
0

Practice

  1. Write a handler that reads body from an HTTP event, parses JSON, and returns 400 if email is missing.
  2. Create a queue with a dead-letter queue and maxReceiveCount 2. Explain what happens to a message whose processing always fails.
  3. Design the events and subscribers for: "when a user signs up, send a welcome email, create a CRM record, and add them to analytics".
  4. Write an EventBridge schedule that runs every weekday at 09:00 India time.
✎ Check your understanding

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?

← Managed databases