Skip to content

Change streams

On a stream-enabled table, each item change and its DynamoDB Streams record commit together. Consumers see no uncommitted change and miss no committed change unless retention trimmed it.

The item, its index entries and its stream record are one FoundationDB commit; the home page figure steps through one.

Order

Scope Guarantee
Shard A record's key ends in the versionstamp that becomes its SequenceNumber. Sequence numbers are unique within a shard and follow commit order.
Partition key All records use one shard per shard set. Across a split, read the parent to its end before its children.
Transaction Records share a transaction version. fdyno's user version orders records from that commit within the shard.
Across shards No order.

Order by SequenceNumber, not ApproximateCreationDateTime, which uses the fdyno process clock. GetRecords returns it in whole epoch seconds, rounded down; several records can share one value. An identical PutItem or deletion of a missing item writes no record.

How a shard is stored

The writer hashes the canonical partition key (not the sort key) with FNV-1a and takes the remainder by the current shard count. A shard set is an epoch. An online split changes the table's metadata revision. An item transaction using the old revision cannot commit into the closed set after that change; it must retry with the new routing. See the concurrent-writer split test.

Every stream uses the generation-scoped layout. The first generation is 1. Builds before cluster version 12 also wrote the other layouts in the table below. This build does not read them: it serves only a store at cluster version 12, and it refuses to start on a store written by an earlier build (first start).

Layout Record key inside the table directory
Generation-scoped (the only layout at cluster version 12) ("vg", generation, epoch, shard, stamp)
Before cluster version 12 only: original single shard ("v", stamp)
Before cluster version 12 only: original multi-shard ("v", shard, stamp)
Before cluster version 12 only: new epoch after a split of the original stream ("ve", epoch, shard, stamp)

FoundationDB fills the 10-byte transaction part of stamp at commit; fdyno sets its 2-byte user version. The API renders the result as a 30-digit decimal string. A sequence number can be converted back into a key in its shard. So seeking does not scan earlier records or depend on how many have been trimmed. Each record uses one FoundationDB value. See the sequence encoding test and the full key layout.

Choose the shard count when enabling a stream

DYNODB_STREAM_SHARDS: default 1, maximum 100; set alike on every process. The partition key's hash selects its shard. Shards add read parallelism, not write capacity; one hot partition key cannot split.

Split shards online

The autosplit worker doubles an enabled stream without changing its ARN or losing records. It never merges shards.

Rule Behavior
Predictable burst On a dedicated deployment, set DYNODB_STREAM_SHARDS alike on all processes before enabling the stream. This sets its initial count and does not resize existing streams. Automatic splitting acts only after the average per-shard record-byte rate passes the threshold, and it runs on an interval with at most one split per table in a pass (worker limits), so consumers of a known burst can lag until the splits finish. Setting the count first avoids that wait. More shards do not help one hot partition key.
Switch One transaction switches writers; old shards close with EndingSequenceNumber.
Parent Child j has parent j mod N (N = old count); every child key came from that parent. For 2→4: parent 0 → children 0, 2; parent 1 → children 1, 3.
Consumer Read parents to their end before children for per-key order, as Kinesis Client Library does. ShardFilter=CHILD_SHARDS lists children.
Trimmed parent Once trimmed empty, a closed shard leaves DescribeStream; children still name it. An iterator or AFTER_SEQUENCE_NUMBER checkpoint at its end still reads the end; earlier positions return TrimmedDataAccessException.

Step-through: a split from two shards to four. Old shards close; child j has parent j mod 2; read parents to their end before children.

Split shards automatically

By default, the stream-autosplit lease holder measures record bytes and doubles above the average per-shard threshold, using the online split.

Setting or rule Value and behavior
Measurement period 30 s; at most one doubling per interval.
DYNODB_STREAM_AUTO_SPLIT_BYTES_PER_SECOND Default 1 MiB/s (one DynamoDB shard's write rate); 0 disables. At/below threshold: no change.
Measurement FoundationDB estimate of the record range. A count change since measurement refuses the split without changes.
Cap 64 shards; at most 8 live shard sets. Older sets drop once trimmed empty.
Priority Default priority; runs when batch work is throttled.
Hot key Cannot cool one hot partition key. Lower the threshold if one consumer per shard falls behind.
Consumer Discover children; read parents first, as Kinesis Client Library does. Initial-shards-only readers stop receiving records. Tested consumers.
Growth No merge. Disable and re-enable to reduce the count. No new format; older binaries read split streams.

Stream API and iterator positions

fdyno supports ListStreams, DescribeStream, GetShardIterator and GetRecords, with every iterator type:

Iterator type Starts at
TRIM_HORIZON The oldest retained record.
LATEST Immediately after the newest record.
AT_SEQUENCE_NUMBER That record.
AFTER_SEQUENCE_NUMBER Immediately after that record.
AT_TIMESTAMP The first record at or after Timestamp (epoch seconds; fractions are honored). Before the trim point, it starts at TRIM_HORIZON. A Timestamp copied from a returned ApproximateCreationDateTime can replay earlier records from that second. To resume exactly, use AFTER_SEQUENCE_NUMBER with the last processed SequenceNumber, and follow the shard lineage.
Boundary Behavior
Lifetime 15 minutes from issue, then ExpiredIteratorException; each NextShardIterator renews for 15 minutes.
Page Up to 1,000 records; ends before the stored record bytes pass 1 MiB. The first record always returns, even if larger.
End Closed or disabled shard at end: no NextShardIterator.
DescribeStream shards Up to 100 per call, closed parents included; Limit sets 1–100. Pass LastEvaluatedShardId as ExclusiveStartShardId until it is absent.
Timestamp search Skipping old records with AT_TIMESTAMP can return an empty page with a next iterator. Keep polling.

Empty reads

An empty GetRecords returns at once with a NextShardIterator, as in DynamoDB. Poll again; the AWS SDKs and the KCL already wait between empty reads. DYNODB_STREAMS_GETRECORDS_WAIT_MS is retired: 0 still starts, and any other value stops startup.

View types

View type Record holds
KEYS_ONLY The primary key.
NEW_IMAGE The item after the change.
OLD_IMAGE The item before the change.
NEW_AND_OLD_IMAGES Both images when both exist. fdyno can store the old image as a difference from the new one.

Larger views add latency and transaction size; choose the smallest needed. With KEYS_ONLY, reading the current item may return a newer value.

Every record has eventSource aws:dynamodb, eventVersion 1.1 and awsRegion local, the same Region as the stream and table ARNs. Route by the endpoint you configured, not by this synthetic Region.

TTL and ordinary deletes

A TTL REMOVE includes userIdentity with Type: Service and PrincipalId: dynamodb.amazonaws.com. An ordinary delete of a live item omits userIdentity. A REMOVE has no NewImage. It includes OldImage only with OLD_IMAGE or NEW_AND_OLD_IMAGES.

The TTL record appears when the sweeper or a later write deletes the item, not when a read hides it. A write that replaces an expired item emits the TTL REMOVE first and then its own INSERT.

Transactional writes

A committed TransactWriteItems request emits one record for each item it changes on a stream-enabled table, not one record for the whole request. ConditionCheck, unchanged items, and canceled transactions produce no records of their own. An identical token replay within the 10-minute window adds no records. A TTL removal during the write still has its own REMOVE record.

Consumer checkpoints and delivery semantics

fdyno keeps no consumer groups or checkpoints. Delivery is at least once. For each stream ARN and shard:

  1. Resume with AFTER_SEQUENCE_NUMBER at your checkpoint, or TRIM_HORIZON.
  2. Read a page.
  3. Apply records idempotently. ARN, shard ID and sequence number identify a record.
  4. Save the last applied sequence number after its effect is durable.

Saving first can lose records; applying first can repeat them. Make the sink idempotent unless it commits with the checkpoint.

A trimmed position returns TrimmedDataAccessException, counted in fdyno_stream_trimmed_access_total, never a silent skip. Records were lost: alert, then restart at TRIM_HORIZON or rebuild the sink.

Disabled and re-enabled generations

Event Behavior
Disable Stops new records; consumers can drain old records. Changes while disabled have no records.
Re-enable New generation, new ARN. Retained generations remain readable by old ARN. ListStreams lists both; LatestStreamArn names the new one.
Limit At most eight retired generations per table. A ninth re-enable fails with LimitExceededException until trimming removes an expired one; without trimming, never.
Removal A removed generation returns ResourceNotFoundException.

Keep checkpoints per ARN and shard. Do not jump to LatestStreamArn after losing an old generation's records.

Streams of deleted tables

An enabled stream is kept for 24 hours after table deletion. So is the table's latest stream if it is disabled with no recorded disable time. For an already-disabled generation with a recorded disable time, deletion does not restart its retention clock. The kept table's cleanup time uses the latest expiry among its retained generations. See the expiry rule and deletion and name-reuse test.

Event Behavior
DeleteTable Disables the enabled stream and closes its shards. DescribeStream shows DISABLED. ListStreams lists it until the kept stream is removed, by the table name or without one. A name's streams are listed newest first, as in DynamoDB.
Read GetShardIterator and GetRecords use the old ARN even if a new table or restore holds the same name. Retained retired generations remain readable.
Items and indexes Freed at deletion; a PITR table keeps them in its SYSTEM backup.
Cleanup The pitr-trim worker removes the kept-stream metadata after expiry plus the clock-skew margin. After cleanup, a lookup of the old ARN returns ResourceInUseException while a same-name restore is CREATING. It returns ResourceNotFoundException once the table is ACTIVE or absent.

Deletion moves the table directory without changing its key prefix. Without PITR, deletion keeps only the stream key ranges. With PITR, the SYSTEM backup owns the directory. A record keyed by table name and TableId points to the metadata and directory saved at deletion. Deletes index each retained generation by its full ARN. Reads check the ARN against that saved metadata before returning a stream.

Stream cleanup removes the index entries with its metadata and removes only a directory it owns. If the SYSTEM backup is removed before stream cleanup, the stream takes ownership of the directory and keeps only the CDC keys. Deleting the backup does not shorten stream retention.

Stream labels use millisecond timestamps. Writers reserve labels in increasing order for each table name, including when the name is reused. The label does not determine retention.

Retention and trimming

With DYNODB_CDC_TRIM_INTERVAL=off, the CDC trimmer does not remove records from live tables. It runs every 5 minutes by default. Deleted-table cleanup still runs.

Setting or rule Value and behavior
Trim age Delete records older than DYNODB_CDC_RETENTION (default 24 h) plus DYNODB_CDC_TRIM_SKEW_MARGIN (default 5 min), and expired retired generations.
Interval Run every 1 to 5 minutes; a pass works up to half the interval.
Clock margin Must cover the clock difference between processes.
Undated record Stops the trimmer.
Backlog fdyno_cdc_trim_oldest_record_age_seconds above retention plus margin means the trimmer is behind; see a worker falls behind.

Retain records longer than your worst consumer outage.

Where the trimmer stops

The lease holder computes threshold = trimmer time − retention − skew margin. Within each shard it walks commit order, not timestamp order. It clears only an expired prefix. A record at or above the threshold, or without a timestamp, stops the prefix. This holds even if a later record has an older timestamp. See the clock-skew test.

A trim page uses a snapshot read and adds a read conflict only through the last event it inspected. A later versionstamped append sorts after that range and does not conflict with it. A competing clear inside the range still forces a retry. See the append and competing-clear tests.

The transaction clears the prefix and advances the shard's trim head to immediately after the last cleared key. A cursor below the head gets TrimmedDataAccessException; at the head it remains valid. For example, AFTER_SEQUENCE_NUMBER at the last cleared record can still resume, but AT_SEQUENCE_NUMBER there cannot. A new TRIM_HORIZON starts at the retained range. See the trim-head tests.

When a read fails

GetRecords checks an iterator in a fixed order and returns the first failure. The first four checks read nothing from FoundationDB. The stream, its shard, the trim head and the records then come from one snapshot. So a split, trim, disable or re-enable is wholly before or wholly after the read (streams.go).

GetRecords(iterator), before any read

Step Check Outcome
1 Limit is 1..1000 Out of range: ValidationException
2 The iterator decodes Does not decode: ValidationException
3 The stream ARN is well formed Malformed: ValidationException
4 The iterator is within its window (DYNODB_STREAMS_ITERATOR_TTL, 15m) Expired: ExpiredIteratorException

One snapshot

Step Check Outcome
5 The stream ARN resolves Not found: ResourceNotFoundException
6 The shard is in a live shard set Shard set pruned: an iterator at its end gets an empty page and no next iterator; one behind it gets TrimmedDataAccessException. Other shard IDs: ResourceNotFoundException
7 The position is inside its shard Outside: ValidationException
8 The position is not below the trim head Below: TrimmedDataAccessException
9 Read up to Limit records and 1 MiB of stored record bytes (the first record always returns)

Step 5 can also return ResourceInUseException for a deleted table's old ARN. This happens while a same-name restore is CREATING, once the kept stream is cleaned up (streams of deleted tables).

Step 6 can return TrimmedDataAccessException even at a pruned shard's end. This happens for the first shard set of a stream that is not generation-scoped (layouts), once the next set is also pruned.

See stream_epochs.go).

Reader situation Result Records lost What to do
One iterator held for more than 15 minutes without a call ExpiredIteratorException No GetShardIterator with AFTER_SEQUENCE_NUMBER at the last applied SequenceNumber.
Polling an open shard with no new records An empty page and a new NextShardIterator with a new issue time No Keep polling with the newest iterator.
Shard split while reading the parent The rest of the parent's records, then a page without NextShardIterator No Read each child from TRIM_HORIZON.
Stream disabled while reading The rest of the shard's records, then a page without NextShardIterator No Stop. A re-enabled stream has a new ARN.
Position fell below the trim head, including a TRIM_HORIZON iterator the trimmer passed TrimmedDataAccessException Yes Alert, then restart at TRIM_HORIZON or rebuild the sink.
Position exactly at the trim head Records from the first survivor No None.
Shard set pruned; iterator or checkpoint at the shard's end An empty page without NextShardIterator No Read the children.
Shard set pruned; position behind the shard's end TrimmedDataAccessException Yes Alert. List shards again with DescribeStream and read the listed shards from TRIM_HORIZON, or rebuild the sink. TRIM_HORIZON on the pruned shard also returns TrimmedDataAccessException.
Shard ID not in this stream generation ResourceNotFoundException (Shard not found) — List shards with DescribeStream on the iterator's ARN.
Iterator position outside its own shard ValidationException (invalid shard iterator) — fdyno did not issue it for that shard. Get a new iterator.
Stream generation removed after its retention ResourceNotFoundException Unread records, yes See disabled and re-enabled generations.

Every TrimmedDataAccessException from GetRecords or GetShardIterator adds to fdyno_stream_trimmed_access_total.

Iterator expiry

An iterator carries its issue time: the issuing process's clock, in Unix milliseconds. The reading process compares it with its own clock. The window is DYNODB_STREAMS_ITERATOR_TTL, default 15m; the production profile accepts only 15m. A clock difference between the two processes moves the window. An iterator from a process whose clock runs behind expires earlier by that difference. An iterator stamped ahead of the reader's clock is not expired. See clock synchronization and stream_cursor.go.

Every NextShardIterator gets a new issue time, also after an empty page. So only a reader that holds one iterator longer than the window sees the error. The error message names the issue time, the reader's time and the window in milliseconds, in DynamoDB's format. An iterator without an issue time is refused with ValidationException (malformed shard iterator). Only binaries from before iterator expiry made one, and they cannot serve a current store.

An expired iterator loses no records; only the iterator is gone. Resume from the saved checkpoint with AFTER_SEQUENCE_NUMBER. That checkpoint can itself fall below the trim head if the first record after it is older than DYNODB_CDC_RETENTION plus DYNODB_CDC_TRIM_SKEW_MARGIN.

A split during a read

Moment Reader on parent P Split transaction Writer of key k Why
Before the split GetRecords(P) returns a page an attempt reads the old routing and selects P; it has not committed
The split commits writes the new shard set to the table metadata; the boundary B is its own commit versionstamp The split is one transaction.
The writer retries its commit conflicts with the split; the retry sends k to a child of P A writer that read the old metadata conflicts with the split's commit and retries with the new routing. So every parent record sorts below B, and no record reaches P after it.
The reader finishes P GetRecords(P) returns the rest of P; the last page has no NextShardIterator A shard that no record can reach any more is closed. A page that is full at Limit still has a NextShardIterator. If that page held the last remaining record, the next page is empty and ends the shard.
The reader moves on DescribeStream: the children name P as ParentShardId; GetShardIterator(child, TRIM_HORIZON) returns an iterator at B A child's TRIM_HORIZON is its trim head if records were trimmed, otherwise its start: the boundary B. Pictured: nothing trimmed.

The split is one transaction. It writes the new shard set to the table metadata and stores its own commit versionstamp as the boundary. A writer that read the old metadata conflicts with that commit and retries with the new routing. So every parent record sorts below the boundary, and no record reaches the parent after it (stream_reshard.go).

A reader keeps its parent iterator. It reads the rest of the parent. A shard that no record can reach any more is closed: once a read reaches its end, the page has no NextShardIterator. A page that is full at Limit still has one. If that page held the shard's last remaining record, the next page is empty and ends the shard. Otherwise the next page reads on.

Each child's TRIM_HORIZON starts at its oldest surviving record. That is its trim head if records were trimmed. Otherwise it is the start of its shard range, at the boundary. See the split test, whose early consumer drains its closed shard and is closed.

TRIM_HORIZON after a trim

GetShardIterator with TRIM_HORIZON returns a fixed position: the trim head at that moment, or the shard's start if nothing was trimmed. The position does not follow later trims. If the trimmer clears past it before the reader reads there, GetRecords returns TrimmedDataAccessException. A position at the head stays valid: AFTER_SEQUENCE_NUMBER at the last cleared record still reads on. See the trim-head tests, where a TRIM_HORIZON iterator issued before a trim fails after it.

A new consumer that starts at TRIM_HORIZON reads the oldest records first. Those are the next records to pass the trim threshold. If it reads them slower than the trimmer clears them, its position falls below the head. A new TRIM_HORIZON then starts after the cleared records, and that consumer never sees them.

Troubleshooting a consumer

If records stop:

  1. Check the ARN; an old generation remains readable after re-enable.
  2. DescribeStream, following LastEvaluatedShardId to the last page: poll every open shard; follow closed shards to children.
  3. Check whether LATEST was used after the expected writes.
  4. Diagnose with TRIM_HORIZON without moving the real checkpoint.
  5. Check retention and generation removal.
  6. Check trimmer metrics and clock synchronization.

Writes failing only on stream-enabled tables are too large for one transaction: reduce view, indexes or item size.

Not guaranteed

No order across shards, consumer checkpoints or exactly-once delivery. Retention can remove unread records; gaps return errors. Splitting cannot increase write capacity or divide a hot partition key. Disabled streams capture no changes. Physical TTL deletion does not happen at read expiry.

How we know: stream model and its limits.