Working with Items: CRUD Operations in DynamoDB
A database without data is like a library without books.
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
Insert or replace item
Fetch one item by key
Modify selected attributes
Remove item by key
| CRUD | DynamoDB API | Purpose | Key Behavior |
|---|---|---|---|
| Create | PutItem | Insert item | Can overwrite existing item |
| Read | GetItem | Retrieve one item | Requires full primary key |
| Update | UpdateItem | Modify attributes | Does not replace the whole item |
| Delete | DeleteItem | Remove item | Can 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.
{"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
Read
GetItem Request Flow
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.
UpdateExpression: SET RewardPoints = :pExpressionAttributeValues::p = 3000
DeleteItem permanently removes an item by primary key. For sensitive workflows, use a condition expression or soft-delete attribute before physical deletion.
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.
UpdateItem return values:NONEALL_NEWUPDATED_NEWALL_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.
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
aws dynamodb put-item \--table-name Customers \--item '{"CustomerId": { "S": "CUST1001" },"Name": { "S": "Rahul" },"City": { "S": "Bhubaneswar" }}'
Java SDK v2: PutItem
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
table.put_item(Item={"CustomerId": "CUST1001","Name": "Rahul","City": "Bhubaneswar"})
Node.js SDK v3: PutItem
await docClient.send(new PutCommand({TableName: "Customers",Item: {CustomerId: "CUST1001",Name: "Rahul",City: "Bhubaneswar"}}));
Java SDK v2: GetItem
GetItemRequest request = GetItemRequest.builder().tableName("Customers").key(Map.of("CustomerId",AttributeValue.builder().s("CUST1001").build())).build();GetItemResponse response = client.getItem(request);
Python Boto3: GetItem
response = table.get_item(Key={"CustomerId": "CUST1001"})
Node.js SDK v3: GetItem
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:
PutItemwithattribute_not_exists(UserId). - Profile page:
GetItembyCustomerId. - Loyalty points:
UpdateItemfor only the points attribute. - Account deletion:
DeleteItemor soft delete depending on compliance. - Bulk import:
BatchWriteItemwith 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.
Version: 1User A updates with condition Version = 1-> set Version = 2User 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.
Customer|vAPI|vPutItem(Order)|vUpdateItem(Customer RewardPoints)|vUpdateItem(Product Stock)|vSuccess
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
Used for multiple puts and deletes.
BatchGetItem
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.
| Exception | Meaning | Retry? |
|---|---|---|
| ResourceNotFoundException | Table does not exist | No, fix configuration |
| ConditionalCheckFailedException | Condition expression failed | No, handle business conflict |
| ProvisionedThroughputExceededException | Capacity exceeded | Yes, retry with backoff |
| ValidationException | Invalid request | No, fix request |
| InternalServerError | Temporary AWS issue | Yes, retry with backoff |
Best practices
- Prefer
UpdateItemover 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
PutItemto 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.
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
ConditionExpression prevents the operation.3IntermediateQuestionWhy are conditional writes important?+
Answer
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
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
UpdateItemis generally preferred overPutItemfor 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.