DynamoDB Streams, Transactions, Batching and DAX
Overview
Beyond basic reads and writes, DynamoDB offers features that make applications reactive and reliable: Streams emit a log of changes, transactions make multiple writes atomic, batch APIs reduce round trips, and DAX provides a microsecond cache.
Streams are like a security camera on the filing warehouse: every item added, changed or removed is recorded for 24 hours so other systems can react. Transactions are an "all or nothing" order form: either every line is processed or none is. DAX is a fast desk next to the clerk that remembers recently requested files.
The exam tests which feature fits which need, plus limits and error behaviour.
Key Concepts
- DynamoDB Streams keep an ordered, per-item log of changes for 24 hours, with view types: KEYS_ONLY, NEW_IMAGE, OLD_IMAGE, NEW_AND_OLD_IMAGES.
- Lambda reads streams through an event source mapping, enabling triggers, materialised views, auditing and cross-system sync.
- Kinesis Data Streams for DynamoDB is an alternative for longer retention and more consumers.
- TransactWriteItems / TransactGetItems provide ACID across up to 100 items (4 MB) in one or more tables in a Region; they cost 2x capacity.
- BatchWriteItem (25 puts/deletes, 16 MB) and BatchGetItem (100 items) are not atomic; handle
UnprocessedItemswith retries. - DAX is an in-memory, write-through, API-compatible cache for eventually consistent reads, giving microsecond latency.
- Global tables provide multi-Region, multi-active replication with last-writer-wins conflict resolution.
- PITR restores to any second in the last 35 days; on-demand backups persist until deleted; export to S3 does not consume capacity.
Detailed Notes
Streams and Lambda
Resources:
StreamFn:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.12
Handler: app.handler
Events:
Ddb:
Type: DynamoDB
Properties:
Stream: !GetAtt OrdersTable.StreamArn
StartingPosition: LATEST
BatchSize: 100
BisectBatchOnFunctionError: true
MaximumRetryAttempts: 3
def handler(event, context):
for r in event["Records"]:
if r["eventName"] == "INSERT":
new = r["dynamodb"]["NewImage"] # DynamoDB JSON format
print("new order", new["pk"]["S"])
Records are ordered per item (per partition key). Stream records appear in near real time. Because Lambda retries until success, make processing idempotent.
Transactions
import boto3
client = boto3.client("dynamodb")
client.transact_write_items(
TransactItems=[
{"Update": {
"TableName": "Accounts",
"Key": {"id": {"S": "A"}},
"UpdateExpression": "SET balance = balance - :amt",
"ConditionExpression": "balance >= :amt",
"ExpressionAttributeValues": {":amt": {"N": "100"}}}},
{"Update": {
"TableName": "Accounts",
"Key": {"id": {"S": "B"}},
"UpdateExpression": "SET balance = balance + :amt",
"ExpressionAttributeValues": {":amt": {"N": "100"}}}},
],
ClientRequestToken="transfer-8841", # idempotency for 10 minutes
)
If any condition fails the whole transaction is cancelled with TransactionCanceledException. A ClientRequestToken makes retries idempotent.
Batch vs transaction
| Batch APIs | Transactions | |
|---|---|---|
| Atomic | No | Yes |
| Max items | 25 writes / 100 reads | 100 |
| Capacity | Normal | 2x |
| Failure | Partial; UnprocessedItems | All or nothing |
| Conditions | Not supported on batch writes | Supported |
with table.batch_writer() as batch: # handles chunking and unprocessed items
for row in rows:
batch.put_item(Item=row)
DAX
DAX sits between the app and DynamoDB and uses a DAX client. Item cache (default TTL 5 min) serves GetItem and BatchGetItem; query cache serves Query and Scan. It is write-through, but strongly consistent reads and transactional reads bypass the cache. DAX suits read-heavy, repeated key access and not write-heavy or strongly consistent workloads. It runs in a VPC, so Lambda needs VPC access.
| Need | Choice |
|---|---|
| Microsecond reads of hot items | DAX |
| Cache arbitrary computed results or sessions | ElastiCache |
| React to changes | Streams + Lambda |
| Cross-Region active-active | Global tables |
Global tables and backups
Global tables require streams enabled and replicate in typically under a second. Use PITR for accidental deletes and AWS Backup for centralised policies.
PartiQL
aws dynamodb execute-statement --statement \
"SELECT * FROM Orders WHERE pk = 'USER#123'"
PartiQL provides SQL-like syntax but still follows key-based access; unbounded selects become scans.
Common errors
| Error | Meaning |
|---|---|
| ConditionalCheckFailedException | Condition expression false |
| TransactionCanceledException | One item failed or conflicted |
| ProvisionedThroughputExceededException | Throttled |
| ValidationException | Bad request, e.g. item > 400 KB |
Stream view types and Lambda consumption
| StreamViewType | Record contains |
|---|---|
| KEYS_ONLY | Key attributes only |
| NEW_IMAGE | Entire item after the change |
| OLD_IMAGE | Entire item before the change |
| NEW_AND_OLD_IMAGES | Both, useful for diffing and auditing |
Stream records are ordered per item, retained for 24 hours, and delivered to Lambda in batches per shard. Configure the mapping with a bisect on error, maximum retry attempts and an on-failure destination, otherwise a poison record blocks the shard until it expires.
aws lambda create-event-source-mapping --function-name audit-fn \
--event-source-arn arn:aws:dynamodb:eu-west-1:111122223333:table/Orders/stream/2025-01-01T00:00:00.000 \
--starting-position LATEST --batch-size 100 --bisect-batch-on-function-error \
--maximum-retry-attempts 3 \
--destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:eu-west-1:111122223333:stream-dlq"}}' \
--filter-criteria '{"Filters":[{"Pattern":"{\"eventName\":[\"INSERT\"]}"}]}'
Transaction rules and DAX behaviour
TransactWriteItems accepts up to 100 actions touching different items (4 MB total) in one or more tables in the same Region and account, and every action is all-or-nothing. A ClientRequestToken makes the call idempotent for 10 minutes. Transactions cost twice the normal capacity, and a conflict raises TransactionCanceledException with per-item cancellation reasons.
DAX is a write-through, item and query cache that speaks the DynamoDB API, so you change only the client endpoint. It helps read-heavy, repeated reads and eventually consistent reads; strongly consistent reads bypass the cache. It does not help write-heavy or rarely repeated workloads.
Real World Example
A bank's account service transfers money between two items using a TransactWriteItems call with a balance condition so overdrafts are impossible and retries use a ClientRequestToken. A stream feeds a Lambda that writes an immutable audit record to S3 and publishes a notification to SNS. Product-catalogue reads, which hit the same items thousands of times per second, were moved behind DAX, cutting latency from 5 ms to under 500 microseconds.
Architecture Diagram
Writes trigger downstream reactions; hot reads are served from cache.
- 1The app reads hot items through DAX for microsecond latency.
- 2Writes go through DAX to DynamoDB (write-through).
- 3Each change appears in the stream in item order.
- 4Lambda processes records and notifies other systems.
Best Practices
- ✓Use transactions only where atomicity is required; they cost double.
- ✓Always handle UnprocessedItems from batch calls with backoff.
- ✓Make stream consumers idempotent and configure retry limits and failure destinations.
- ✓Use DAX for read-heavy eventually consistent workloads.
- ✓Enable PITR on production tables.
Common Interview Questions
Exam Tips
DVA-C02 focus
- React to item changes -> DynamoDB Streams + Lambda.
- Microsecond reads without app rewrite -> DAX.
- All-or-nothing multi-item writes -> TransactWriteItems (max 100 items).
- Multi-Region active-active -> global tables.
Finished this lesson?
0 of 46 lessons done · 0% of the course

