← Back to Node.js, page 9

nodejs-0175 · Hard senior

What are the common pitfalls of Node.js serverless functions: database connections, timeouts, duplicate events and work after the response?

Each concurrent execution has its own environment, so many functions can open too many database connections (reuse clients outside the handler and use a pooler or proxy). Functions are killed at the timeout, so budget time with the remaining time from the context. Events are delivered at least once, so handlers must be idempotent. After the handler returns the environment is frozen, so work that was not awaited may never finish.

Full answer
  1. Connections
  • A pool of 10 connections per environment times 200 concurrent executions is 2000 connections, which can overwhelm a database. Create the client once per environment (outside the handler), use a small pool (1 to 2), and use a connection pooler or proxy (RDS Proxy, PgBouncer, an HTTP-based data API) for relational databases.
  1. Time budget
  • The platform stops the function at its timeout, with no cleanup. Read context.getRemainingTimeInMillis(), give downstream calls a deadline that is shorter (with AbortSignal.timeout), and return a clean error or partial result before the kill. Also set sensible timeouts on SDK clients.
  1. Duplicate delivery
  • Queues (SQS), streams, EventBridge and retries by the platform deliver at least once. The same event can arrive twice, or arrive out of order. Make the handler idempotent: record the event id with a conditional write, use natural idempotency keys for payments, and use upserts.
  • For SQS batches report partial failures, so one bad message does not return the whole batch.
  1. Work after the response
  • When the handler returns, the environment is frozen, and timers and promises that were not awaited are paused or lost. Await everything before returning. For follow-up work use a queue or an extension that supports it.
  1. Other points
  • Cold start latency on user-facing paths: lighter bundles, provisioned concurrency.
  • Local state: the filesystem (/tmp) and module memory survive only by chance, so treat them as a cache.
  • Concurrency limits and cost surprises: set reserved concurrency and budgets, and protect downstream systems with queues.
  • Observability: structured logs with the request id, and tracing across functions.
javascript
const { setTimeout: sleep } = require('node:timers/promises');

// A stand-in runtime (not AWS code) that keeps one environment and freezes it after each handler returns.
class FakeEnvironment {
  constructor() { this.frozen = false; this.clientsCreated = 0; this.processed = new Set(); }
  async invoke(handler, event, timeoutMs) {
    this.frozen = false;
    const deadline = Date.now() + timeoutMs;
    const context = { getRemainingTimeInMillis: () => deadline - Date.now() };
    const result = await handler(event, context, this);
    this.frozen = true;                      // after the response the environment is paused
    return result;
  }
}

const dbClientPerInvoke = (env) => { env.clientsCreated++; return {}; };
let sharedClient;
const dbClientShared = (env) => (sharedClient ??= (env.clientsCreated++, {}));

async function main() {
  // 1. Connections
  const env = new FakeEnvironment();
  for (let i = 0; i < 5; i++) await env.invoke(async (e, c, environment) => dbClientPerInvoke(environment), {}, 1000);
  const perInvoke = env.clientsCreated;
  env.clientsCreated = 0;
  for (let i = 0; i < 5; i++) await env.invoke(async (e, c, environment) => dbClientShared(environment), {}, 1000);
  console.log('1. clients created in 5 invocations: per invoke =', perInvoke, '| shared =', env.clientsCreated);

  // 2. Time budget: stop waiting before the platform would kill us.
  const slowDependency = (signal) => new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve('data'), 500);
    signal.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); });
  });
  const result = await env.invoke(async (event, context) => {
    const budget = context.getRemainingTimeInMillis() - 100;           // keep 100 ms to answer
    try { return await slowDependency(AbortSignal.timeout(budget)); }
    catch (err) { return { statusCode: 504, error: err.name }; }
  }, {}, 250);
  console.log('2. dependency slower than the budget ->', JSON.stringify(result));

  // 3. Duplicate delivery
  const handler = async (event, context, environment) => {
    if (environment.processed.has(event.id)) return 'duplicate skipped';
    environment.processed.add(event.id);                                // a conditional write in a real table
    return 'processed ' + event.id;
  };
  console.log('3. same event twice ->', await env.invoke(handler, { id: 'evt-1' }, 1000), '|', await env.invoke(handler, { id: 'evt-1' }, 1000));

  // 4. Work that is not awaited
  const steps = [];
  await env.invoke(async (event, context, environment) => {
    (async () => { for (let i = 1; i <= 3; i++) { await sleep(20); if (environment.frozen) { steps.push('frozen at step ' + i); return; } steps.push('step ' + i); } })();
    return 'response sent';                                              // returns without awaiting the background work
  }, {}, 1000);
  await sleep(100);
  console.log('4. background work after the response ->', steps.join(', '));
}
main();

A simulated environment is frozen after each response. It shows shared clients, a time budget, a duplicate event, and background work that stops after the handler returns. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. clients created in 5 invocations: per invoke = 5 | shared = 1 2. dependency slower than the budget -> {"statusCode":504,"error":"TimeoutError"} 3. same event twice -> processed evt-1 | duplicate skipped 4. background work after the response -> frozen at step 1

Key points

  • Reuse clients per environment and limit total database connections.
  • Use the remaining time to set deadlines before the platform kills the function.
  • At-least-once delivery requires idempotent handlers.
  • Unawaited work after the return can be lost.
  • Use queues to smooth load and protect downstream systems.

Common mistakes

  • A big pool per function with hundreds of concurrent executions.
  • No deadline on downstream calls, so the platform kills the function.
  • Assuming a message is delivered exactly once.
  • Starting a promise and returning without awaiting it.
  • Keeping state in module variables and relying on it.

Follow-ups

  • How does RDS Proxy help?
  • How do you report partial batch failures for SQS?
  • How do you limit the concurrency that hits a database?

Tips

  • Give the four pitfalls as a list.
  • Say 'at least once, so idempotent'.
  • Mention the frozen environment.