DynamoDB
createTable
conditional creation
AWS
database management

DynamoDB createTable if not exists

System Design practice on Codemia

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

Practice system design

Introduction to DynamoDB's CreateTable

Amazon DynamoDB is a fully-managed NoSQL database service that provides fast and predictable performance with seamless scalability. It is often used in applications where high throughput, consistent low latency, and the ability to process large volumes of data in real-time are critical. One common operation when working with DynamoDB in the AWS ecosystem is creating a new table.

In typical relational databases, there's a concept of "CREATE TABLE IF NOT EXISTS" allowing users to create a table only when it does not already exist. However, in DynamoDB, this behavior needs to be handled programmatically.

Table Creation in DynamoDB

When you create a table in DynamoDB, you define its primary key attributes, provisioned throughput settings, and optional secondary indexes. Here's a basic example of creating a DynamoDB table in Python using the AWS SDK (Boto3):

python
1import boto3
2
3# Initialize a session using Amazon DynamoDB
4dynamodb = boto3.resource('dynamodb')
5
6# Define table service client
7table_name = 'MyTable'
8try:
9    # Check if the table already exists
10    table = dynamodb.Table(table_name)
11    table.load()  # This will raise an error if the table does not exist
12    print(f"Table {table_name} already exists.")
13except dynamodb.meta.client.exceptions.ResourceNotFoundException:
14    # Create the table because it doesn't exist
15    table = dynamodb.create_table(
16        TableName=table_name,
17        KeySchema=[
18            {
19                'AttributeName': 'ID',
20                'KeyType': 'HASH'  # Partition key
21            },
22            {
23                'AttributeName': 'SortKey',
24                'KeyType': 'RANGE'  # Sort key
25            }
26        ],
27        AttributeDefinitions=[
28            {
29                'AttributeName': 'ID',
30                'AttributeType': 'S'  # String
31            },
32            {
33                'AttributeName': 'SortKey',
34                'AttributeType': 'N'  # Number
35            }
36        ],
37        ProvisionedThroughput={
38            'ReadCapacityUnits': 5,
39            'WriteCapacityUnits': 5
40        }
41    )
42    print(f"Creating {table_name} table.")
43    table.wait_until_exists()  # Wait until the table is created

Key Steps and Considerations

  1. Resource Initialization: The script initializes the DynamoDB resource using Boto3, the AWS SDK for Python. This establishes a connection to your AWS account.
  2. Error Handling: By attempting to load the table, ResourceNotFoundException is raised if the table doesn't exist. This is crucial as DynamoDB does not have a direct "CREATE TABLE IF NOT EXISTS" statement like SQL databases.
  3. Table Creation: If the table doesn’t exist, the code proceeds to create it, defining necessary attributes and setting provisioned throughput.
  4. Synchronization: The wait_until_exists function ensures your script will only proceed once the table is fully created and active.

Key Parameter Definitions

ParameterDescription
TableNameName of the table you want to create.
KeySchemaSpecifies the attributes that make up the primary key of the table.
AttributeDefinitionsSpecifies the data types for the primary key elements.
ProvisionedThroughputOverall throughput settings for the table which affect read/write capacity.
ReadCapacityUnitsNumber of consistent reads per second you want to be able to support.
WriteCapacityUnitsNumber of writes per second you want to be able to support.

Additional Details

  • DynamoDB Capacity Modes: DynamoDB offers two capacity modes, on-demand and provisioned. In this example, we've used provisioned throughput. If you plan on fluctuating loads, consider using on-demand capacity mode by omitting ProvisionedThroughput from the table creation request.
  • Secondary Indexes: Additional attributes can be indexed to enhance query capabilities. You can add Local Secondary Indexes (LSIs) and Global Secondary Indexes (GSIs) during or after table creation, depending on your needs.
  • IAM Roles and Policies: Always ensure your AWS IAM roles and policies are set correctly to allow for creation, modification, and deletion of tables.
  • Cost Management: Aside from provisioned throughput, the choice of partition keys/secondary indexes and table size contribute to overall cost.

Conclusion

Handling the "create table if it's not already present" scenario in DynamoDB requires a programmatic approach. By using AWS SDKs available in languages like Python, you can efficiently manage DynamoDB resources and save on unnecessary re-creation of tables, optimizing both performance and cost-effectiveness. Always ensure your code includes robust error handling and synchronization methods to ensure smooth database operations.


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.