← Back to Node.js, page 9

nodejs-0174 · Easy fresher

How does a Node.js AWS Lambda handler work, what is a cold start, and what should run in init code versus in the handler?

A Lambda function exports a handler (event, context). The platform starts an execution environment on demand: it loads your module (the init phase, a cold start) and then calls the handler. The environment is reused for later invocations (warm), so code outside the handler runs once per environment and is the place for clients and configuration, while per-request work stays inside the handler. Cold starts grow with bundle size, heavy imports and init work.

Full answer

Handler basics

  • export const handler = async (event, context) => { ... return result }. The event shape depends on the trigger. For API Gateway or a function URL, event has httpMethod or requestContext, headers, body (a string, base64 encoded when isBase64Encoded is true) and the response needs statusCode, headers and body.
  • context gives awsRequestId, functionName and getRemainingTimeInMillis().
  • Async handlers return a value or throw. Throwing makes the invocation fail with errorType and errorMessage (and the platform may retry, depending on the trigger).
  • The older callback style exists. With callbacks, context.callbackWaitsForEmptyEventLoop decides whether Lambda waits for pending work. Prefer async functions.

Lifecycle

  • Init phase (cold start): download the code, start the runtime, run top-level module code. It happens once for a new execution environment.
  • Invoke phase: the handler runs. After it returns the environment is frozen, and may be reused for a later event (warm start) or discarded.
  • Concurrency: one environment handles one request at a time. A spike creates more environments, each with a cold start.

What belongs where

  • Outside the handler (once): SDK and database clients, config loading, compiled regular expressions, caches.
  • Inside the handler (each time): reading the event, per-request state, business logic. Never keep user data in module variables that could leak between requests.

Reducing cold starts

  • Bundle and minify (esbuild), import only what you need (modular AWS SDK v3 clients), avoid heavy init work, choose more memory (more CPU), keep functions small, and use provisioned concurrency or SnapStart where available when latency matters.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

// A handler file, as you would deploy it.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lambda-'));
const file = path.join(dir, 'handler.js');
fs.writeFileSync(file, `
let initRuns = 0;
initRuns++;                                     // top-level code: runs once per execution environment
const client = { createdAt: 'init' };           // a database or SDK client would be created here
let invocations = 0;

exports.handler = async (event, context) => {
  invocations++;
  const raw = event.isBase64Encoded ? Buffer.from(event.body, 'base64').toString() : event.body;
  const body = raw ? JSON.parse(raw) : {};
  if (body.crash) throw new Error('something broke');
  return {
    statusCode: 200,
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ hello: body.name ?? 'world', invocations, initRuns, coldStart: invocations === 1, client: client.createdAt, msLeft: context.getRemainingTimeInMillis() > 0 }),
  };
};
`);

// A tiny stand-in for the Lambda runtime (not AWS code): load once, then call the handler per event.
let handlerModule;
async function invoke(event, timeoutMs = 3000) {
  handlerModule ??= require(file);               // the first invoke pays the "init" cost
  const deadline = Date.now() + timeoutMs;
  const context = { awsRequestId: 'req-' + Math.random().toString(36).slice(2, 8), getRemainingTimeInMillis: () => deadline - Date.now() };
  try { return await handlerModule.handler(event, context); }
  catch (err) { return { errorType: err.name, errorMessage: err.message }; }
}

(async () => {
  const print = (label, result) => console.log(label.padEnd(18), typeof result.body === 'string' ? `${result.statusCode} ${result.body}` : JSON.stringify(result));
  print('1st invoke (cold)', await invoke({ body: JSON.stringify({ name: 'Asha' }) }));
  print('2nd invoke (warm)', await invoke({ body: JSON.stringify({ name: 'Ravi' }) }));
  print('base64 body', await invoke({ isBase64Encoded: true, body: Buffer.from('{"name":"Meera"}').toString('base64') }));
  print('handler throws', await invoke({ body: '{"crash":true}' }));
  fs.rmSync(dir, { recursive: true });
})();

A small simulated runtime (not AWS code) loads a handler file once and calls it several times, so the cold and warm behaviour can be seen. Real Lambda adds the platform, billing, limits and freezing. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1st invoke (cold) 200 {"hello":"Asha","invocations":1,"initRuns":1,"coldStart":true,"client":"init","msLeft":true} 2nd invoke (warm) 200 {"hello":"Ravi","invocations":2,"initRuns":1,"coldStart":false,"client":"init","msLeft":true} base64 body 200 {"hello":"Meera","invocations":3,"initRuns":1,"coldStart":false,"client":"init","msLeft":true} handler throws {"errorType":"Error","errorMessage":"something broke"}

Key points

  • The handler receives (event, context) and returns or throws.
  • Top-level code runs once per execution environment (cold start).
  • Create clients outside the handler and reuse them.
  • Keep per-request data inside the handler.
  • Smaller bundles and lighter init reduce cold starts.

Common mistakes

  • Creating database clients inside the handler for every request.
  • Storing per-user data in module-level variables.
  • Importing the whole AWS SDK and large libraries.
  • Forgetting that the body can be base64 encoded.
  • Doing slow init work that every cold start pays for.

Follow-ups

  • What is the difference between provisioned concurrency and SnapStart?
  • How does memory size change CPU and cost?
  • What happens to a failed asynchronous invocation?

Tips

  • Explain init versus invoke.
  • Say 'clients outside, request data inside'.
  • Give two ways to reduce cold starts.