Deploy to Vercel

Serverless Functions and APIs

35 min

Route handlers become functions

// app/api/subscribe/route.js (Next.js)
export async function POST(request) {
  const { email } = await request.json();
  if (!email || !email.includes("@")) {
    return Response.json({ error: "Valid email required" }, { status: 400 });
  }
  await addToNewsletter(email, process.env.NEWSLETTER_API_KEY);
  return Response.json({ ok: true });
}

Each route runs as a function that scales automatically with traffic.

Limits to design around

  • Maximum duration per invocation (depends on plan and configuration): keep work short or hand it to a queue.
  • Cold starts: the first request to an idle function is slower. Keep dependencies small.
  • Statelessness: no in-memory state survives between invocations. Store sessions, caches and rate-limit counters in a database or Redis service.
  • No background work after responding unless you use the platform's supported mechanism for it.

Databases from serverless

Thousands of short-lived functions can each open a database connection and exhaust the database. Use:

  • a connection pooler (for example a provider's pooled connection string or PgBouncer),
  • or serverless-friendly databases and drivers that work over HTTP.

Edge vs Node.js runtime

The edge runtime runs close to users with very fast start-up, but supports only web-standard APIs (no full Node.js). Use it for lightweight logic such as redirects, geolocation and auth checks; use the Node.js runtime for anything needing Node libraries or long work.

Rate limiting and abuse

Public functions can be called by anyone. Validate input, rate-limit with a shared store, add bot protection on forms and set spending limits so a traffic spike cannot surprise you.

Exercise

Build a newsletter sign-up API route with validation, a rate limit stored in a hosted Redis, and a database write through a pooled connection. Measure the cold-start and warm response times.

Check yourself

  • Why can't serverless functions keep rate-limit counters in memory?
  • How do you avoid exhausting database connections?
  • When is the edge runtime a good fit?

Seu progresso fica salvo apenas neste navegador.

Enviar para revisão (10 pontos)