Serverless Deep Dive: AWS & Vercel

Serverless Deep Dive: AWS & Vercel in JavaScript: Serverless is like a Pay-as-you-go phone plan.

Concept Explanation

Serverless is like a Pay-as-you-go phone plan. You don't pay for the phone; you only pay for the minutes you use. With AWS Lambda or Vercel Functions, you don't pay for the server; you only pay for the milliseconds your code is actually running.

The name is a lie in a useful way. There is absolutely a server; you just never meet it. No SSH, no OS patches, no capacity planning, no PM2 keeping a process alive. You hand over a function and the platform runs it on demand, from zero copies to ten thousand, and back to zero.

What you trade away is persistence. A traditional Node server boots once and lives for weeks, so it can hold a connection pool, an in-memory cache, a WebSocket, a background timer. A serverless function is summoned, answers one request, and may be destroyed. Anything you want to remember has to live somewhere else. Every serverless design decision follows from that one constraint.


Syntax or Core Structure (Vercel)

// api/hello.js
export default function handler(req, res) {
  const name = req.query.name || 'Stranger';
  res.status(200).send(`Hello ${name} from the cloud!`);
}

The same idea on AWS Lambda

export const handler = async (event) => {
  const name = event.queryStringParameters?.name ?? 'Stranger';
  return {
    statusCode: 200,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ message: 'Hello ' + name })
  };
};

Reusing what you can across invocations

// Module scope runs ONCE per container, not once per request.
// It survives while the container stays warm, so put clients here.
const db = createClient({ url: process.env.DATABASE_URL });

export default async function handler(req, res) {
  const rows = await db.query('select 1');   // reuses the warm connection
  res.json(rows);
}

Cold Starts, Concretely

The first request to an idle function pays for the platform to allocate a container, load your code, and run module-level initialisation. That is the cold start, typically tens to a few hundred milliseconds for a small Node bundle. Subsequent requests hit the warm container and skip all of it.

Three things make cold starts worse, and all three are under your control:

  • Bundle size. Importing an entire cloud SDK to send one email adds real milliseconds. Import only what you use.
  • Heavy top-level work. Reading a large config file or compiling a schema at module scope is paid on every cold start.
  • VPC and memory configuration. Private networking adds setup latency; more memory also buys more CPU, so a larger function is sometimes cheaper because it finishes sooner.

Edge functions (Vercel Edge, Cloudflare Workers) cut cold starts to near zero by running a lighter runtime close to the user, at the cost of a restricted API surface: no full set of Node built-ins, tight CPU limits, no long-running work.


Real World Example

The connection-pool outage. A team moved a well-behaved Express API to Lambda unchanged, including new Pool() inside the request handler. Traffic spiked, the platform helpfully scaled to 800 concurrent executions, and each one opened its own database connections. Postgres hit max_connections and began refusing everything, including the admin dashboard.

The application had not become slower. It had become too good at scaling for the database behind it. The fix was two-part: move the client to module scope so warm containers reuse it, and put a connection proxy in front of Postgres. The general lesson is worth keeping: serverless scales compute instantly, and every stateful thing downstream becomes the new bottleneck.


Common Mistakes

  • Creating the DB client inside the handler. One connection per request, no reuse, and eventual connection exhaustion.
  • Storing state in a global and trusting it. Warm containers make this appear to work, which is worse than failing outright, because it breaks only under load or after a scale-down.
  • Writing to the local filesystem. Usually only /tmp is writable, it is small, and it disappears with the container.
  • Long-running jobs in a request handler. There is a hard timeout, often 10-60 seconds on HTTP paths. Video encoding belongs in a queue with a worker.
  • Ignoring the cost model. Serverless is cheap at low and spiky volume and can be markedly more expensive than a small VPS at sustained high throughput. Do the arithmetic before migrating.
  • No idempotency. Platforms retry on failure, so a payment handler that charges on every invocation will eventually double-charge someone.
  • Forgetting concurrency limits. An unbounded function can exhaust an account-wide quota and take down unrelated services.

Best Practices

  • Initialise clients at module scope; keep handlers stateless and small.
  • Keep bundles lean: tree-shake, import narrowly, and check the size of the deployed artifact.
  • Make handlers idempotent, keyed on a request or event ID, so retries are harmless.
  • Read configuration and secrets from platform-managed environment variables, never from the repository.
  • Put a queue between the HTTP entry point and any slow work, and set explicit timeouts and concurrency caps.
  • Instrument everything. With no server to SSH into, structured logs, traces and metrics are your only visibility.
  • Choose deliberately: serverless for spiky, event-driven and glue work; a long-lived server for WebSockets, sustained throughput, and anything that needs a warm in-process cache.

Practice Exercises

  1. The Cloud Deploy: Create a free Vercel account and deploy a single "Hello World" function.
  2. The Environment Trap: Research why process.env is used to store database passwords in cloud environments.
  3. The Scaling Test: Explain how a serverless function handles 1,000,000 users coming to your site at the exact same second, and name the first thing that will break downstream.