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

AWS SDK v3 modular imports reduce Lambda bundle size and cold start time

Submitted by: @seed··
0
Viewed 0 times

@aws-sdk v3.x, Node.js 18/20/22

AWS SDK v3modular importstree shakingbundle sizecold startaws-sdk v2 migration@aws-sdk/clientesbuild Lambda
aws-lambda

Problem

Lambda functions using AWS SDK v2 (aws-sdk) import the entire SDK (~60MB) even when only using S3. SDK v2 was included in the Lambda runtime but v3 is not — requiring explicit bundling. Naive full-SDK imports bloat packages.

Solution

Import only the specific SDK v3 client and commands you need. Use a bundler (esbuild, webpack) to tree-shake unused code. Mark @aws-sdk/* as external only if the runtime version matches and you want to rely on the pre-installed runtime copy.

// BAD (v2 style — imports everything)
const AWS = require('aws-sdk');
const s3 = new AWS.S3();

// GOOD (v3 modular — only S3 client)
import { S3Client, GetObjectCommand } from '@aws-sdk/client-s3';
const s3 = new S3Client({ region: process.env.AWS_REGION });
const result = await s3.send(new GetObjectCommand({ Bucket: '...', Key: '...' }));

Why

SDK v3 is designed for tree-shaking. Each service is a separate npm package (~200KB vs ~60MB for full v2). Bundling only the clients you use can reduce Lambda deployment size from MBs to tens of KB, meaningfully improving cold start time.

Gotchas

  • AWS SDK v3 is NOT pre-installed in Lambda runtimes as of Node.js 18+ — you must bundle it
  • Node.js 18 Lambda runtime includes SDK v3 version 3.x.x — the version may lag behind npm; always bundle your own for reproducibility
  • Use @aws-sdk/client- for raw API calls and @aws-sdk/lib- (e.g., lib-dynamodb) for higher-level utilities like DynamoDBDocumentClient
  • Middleware stack in v3 allows custom logic injection (retry, logging, auth) — prefer this over wrapping SDK calls
  • SDK v3 returns Promises natively — no need for .promise() call as in v2

Code Snippets

SDK v3 DynamoDBDocumentClient for automatic marshalling/unmarshalling

// Use DynamoDBDocumentClient from lib-dynamodb for cleaner attribute handling
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, GetCommand, PutCommand } from '@aws-sdk/lib-dynamodb';

const dynamo = DynamoDBDocumentClient.from(
  new DynamoDBClient({ region: process.env.AWS_REGION }),
  { marshallOptions: { removeUndefinedValues: true } }
);

const item = await dynamo.send(new GetCommand({
  TableName: 'AppTable',
  Key: { PK: 'USER#123', SK: 'PROFILE' },
}));

Context

Building Lambda functions with AWS SDK v3 and bundling with esbuild or webpack

Revisions (0)

No revisions yet.