Your blogging app’s /api/posts?tag=tech endpoint is getting slow for users in Asia. You want to speed it up using the edge function below. What changes would make it perform better globally?
/api/posts?tag=tech
import type { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'nodejs', // Current setting }; export default async function handler(req: NextRequest): Promise<NextResponse> { const url = new URL(req.url); const tag = url.pathname.slice(1); if (tag) { url.pathname = '/api/posts'; url.searchParams.set('tag', tag); return fetch(url); } return new NextResponse('Invalid tag', { status: 400 }); }
Cache the fetch response at the edge
Add a DynamoDB query inside the function
Move the function to AWS Lambda
Increase the function’s memory allocation
Change runtime: 'nodejs' to runtime: 'edge'
runtime: 'nodejs'
runtime: 'edge'
BlogStar, your blogging app, gets a traffic spike to 10,000 users after a viral post. The /api/posts Lambda function below handles it. Which factors ensure it scales without crashing?
/api/posts
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb'; import { unmarshall } from '@aws-sdk/util-dynamodb'; const client = new DynamoDBClient({ region: 'us-east-1' }); export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => { const tag = event.queryStringParameters?.tag || ''; const params = { TableName: 'BlogPosts', FilterExpression: tag ? 'contains(tags, :tag)' : undefined, ExpressionAttributeValues: tag ? { ':tag': { S: tag } } : undefined, }; try { const result = await client.send(new ScanCommand(params)); const posts = result.Items?.map(item => unmarshall(item)) || []; return { statusCode: 200, body: JSON.stringify(posts), }; } catch (error) { return { statusCode: 500, body: JSON.stringify({ error: 'Failed to fetch posts' }), }; } };
Static file hosting on S3
Error handling with try-catch
Using runtime: 'edge' for speed
Lambda’s automatic scaling
DynamoDB’s ability to handle high read requests
You deploy an edge function to rewrite /tech to /api/posts?tag=tech, but users see a 504 Timeout error. What likely caused it, based on this code?
/tech
import type { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function handler(req: NextRequest): Promise<NextResponse> { const url = new URL(req.url); const tag = url.pathname.slice(1); if (tag) { const posts = await fetch('https://slow-api.com/posts').then(res => res.json()); const filtered = posts.filter((post: any) => post.tags.includes(tag)); return new NextResponse(JSON.stringify(filtered), { status: 200 }); } return new NextResponse('Invalid tag', { status: 400 }); }
Cold start delays in Lambda
Missing runtime: 'edge' configuration
Missing TypeScript type definitions
Incorrect IAM permissions for DynamoDB
Slow API call and filtering in the function
Blog’s admin page at /admin is slow to load during peak times. You’re deploying the Next.js app as Lambda. What can improve performance?
/admin
Set output: 'serverless' in next.config.js
output: 'serverless'
next.config.js
Increase API Gateway timeout limits
Rewrite /admin with an edge function
Store admin data in DynamoDB instead of S3
Use a warmup plugin to reduce cold starts
A user in London visits /tech on your blog, expecting fast load times. Your edge function uses country-based personalization. What ensures the speed?
import type { NextRequest, NextResponse } from 'next/server'; export const config = { runtime: 'edge', }; export default async function handler(req: NextRequest): Promise<NextResponse> { const url = new URL(req.url); const tag = url.pathname.slice(1); const country = req.headers.get('x-vercel-ip-country') || 'US'; if (tag) { url.pathname = '/api/posts'; url.searchParams.set('tag', tag); url.searchParams.set('country', country); const response = await fetch(url); return new NextResponse(response.body, { status: response.status, headers: { 'x-country': country }, }); } return new NextResponse('Invalid tag', { status: 400 }); }
Lambda scaling for high traffic
Using x-vercel-ip-country header
x-vercel-ip-country
runtime: 'edge' deploying to global CDN
Fetching from a fast /api/posts endpoint
TypeScript’s type safety
You notice high costs for your blog’s Lambda-based API during a traffic spike. What could reduce expenses without losing functionality?
Switch all functions to edge runtime
Lower Lambda memory to 128MB
Cache API responses at the edge
Host static files on CloudFront
Use DynamoDB streams for queries
This content is only available to registered users.Please register at the the home page.