Files
floci/docs/services/dynamodb.md
T
Guilherme Scaranse a9df872956 fix(dynamodb): route Kinesis CDC to the table owner's account and retry failed forwards (#3063)
* fix(dynamodb): resolve Kinesis CDC forwards against the table owner's account

DynamoDB->Kinesis CDC forwarding resolved the target stream against the ambient
account. Out of request scope -- notably the TTL sweep, which forwards a REMOVE per
expired item after the request completes -- the ambient account falls back to the
default, so CDC records could be written into the default account's same-named stream
(a cross-tenant leak) or dropped as ResourceNotFound. This was a live bug on the TTL
path.

- Add KinesisService.putRecordForAccount: resolve, append and persist against a
  specified account (a null account preserves the ambient behavior). It keeps the
  per-stream append lock keyed on region+stream (not account) so explicit-account
  appends stay serialized with request-path producers, preserving the concurrent-
  append fix; and it migrates a legacy unprefixed stream into the account partition on
  write (ownership validated by the stream's ARN/account) so installs upgraded from
  pre-multi-account storage keep forwarding.
- KinesisStreamingForwarder.forward now takes the table owner account and forwards via
  putRecordForAccount.
- DynamoDbService passes the owner account at every forward site: the request paths use
  the request account; the TTL sweep uses the account it derives from the storage key.

AWS Compatibility: CDC records land in the table owner's stream, matching AWS
per-account isolation. Known residual: the DynamoDB Streams subsystem
(DynamoDbStreamsService) has the same ambient-account exposure and is not addressed
here.

* fix(dynamodb): retry and park failed Kinesis CDC forwards instead of dropping them

Change data capture forwarding to a Kinesis streaming destination dropped the
change event whenever putRecord threw, so a transient Kinesis error silently
lost DynamoDB INSERT/MODIFY/REMOVE (and TTL) events.

Forwarding is now a bounded best-effort, in-process retry queue. The write path
only enqueues (it never blocks or throws), and a per-destination single-flight
background drain performs the send outside the lock:

- transient/unknown failures retry with capped exponential backoff (250ms->8s,
  up to 10 attempts) instead of dropping on the first exception;
- deterministic terminal failures (Validation/InvalidArgument) drop only the
  poison record without wedging the queue behind it;
- per-destination FIFO is preserved across retries;
- the buffer is bounded (1000 records per destination, oldest evicted on
  overflow);
- after the retry budget is exhausted the episode gives up, and a later event
  starts a fresh episode that self-heals once the stream recovers.

Disabling a destination or deleting the table discards its buffered records and
stops all future sends for it (a send already in flight may still complete).
Dropped records are counted and per-destination delivery health
(forwarded/retried/dropped, queue depth, last error) is tracked for inspection.
Buffered records are in memory only and are not durable across restarts.

* style(dynamodb): remove em dashes from lines this branch adds

AGENTS.md requires colons, commas or periods instead of em dashes. Comment,
javadoc and docs prose only; no code or string literals change.

* fix(kinesis): resolve the stream inside the append lock, not before it

putRecordInternal resolved the stream before taking the per-stream monitor. That
resolve is not a read: for a legacy unprefixed stream it migrates the entry, and
the two migration paths disagree. The explicit-account path moves it into the
account partition behind an ownership predicate and is synchronized on the
backend, while AccountAwareStorageBackend.get adopts it into the request account
with no ownership check and no synchronization. Racing outside the monitor, an
ambient producer and the owner's CDC producer could migrate the same stream
concurrently, forking it across partitions or adopting it into the default
account, which is the cross-account leak this branch set out to close.

Resolve and validate inside the monitor instead. The separate pre-lock resolve is
gone, so there is one resolve rather than two, and deleteStream holding the same
monitor still makes a concurrently deleted stream fail cleanly.

Residual, pre-existing and not addressed here: AccountAwareStorageBackend.get
still adopts an unprefixed entry into the request account unchecked and
unsynchronized for callers that do not hold a per-resource lock.

* fix(storage): migrate a legacy unprefixed entry under the account monitor

AccountAwareStorageBackend has two migrate-on-read paths that disagree.
getForAccountMigratingLegacy is synchronized and ownership-gated; get is neither.
Because get does not take the monitor the migrating variants hold, two readers
resolving the same pre-multi-account key from different account contexts can each
copy it into their own partition, and the two copies then diverge independently.

The migration branch now runs under that same monitor and re-checks the prefixed
key inside it, so a reader that lost the race returns the winner's entry instead
of migrating again. The hit path stays outside the monitor, so only a miss pays
for it.

This closes the fork for every caller rather than one at a time. The preceding
commit fixed it for KinesisService.putRecordInternal by resolving inside the
append lock, but the Kinesis batch PutRecords handler and roughly twenty read
paths (DescribeStream, GetRecords, GetShardIterator, tag reads) resolve without
any per-resource lock and were still exposed.

Not addressed here: get still adopts an unprefixed entry into whatever account
the request context resolves to, with no ownership check. get is generic over the
stored type and has no notion of an owner, which is why getForAccountMigratingLegacy
takes the predicate from its caller. Gating it generically needs a per-resource-type
predicate and is filed separately.
2026-09-05 21:20:44 -04:00

8.1 KiB

DynamoDB

Protocol: JSON 1.1 (X-Amz-Target: DynamoDB_20120810.*) Endpoint: POST http://localhost:4566/

Supported Actions

Action Description
CreateTable Create a table with indexes
DeleteTable Delete a table
DescribeTable Get table metadata
ListTables List all tables
UpdateTable Update throughput, indexes, streams
PutItem Write an item
GetItem Read an item by primary key
DeleteItem Delete an item
UpdateItem Partially update an item
Query Query by partition key with optional filter
Scan Full table scan with optional filter
BatchWriteItem Write/delete up to 25 items across tables
BatchGetItem Read up to 100 items across tables
TransactWriteItems ACID write transaction
TransactGetItems ACID read transaction
DescribeTimeToLive Get TTL configuration
UpdateTimeToLive Enable/disable TTL on a table
TagResource Tag a table
UntagResource Remove tags
ListTagsOfResource List tags
DescribeContinuousBackups Get PITR backup configuration
UpdateContinuousBackups Enable/disable PITR
DescribeKinesisStreamingDestination List Kinesis streaming destinations
EnableKinesisStreamingDestination Enable Kinesis streaming for a table
DisableKinesisStreamingDestination Disable Kinesis streaming for a table
ExportTableToPointInTime Export table data to S3 as gzip NDJSON
DescribeExport Get export status and metadata
ListExports List exports, optionally filtered by table ARN

Streams

DynamoDB Streams are supported via a separate target (DynamoDBStreams_20120810):

Action Description
ListStreams List all streams
DescribeStream Get stream and shard info
GetShardIterator Get a shard iterator
GetRecords Read stream records from a shard

Configuration

Variable Default Description
FLOCI_SERVICES_DYNAMODB_ENABLED true Enable or disable the service
FLOCI_STORAGE_SERVICES_DYNAMODB_MODE (global default) Storage mode override for DynamoDB (memory, persistent, hybrid, wal)
FLOCI_STORAGE_SERVICES_DYNAMODB_FLUSH_INTERVAL_MS 5000 Flush interval for hybrid/wal storage modes (milliseconds)

Storage and Performance

Under persistent storage mode, single-item writes (PutItem, UpdateItem, DeleteItem) flush the affected table to disk synchronously. Batch operations (BatchWriteItem and TransactWriteItems) batch disk flushes per affected table across the entire operation, rather than flushing on every individual item mutation.

For write-heavy workloads under persistent setups, configuring FLOCI_STORAGE_SERVICES_DYNAMODB_MODE=wal or hybrid is recommended to avoid full-file rewrites on each write operation:

  • wal: Uses an append-only write-ahead log with background compaction.
  • hybrid: Keeps data in memory with periodic asynchronous disk flushes controlled by FLOCI_STORAGE_SERVICES_DYNAMODB_FLUSH_INTERVAL_MS.

Examples

export AWS_ENDPOINT_URL=http://localhost:4566

# Create a table
aws dynamodb create-table \
  --table-name Users \
  --attribute-definitions \
    AttributeName=userId,AttributeType=S \
  --key-schema \
    AttributeName=userId,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST \
  --endpoint-url $AWS_ENDPOINT_URL

# Put an item
aws dynamodb put-item \
  --table-name Users \
  --item '{"userId":{"S":"u1"},"name":{"S":"Alice"},"age":{"N":"30"}}' \
  --endpoint-url $AWS_ENDPOINT_URL

# Get an item
aws dynamodb get-item \
  --table-name Users \
  --key '{"userId":{"S":"u1"}}' \
  --endpoint-url $AWS_ENDPOINT_URL

# Query (partition key)
aws dynamodb query \
  --table-name Users \
  --key-condition-expression "userId = :id" \
  --expression-attribute-values '{":id":{"S":"u1"}}' \
  --endpoint-url $AWS_ENDPOINT_URL

# Scan with filter
aws dynamodb scan \
  --table-name Users \
  --filter-expression "age > :min" \
  --expression-attribute-values '{":min":{"N":"25"}}' \
  --endpoint-url $AWS_ENDPOINT_URL

# Enable TTL
aws dynamodb update-time-to-live \
  --table-name Users \
  --time-to-live-specification Enabled=true,AttributeName=expiresAt \
  --endpoint-url $AWS_ENDPOINT_URL

# Enable Streams
aws dynamodb update-table \
  --table-name Users \
  --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \
  --endpoint-url $AWS_ENDPOINT_URL

Global Secondary Indexes

aws dynamodb create-table \
  --table-name Orders \
  --attribute-definitions \
    AttributeName=orderId,AttributeType=S \
    AttributeName=customerId,AttributeType=S \
  --key-schema AttributeName=orderId,KeyType=HASH \
  --global-secondary-indexes '[{
    "IndexName": "CustomerIndex",
    "KeySchema": [{"AttributeName":"customerId","KeyType":"HASH"}],
    "Projection": {"ProjectionType":"ALL"}
  }]' \
  --billing-mode PAY_PER_REQUEST \
  --endpoint-url $AWS_ENDPOINT_URL

Export to S3

Export table data to an S3 bucket as gzip-compressed NDJSON (DynamoDB JSON format):

# Create a bucket to receive the export
aws s3 mb s3://my-exports --endpoint-url $AWS_ENDPOINT_URL

# Start an export
EXPORT_ARN=$(aws dynamodb export-table-to-point-in-time \
  --table-arn arn:aws:dynamodb:us-east-1:000000000000:table/Users \
  --s3-bucket my-exports \
  --s3-prefix exports \
  --export-format DYNAMODB_JSON \
  --query ExportDescription.ExportArn --output text \
  --endpoint-url $AWS_ENDPOINT_URL)

# Poll until COMPLETED
aws dynamodb describe-export \
  --export-arn $EXPORT_ARN \
  --query ExportDescription.ExportStatus \
  --endpoint-url $AWS_ENDPOINT_URL

# List exports for a table
aws dynamodb list-exports \
  --table-arn arn:aws:dynamodb:us-east-1:000000000000:table/Users \
  --endpoint-url $AWS_ENDPOINT_URL

The export writes to s3://<bucket>/<prefix>/AWSDynamoDB/<exportId>/data/ as one or more .json.gz files, along with manifest-summary.json and manifest-files.json, the same layout as real AWS DynamoDB exports.

Kinesis change data capture (CDC)

When a table has an ACTIVE Kinesis streaming destination (see EnableKinesisStreamingDestination), every item change, INSERT, MODIFY, and REMOVE, including TTL expirations, is forwarded to the destination stream as a Kinesis record in the AWS CDC envelope (eventName, dynamodb.Keys, NewImage/OldImage, ApproximateCreationDateTime).

Delivery contract

Forwarding is bounded best-effort with in-process retry. A write is never blocked or failed by the destination stream: the change event is enqueued and delivered on a background drain, so a slow or unavailable Kinesis stream cannot stall a PutItem/UpdateItem/DeleteItem or the TTL sweep.

The drain gives these guarantees per destination:

  • Retries transient/unknown send failures with capped exponential backoff (250 ms doubling to an 8 s cap, up to 10 attempts) rather than dropping the record on the first exception.
  • Preserves FIFO across retries: the head record is not skipped past (stronger than AWS, which may reorder or duplicate).
  • Drops a poison record immediately on a deterministic terminal failure (ValidationException/InvalidArgumentException) so it cannot wedge the queue behind it.
  • Gives up an episode after the retry budget is exhausted, dropping the buffered records and marking the destination GAVE_UP; a later change event starts a fresh episode and self-heals once the stream recovers.
  • Bounds memory at 1000 buffered records per destination, evicting the oldest on overflow.

Disabling a destination or deleting the table discards that destination's buffered records and stops all future sends for it; a send already in flight at that instant may still complete (teardown cannot recall an in-flight request, an inherent and harmless race). Buffered records are held in memory only: they are not durable and are lost on restart (this is an emulator, not an at-least-once pipeline). Records that are permanently dropped (terminal, give-up, or overflow) are counted and logged, and per-destination delivery health (forwarded/retried/dropped counts, queue depth, last error, and current health) is tracked for inspection.