Backend

Building Serverless Functions

Mayur Dabhi
Mayur Dabhi
May 8, 2026
14 min read

You've got a small app on a VPS, and someone asks for "just one more thing": resize images after upload, send a welcome email, run a cleanup job every hour. Each one means another worker process, another cron entry, another thing to keep alive when the box reboots at 3am. Or traffic is spiky, and you're paying for a server that sits idle most of the day so it can survive the busy hour.

That's the kind of work serverless functions handle well. This post walks through building them on AWS Lambda (with the Serverless Framework) and on Vercel: handlers, event triggers, IAM, cold starts, testing, and the production details that tend to bite later.

What "serverless" actually means

There are still servers. You just don't patch, size, or scale them. You're billed per invocation and per millisecond of compute, and the platform adds or removes instances as requests come in, down to zero when nothing is happening.

How a Serverless Function Behaves

You hand the platform a function and tell it which event should run it (an HTTP request, a queue message, a file upload). When the event fires, the provider finds or creates an execution environment, runs your code, and returns the result. You never see the machine.

A few properties shape how you write code for it:

Client HTTP Request API Gateway Routes & Auth Rate Limiting Lambda Fn A Node.js / Python 128MB to 10GB RAM Lambda Fn B Auth / Email Background Job DynamoDB Database S3 Bucket File Storage SQS Queue Messaging SES / SNS Notifications Serverless architecture: functions talk to managed AWS services

Each function handles a single concern and integrates with managed cloud services

Serverless Platforms Compared

Every major cloud has a FaaS product, and they differ more in limits and runtime model than in features. Treat the numbers below as rough: providers change free tiers and timeouts often, so check the current docs before you commit.

Platform Free Tier Max Timeout Cold Start Best For
AWS Lambda 1M req/month 15 minutes ~100-500ms Enterprise, complex workflows
Vercel Functions 100GB-hours 60 seconds ~50-200ms Next.js, frontend-adjacent APIs
Cloudflare Workers 100K req/day 30 seconds <5ms (V8 isolates) Edge computing, low latency
Google Cloud Functions 2M req/month 60 minutes ~100-400ms GCP ecosystem integrations
Azure Functions 1M req/month Unlimited* ~200-600ms .NET, Azure ecosystem
Choosing a Platform

If you're on Node.js: Lambda when you need queues, S3 triggers and long timeouts; Vercel when the functions are API routes next to a Next.js frontend; Cloudflare Workers when latency matters more than Node API compatibility. In practice the choice usually follows whichever cloud your data already lives in.

Your First AWS Lambda Function

Lambda supports Node.js, Python, Go (via the OS-only runtime), Java, Ruby, .NET, and custom runtimes. The examples here use Node.js 20 and a small users API backed by DynamoDB.

Project Setup with the Serverless Framework

You can click through the Lambda console, but you'll regret it by the third function. The Serverless Framework (or AWS SAM) keeps everything in a config file: packaging, IAM roles, API Gateway routes, and environment variables.

1

Install the Serverless Framework

Install globally and configure your AWS credentials before proceeding.

Terminal
# Install Serverless Framework globally
npm install -g serverless

# Configure AWS credentials (one-time setup)
aws configure
# Enter: AWS Access Key ID, Secret, Region (e.g. us-east-1), Output format (json)

# Create a new serverless project
serverless create --template aws-nodejs --path my-service
cd my-service
npm init -y
2

Define Your Service in serverless.yml

This file declares your functions, events, IAM permissions, and environment configuration.

serverless.yml
service: my-api-service

provider:
  name: aws
  runtime: nodejs20.x
  region: us-east-1
  memorySize: 256       # MB; CPU scales with memory, so raise it for CPU-heavy tasks
  timeout: 10           # seconds (Lambda max is 900)
  environment:
    DB_HOST: ${env:DB_HOST}
    JWT_SECRET: ${env:JWT_SECRET}
    NODE_ENV: ${opt:stage, 'dev'}
  iam:
    role:
      statements:
        - Effect: Allow
          Action:
            - dynamodb:GetItem
            - dynamodb:PutItem
            - dynamodb:UpdateItem
            - dynamodb:DeleteItem
            - dynamodb:Query
          Resource:
            - arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/Users
            - arn:aws:dynamodb:${aws:region}:${aws:accountId}:table/Users/index/*

functions:
  getUser:
    handler: src/users/get.handler
    events:
      - httpApi:
          path: /users/{id}
          method: GET

  createUser:
    handler: src/users/create.handler
    events:
      - httpApi:
          path: /users
          method: POST

  processQueue:
    handler: src/queue/processor.handler
    events:
      - sqs:
          arn: arn:aws:sqs:us-east-1:123456789:my-queue
          batchSize: 10

  scheduledTask:
    handler: src/tasks/cleanup.handler
    events:
      - schedule:
          rate: rate(1 hour)
          enabled: true

plugins:
  - serverless-offline           # local development
  - serverless-dotenv-plugin     # .env support
3

Write the Handler Function

Each handler receives an event (the trigger payload) and a context (Lambda runtime info), and returns a response object.

src/users/get.js
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb');

// Initialize outside the handler so warm invocations reuse it
const client = new DynamoDBClient({ region: process.env.AWS_REGION });
const docClient = DynamoDBDocumentClient.from(client);

const headers = {
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
};

exports.handler = async (event, context) => {
  // Tell Lambda not to wait for empty event loop
  context.callbackWaitsForEmptyEventLoop = false;

  try {
    const { id } = event.pathParameters;

    if (!id) {
      return {
        statusCode: 400,
        headers,
        body: JSON.stringify({ error: 'User ID is required' }),
      };
    }

    const result = await docClient.send(new GetCommand({
      TableName: 'Users',
      Key: { userId: id },
    }));

    if (!result.Item) {
      return {
        statusCode: 404,
        headers,
        body: JSON.stringify({ error: 'User not found' }),
      };
    }

    return {
      statusCode: 200,
      headers,
      body: JSON.stringify(result.Item),
    };
  } catch (error) {
    console.error('GetUser error:', error);
    return {
      statusCode: 500,
      headers,
      body: JSON.stringify({ error: 'Internal server error' }),
    };
  }
};
4

Deploy to AWS

The framework packages your code, uploads it to S3, and creates/updates Lambda functions and API Gateway automatically.

Terminal
# Deploy to dev stage
serverless deploy --stage dev

# Deploy to production
serverless deploy --stage prod

# Deploy only a single function (faster for iteration)
serverless deploy function --function getUser

# Test locally with serverless-offline
serverless offline start

# View logs for a function
serverless logs --function getUser --tail

# Remove all resources
serverless remove --stage dev

Understanding Cold Starts

The first request after a deploy, or after a quiet period, is often noticeably slower than the rest. That's a cold start: Lambda has to create a fresh execution environment, download your code package, start the runtime, and run your module-level code before the handler even begins. A warm start reuses an existing environment and skips all of that.

For a queue consumer nobody waits on, cold starts rarely matter. For a user-facing API with low traffic, they can be the slowest thing in the request.

COLD START Download code Init runtime Init module Your handler ~200-600ms total WARM START Download code Init runtime Init module Your handler ~5-50ms total Dashed steps are skipped because the container is already warm

Cold vs warm start: module-level code only runs on a cold start

Strategies to Reduce Cold Start Impact

Do less work at init time:

// BAD: Heavy imports at module level delay cold start
const aws = require('aws-sdk');             // 40MB+
const moment = require('moment');           // brings locale data
const _ = require('lodash');

// GOOD: Import only what you need
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { format } = require('date-fns');    // tree-shakeable

// GOOD: Lazy-load heavy dependencies inside handler
exports.handler = async (event) => {
  if (event.requiresPdf) {
    const { PDFDocument } = await import('pdf-lib');
    // ...
  }
};

// GOOD: Initialize SDK clients outside handler (reused on warm)
const db = new DynamoDBClient({ region: 'us-east-1' });

exports.handler = async (event) => {
  // db client already exists here and is reused on warm invocations
};

Provisioned Concurrency keeps N environments initialized at all times (and you pay for them while idle):

# serverless.yml: keep 5 warm containers for production
functions:
  getUser:
    handler: src/users/get.handler
    provisionedConcurrency: 5     # always-warm containers
    events:
      - httpApi:
          path: /users/{id}
          method: GET

# OR use Application Auto Scaling for time-based provisioning
# (scale up to 20 before 9am, down to 2 after midnight)
resources:
  Resources:
    GetUserScalableTarget:
      Type: AWS::ApplicationAutoScaling::ScalableTarget
      Properties:
        ServiceNamespace: lambda
        ScalableDimension: lambda:function:ProvisionedConcurrency
        MinCapacity: 2
        MaxCapacity: 20

Lambda SnapStart (Java, Python 3.12+, .NET 8) snapshots the environment after init and restores from it:

# serverless.yml: enable SnapStart for Java functions
functions:
  javaHandler:
    handler: com.example.Handler::handleRequest
    runtime: java21
    snapStart: true    # snapshot taken after init phase
    events:
      - httpApi:
          path: /api/java
          method: POST

# SnapStart restores from snapshot instead of re-initializing
# The biggest wins are on JVM runtimes with slow init
# Not available for Node.js (use Provisioned Concurrency instead)

Event Sources and Triggers

HTTP is only one way in. Most of the useful Lambda work I see is triggered by something else: a file landing in S3, a message on a queue, a schedule. These are the three patterns that come up most.

HTTP API via API Gateway

src/users/create.js: HTTP POST handler
const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb');
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { randomUUID } = require('crypto');

const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}));

exports.handler = async (event) => {
  const body = JSON.parse(event.body || '{}');

  // Validate input
  if (!body.email || !body.name) {
    return {
      statusCode: 422,
      body: JSON.stringify({ error: 'email and name are required' }),
    };
  }

  const user = {
    userId: randomUUID(),
    email: body.email.toLowerCase().trim(),
    name: body.name.trim(),
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  };

  await docClient.send(new PutCommand({
    TableName: 'Users',
    Item: user,
    ConditionExpression: 'attribute_not_exists(email)',  // prevent duplicates
  }));

  return {
    statusCode: 201,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(user),
  };
};
That condition won't stop duplicate emails

attribute_not_exists(email) is only checked against the item with the same primary key. Since userId is a fresh UUID every time, there's never an existing item to compare against, so the write always succeeds. If emails must be unique, write a second item keyed by the email (for example EMAIL#alice@example.com) in the same TransactWriteCommand with attribute_not_exists on that key. Also note that a failed condition throws ConditionalCheckFailedException, which this handler would turn into a 500 unless you catch it and return a 409.

S3 Event Trigger

Run code whenever a file lands in a bucket: resize images, parse CSVs, scan uploads.

src/images/resize.js: S3 trigger
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
const sharp = require('sharp');   // image processing (Lambda layer or bundled)

const s3 = new S3Client({});
const SIZES = [{ w: 400, suffix: 'thumb' }, { w: 1200, suffix: 'large' }];

exports.handler = async (event) => {
  for (const record of event.Records) {
    const bucket = record.s3.bucket.name;
    const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' '));

    // Skip already-processed images (avoid infinite loop!)
    if (key.includes('/processed/')) continue;

    const { Body } = await s3.send(new GetObjectCommand({ Bucket: bucket, Key: key }));
    const imageBuffer = Buffer.from(await Body.transformToByteArray());

    await Promise.all(SIZES.map(async ({ w, suffix }) => {
      const resized = await sharp(imageBuffer)
        .resize(w, null, { withoutEnlargement: true })
        .webp({ quality: 85 })
        .toBuffer();

      const outputKey = key.replace('uploads/', `processed/${suffix}/`)
        .replace(/\.[^.]+$/, '.webp');

      await s3.send(new PutObjectCommand({
        Bucket: bucket,
        Key: outputKey,
        Body: resized,
        ContentType: 'image/webp',
        CacheControl: 'max-age=31536000',
      }));
    }));

    console.log(`Processed ${key} → ${SIZES.length} variants`);
  }
};

The processed/ check matters more than it looks. If the function writes its output back into the same bucket and the trigger isn't scoped by prefix, every output file fires the function again. Put a prefix: uploads/ rule on the S3 event as well, so the guard in code is a second line of defence, not the only one.

SQS Queue Processor

src/queue/processor.js: SQS batch handler
const { SESClient, SendEmailCommand } = require('@aws-sdk/client-ses');

const ses = new SESClient({ region: 'us-east-1' });

exports.handler = async (event) => {
  // Lambda delivers up to batchSize messages at once
  const results = await Promise.allSettled(
    event.Records.map(record => processMessage(JSON.parse(record.body)))
  );

  // Return failed message IDs so Lambda can retry them
  const failures = results
    .map((result, i) => ({ result, record: event.Records[i] }))
    .filter(({ result }) => result.status === 'rejected')
    .map(({ record }) => ({ itemIdentifier: record.messageId }));

  return { batchItemFailures: failures };
};

async function processMessage(message) {
  const { to, subject, body } = message;

  await ses.send(new SendEmailCommand({
    Source: 'noreply@example.com',
    Destination: { ToAddresses: [to] },
    Message: {
      Subject: { Data: subject },
      Body: { Html: { Data: body } },
    },
  }));

  console.log(`Email sent to ${to}`);
}
Make handlers idempotent

Standard SQS queues deliver messages at least once, so the same message can show up twice after a retry or a timeout. Processing it twice should give the same result as processing it once. A conditional write in DynamoDB keyed on a message or business ID is the usual way to enforce that. Otherwise, in this example, someone gets two copies of the same email.

Two SQS details that catch people out. First, returning batchItemFailures does nothing unless the event source mapping has it enabled (in serverless.yml, add functionResponseType: ReportBatchItemFailures under the sqs event). Without it, Lambda ignores the return value, and one bad message retries the whole batch. Second, set the queue's visibility timeout well above the function timeout (AWS suggests at least six times). If it's shorter, messages become visible again while the first invocation is still working on them, and you get duplicates even when nothing failed.

IAM Roles and the Principle of Least Privilege

Each function runs with an execution role, and that role is everything the code can do in your account. It's tempting to attach AmazonDynamoDBFullAccess (or worse, AdministratorAccess) to get past an AccessDeniedException and move on. Then a bug or an injected input in one small function can delete tables it never needed to touch. Give each function its own role with the specific actions and resources it uses:

serverless.yml: scoped IAM permissions per function
provider:
  name: aws
  runtime: nodejs20.x
  # No global IAM here; each function gets its own role

functions:
  getUser:
    handler: src/users/get.handler
    role: GetUserRole   # custom role with minimal permissions
    events:
      - httpApi:
          path: /users/{id}
          method: GET

  processImages:
    handler: src/images/resize.handler
    role: ImageProcessorRole

resources:
  Resources:
    # Read-only DynamoDB access for getUser
    GetUserRole:
      Type: AWS::IAM::Role
      Properties:
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service: lambda.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: GetUserPolicy
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - logs:CreateLogGroup
                    - logs:CreateLogStream
                    - logs:PutLogEvents
                  Resource: '*'
                - Effect: Allow
                  Action:
                    - dynamodb:GetItem
                  Resource:
                    - arn:aws:dynamodb:us-east-1:*:table/Users

    # S3 read + write for image processor
    ImageProcessorRole:
      Type: AWS::IAM::Role
      Properties:
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service: lambda.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: ImageProcessorPolicy
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - logs:CreateLogGroup
                    - logs:CreateLogStream
                    - logs:PutLogEvents
                  Resource: '*'
                - Effect: Allow
                  Action:
                    - s3:GetObject
                    - s3:PutObject
                  Resource: arn:aws:s3:::my-image-bucket/*

Vercel Serverless Functions

If you're already on Next.js, Vercel skips most of the setup above. Any file under pages/api (or a route.ts under app/ with the App Router) becomes a function on deploy. There's no YAML and no IAM, and deploying is a git push. The trade-off is less control over triggers: you get HTTP and cron, not S3 or SQS events.

pages/api/users/[id].ts: Next.js API Route
import type { NextApiRequest, NextApiResponse } from 'next';
import { db } from '@/lib/database';

type User = {
  id: string;
  name: string;
  email: string;
};

type ErrorResponse = {
  error: string;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<User | ErrorResponse>
) {
  const { id } = req.query;

  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const user = await db.user.findUnique({
      where: { id: String(id) },
      select: { id: true, name: true, email: true },
    });

    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    // Cache for 60s at edge, stale-while-revalidate for 5 minutes
    res.setHeader('Cache-Control', 's-maxage=60, stale-while-revalidate=300');
    return res.status(200).json(user);
  } catch (error) {
    console.error('Database error:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
}

Vercel Edge Functions

Edge Functions and Middleware run in V8 isolates on Vercel's edge network instead of a full Node.js process. Startup is close to instant, but you only get Web APIs: no fs, no net, and plenty of npm packages that assume Node won't load. Middleware is a good fit for auth redirects and rewrites like this:

middleware.ts: Vercel Edge Middleware
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// Runs at the edge, before any serverless function
export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token')?.value;

  // Protect /dashboard routes
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    if (!token) {
      return NextResponse.redirect(new URL('/login', request.url));
    }
  }

  // Geolocation-based routing
  const country = request.geo?.country || 'US';
  if (country === 'GB') {
    return NextResponse.rewrite(new URL('/uk' + request.nextUrl.pathname, request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/((?!api|_next/static|favicon.ico).*)'],
};

One version note: request.geo was removed from NextRequest in Next.js 15. On newer versions, use geolocation(request) from @vercel/functions instead, or you'll get undefined and every visitor falls through to the default.

Running It in Production

The handler code is the easy part. What causes trouble later is not being able to see what failed, a bill you didn't expect, and database connections.

Observability: Logging, Tracing, and Metrics

Log JSON, not free text. CloudWatch Logs Insights can then filter and aggregate on fields like requestId or level:

// Structured logger utility
const log = {
  info: (msg, data = {}) => console.log(JSON.stringify({
    level: 'INFO', message: msg, timestamp: new Date().toISOString(), ...data
  })),
  error: (msg, error, data = {}) => console.error(JSON.stringify({
    level: 'ERROR', message: msg,
    error: { name: error.name, message: error.message, stack: error.stack },
    timestamp: new Date().toISOString(), ...data
  })),
};

exports.handler = async (event) => {
  const requestId = event.requestContext?.requestId;
  log.info('Handler invoked', { requestId, path: event.path });

  try {
    const result = await processRequest(event);
    log.info('Handler success', { requestId, statusCode: 200 });
    return result;
  } catch (error) {
    log.error('Handler failed', error, { requestId });
    throw error;  // Let Lambda mark invocation as failed
  }
};

For tracing across Lambda → DynamoDB → SQS chains, turn on AWS X-Ray with tracing: lambda: true under the provider block in serverless.yml.

When a function is killed for running too long, the log line is Task timed out after 10.00 seconds and your catch block never runs. If you see that with no error logged before it, look at what the handler was waiting on (usually a network call with no timeout of its own) before you raise the Lambda timeout.

Cost Optimization

TechniqueImpactEffort
Right-size memoryHighLow: measure with AWS Lambda Power Tuning
Reduce package sizeMediumLow: bundle and tree-shake with esbuild
Use Graviton2 ARM~20% lower price per GB-secondLow: add architecture: arm64 (check native deps like sharp)
Async where possibleHighMedium: push work to SQS instead of doing it in the HTTP request
Set concurrency limitsSafetyLow: caps how far a bug or traffic spike can run up the bill
# Graviton2 ARM (lower price per GB-second, often similar or better speed)
provider:
  name: aws
  runtime: nodejs20.x
  architecture: arm64    # Graviton2

# Reserve concurrency to prevent cost surprises
functions:
  getUser:
    handler: src/users/get.handler
    reservedConcurrency: 100   # max 100 simultaneous instances

VPC and Database Connections

The old advice was to avoid VPCs because attaching a network interface added seconds to cold starts. AWS fixed most of that in 2019 with shared Hyperplane ENIs, so a VPC is fine now. The real problem with RDS is connections: every concurrent Lambda environment opens its own, and a traffic spike can exhaust Postgres's max_connections and start throwing sorry, too many clients already. Put RDS Proxy in front of the database so it pools them:

# serverless.yml: Lambda in a VPC, talking to RDS through RDS Proxy
functions:
  getUser:
    handler: src/users/get.handler
    vpc:
      securityGroupIds:
        - sg-xxxxxxxxx
      subnetIds:
        - subnet-xxxxxxxx
        - subnet-yyyyyyyy

# Connect to RDS Proxy endpoint instead of RDS directly
# handler.js
const { Pool } = require('pg');

// Initialized once and reused across warm invocations
const pool = new Pool({
  host: process.env.DB_PROXY_ENDPOINT,  // RDS Proxy endpoint
  database: process.env.DB_NAME,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  max: 1,         // Lambda containers are single-threaded
  idleTimeoutMillis: 120000,
});

Local Development and Testing

Deploying to test every change gets old fast. serverless-offline emulates API Gateway and Lambda on your machine, which covers most HTTP work. AWS SAM runs functions in Docker with the real Lambda runtime images, so it's slower but closer to production. For the handler logic itself, plain unit tests with the SDK mocked are quickest:

Testing a Lambda handler with Jest
// tests/users/get.test.js
const { handler } = require('../../src/users/get');

// Mock AWS SDK
jest.mock('@aws-sdk/client-dynamodb');
jest.mock('@aws-sdk/lib-dynamodb', () => ({
  DynamoDBDocumentClient: {
    from: jest.fn(() => ({ send: jest.fn() })),
  },
  GetCommand: jest.fn(),
}));

const { DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb');

describe('GET /users/:id', () => {
  let mockSend;

  beforeEach(() => {
    mockSend = jest.fn();
    DynamoDBDocumentClient.from.mockReturnValue({ send: mockSend });
  });

  it('returns 200 with user data', async () => {
    mockSend.mockResolvedValue({
      Item: { userId: '123', name: 'Alice', email: 'alice@example.com' },
    });

    const event = { pathParameters: { id: '123' } };
    const context = { callbackWaitsForEmptyEventLoop: false };

    const response = await handler(event, context);

    expect(response.statusCode).toBe(200);
    expect(JSON.parse(response.body).name).toBe('Alice');
  });

  it('returns 404 when user not found', async () => {
    mockSend.mockResolvedValue({ Item: undefined });

    const event = { pathParameters: { id: 'nonexistent' } };
    const response = await handler(event, {});

    expect(response.statusCode).toBe(404);
  });

  it('returns 400 when id is missing', async () => {
    const event = { pathParameters: {} };
    const response = await handler(event, {});

    expect(response.statusCode).toBe(400);
  });
});

One trap in this exact setup: get.js creates docClient at module level, and the require at the top of the test runs before beforeEach. So the handler holds the client created by the mock factory, not the one wired to mockSend, and the 200 and 404 tests get a 500 instead. Either require the handler inside beforeEach after setting the mock (with jest.resetModules()), or have the factory return a shared send mock that the tests configure.

When I'd Use Serverless (and When I Wouldn't)

I'd reach for functions when the work is triggered by events and the traffic is uneven: image processing on upload, webhook receivers, queue consumers, scheduled cleanup jobs, and APIs that get a few hundred requests an hour with the occasional burst. In those cases you avoid paying for idle servers and you don't babysit worker processes.

I wouldn't use them for:

Before shipping, check the things that cause real incidents: each function has its own narrow IAM role, every queue and S3 consumer is safe to run twice, reservedConcurrency is set on anything that could loop, and SQS visibility timeouts are longer than function timeouts. Most of the rest you can tune once you have real traffic to look at.

Serverless Lambda Functions AWS Vercel FaaS Cloud
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.