DynamoDB
AWS Lambda
Local Development
Serverless Applications
AWS Deployment

How to use DynamoDB locally with Lambda

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Setting up and developing applications with AWS DynamoDB and AWS Lambda locally can greatly speed up your development process. This approach allows you to test your serverless applications without incurring costs or needing an internet connection. In this guide, we will explain how to set up and use AWS DynamoDB with AWS Lambda locally.

Prerequisites

  1. AWS CLI: Ensure AWS Command Line Interface is installed and configured on your local machine.
  2. AWS SAM CLI: The Serverless Application Model Command Line Interface aids in building serverless applications.
  3. Docker: Use this to run Lambda functions and DynamoDB locally.
  4. Java Runtime Environment: It's required for DynamoDB Local.

Setting Up DynamoDB Local

To start, you'll need to set up DynamoDB Local, which can be run as a Java application.

  1. Download DynamoDB Local: You can download DynamoDB Local from the AWS website as a .tar.gz or .zip file.
  2. Extract the file: Once downloaded, extract the files to a desired location.
  3. Run DynamoDB: Navigate to the directory where DynamoDB Local is extracted and run it using the command:
bash
   java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

The -sharedDb option is used to allow all clients to share a single database file. You can confirm that DynamoDB Local is running by visiting http://localhost:8000/ in a web browser.

Creating a Table in DynamoDB Local

To interact with DynamoDB Local, you can use the AWS CLI. Here’s how to create a table:

bash
1aws dynamodb create-table \
2    --table-name Music \
3    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
4    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
5    --billing-mode PAY_PER_REQUEST \
6    --endpoint-url http://localhost:8000

Here, we are creating a table named "Music" with a composite primary key comprised of "Artist" (HASH) and "SongTitle" (RANGE).

Running AWS Lambda Locally

Lambda functions can be executed locally using the AWS SAM CLI. Here’s how you can set it up:

  1. Create Lambda Function: Use sam init to generate a new Lambda project. This provides boilerplate code and configuration.
  2. Configure template.yaml: Update your template.yaml as follows to specify the resource required by the Lambda function:
yaml
1   Resources:
2     MyFunction:
3       Type: AWS::Serverless::Function
4       Properties:
5         Handler: app.lambda_handler
6         Runtime: python3.8
7         Environment:
8           Variables:
9             TABLE_NAME: Music
10         Policies:
11           - DynamoDBCrudPolicy:
12               TableName: Music
  1. Run the Lambda Function: Use the sam local invoke command to execute your Lambda function locally.
bash
   sam local invoke MyFunction --event event.json

Make sure that event.json contains the event data necessary for your Lambda function.

Connecting Lambda to DynamoDB Locally

Your Lambda function needs to connect to DynamoDB Local. Setup the SDK in your Lambda as follows:

python
1import boto3
2from botocore.config import Config
3
4def lambda_handler(event, context):
5    # Local DynamoDB Instance
6    local_config = Config(region_name='us-west-2', endpoint_url='http://localhost:8000')
7
8    # Create a DynamoDB client
9    dynamodb = boto3.resource('dynamodb', config=local_config)
10
11    # Fetch table using table name from environment variable
12    table = dynamodb.Table('Music')
13    
14    # Operations on table
15    response = table.get_item(Key={'Artist': 'No One You Know', 'SongTitle': 'Call Me Today'})
16    return response

Summary Table

This table encapsulates the key points when setting up and using DynamoDB Local with Lambda:

Key PointDescription
Download & Run DynamoDB LocalJava application with shared DB capabilities
Create TableUse AWS CLI to define tables with attribute schemas
Configure Lambda with SAM CLIUse sam init and configure AWS resources
Local Connection ConfigurationUse boto3 library with endpoint as http://localhost:8000
Environment Variable for Table NameSet in template.yaml
Executionsam local invoke for testing Lambda locally

Additional Tips

  • Error Handling: Ensure proper error catching and logging to troubleshoot issues effectively.
  • Testing Frameworks: Leverage testing frameworks to automate tests of your Lambda functions.
  • Data Lifecycle: Consider how to persist data changes between starts and stops of DynamoDB Local, particularly when used in a shared or testing environment.

By following these steps, you can efficiently build and test applications that interact with DynamoDB using AWS Lambda on your local machine. This local development environment setup helps you to save costs and time during the development lifecycle.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.