Lesson 9 of 10 Amazon DynamoDB

Working with DynamoDB Expressions, Errors and Local Tools in the SDKs

This lesson explains how to work with DynamoDB from code: handling its typed data format, writing expressions correctly, and knowing which errors the SDK retries and which the application must handle.

Learning outcomes

After completing this lesson, you will be able to:

  • Distinguish the low-level API's type descriptors from higher-level clients that use native objects.
  • Describe the role of key condition, filter, projection, condition and update expressions.
  • Distinguish errors that should be retried from errors that indicate a bug.
  • Describe how DynamoDB Local and NoSQL Workbench support development without an AWS account.

Low-level and higher-level clients

The low-level API represents values with type descriptors such as {"S": "abc"} and {"N": "42"}. Higher-level clients convert to and from native objects:

LanguageHigher-level client
PythonThe boto3 Table resource; numbers must be Decimal, not float
JavaScriptDynamoDBDocumentClient, or marshall and unmarshall
JavaThe Enhanced Client

Example. The same write through the low-level client and through the Table resource. The resource converts native Python types, but numbers must be Decimal.

from decimal import Decimal
import boto3

boto3.client("dynamodb").put_item(
    TableName="Orders",
    Item={"pk": {"S": "ORDER#9017"}, "total": {"N": "249.99"}, "paid": {"BOOL": True}},
)

boto3.resource("dynamodb").Table("Orders").put_item(
    Item={"pk": "ORDER#9017", "total": Decimal("249.99"), "paid": True},
)

PartiQL offers SQL-compatible statements, such as SELECT * FROM "Orders" WHERE pk = 'ORDER#9017', through ExecuteStatement. A PartiQL SELECT without a key condition still performs a full scan.

Expressions

DynamoDB operations use expressions, short strings in a syntax specific to DynamoDB, to describe which items to read, which attributes to return and how to change an item. Each type of expression has its own role.

In a Query, the KeyConditionExpression selects the items to read by partition key and, optionally, by a sort key condition; it is what makes a query efficient. A FilterExpression then removes items that do not match other conditions, but only after they have been read and charged for. A ProjectionExpression limits the attributes returned, which reduces the data transferred but not the capacity consumed.

For writes, a ConditionExpression makes the operation succeed only if a condition is true, which is how DynamoDB prevents lost updates. For example, attribute_not_exists(pk) stops a put from overwriting an existing item, and comparing a version number implements optimistic locking. An UpdateExpression changes individual attributes in place: SET assigns values, REMOVE deletes attributes, ADD increments numbers atomically, which suits counters, and DELETE removes elements from a set. The following table summarises the expression types.

ExpressionPurpose
KeyConditionExpressionSelects items by partition key and optional sort key condition in a Query
FilterExpressionRemoves items after they are read; does not reduce consumed capacity
ProjectionExpressionReturns only the named attributes
ConditionExpressionMakes a write succeed only if a condition holds
UpdateExpressionChanges attributes with SET, REMOVE, ADD and DELETE

Expression attribute names (#name) replace reserved words and special characters, and expression attribute values (:value) supply values safely.

Sort into groups

Which expression?

Exam skills 1.1.5 · 1.3.4

Choose the expression type for each job in a DynamoDB request.

Log in to try this activity Interactive activities are free with an account.

Errors your code must handle

DynamoDB errors fall into groups that need different responses, and the most important distinction is whether retrying can help.

Throttling errors mean the request exceeded the table's capacity or a request-rate limit. They are temporary, so the AWS SDKs retry them automatically with exponential backoff; persistent throttling needs more capacity or a key that spreads the load. Partial batch results are not errors at all: BatchWriteItem and BatchGetItem succeed even when some items were not processed, and return them in UnprocessedItems or UnprocessedKeys. Code that ignores these fields loses data silently, so it must resubmit them with backoff.

Conditional failures mean the request was valid but a condition was false, usually because another client changed the item first. Retrying the same request would fail again or overwrite the other client's change, so the code re-reads the item and decides what to do. A cancelled transaction reports a reason for each item, which shows which condition or conflict caused it. Validation errors mean the request itself is wrong, for example a missing key attribute, and must be fixed in code. The following table summarises the errors.

ErrorMeaningHandling
ProvisionedThroughputExceededException, ThrottlingExceptionCapacity or request-rate limit reachedRetried by the SDK with backoff; persistent errors need capacity or key changes
UnprocessedItems or UnprocessedKeys in a batch responsePart of a batch was not processedRetry those items with backoff; not raised as an exception
ConditionalCheckFailedExceptionA conditional write failed, often because another client changed the item firstRe-read and retry, or report the conflict; never retry blindly
TransactionCanceledExceptionA transaction was cancelledInspect the cancellation reasons to find the failing part
ValidationExceptionThe request is malformedFix the code; do not retry
Sort into groups

How should the code respond?

Exam skills 1.1.3 · 1.1.5

Decide how code should respond to each kind of DynamoDB error or result.

Log in to try this activity Interactive activities are free with an account.

Local development

DynamoDB Local runs a compatible database on a developer machine or in CI, and NoSQL Workbench models tables, visualises access patterns and generates code, all without an AWS account. Pointing the SDK at the local endpoint requires only an endpoint_url setting.

Worked example

Handling throttling and partial batches

A bulk import with BatchWriteItem reports success, but 3% of items are missing. The response contained UnprocessedItems, which the code ignored.

Error or responseCorrect handling
UnprocessedItems in a batch responseRetry those items with exponential backoff
ProvisionedThroughputExceededExceptionThe SDK retries automatically; persistent errors mean more capacity, on-demand mode or better key distribution
ConditionalCheckFailedExceptionExpected business outcome; do not retry blindly
ValidationExceptionA bug in the request; fix the code, never retry

Using the higher-level batch_writer in Boto3 handles unprocessed items automatically. Knowing which errors are retryable, and which are not, is a recurring theme in the exam.

Check yourself

What is the difference between a key condition expression and a filter expression in a Query?

Show answer

The key condition decides which items DynamoDB reads, so it determines the cost. The filter is applied after the read and only removes items from the result, so filtered items still consume read capacity.

Exam Tips

Remember for the exam

  • When DynamoDB rejects a Python float, use Decimal.
  • To work with native types instead of type descriptors, use the Document Client, the boto3 Table resource or the Java Enhanced Client.
  • A conditional write that loses a race raises ConditionalCheckFailedException, which your code must handle.
  • Unprocessed items in a batch response must be retried by your code.
  • To model and test access patterns visually, use NoSQL Workbench.