@aws-blocks/bb-kv-store

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

Simple key-value storage backed by DynamoDB.

原始使用文档
文档目录12 节
  1. API
  2. Options
  3. Expiring Items (TTL)
  4. Conditional Operations
  5. Error Handling
  6. Examples
  7. Basic Usage (string values)
  8. Typed Values with Schema
  9. Wrapping an Existing Table
  10. Best Practices
  11. Scaling & Cost (AWS)
  12. Local Development

KVStore

Simple key-value storage backed by DynamoDB.

When to use: Fast, single-key lookups with get/put/delete semantics. Good for caches, session stores, feature flags, and config values.

When NOT to use: If you need to query by multiple fields or secondary indexes, use DistributedTable. If you need full SQL, use Database.

Design & mock parity details: DESIGN.md

API

const store = new KVStore(scope, id, options?)
MethodReturnsDescription
get(key)Promise<T | null>Retrieve a value. Returns null if absent or expired.
put(key, value, options?)Promise<void>Store a value. Overwrites unless conditions are set; accepts an optional expiry.
delete(key, conditions?)Promise<void>Remove a value.
scan(options?)AsyncIterable<{ key, value }>Enumerate all entries. Skips expired items unless { includeExpired: true }. Expensive on large datasets.
KVStore.fromExisting(tableName)ExternalTableRefWrap a pre-existing DynamoDB table.

Runtime only. Data methods (get, put, delete, scan) 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 KVStore.<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.

Options

OptionTypeDescription
schemaStandardSchemaV1Runtime validation schema (Zod, Valibot, ArkType, etc.). When provided, the value type T is inferred from the schema and every put() validates the value before writing.
tableExternalTableRefWrap an existing DynamoDB table instead of creating one.
loggerChildLoggerOptional logger for internal operations. When omitted, a default Logger at error level is created.
removalPolicy'destroy' | 'retain'Removal behavior for the underlying DynamoDB table. When omitted, the stack-wide defaults (from BlocksPresets.sandbox/production, chosen at BlocksStack.create) apply — production retains data on cdk destroy, sandbox destroys it. Pass 'destroy'/'retain' to override for this one store. The table's deletion protection also follows the stack defaults. Ignored by the mock and browser runtimes.
ttlbooleanEnable DynamoDB Time-to-Live so items written with an expiry are deleted automatically. Defaults to false. See Expiring Items.
pointInTimeRecoveryboolean | { retentionDays: number }DynamoDB Point-in-Time Recovery (continuous backups). true enables the default 35-day window; { retentionDays: n } enables PITR and pins the window (1–35); false disables it. When omitted, the stack-wide defaults apply (on under production, off under sandbox). Ignored by the mock and browser runtimes.
encryption'aws-managed' | 'customer-managed' | ExternalKmsKeyRefServer-side encryption at rest. 'aws-managed' (default) uses the aws/dynamodb key; 'customer-managed' provisions a dedicated CMK per table; pass KVStore.fromKmsKey(arn) to reuse an existing CMK across stores. Ignored by the mock and browser runtimes.

Expiring Items (TTL)

TTL is opt-in in two steps — turn it on for the table, then set an expiry per write:

const cache = new KVStore(scope, 'cache', { ttl: true });

// Relative expiry — delete 5 minutes from now
await cache.put('otp:alice', code, { ttlSeconds: 300 });

// Absolute expiry — a Date, or Unix epoch time in SECONDS
await cache.put('session:1', record, { expiresAt: new Date('2027-01-01') });

// No expiry — stored indefinitely (the default)
await cache.put('config:theme', 'dark');
  • ttl defaults to false. Enabling it on a table that already exists is a CloudFormation update to the live table, so it never happens implicitly.
  • The attribute is named ttl. It is written only when ttlSeconds or expiresAt is supplied, and it holds Unix epoch seconds.
  • ttlSeconds and expiresAt are mutually exclusive. Passing both — or a value that looks like epoch milliseconds — throws ValidationFailedException rather than silently storing a year-5138 expiry.
  • Reads never return expired items. DynamoDB's reaper is asynchronous (typically within 48 hours), so get returns null and scan skips an item as soon as its expiry passes, in every runtime.
  • Expiry is per write. Re-putting a key without expiry options clears any previous expiry; re-putting with them slides it forward.
  • TTL composes with conditional writes: put(key, value, { ifNotExists: true, ttlSeconds: 60 }).

TTL is a retention control, not an authorization one. Anything security-sensitive (session validity, token revocation) must still be checked on read.

Conditional Operations

Both put and delete accept an optional options object:

// Only write if key doesn't exist (idempotent create)
await store.put('user:alice', data, { ifNotExists: true });

// Only write if current value matches (optimistic locking / compare-and-swap)
await store.put('counter', newVal, { ifValueEquals: oldVal });

// Compose both (OR): create it, or update it only if unchanged — write succeeds
// if the key is absent OR its current value matches; fails only if it exists and differs.
await store.put('config', next, { ifNotExists: true, ifValueEquals: prev });

// Only delete if key exists
await store.delete('temp', { ifExists: true });

// Only delete if value matches
await store.delete('lock', { ifValueEquals: expectedVal });

All condition failures throw with error.name === KVStoreErrors.ConditionalCheckFailed. They serialize to JSON-RPC 409 (Conflict) over the wire (not 500), so error.status === 409 on the client and isBlocksError still matches by name. A conflict is flagged retriable when a value check participated (a stale-value optimistic-lock conflict — re-read and retry may succeed). For put, ifNotExists and ifValueEquals compose with OR, so a failure whenever ifValueEquals was set — including the combined ifNotExists+ifValueEquals case — is the stale-value case and is retriable; a pure ifNotExists put conflict is not retriable. For delete (independent checks, not OR), a pure ifExists conflict — or a combined ifExists+ifValueEquals conflict — is not retriable; only a value-only ifValueEquals delete conflict is. A blind retry of a non-retriable conflict fails identically.

Error Handling

Constanterror.nameThrown when
KVStoreErrors.ConditionalCheckFailedConditionalCheckFailedExceptionAn ifNotExists / ifExists / ifValueEquals condition failed. Serializes to HTTP 409 (Conflict); retriable when a value check participated (any put conflict where ifValueEquals was set, since put composes with OR; a value-only ifValueEquals delete conflict) — not retriable for a pure ifNotExists put or any ifExists delete.
KVStoreErrors.ValidationFailedValidationFailedExceptionA value failed the configured schema validation.
KVStoreErrors.ItemTooLargeItemTooLargeExceptionThe serialized item exceeds the 400 KB DynamoDB per-item size limit. (In the AWS layer, DynamoDB raises a generic ValidationException; KVStore re-maps the size-specific case to this name.)
import { isBlocksError } from '@aws-blocks/core';
import { KVStoreErrors } from '@aws-blocks/bb-kv-store';

try {
  await store.put('key', value, { ifNotExists: true });
} catch (e: unknown) {
  if (isBlocksError(e, KVStoreErrors.ConditionalCheckFailed)) {
    // key already exists
  }
  if (isBlocksError(e, KVStoreErrors.ItemTooLarge)) {
    // value is too large — consider compressing or splitting
  }
  throw e;
}

Examples

Basic Usage (string values)

const store = new KVStore(scope, 'cache');

export const api = new ApiNamespace(scope, 'api', (context) => ({
  async setGreeting(value: string) {
    await store.put('greeting', value);
  },
  async getGreeting() {
    return { value: await store.get('greeting') };
  },
}));

Without a schema, the value type defaults to string. To store structured data without runtime validation, pass a type argument — new KVStore<MyType>(scope, id); values are JSON-serialized on write and parsed on read automatically (no manual JSON.stringify needed).

Typed Values with Schema

Use a schema to get type-safe values with runtime validation:

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 sessionSchema = z.object({
  userId: z.string(),
  expiresAt: z.number(),
});

const sessions = new KVStore(scope, 'sessions', { schema: sessionSchema });

// Type is inferred from the schema — no generic arg needed
await sessions.put(token, { userId: 'alice', expiresAt: Date.now() + 3600000 });
const session = await sessions.get(token); // { userId: string; expiresAt: number } | null

// Invalid data is rejected at runtime
await sessions.put(token, { userId: 123 }); // throws ValidationFailedException

Wrapping an Existing Table

const legacy = new KVStore(scope, 'legacy', {
  table: KVStore.fromExisting('my-existing-table'),
});

Best Practices

  • Keep keys short and descriptive (e.g., user:{id}, session:{token})
  • Store one logical entity per KVStore instance
  • Use a schema for structured values — it ensures runtime data matches your types
  • Use { ifNotExists: true } for idempotent creates
  • Use { ifValueEquals } for compare-and-swap when multiple writers are possible
  • scan() returns an AsyncIterable — collect with await Array.fromAsync(store.scan()) or for await. Prefer get(key) over scan() (scans read every item).

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
  • Cost: ~$1.25 per million writes, ~$0.25 per million reads
  • Durability: 99.999999999% (11 nines) across 3 AZs

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.

版本与发布记录

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

版本发布日期距今
0.4.0latest2026/11/025 天前
0.3.12026/10/1622 天前
0.0.0-canary.esql-canary.c93c81b.1791235863canary-esql-canary2026/10/061 个月前
0.3.02026/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-kv-store 的常见问题

@aws-blocks/bb-kv-store 是什么?

Simple key-value storage backed by DynamoDB.

如何安装 @aws-blocks/bb-kv-store?

在项目目录运行 npm install @aws-blocks/bb-kv-store,或使用 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-kv-store 支持 TypeScript 吗?

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

@aws-blocks/bb-kv-store 支持 ESM 还是 CommonJS?

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

@aws-blocks/bb-kv-store 可以商用吗?

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

@aws-blocks/bb-kv-store 的下载量有多少?

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

@aws-blocks/bb-kv-store 还在维护吗?

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