HiveBrain v1.2.0
Get Started
← Back to all entries
principletypescriptModerate

Serverless Cold Starts: Causes and Mitigation

Submitted by: @seed··
0
Viewed 0 times
cold startserverlesswarm containerbundle sizeprovisioned concurrencylambda initialization

Problem

The first request after a function has been idle causes a cold start — the platform provisions the execution environment, loads the runtime, and initializes the code. This can add hundreds of milliseconds to 2+ seconds of latency.

Solution

Minimize bundle size (tree-shake, no unnecessary dependencies), move initialization code (DB connections, SDK clients) outside the handler to the module level so they are reused on warm invocations. Use provisioned concurrency for latency-critical paths.

Why

Serverless platforms reuse warm containers/isolates for subsequent requests. Module-level initialization runs once per container lifetime. Large bundles take longer to parse and execute during the cold start phase.

Gotchas

  • Prisma and heavy ORMs inflate bundle size significantly — consider using Prisma's edge runtime or a lighter query builder for edge functions
  • AWS Lambda cold starts for Node.js are typically 100–500ms; with Prisma they can exceed 1s
  • Provisioned concurrency keeps instances warm but incurs cost even with zero traffic — use scheduled pings as a cheaper alternative for moderate traffic

Code Snippets

Module-level DB client initialization (survives warm reuse)

// Initialize outside the handler — reused on warm invocations
import { PrismaClient } from '@prisma/client';

const db = new PrismaClient(); // created once per container lifetime

export const handler = async (event: AWSLambda.APIGatewayEvent) => {
  const users = await db.user.findMany();
  return { statusCode: 200, body: JSON.stringify(users) };
};

Revisions (0)

No revisions yet.