AWS Builder Center
Setting up the Backend with Amazon DynamoDB and AWS Lambda

Setting up the Backend with Amazon DynamoDB and AWS Lambda

Build a production-ready backend with AWS Lambda and Amazon DynamoDB. Part 1 of Zero to Serverless covers NoSQL design, IAM security, and TypeScript

Series: Zero to Serverless (1 article)

  1. 1
    Setting up the Backend with Amazon DynamoDB and AWS Lambda This article
The serverless paradigm has fundamentally shifted how we architect cloud applications. By abstracting away infrastructure management, serverless allows engineering teams to focus entirely on business logic. At the core of the AWS serverless ecosystem sits the most proven combination for backend development: AWS Lambda for compute and Amazon DynamoDB for state.In this first installment of the Zero to Serverless series, we will build a production-ready backend foundation. You will learn how to design a NoSQL table, configure secure IAM permissions, and write highly optimized AWS Lambda functions using TypeScript and the AWS SDK v3.
Why Lambda and DynamoDB?
Traditional relational databases use persistent, stateful connections. When you attach thousands of highly concurrent, ephemeral Lambda functions to a traditional PostgreSQL or MySQL database, you risk exhausting the connection pool and crashing the database.
DynamoDB, by contrast, is accessed via stateless HTTP APIs. It natively handles the massive, sudden concurrency spikes that AWS Lambda generates. This synergy provides a backend that scales from zero to tens of thousands of requests per second without a single configuration change, and you only pay for what you use.
The Mental Shift: Relational vs. NoSQL
Before provisioning resources, you must unlearn relational database habits. DynamoDB does not support complex database JOIN operations; data must be pre-joined or structured based on access patterns.
Relational Database (SQL)
Amazon DynamoDB (NoSQL)
Purpose
Table
Table
The core collection of data.
Row
Item
A single record. Items in the same table can have varying attributes.
Column
Attribute
A specific data field (e.g., email, createdAt).
Primary Key
Partition Key (PK)
A hash attribute that determines the physical server where the data is stored.
Composite Key
Partition Key + Sort Key (SK)
Allows sorting and complex querying of related items within a single Partition Key.
Step 1: Architecting the DynamoDB Table
For our example, we will build a backend for a Product Catalog.In DynamoDB, you must define the primary key upfront. We will use a composite primary key structure to allow for maximum flexibility:
  • Partition Key (PK): String (e.g., STORE#123)
  • Sort Key (SK): String (e.g., PRODUCT#456)
By using generic names like PK and SK instead of storeId and productId, you open the door to Single-Table Design—a highly efficient technique where multiple entity types (products, users, orders) live in the exact same table, drastically reducing infrastructure overhead.
Key insight: To create this table via the AWS Console or Infrastructure as Code (IaC), you only need to define the PK and SK schema. You do not need to pre-define attributes like price or name before inserting data.
Step 2: The Least Privilege IAM Role
AWS operates on a strict default-deny security posture. For your Lambda function to read or write to your DynamoDB table, it requires an IAM Execution Role. Never grant AmazonDynamoDBFullAccess in a production environment. Instead, scope the permissions specifically to the table you created, allowing only the actions your business logic dictates.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:Query"
],
"Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/ProductCatalog"
}
]
}
Note: Your Lambda execution role will also need the managed AWSLambdaBasicExecutionRole policy to push diagnostic logs to Amazon CloudWatch.
Step 3: Writing the Lambda Function (TypeScript)
Modern AWS development utilizes the AWS SDK for JavaScript v3, which features a modular architecture that reduces your deployment bundle size and mitigates Lambda cold starts. Here is a robust, production-ready Lambda handler that processes an incoming event to create a new product.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
// 1. Initialize clients OUTSIDE the handler for connection reuse and cold-start optimization.
const client = new DynamoDBClient({ region: process.env.AWS_REGION });
// 2. Use the DocumentClient to automatically marshall/unmarshall native JavaScript objects.
const dynamo = DynamoDBDocumentClient.from(client);
const TABLE_NAME = process.env.TABLE_NAME;
export const handler = async (event: any) => {
try {
// 3. Robust event validation
if (!event.body) {
return { statusCode: 400, body: JSON.stringify({ error: "Missing request body" }) };
}
const data = JSON.parse(event.body);
// 4. Construct the DynamoDB PutCommand
const command = new PutCommand({
TableName: TABLE_NAME,
Item: {
PK: `STORE#${data.storeId}`,
SK: `PRODUCT#${data.productId}`,
name: data.name,
price: data.price,
createdAt: new Date().toISOString(),
},
});
// 5. Execute the command
await dynamo.send(command);
return {
statusCode: 201,
body: JSON.stringify({ message: "Product created successfully" }),
};
} catch (error) {
// 6. Avoid leaking stack traces in production API responses
console.error("Error creating product:", error);
return {
statusCode: 500,
body: JSON.stringify({ error: "Internal Server Error" }),
};
}
};
Critical Code Practices to Observe:
  • Outside Initialization: The DynamoDBClient is instantiated outside the handler function. When AWS Lambda receives subsequent requests, it reuses the warm execution environment. Initializing the client globally prevents the overhead of establishing a new TCP connection and TLS handshake for every single request.
  • The Document Client: We wrap the raw client in DynamoDBDocumentClient. This utility automatically translates standard JavaScript objects into DynamoDB's strict data typing format, saving you from writing verbose syntax like price: { N: "19.99" }.
  • Modular Imports: By importing specifically from @aws-sdk/client-dynamodb and @aws-sdk/lib-dynamodb rather than a monolithic SDK, we keep the Lambda bundle size strictly limited to what we use.
Step 4: Cost and Performance Optimization
Once your backend is functional, production readiness requires fine-tuning the levers AWS provides.
  • Memory vs. CPU Trade-offs: In AWS Lambda, you do not directly allocate CPU. CPU power scales proportionately with the memory you allocate. If your DynamoDB queries are processing large datasets, bumping the Lambda memory from 512MB to 1024MB might cut the execution time in half, giving your users better performance for the exact same overall cost.
  • Structured Logging: Default console.log statements become difficult to trace at scale. Adopt structured JSON logging (using libraries like AWS Lambda Powertools) to enable powerful querying and filtering in CloudWatch Logs Insights.
  • Idempotency: In a distributed system, network timeouts can cause a client to retry a request that actually succeeded on the backend. Always design your DynamoDB operations to be idempotent (safe to run multiple times). A simple PutItem is naturally idempotent—it simply overwrites the existing data with the exact same data.

Series: Zero to Serverless (1 article)

  1. 1
    Setting up the Backend with Amazon DynamoDB and AWS Lambda This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article