AWS Builder Center

Building a Dynamic Database Layer with AWS DynamoDB and Lambda

A hands-on guide to designing a scalable, serverless dynamic database layer using Amazon DynamoDB and AWS Lambda — from schema design to real-time data access patterns.

student

Educational Disclaimer

The following technical guide is provided strictly for educational and learning purposes. Any architecture, code, or configuration should be adapted and tested thoroughly before use in production environments.



Introduction

In modern cloud-native applications, data storage needs to scale dynamically with traffic, support unpredictable workloads, and respond in milliseconds. Amazon DynamoDB combined with AWS Lambda provides a fully serverless, auto-scaling database layer that eliminates infrastructure management while delivering single-digit millisecond performance at any scale
 3 
.

This article walks through building a dynamic database layer — one that adapts to changing data models, supports flexible queries, and scales automatically.



Why DynamoDB for Dynamic Data?

Traditional relational databases require predefined schemas and often struggle with elastic scaling. DynamoDB solves this with:
  • Schema-less design — each item can have different attributes, making it ideal for evolving data models
  • Automatic partitioning — data is distributed across hundreds of servers with no manual sharding
  • On-demand capacity — pay per request, no capacity planning needed
  • Built-in security — IAM integration, encryption at rest, and VPC endpoints  4 



Architecture Overview

+----------+ +----------+ +-------------+
| Client | ---> | Lambda | ---> | DynamoDB |
| (App/UI) | <--- | (Handler) | <--- | (Table) |
+----------+ +----------+ +-------------+
The flow is straightforward:
  1. A client (mobile app, web frontend, or API consumer) sends a request
  1. An AWS Lambda function processes the request — validating input, transforming data, and handling business logic
  1. DynamoDB stores or retrieves the data
  1. Lambda returns a response to the client



Step 1: Create the DynamoDB Table

First, create a DynamoDB table with a partition key and sort key. For a dynamic user profile system, use:
  • TableName:  UserProfiles 
  • Partition Key:  userId (String)
  • Sort Key:  profileType (String) — e.g.,  "basic" ,  "premium" ,  "settings" 
This design allows a single user to have multiple profile variants stored efficiently
 3 
.

You can create the table via the AWS Console, AWS CLI, or CloudFormation:
bashCopyaws dynamodb create-table \ --table-name UserProfiles \
--attribute-definitions \
AttributeName=userId,AttributeType=S \
AttributeName=profileType,AttributeType=S \
--key-schema \
AttributeName=userId,KeyType=HASH \
AttributeName=profileType,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST
The  PAY_PER_REQUEST billing mode ensures you only pay for what you use — no over-provisioning.



Step 2: Lambda Handler for Dynamic CRUD Operations

Here is a Node.js Lambda function that handles create, read, update, and delete operations dynamically:
javascriptCopyconst { DynamoDBClient } = require("@aws-sdk/client-dynamodb");const { DynamoDBDocumentClient, PutCommand, GetCommand, UpdateCommand, DeleteCommand } = require("@aws-sdk/lib-dynamodb");
const client = new DynamoDBClient({});const docClient = DynamoDBDocumentClient.from(client);
exports.handler = async (event) => { const { userId, profileType, action, data } = JSON.parse(event.body);
const params = { TableName: "UserProfiles", Key: { userId, profileType } };

switch (action) { case "create": await docClient.send(new PutCommand({ ...params,
Item: { ...params.Key, ...data, createdAt: new Date().toISOString() } }));
break;
case "read": const result = await docClient.send(new GetCommand(params)); return { statusCode: 200, body: JSON.stringify(result.Item) };
case "update": await docClient.send(new UpdateCommand({ ...params,
UpdateExpression: "SET #d = :d", ExpressionAttributeNames: { "#d": "data" }, ExpressionAttributeValues: { ":d": data } }));
break;
case "delete": await docClient.send(new DeleteCommand(params)); break; }

return { statusCode: 200, body: JSON.stringify({ message: `${action} successful` }) };};
This pattern allows the same function to handle multiple dynamic operations without hardcoding logic for each case.



Step 3: Add Global Secondary Indexes (GSI)

By default, DynamoDB queries are constrained to the partition key. To support dynamic queries — like "find all users with a premium profile" — add a Global Secondary Index:
bashCopyaws dynamodb update-table \ --table-name UserProfiles \
--attribute-definitions AttributeName=profileType,AttributeType=S \
--global-secondary-index-updates \
'[{
"Create": { "IndexName": "ProfileTypeIndex", "KeySchema": [{"AttributeName": "profileType", "KeyType": "HASH"}], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5} }
}]'
Now you can query by  profileType independently of  userId .



Step 4: Add API Gateway Integration

Expose the Lambda function via Amazon API Gateway to create a RESTful endpoint:
  1. Create an HTTP API in API Gateway
  1. Set the Lambda function as the integration target
  1. Define methods:  POST /profiles (create),  GET /profiles/{userId} (read),  PATCH /profiles/{userId} (update),  DELETE /profiles/{userId} (delete)
  1. Enable CORS for cross-origin requests
This gives your dynamic database layer a clean, public-facing API.



Challenges & Lessons Learned

  • Hot partitions: If a single  userId receives disproportionate traffic, DynamoDB throttles. Use more granular keys or distribute writes  3 .
  • No JOINs: DynamoDB doesn't support joins. Denormalize data and embed related information in each item.
  • Consistency defaults: DynamoDB uses eventual consistency by default. Use  ConsistentRead: true when strong consistency is required.



Results

With this architecture, the database layer:
  • Scales automatically — from zero to millions of requests without manual intervention
  • Supports dynamic schemas — each item can have unique attributes, adapting to evolving business requirements
  • Delivers sub-10ms latency — thanks to DynamoDB's SSD-backed, partitioned storage
  • Costs nothing at idle — with on-demand billing, you only pay for actual reads and writes
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