Unit 5.5 · Tutorial 2

Serverless & Edge Computing

Chapter 16 · System Design & Deployment
~2.5 hours Advanced Serverless · Lambda · Edge · Cloudflare

Overview

Serverless and edge computing are transforming how applications are built and deployed. This tutorial covers AWS Lambda, API Gateway, and edge computing platforms like Cloudflare Workers and Vercel Edge. You'll learn to build event‑driven, globally distributed applications with minimal operational overhead.

Why this matters: Serverless reduces infrastructure management and scales automatically. Edge computing brings code closer to users, reducing latency and improving performance.

1. Introduction to Serverless

Serverless (FaaS) allows you to run code without provisioning or managing servers.

Key characteristics

  • Event‑driven: Functions are triggered by events (HTTP requests, database changes, etc.).
  • Auto‑scaling: Automatically scales from 0 to thousands of concurrent executions.
  • Pay‑per‑use: Only pay for execution time (millisecond billing).
  • Managed infrastructure: No server maintenance.

Popular serverless platforms

  • AWS Lambda: Most mature, integrated with AWS ecosystem.
  • Google Cloud Functions: Integrated with GCP.
  • Azure Functions: Integrated with Microsoft ecosystem.
  • Vercel Functions: Built for Next.js applications.
  • Cloudflare Workers: Edge‑based serverless (global edge).

2. AWS Lambda

AWS Lambda is the most popular serverless platform. Functions run in response to events and scale automatically.

// AWS Lambda function (Node.js) exports.handler = async (event) => { console.log('Received event:', JSON.stringify(event, null, 2)); // Parse request body from API Gateway const body = event.body ? JSON.parse(event.body) : {}; const response = { statusCode: 200, body: JSON.stringify({ message: `Hello, ${body.name || 'World'}!`, timestamp: new Date().toISOString(), }), headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, }; return response; };

Infrastructure as Code (Serverless Framework)

# serverless.yml service: my-api provider: name: aws runtime: nodejs18.x region: us-east-1 functions: hello: handler: handler.hello events: - http: path: hello method: get - http: path: hello method: post
# Deploy npm install -g serverless serverless deploy

3. API Gateway

API Gateway is a managed service for creating and managing APIs that expose Lambda functions (or other backends) via HTTP.

// API Gateway integration (AWS CDK) import * as apigateway from 'aws-cdk-lib/aws-apigateway'; import * as lambda from 'aws-cdk-lib/aws-lambda'; const helloFn = new lambda.Function(this, 'HelloHandler', { runtime: lambda.Runtime.NODEJS_18_X, code: lambda.Code.fromAsset('lambda'), handler: 'handler.hello', }); const api = new apigateway.RestApi(this, 'MyApi', { restApiName: 'My Service', }); const helloIntegration = new apigateway.LambdaIntegration(helloFn); api.root.addMethod('GET', helloIntegration); api.root.addMethod('POST', helloIntegration);

4. Edge Computing

Edge computing runs code at the edge (closest to users), reducing latency.

Cloudflare Workers

// Cloudflare Worker export default { async fetch(request, env) { const url = new URL(request.url); // Route based on URL if (url.pathname === '/api/hello') { const name = url.searchParams.get('name') || 'World'; return new Response(JSON.stringify({ message: `Hello, ${name}!` }), { headers: { 'Content-Type': 'application/json' }, }); } // Edge caching const cache = caches.default; const cached = await cache.match(request); if (cached) return cached; const response = await fetch(request); const cacheResponse = new Response(response.body, response); cacheResponse.headers.set('Cache-Control', 'public, max-age=3600'); await cache.put(request, cacheResponse.clone()); return cacheResponse; } };

Vercel Edge Functions

// api/edge/hello.ts (Vercel Edge) export const config = { runtime: 'edge', }; export default async function handler(req) { const name = req.nextUrl.searchParams.get('name') || 'World'; return new Response( JSON.stringify({ message: `Hello, ${name}!` }), { status: 200, headers: { 'Content-Type': 'application/json' }, } ); }
Edge use cases:
  • Geolocation‑based personalisation
  • A/B testing
  • Bot protection
  • Real‑time user personalisation
  • Edge caching of API responses

5. Use Cases & Best Practices

Best use cases for serverless

  • APIs with variable traffic: Auto‑scales to handle spikes.
  • Background processing: Image/video processing, data transformation.
  • Event‑driven workflows: File uploads, database changes, schedule tasks.
  • Microservices: Small, focused functions.
  • Prototyping: Fast development and iteration.

Best practices

  • Keep functions small: Single responsibility.
  • Use environment variables: For configuration.
  • Monitor and log: Use CloudWatch, Datadog, etc.
  • Optimise cold starts: Use provisioned concurrency if needed.
  • Secure your functions: Use IAM roles, API keys, JWT.
// Cold start mitigation // Use provisioned concurrency provider: lambda: provisionedConcurrency: 1 // Optimise package size // Use Webpack to bundle dependencies // Use layers for shared dependencies

Quiz

Question 1

What is the primary billing model for AWS Lambda?

  • Fixed monthly fee
  • Per‑request + per‑execution time
  • Per‑GB of storage
  • Based on the number of concurrent executions
Show answer
B. Per‑request + per‑execution time (measured in milliseconds).

Question 2

Which platform runs code at the edge, closest to users?

  • AWS Lambda
  • Cloudflare Workers
  • Google Cloud Functions
  • Azure Functions
Show answer
B. Cloudflare Workers (and Vercel Edge).

Question 3

What is a "cold start" in serverless?

  • When the function runs for the first time after being idle
  • When the function encounters an error
  • When the function is deployed
  • When the function times out
Show answer
A. When the function runs for the first time after being idle (adding latency).

Exercises

Exercise 1

Write an AWS Lambda function that returns a random number between 1 and 100. Deploy it with API Gateway.

Sample answer
exports.handler = async (event) => { const random = Math.floor(Math.random() * 100) + 1; return { statusCode: 200, body: JSON.stringify({ random }), headers: { 'Content-Type': 'application/json' }, }; };

Use Serverless Framework or AWS Console to deploy.

Exercise 2

Write a Cloudflare Worker that caches API responses for 1 hour and returns a custom greeting based on the user's geolocation.

Sample answer
export default { async fetch(request, env) { const cache = caches.default; const cached = await cache.match(request); if (cached) return cached; const country = request.cf?.country || 'World'; const response = new Response( JSON.stringify({ greeting: `Hello from ${country}!` }), { headers: { 'Content-Type': 'application/json' } } ); const cacheResponse = new Response(response.body, response); cacheResponse.headers.set('Cache-Control', 'public, max-age=3600'); await cache.put(request, cacheResponse.clone()); return cacheResponse; } };

Homework

Homework 1

Deploy a serverless function for your capstone project's backend using AWS Lambda or Cloudflare Workers. Include a REST API endpoint and implement caching.

Sample outline
  • Platform: AWS Lambda + API Gateway.
  • Function: Products API (GET /products, GET /products/:id).
  • Caching: Use CloudFront or API Gateway caching.
  • Monitoring: CloudWatch logs and metrics.

Mini‑Project

Serverless Application

Build a complete serverless application with:

  • AWS Lambda + API Gateway for the backend
  • S3 for static assets (frontend)
  • Edge caching with CloudFront or Cloudflare
  • Database (DynamoDB or RDS)
  • Monitor with CloudWatch
Sample outline
  • Backend: Lambda functions for CRUD operations.
  • API: API Gateway REST API.
  • Frontend: Static site in S3.
  • Database: DynamoDB for low‑cost storage.
  • Edge: CloudFront CDN for global delivery.

Tutorial Summary

You learned about serverless platforms (AWS Lambda, API Gateway) and edge computing (Cloudflare Workers, Vercel Edge). You can now build event‑driven, globally distributed applications that scale automatically and cost efficiently.

Key takeaway: Serverless and edge computing represent the future of cloud architecture — focusing on code, not infrastructure.