Lesson 6 of 10 Amazon DynamoDB

Reacting to Table Changes with DynamoDB Streams

This lesson explains how DynamoDB Streams captures every item-level change to a table, in order, so that other systems can react to inserts, updates and deletes without changing the code that writes the data.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe what a stream record contains and how long it is kept.
  • Explain how a Lambda event source mapping processes a stream and the error-handling settings that keep a failing batch from blocking a shard.
  • Choose between DynamoDB Streams and Kinesis Data Streams for DynamoDB for capturing changes.

How streams work

DynamoDB Streams records every item-level change, whether an insert, an update or a delete, and keeps each record for 24 hours. Each change appears exactly once in the stream, and changes to the same item appear in the order they were made. Lambda can consume the stream through an event source mapping, processing changes in order within each shard.

The stream view type decides how much of each item is written to the record. KEYS_ONLY is enough when the consumer only needs to know which item changed and will read it again if necessary. NEW_IMAGE suits consumers that copy the current state elsewhere, such as a search index. OLD_IMAGE preserves what a deleted or overwritten item contained, for example for an audit log. NEW_AND_OLD_IMAGES lets the consumer compare the two, such as detecting that an order's status changed from PAID to SHIPPED. The view type is chosen when the stream is enabled; changing it requires disabling the stream and enabling a new one.

The following table summarises the view types.

View typeRecords
KEYS_ONLYOnly the key attributes
NEW_IMAGEThe item after the change
OLD_IMAGEThe item before the change
NEW_AND_OLD_IMAGESBoth

Example. With NEW_AND_OLD_IMAGES, a function can detect status changes. TTL deletions arrive as REMOVE records whose userIdentity names the DynamoDB service.

def handler(event, context):
    for record in event["Records"]:
        name = record["eventName"]                    # INSERT, MODIFY or REMOVE
        images = record["dynamodb"]
        if name == "MODIFY":
            old, new = images["OldImage"], images["NewImage"]
            if old["status"]["S"] != new["status"]["S"]:
                notify_status_change(new)
        elif name == "REMOVE" and record.get("userIdentity", {}).get("principalId") == "dynamodb.amazonaws.com":
            archive_expired_session(images["OldImage"])
Sort into groups

Choose the stream view type

Exam skills 1.1.6 · 1.2.4

Choose how much of each item a stream record should hold.

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

Processing streams with Lambda

A Lambda event source mapping reads each shard in order and invokes the function with batches. A failing batch blocks its shard until it succeeds or expires, so configure error handling:

  • Bisect batch on function error splits a failing batch to isolate the bad record.
  • Maximum retry attempts and maximum record age stop endless retries.
  • An on-failure destination (SQS, SNS or S3) records the details of discarded records.
  • Event filtering invokes the function only for matching records, for example only MODIFY events, reducing invocations and cost.
  • Up to two Lambda consumers per stream shard are recommended; more consumers risk throttling on the stream's reads.

Streams and related features

DynamoDB offers more than one way to capture changes, and they suit different consumers.

DynamoDB Streams is the native option and the usual choice for triggering Lambda functions. It keeps records for 24 hours, guarantees that each change appears once and in order for each item; AWS recommends no more than two consumers reading each shard at the same time. Kinesis Data Streams for DynamoDB sends the changes to a Kinesis data stream in your account instead. The data can be retained for up to a year, read by many consumers, including enhanced fan-out consumers, and delivered to destinations through Amazon Data Firehose, which suits analytics pipelines. Records can arrive out of order or more than once, so consumers compare timestamps and deduplicate.

Global tables use change capture internally to replicate a table to other Regions. Every replica accepts reads and writes, and changes propagate to the others, typically within a second, which gives users low-latency access in several Regions and keeps the application available if a Region fails. With the default multi-Region eventual consistency, concurrent updates to the same item in different Regions are resolved by keeping the last write.

The following table summarises the three features.

FeatureUse it for
DynamoDB StreamsReacting to changes with Lambda; 24-hour retention; ordered per item
Kinesis Data Streams for DynamoDBAnalytics pipelines that need retention of up to a year, more consumers, or Firehose delivery
Global tablesMulti-Region, multi-active replication, which is built on change streams
Scenario questions

Streams in practice

Exam skills 1.1.6 · 1.2.3 · 1.2.4

Choose the right change-capture feature and keep stream processing healthy.

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

Reacting to changes and expiring data

A shopping cart table needs three behaviours, each provided by a different feature:

BehaviourFeature
Abandoned carts disappear after 7 days, at no costTTL on an expiresAt attribute (epoch seconds)
When an item is added, update a recommendation serviceDynamoDB Streams with a Lambda trigger, view type NEW_IMAGE
Product price lookups in microseconds during flash salesDAX in front of the product table

TTL deletions also appear in the stream (as service deletions), so the developer filters them out in the Lambda event source mapping to avoid recommending items from expired carts. DAX helps only reads that are eventually consistent; strongly consistent reads pass through to DynamoDB.

Check yourself

A stream consumer needs both the old and the new values of each updated item. Which stream view type must be enabled?

Show answer

NEW_AND_OLD_IMAGES. KEYS_ONLY, NEW_IMAGE and OLD_IMAGE each provide less.

Exam Tips

Remember for the exam

  • To react to item changes with Lambda, use DynamoDB Streams.
  • To compare an item before and after a change, choose the NEW_AND_OLD_IMAGES view type.
  • For longer retention and many consumers, use Kinesis Data Streams for DynamoDB.
  • One bad record blocking stream processing is fixed with bisect on error, a retry limit and an on-failure destination.
  • TTL deletions appear in the stream as REMOVE records made by the DynamoDB service.