Amazon DynamoDB Tutorial 0/6 lessons ~6 min read Lesson 6

    Working with Items: CRUD Operations in DynamoDB

    A database without data is like a library without books.

    Course progress0%
    Focus
    20 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    A database without data is like a library without books. Creating a DynamoDB table is only the first step. The real value comes from how efficiently your application can create, read, update, and delete items.

    Every backend application performs these four core operations: Create, Read, Update, and Delete. Together, they are called CRUD operations. In DynamoDB, the core item-level APIs are PutItem, GetItem, UpdateItem, and DeleteItem.

    In this lesson, we will use a Customers table with CustomerId as the partition key.

    Purpose of this lesson

    By the end of this lesson, you will understand DynamoDB CRUD operations, conditional writes, batch operations, return values, common exceptions, retry strategy, optimistic locking, and SDK examples in Java, Python, and Node.js.

    Understanding the topic

    DynamoDB item APIs map cleanly to the CRUD workflow. Each API targets a table and uses the primary key when reading, updating, or deleting a specific item.

    CRUD Workflow

    Application Operations to DynamoDB APIs

    item-level APIs
    Application
    Customer service, order service, profile service
    PutItem
    Create

    Insert or replace item

    GetItem
    Read

    Fetch one item by key

    UpdateItem
    Update

    Modify selected attributes

    DeleteItem
    Delete

    Remove item by key

    DynamoDB Table: Customers
    Partition Key: CustomerId
    CRUDDynamoDB APIPurposeKey Behavior
    CreatePutItemInsert itemCan overwrite existing item
    ReadGetItemRetrieve one itemRequires full primary key
    UpdateUpdateItemModify attributesDoes not replace the whole item
    DeleteDeleteItemRemove itemCan use conditions for safety

    Internal architecture

    We will use a simple Customers table throughout the lesson. The partition key is CustomerId, and each customer item stores profile and loyalty information.

    json
    {
    "CustomerId": "CUST1001",
    "Name": "Rahul Sharma",
    "Email": "rahul@gmail.com",
    "City": "Bhubaneswar",
    "Membership": "Gold",
    "RewardPoints": 2500
    }

    Data flow

    PutItem creates a new item. If an item with the same primary key already exists, DynamoDB replaces it unless you add a condition expression.

    Create

    PutItem Request Flow

    1Application
    2PutItem()
    3DynamoDB
    4Store Item
    5Success

    Read

    GetItem Request Flow

    1Application
    2GetItem()
    3Partition Lookup
    4Return Item

    Visual explanation

    UpdateItem changes selected attributes while leaving the rest of the item unchanged. This is usually safer and cheaper than replacing the full item with PutItem.

    text
    UpdateExpression: SET RewardPoints = :p
    ExpressionAttributeValues:
    :p = 3000

    DeleteItem permanently removes an item by primary key. For sensitive workflows, use a condition expression or soft-delete attribute before physical deletion.

    text
    Delete key:
    CustomerId = CUST1001

    Syntax reference

    Update expressions let you modify only the attributes you need. Return values can send updated data back to the application immediately.

    • NONE: return no item attributes.
    • ALL_NEW: return the entire item after update.
    • UPDATED_NEW: return only changed attributes after update.
    • ALL_OLD: return the entire item before update.
    text
    UpdateItem return values:
    NONE
    ALL_NEW
    UPDATED_NEW
    ALL_OLD

    Production implementation

    Here are the core create and read examples. In production, prefer the higher-level document clients where available because they let you work with normal JSON-like values instead of low-level DynamoDB attribute wrappers.

    Update and delete examples

    Use UpdateItem when modifying reward points or profile fields. Use DeleteItem when removing a customer record.

    java
    UpdateItemRequest request = UpdateItemRequest.builder()
    .tableName("Customers")
    .key(Map.of(
    "CustomerId",
    AttributeValue.builder().s("CUST1001").build()))
    .updateExpression("SET RewardPoints = :p")
    .expressionAttributeValues(Map.of(
    ":p",
    AttributeValue.builder().n("3000").build()))
    .build();

    Python equivalent:

    table.update_item(Key={"CustomerId":"CUST1001"}, UpdateExpression="SET RewardPoints=:p", ExpressionAttributeValues={":p":3000})

    Delete equivalent:

    table.delete_item(Key={"CustomerId":"CUST1001"})

    Create and read examples

    AWS CLI: PutItem

    bash
    aws dynamodb put-item \
    --table-name Customers \
    --item '{
    "CustomerId": { "S": "CUST1001" },
    "Name": { "S": "Rahul" },
    "City": { "S": "Bhubaneswar" }
    }'

    Java SDK v2: PutItem

    java
    Map<String, AttributeValue> item = new HashMap<>();
    item.put("CustomerId", AttributeValue.builder().s("CUST1001").build());
    item.put("Name", AttributeValue.builder().s("Rahul").build());
    item.put("City", AttributeValue.builder().s("Bhubaneswar").build());
    client.putItem(PutItemRequest.builder()
    .tableName("Customers")
    .item(item)
    .build());

    Python Boto3: PutItem

    python
    table.put_item(
    Item={
    "CustomerId": "CUST1001",
    "Name": "Rahul",
    "City": "Bhubaneswar"
    }
    )

    Node.js SDK v3: PutItem

    javascript
    await docClient.send(
    new PutCommand({
    TableName: "Customers",
    Item: {
    CustomerId: "CUST1001",
    Name: "Rahul",
    City: "Bhubaneswar"
    }
    })
    );

    Java SDK v2: GetItem

    java
    GetItemRequest request = GetItemRequest.builder()
    .tableName("Customers")
    .key(Map.of(
    "CustomerId",
    AttributeValue.builder().s("CUST1001").build()))
    .build();
    GetItemResponse response = client.getItem(request);

    Python Boto3: GetItem

    python
    response = table.get_item(
    Key={
    "CustomerId": "CUST1001"
    }
    )

    Node.js SDK v3: GetItem

    javascript
    await docClient.send(
    new GetCommand({
    TableName: "Customers",
    Key: {
    CustomerId: "CUST1001"
    }
    })
    );

    Real-world use

    CRUD operations power nearly every DynamoDB-backed feature. User profiles use GetItem and UpdateItem. Registration uses PutItem with a condition. Order creation uses PutItem. Inventory systems often use UpdateItem with conditions.

    • User registration: PutItem with attribute_not_exists(UserId).
    • Profile page: GetItem by CustomerId.
    • Loyalty points: UpdateItem for only the points attribute.
    • Account deletion: DeleteItem or soft delete depending on compliance.
    • Bulk import: BatchWriteItem with retry handling for unprocessed items.

    Enterprise use cases

    Conditional writes are one of DynamoDB's most important data-integrity features. They let an operation succeed only when a condition is true.

    • Prevent duplicate customer creation: attribute_not_exists(CustomerId).
    • Payment processing: only mark payment successful if current status is PENDING.
    • Inventory management: only reduce stock if available quantity is greater than zero.
    • Booking systems: only reserve a seat if it is not already booked.
    text
    Version: 1
    User A updates with condition Version = 1
    -> set Version = 2
    User B also tries condition Version = 1
    -> fails because Version is now 2

    Optimistic locking is a common conditional-write pattern. Store a version attribute and update only when the current version matches the expected version.

    Production case study

    In an online shopping application, an order workflow may create an order, update customer reward points, and reduce product stock.

    text
    Customer
    |
    v
    API
    |
    v
    PutItem(Order)
    |
    v
    UpdateItem(Customer RewardPoints)
    |
    v
    UpdateItem(Product Stock)
    |
    v
    Success

    Each operation can execute within milliseconds when keys are designed well. For correctness, stock updates and payment workflows should use conditional writes.

    Scalability analysis

    Batch operations reduce network overhead when reading or writing multiple items. They are faster than sending many individual requests, but your application must still handle unprocessed items and retries.

    Batch Operations

    Fewer Network Calls for Many Items

    BatchWriteItem

    100 items → fewer requests

    Used for multiple puts and deletes.

    BatchGetItem

    50 customers → one batch read

    Used for retrieving multiple known keys.

    Failure scenarios

    Production applications must handle DynamoDB exceptions. Some failures are permanent and should be fixed in the request; others are transient and should be retried with exponential backoff.

    ExceptionMeaningRetry?
    ResourceNotFoundExceptionTable does not existNo, fix configuration
    ConditionalCheckFailedExceptionCondition expression failedNo, handle business conflict
    ProvisionedThroughputExceededExceptionCapacity exceededYes, retry with backoff
    ValidationExceptionInvalid requestNo, fix request
    InternalServerErrorTemporary AWS issueYes, retry with backoff

    Best practices

    • Prefer UpdateItem over replacing the entire item.
    • Use conditional writes whenever data integrity matters.
    • Keep item size small.
    • Use batch operations to reduce network overhead for multi-item workloads.
    • Retry throttled and transient requests with exponential backoff.
    • Always validate input before writing.
    • Use return values when the application immediately needs updated data.
    • Enable CloudWatch monitoring for errors, latency, and throttling.

    Common mistakes

    • Using PutItem to update an existing record without conditions.
    • Replacing entire items unnecessarily.
    • Ignoring condition expressions.
    • Making thousands of individual requests instead of batch requests.
    • Forgetting retry logic for throttling and transient failures.
    • Treating conditional check failures as infrastructure errors instead of business conflicts.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionWhat is the difference between PutItem and UpdateItem?+

    Answer

    PutItem creates a new item or completely replaces an existing item. UpdateItem modifies only the specified attributes while leaving the remaining attributes unchanged.
    2BeginnerQuestionWhat happens if PutItem is called with an existing primary key?+

    Answer

    The existing item is overwritten unless a ConditionExpression prevents the operation.
    3IntermediateQuestionWhy are conditional writes important?+

    Answer

    Conditional writes protect data integrity by allowing operations only when specific conditions are met. They help prevent duplicate records, conflicting updates, invalid stock reductions, and double booking.
    4IntermediateQuestionWhat is BatchWriteItem?+

    Answer

    BatchWriteItem sends multiple put and delete operations in a single request, improving throughput and reducing network overhead. Applications must handle unprocessed items and retry them.
    5AdvancedQuestionWhat is optimistic locking?+

    Answer

    Optimistic locking uses a version attribute to detect concurrent updates. An update succeeds only if the stored version matches the expected version, preventing accidental overwrites.

    Hands-on exercise

    Create a simple Customer Management System using DynamoDB.

    • Insert a new customer.
    • Retrieve customer details by CustomerId.
    • Update the customer's reward points.
    • Delete a customer record.
    • Prevent duplicate customer creation using a conditional write.
    • Retrieve multiple customers using a batch operation.
    • Explain why UpdateItem is generally preferred over PutItem for modifying records.
    • List which exceptions your application should retry automatically.

    Summary

    In this lesson, you learned how to work with DynamoDB items using PutItem, GetItem, UpdateItem, and DeleteItem. You also learned why conditional writes matter, how batch operations improve efficiency, how return values help after updates, and how optimistic locking prevents concurrent overwrites.

    Reliable DynamoDB applications are not just CRUD wrappers. They validate inputs, protect writes with conditions, retry transient failures with backoff, avoid unnecessary item replacement, use batch APIs carefully, and monitor production behavior with CloudWatch.

    Next: Lesson 7 covers Query vs Scan, key condition expressions, filters, projection expressions, pagination, query optimization, SDK examples, cost tuning, and interview questions.

    Ready to mark this lesson complete?Track your journey across the entire course.