@aws-blocks/bb-distributed-table

中文文档
0.3.0发布于 2026/11/02Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 6.3万

Structured data storage backed by DynamoDB with secondary indexes and rich query capabilities.

原始使用文档
文档目录17 节
  1. API
  2. Options
  3. Key Object Pattern
  4. Query
  5. Conditional Operations
  6. Reads and schema evolution
  7. Error Handling
  8. Examples
  9. Basic CRUD
  10. Query with Sort Key Conditions
  11. TTL (Auto-Expiring Items)
  12. Batch Operations
  13. Wrapping an Existing Table
  14. Best Practices
  15. Scaling & Cost (AWS)
  16. Durability & Security defaults
  17. Local Development

DistributedTable

Structured data storage backed by DynamoDB with secondary indexes and rich query capabilities.

When to use: You need to query by multiple fields, use composite keys, or perform sort-key-based range queries. Good for entities with relationships, time-series data, and access patterns that require multiple indexes.

When NOT to use: If you only need single-key lookups, use KVStore. If you need full SQL (joins, aggregations), use Database.

Design & mock parity details: DESIGN.md

API

const table = new DistributedTable(scope, id, options)

Type inference (important): Do not pass a single explicit type argument like new DistributedTable<MyType>(...). Doing so pins only T and lets the key/index generics fall back to their broad defaults, which breaks key-type inference — get() and query({ where }) will then demand every field of the type instead of just the key fields. Either let all generics infer (new DistributedTable(scope, id, { schema, key, indexes }) with no explicit <...>), or pass all three generics. Note that as const alone does not fix it.

MethodReturnsDescription
get(key)Promise<T | null>Retrieve a single item by primary key.
put(item, options?)Promise<void>Store an item. Overwrites unless conditions are set.
delete(key, options?)Promise<void>Remove an item by primary key.
query(options)AsyncIterable<T>Query items by index or primary key.
scan(options?)AsyncIterable<T>Enumerate all items. Expensive on large datasets.
getBatch(keys)Promise<(T | null)[]>Retrieve multiple items by key.
putBatch(items)Promise<void>Store multiple items.
deleteBatch(keys)Promise<void>Remove multiple items by key.
DistributedTable.fromExisting(tableName)ExternalTableRefWrap a pre-existing DynamoDB table.

Runtime only. Data methods (get, put, delete, query, scan, getBatch, putBatch, deleteBatch) run at request time — call them inside an ApiNamespace method, RawRoute handler, job handler, or a runtime script, not at the top level of your aws-blocks/index.ts. Top-level code runs during CDK synth, where the block resolves to its infrastructure construct, whose data methods are guards: a top-level call throws an Error reading DistributedTable.<method>() cannot be called during CDK synth. Data methods run at request time — …. To seed data, do it from inside a handler or a separate runtime script. Constructing the block at module scope is fine; only method calls must move into handlers.

Collecting scan() results: like query(), scan() returns an AsyncIterable — collect with await Array.fromAsync(table.scan()) or iterate with for await. Prefer query() over scan() (scans read every item).

Options

OptionTypeRequiredDescription
schemaStandardSchemaV1YesRuntime validation schema (Zod, Valibot, ArkType, etc.). Type T is inferred from the schema.
keyTableKeyConfig<T>YesPrimary key configuration: { partitionKey, sortKey? }. Field names must exist in the schema.
indexesRecord<string, TableKeyConfig<T>>NoGlobal secondary index definitions.
ttlkeyof T & stringNoEnable DynamoDB TTL on the specified attribute. The field should contain a Unix epoch timestamp in seconds.
pointInTimeRecoveryboolean | { retentionDays: number }NoPoint-in-Time Recovery (continuous backups). true = on with the default 35-day window; false = off; { retentionDays: n } = on with an n-day window (1–35). Defaults to the stack defaults.pointInTimeRecovery (on under BlocksPresets.production, off under sandbox). Bills for backup storage per GB-month; a shorter window trims cost.
protection'disposable' | 'retained' | 'locked'NoHow hard the table is to destroy (spans removal policy + deletion protection). 'disposable' = deleted with the stack; 'retained' = orphaned on stack delete but a direct delete still works; 'locked' = orphaned and deletion-protected. When omitted, removal policy + deletion protection follow the stack defaults (BlocksPresets.production ≈ 'locked', sandbox ≈ 'disposable').
encryption'aws-managed' | 'customer-managed' | ExternalKmsKeyRefNoAt-rest encryption key. 'aws-managed' (default) uses the aws/dynamodb KMS key (auditable, no key charge); 'customer-managed' provisions a dedicated CMK; pass DistributedTable.fromKmsKey(arn) to encrypt with an existing CMK you own (shareable across tables).
readValidation'off' | 'coerce' | 'strict'NoHow reads (get/getBatch/query/scan) reconcile a stored item with schema. 'coerce' (default) returns the coerced value and, on failure, the raw value + a warning (never throws); 'strict' throws ValidationFailed on a non-conforming item; 'off' returns the raw value with no validation. See Reads and schema evolution.
tableExternalTableRefNoWrap an existing DynamoDB table instead of creating one. Durability/encryption options are ignored — the customer owns the table's configuration.
loggerChildLoggerNoOptional logger for internal operations. When omitted, a default Logger at warn level is created so readValidation: 'coerce' fallback warnings surface.

Key Object Pattern

All methods that accept a key (get, delete, getBatch, deleteBatch) take a key object with the partition key field (and sort key field if defined). The key type is computed from your schema and key configuration — TypeScript enforces exactly the right fields:

// Table with partition key + sort key
const orders = new DistributedTable(scope, 'orders', {
  schema: orderSchema,
  key: { partitionKey: 'userId', sortKey: 'orderId' },
});

// Key object requires both fields
await orders.get({ userId: 'alice', orderId: '001' });

// Table with partition key only
const settings = new DistributedTable(scope, 'settings', {
  schema: settingsSchema,
  key: { partitionKey: 'settingId' },
});

// Key object requires only the partition key
await settings.get({ settingId: 'theme' });

Query

query() takes a single options object. Specify index to query a GSI, or omit it to query the primary key. The where clause is type-safe — field names and condition types are computed from the index (or primary key) definition.

// Query a GSI
for await (const order of orders.query({
  index: 'byStatus',
  where: { status: { equals: 'pending' } },
  limit: 10,
  order: 'desc',
})) {
  console.log(order);
}

// Query the primary key (omit index)
for await (const order of orders.query({
  where: { userId: { equals: 'alice' }, orderId: { beginsWith: '2024-' } },
})) {
  console.log(order);
}

Tip: When collecting all results into an array, use Array.fromAsync() instead of a manual loop:

const pending = await Array.fromAsync(orders.query({
  index: 'byStatus',
  where: { status: { equals: 'pending' } },
}));

Query options:

FieldTypeRequiredDescription
indexkeyof IndexesNoGSI to query. Omit to query the primary key.
whereKeyCondition<T, K>YesKey conditions. Partition key requires { equals }. Sort key supports equals, greaterThan, lessThan, between, beginsWith, etc.
limitnumberNoMaximum number of items to return.
order'asc' | 'desc'NoSort direction on the sort key. Defaults to 'asc'.

Conditional Operations

Both put and delete accept optional conditions:

// Only write if key doesn't exist (idempotent create)
await table.put(item, { ifNotExists: true });

// Only write if existing item's field matches (optimistic locking)
await table.put(updatedItem, { ifFieldEquals: { version: 3 } });

// Only delete if item exists
await table.delete(key, { ifExists: true });

// Only delete if field matches
await table.delete(key, { ifFieldEquals: { status: 'archived' } });

All condition failures throw with error.name === DistributedTableErrors.ConditionalCheckFailed. They serialize to JSON-RPC 409 (Conflict) over the wire (not 500), in both the mock and AWS runtime. Only ifFieldEquals optimistic-lock conflicts are flagged retriable; ifNotExists / ifExists existence assertions are not retriable (a blind retry fails identically).

No partial update: There is no update() or patch() method. To change a field, do a read-modify-write — get() the item, mutate it, then put() the full item back. For safe concurrent updates, pass { ifFieldEquals: { version: <previous> } } to put() so the write fails (via ConditionalCheckFailed) if another writer changed the item in the meantime (optimistic locking).

Reads and schema evolution

Writes always validate against schema. Reads reconcile a stored item with the schema according to the readValidation option, which matters after a schema change: a row written under an older schema may no longer match the declared type T — a newly added field is absent from the read (so the value silently violates T, and a .default() is neither applied nor persisted on write-back), and a required, no-default field makes the read-modify-write cycle above fail on the write as put() rejects the legacy shape.

readValidation has three modes:

ModeOn readOn a non-conforming item
'coerce' (default)returns the schema's coerced output (defaults filled, types narrowed)returns the raw value + logs a warning — never throws
'strict'validates against the schemathrows ValidationFailed
'off'returns the raw stored value, no validationreturns it as-is

The default 'coerce' closes the schema-evolution gap so a legacy row round-trips cleanly:

const orderSchema = z.object({
  orderId: z.string(),
  total: z.number(),
  currency: z.string().default('USD'),   // added in a later release
});

const orders = new DistributedTable(scope, 'orders', {
  schema: orderSchema,
  key: { partitionKey: 'orderId' },
  // readValidation: 'coerce' is the default
});

const order = await orders.get({ orderId: 'o1' }); // legacy row → { …, currency: 'USD' }
await orders.put({ ...order, total: 20 });          // round-trips without ValidationFailed

'coerce' never throws: a value that genuinely can't be coerced (e.g. a required field with no default) is returned as-is with a warning, so unrecoverable rows stay readable for migration and get() never throws for a bad row.

Best-effort coercion (validator-dependent). Coercion depends on the schema transforming its input. Zod fills defaults and casts; a check-only Standard Schema validator (some Valibot/ArkType schemas) validates without transforming, so 'coerce' returns the value unchanged for those — it never invents data.

'coerce' preserves stored keys not in the schema. Many schemas discard unrecognized keys when they validate (Zod object schemas .strip() by default), which would drop attributes a stored row carries beyond the current schema — and a read-modify-write would then persist the loss. To avoid that, 'coerce' deep-merges the coerced output over the raw stored item: schema output wins per key (defaults filled, types narrowed), while attributes the schema doesn't declare — from an older schema version, or columns another writer owns — are kept. Arrays are replaced wholesale (the coerced array wins), and nested unknown keys are preserved too. So a routine read-modify-write never silently deletes a field you didn't touch. (Use 'strict' if you instead want a schema mismatch to be rejected, or 'off' to skip the schema pass entirely.)

Choose 'strict' for tables where a schema mismatch should be treated as corruption and rejected (note: one bad row then fails the whole query/scan/getBatch). Choose 'off' for hot paths, data you trust was written through this schema, or to read (and preserve) rows you can't yet coerce during a migration.

Error Handling

Errors thrown by DistributedTable carry an error.name you can match with isBlocksError:

Constanterror.nameThrown when
DistributedTableErrors.ConditionalCheckFailedConditionalCheckFailedExceptionAn ifNotExists / ifExists / ifFieldEquals condition failed. Serializes to HTTP 409 (Conflict); retriable only for ifFieldEquals optimistic-lock conflicts (not ifNotExists / ifExists).
DistributedTableErrors.ValidationFailedValidationFailedExceptionAn item failed the configured schema validation on put() / putBatch().
DistributedTableErrors.InvalidQueryInvalidQueryExceptionThe query/condition shape is wrong: missing where, partition key not given as { equals }, unknown index, multiple sort-key conditions, or an empty ifFieldEquals. A caller bug.
DistributedTableErrors.ItemTooLargeItemTooLargeExceptionA put/putBatch item exceeds DynamoDB's 400 KB per-item size limit.
DistributedTableErrors.BatchIncompleteBatchIncompleteExceptionA batch op left entries unprocessed after the retry budget (sustained throttling). AWS runtime only.
import { isBlocksError } from '@aws-blocks/core';
import { DistributedTableErrors } from '@aws-blocks/bb-distributed-table';

try {
  await table.put(item, { ifNotExists: true });
} catch (e: unknown) {
  if (isBlocksError(e, DistributedTableErrors.ConditionalCheckFailed)) {
    // item already exists
  }
  if (isBlocksError(e, DistributedTableErrors.ItemTooLarge)) {
    // item > 400 KB — split it or store a reference instead
  }
  throw e;
}

Examples

Basic CRUD

The examples use Zod, but schema accepts any StandardSchemaV1 implementation (Zod, Valibot, ArkType). Install your chosen library, e.g. npm install zod.

import { z } from 'zod';

const orderSchema = z.object({
  userId: z.string(),
  orderId: z.string(),
  total: z.number(),
  status: z.string(),
  createdAt: z.number(),
});

const orders = new DistributedTable(scope, 'orders', {
  schema: orderSchema,
  key: { partitionKey: 'userId', sortKey: 'orderId' },
});

export const api = new ApiNamespace(scope, 'api', (context) => ({
  async getOrder(userId: string, orderId: string) {
    return await orders.get({ userId, orderId });
  },
  async createOrder(order: z.infer<typeof orderSchema>) {
    await orders.put(order, { ifNotExists: true });
  },
  async deleteOrder(userId: string, orderId: string) {
    await orders.delete({ userId, orderId });
  },
}));

Query with Sort Key Conditions

const orders = new DistributedTable(scope, 'orders', {
  schema: orderSchema,
  key: { partitionKey: 'userId', sortKey: 'orderId' },
  indexes: {
    byDate: { partitionKey: 'userId', sortKey: 'createdAt' },
  },
});

// Ctrl+Space on the where object shows: userId, createdAt
// userId requires { equals }, createdAt supports greaterThan, between, etc.
const results = [];
for await (const order of orders.query({
  index: 'byDate',
  where: {
    userId: { equals: 'alice' },
    createdAt: { greaterThan: Date.now() - 86400000 },
  },
})) {
  results.push(order);
}

TTL (Auto-Expiring Items)

const sessions = new DistributedTable(scope, 'sessions', {
  schema: sessionSchema,
  key: { partitionKey: 'sessionId' },
  ttl: 'expiresAt',
});

// DynamoDB automatically deletes items after the TTL timestamp
await sessions.put({
  sessionId: 'abc123',
  userId: 'alice',
  expiresAt: Math.floor(Date.now() / 1000) + 3600, // 1 hour from now
});

Batch Operations

// Write many items
await orders.putBatch([order1, order2, order3]);

// Read many items
const items = await orders.getBatch([
  { userId: 'alice', orderId: '001' },
  { userId: 'bob', orderId: '002' },
]);

// Delete many items
await orders.deleteBatch([
  { userId: 'alice', orderId: '001' },
  { userId: 'bob', orderId: '002' },
]);

Wrapping an Existing Table

const legacy = new DistributedTable(scope, 'legacy', {
  schema: orderSchema,
  key: { partitionKey: 'userId', sortKey: 'orderId' },
  table: DistributedTable.fromExisting('my-existing-table'),
});

Best Practices

  • Design partition keys for even data distribution (e.g., userId, tenantId)
  • Use sort keys for range queries (e.g., timestamps, alphabetical ordering)
  • Define GSIs upfront for known access patterns — adding them later requires backfill
  • Use { ifNotExists: true } for idempotent creates
  • Use { ifFieldEquals } for optimistic locking when multiple writers are possible
  • Prefer query() over scan() — scans read every item and are expensive

Scaling & Cost (AWS)

  • Billing: PAY_PER_REQUEST — no provisioned capacity to manage
  • Latency: Single-digit ms reads and writes
  • Throughput: Scales automatically, no upper limit on table size
  • Item size limit: 400 KB per item
  • GSI limit: Up to 20 global secondary indexes per table
  • Cost: ~$1.25 per million writes, ~$0.25 per million reads
  • Durability: 99.999999999% (11 nines) across 3 AZs

Durability & Security defaults

Durability posture comes from the stack-wide BlocksDefaults you pass to BlocksStack.create / BlocksBackend.create (BlocksPresets.production or BlocksPresets.sandbox from @aws-blocks/core/cdk) — the same knobs every Building Block reads, so a table's removal policy, deletion protection, and continuous-backup posture all follow the app's chosen preset. There's no per-block sandboxMode guessing.

Under BlocksPresets.production, every table this block provisions ships with:

  • Point-in-Time Recovery enabled (defaults.pointInTimeRecovery) — restore to any second in the last 35 days.
  • Retained + deletion-protected (defaults.removalPolicy = RETAIN, defaults.deletionProtection = true) — neither a stack teardown nor a stray cdk destroy/console delete can wipe the table until you explicitly relax it. (Equivalent to protection: 'locked'.)
  • SSE-KMS with the AWS-managed aws/dynamodb key — encryption-at-rest that's auditable via CloudTrail, at no per-key charge.

Under BlocksPresets.sandbox these flip the other way — PITR off, RemovalPolicy.DESTROY, deletion protection off (equivalent to protection: 'disposable') — so throwaway stacks stay cheap and sandbox:destroy is a one-command teardown. SSE-KMS stays on in both (encryption isn't part of BlocksDefaults — it's a per-block option defaulting to aws-managed).

PITR is not free. Point-in-Time Recovery charges for continuous-backup storage (per GB-month of table size), so a large production table carries an ongoing cost. It's on by default because unrecoverable data loss is usually the worse outcome — but for regenerable data (caches, derived tables) set pointInTimeRecovery: false.

protection: 'locked'/'retained' orphans the table on stack delete. Because the removal policy is RETAIN, deleting the stack leaves the table behind (by design — your data survives). But the table name is derived deterministically from the block's id, so redeploying the same app afterward fails with Table already exists until you delete the orphaned table (aws dynamodb delete-table, after disabling deletion protection if 'locked') or import it into the new stack. This is inherent to retain-on-delete; use protection: 'disposable' for tables you expect to recreate freely.

Indexes follow the config while the table is in the stack. Removing an index (or the whole indexes option) from your config and redeploying drops it from the table. When the table itself leaves the stack (you delete the stack, or remove the DistributedTable from your app) its indexes are left alone: an orphaned 'locked'/'retained' table keeps all of them, so importing it into a new stack needs no index rebuild. To tell the two apart the GSI manager reads the stack's template. If it cannot read it in the cleanup phase of an update (or of a rolled-back update), it leaves the indexes in place and reports a DELETE_FAILED event for the table's GSI custom resource (logical ID containing gsiresource) that names the table and the indexes. The deploy itself still succeeds, so check the deploy output (or the stack's events) for that event. To remove an index your config no longer has, run aws dynamodb update-table --table-name <table> --global-secondary-index-updates '[{"Delete":{"IndexName":"<index>"}}]'; DynamoDB takes one index change per call, so wait for each delete to finish before the next.

Every stack default is overridable per table (a per-block option always wins over defaults):

// Cost-sensitive prod table: keep it protected, skip PITR's backup cost
const cache = new DistributedTable(scope, 'cache', {
  schema, key: { partitionKey: 'id' },
  pointInTimeRecovery: false,
});

// Long-lived data you still want to be able to delete directly
const staging = new DistributedTable(scope, 'staging', {
  schema, key: { partitionKey: 'id' },
  protection: 'retained',   // survives stack delete, but not deletion-protected
});

// Compliance-strict table: dedicated customer-managed KMS key
const ledger = new DistributedTable(scope, 'ledger', {
  schema, key: { partitionKey: 'id' },
  encryption: 'customer-managed',
});

// Share one customer-managed key across several tables (one key, one bill)
const key = DistributedTable.fromKmsKey('arn:aws:kms:us-east-1:111122223333:key/abcd-1234');
const orders = new DistributedTable(scope, 'orders', {
  schema, key: { partitionKey: 'id' },
  encryption: key,
});
const events = new DistributedTable(scope, 'events', {
  schema, key: { partitionKey: 'id' },
  encryption: key,
});

Overrides always win over the environment default, so you can force a fully durable, protected table in a sandbox (or relax one in prod) explicitly. When you bring your own table via fromExisting(), none of these options apply — you own that table's configuration.

customer-managed provisions a dedicated CMK per table — an app with a dozen customer-managed tables gets a dozen KMS keys (~$1/month each, plus request charges). To share one key across several tables, create the key once and pass DistributedTable.fromKmsKey(keyArn) as the encryption option on each table (see below). Use the default 'aws-managed' unless a table needs its own rotation/key-policy control.

Local Development

Mock data persists to disk at .bb-data/{fullId}/ across dev server restarts. Wipe with rm -rf .bb-data. The mock validates the 400 KB item size limit, schema validation, and conditional check failures, matching AWS behavior. Index queries are implemented via in-memory filtering — correctness is preserved but performance characteristics differ from DynamoDB.

版本与发布记录

@aws-blocks/bb-distributed-table 共发布 15 个版本,首次发布于 2026/06/16;过去 12 个月发布了 15 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.0latest2026/11/025 天前
0.2.22026/10/1622 天前
0.0.0-canary.esql-canary.c93c81b.1791235863canary-esql-canary2026/10/061 个月前
0.2.12026/10/051 个月前
0.0.0-canary.esql-canary.f7f39ac.17909891272026/10/031 个月前
0.0.0-canary.ci-publish-canary-npm.f53dfdc.1790988617canary-ci-publish-canary-npm2026/10/031 个月前

关于 @aws-blocks/bb-distributed-table 的常见问题

@aws-blocks/bb-distributed-table 是什么?

Structured data storage backed by DynamoDB with secondary indexes and rich query capabilities.

如何安装 @aws-blocks/bb-distributed-table?

在项目目录运行 npm install @aws-blocks/bb-distributed-table,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:constructs(^10.6.0)、aws-cdk-lib(^2.257.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-blocks/bb-distributed-table 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-blocks/bb-distributed-table 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@aws-blocks/bb-distributed-table 可以商用吗?

@aws-blocks/bb-distributed-table 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-blocks/bb-distributed-table 的下载量有多少?

根据 npm 官方下载统计,@aws-blocks/bb-distributed-table 在 2026/10/07 – 2026/11/05 这 30 天内被下载 63,453 次,日均约 2,115 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-blocks/bb-distributed-table 还在维护吗?

最新版本 0.3.0 发布于 2026/11/02(5 天前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/06/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。