Amazon Keyspaces · 2026-11-13 · Keyspaces arc

Amazon Keyspaces for MCP Servers: Complete Cassandra Playbook — Driver Setup, Data Modeling, TTL, and Capacity

Amazon Keyspaces is not a DynamoDB clone with SQL syntax. It is a fully managed Apache Cassandra service with its own mental model: data is organized around access patterns before schema, writes are appended rather than updated in place, and the partition key determines which node receives every read and write. MCP server developers who approach Keyspaces expecting DynamoDB behavior run into a predictable set of walls: a NoHostAvailableException that appears even with correct credentials (the localDataCenter doesn't match the region string exactly), a CQL INSERT that leaves a zombie row with partially expired columns (cell-level TTL is not row-level TTL), a range query that runs fine in development and throws InvalidQueryError: ALLOW FILTERING in production (the partition key was left out of the WHERE clause), and a table that grows unboundedly until reads slow down (tombstone accumulation from explicit DELETEs on a table that should use TTL instead). This playbook synthesizes the four critical areas — driver connection and authentication, Cassandra data modeling for MCP access patterns, TTL and session state management, and capacity planning and disaster recovery — into a single reference that eliminates those failure modes before you hit them in production.

TL;DR

Part 1: Connecting to Amazon Keyspaces

The two-API model

Unlike DynamoDB, which routes all operations through a single SDK client, Keyspaces splits management and data operations into fundamentally different interfaces. This is not an implementation detail — it reflects the underlying architecture: management operations are AWS API calls (HTTPS + SigV4); data operations use the Apache Cassandra CQL binary protocol over a separate TLS connection. Getting confused about which API handles which operation is the first trap.

OperationPackageProtocolAuth
Create/delete keyspace, list keyspaces@aws-sdk/client-keyspacesHTTPS + SigV4Standard IAM
Create/alter/drop table@aws-sdk/client-keyspaces (or CQL DDL)HTTPS or CQL binaryIAM or service-specific
SELECT / INSERT / UPDATE / DELETEcassandra-driverCQL binary (port 9142, TLS)Service-specific credentials
PITR / on-demand backups@aws-sdk/client-keyspacesHTTPS + SigV4Standard IAM
CloudWatch metrics@aws-sdk/client-cloudwatchHTTPS + SigV4Standard IAM

In a typical MCP server setup: use the management SDK in migration scripts or at deploy time to provision the keyspace and tables, and use cassandra-driver in every tool handler for data access.

Service-specific credentials — the correct CQL auth mechanism

The CQL binary protocol used by cassandra-driver does not support AWS SigV4 natively. The standard production auth method is service-specific credentials: a username and password pair that IAM generates scoped to cassandra.amazonaws.com. These authenticate at the CQL layer and are entirely separate from the IAM user's console and API credentials.

# Generate service-specific credentials for an IAM user
aws iam create-service-specific-credential \
  --user-name keyspaces-mcp-user \
  --service-name cassandra.amazonaws.com
# Returns: ServiceUserName, ServicePassword
# Store in Secrets Manager immediately — ServicePassword is shown only once

Important properties of service-specific credentials:

For MCP servers on Lambda or ECS that need to use the execution role (no IAM user), use the Amazon Keyspaces SigV4 auth plugin or generate service-specific credentials dynamically via iam:CreateServiceSpecificCredential at startup. The simpler path for most deployments: generate service-specific credentials once, store in Secrets Manager, rotate via Lambda rotation function.

Connecting cassandra-driver to Keyspaces

Install the driver and the Amazon root CA certificate. The CA cert is required for TLS validation — Keyspaces rejects unencrypted connections.

npm install cassandra-driver
curl -O https://www.amazontrust.com/repository/AmazonRootCA1.pem

Create the client. Instantiate it once at module initialization, not inside request handlers. Connecting costs 100–500 ms for the TLS handshake plus the driver loading metadata from Keyspaces system tables (system_schema, system_schema_mcs). Every cold start where you create a new Client inside the handler pays that cost on every tool call.

import { Client, auth, policies } from 'cassandra-driver';
import * as fs from 'fs';
import { getSecret } from './secrets.js';

export async function createKeyspacesClient(region: string): Promise<Client> {
  const { ServiceUserName, ServicePassword } = JSON.parse(
    await getSecret('keyspaces/service-credentials')
  );

  const client = new Client({
    contactPoints: [`cassandra.${region}.amazonaws.com`],
    localDataCenter: region,          // MUST match region string exactly: 'us-east-1', not 'US-EAST-1'
    authProvider: new auth.PlainTextAuthProvider(ServiceUserName, ServicePassword),
    sslOptions: {
      ca: [fs.readFileSync('./AmazonRootCA1.pem')],
      host: `cassandra.${region}.amazonaws.com`,
      rejectUnauthorized: true,
    },
    keyspace: 'mcp_server',
    protocolOptions: { port: 9142 },   // Keyspaces uses 9142, not the default Cassandra 9042
    pooling: {
      local: { coreConnectionsPerHost: 2, maxRequestsPerConnection: 1024 },
    },
    socketOptions: { connectTimeout: 5000, readTimeout: 12000 },
    policies: {
      retry: new policies.retry.RetryPolicy(),
      reconnection: new policies.reconnection.ExponentialReconnectionPolicy(1000, 60000),
      timestampGeneration: new policies.timestampGeneration.MonotonicTimestampGenerator(),
    },
  });

  await client.connect();
  return client;
}

// Lambda-safe singleton pattern
let _client: Client | null = null;
async function getClient(): Promise<Client> {
  if (!_client) _client = await createKeyspacesClient(process.env.AWS_REGION!);
  return _client;
}

Four configuration gotchas worth memorizing:

CRUD patterns in MCP tool handlers

Always use { prepare: true } in client.execute(). Keyspaces compiles the query plan on the first execution and caches it, reducing per-request latency on subsequent calls. Never interpolate user-supplied values into CQL strings — this is a CQL injection vector equivalent to SQL injection.

import { types } from 'cassandra-driver';

// INSERT with explicit per-row TTL
await client.execute(
  `INSERT INTO mcp_server.tool_sessions
   (session_id, created_at, tool_name, payload, status)
   VALUES (?, ?, ?, ?, ?)
   USING TTL 3600`,
  [types.Uuid.random(), new Date(), 'search_codebase', JSON.stringify(input), 'pending'],
  { prepare: true }
);

// SELECT with partition key (efficient — single partition scan)
const result = await client.execute(
  `SELECT session_id, created_at, tool_name, status
   FROM mcp_server.tool_sessions
   WHERE session_id = ?
   ORDER BY created_at ASC
   LIMIT 100`,
  [sessionId],
  { prepare: true, fetchSize: 100 }
);

// Conditional UPDATE (lightweight transaction — costs 4x a regular write; use sparingly)
const lwtResult = await client.execute(
  `UPDATE mcp_server.tool_sessions
   SET status = ?
   WHERE session_id = ? AND created_at = ?
   IF status = 'pending'`,
  ['running', sessionId, createdAt],
  { prepare: true }
);
const applied = lwtResult.rows[0]?.['[applied]'] ?? false;

Consistency levels in Keyspaces are restricted to LOCAL_-prefixed variants. Attempting to use QUORUM or ONE (without the LOCAL prefix) returns InvalidQueryError: Consistency level LOCAL_QUORUM is not supported. The effective choices: LOCAL_QUORUM (default, appropriate for all production MCP tool reads and writes), LOCAL_ONE (0.5 RCU per read — suitable for high-throughput analytics tools where stale reads are acceptable), and LOCAL_SERIAL (required for lightweight transaction read-your-writes consistency).

See the full driver setup guide for the complete IAM policy required for Keyspaces data and management access.

Part 2: Cassandra Data Modeling for MCP Access Patterns

The partition key constraint — design around it, not against it

In Cassandra (and therefore Keyspaces), all data for a given partition key value lives on the same physical node. A CQL WHERE clause without the full partition key is either rejected outright or requires ALLOW FILTERING — which forces a full cluster scan. ALLOW FILTERING is not a performance knob to tune; it is an emergency escape hatch that defeats the purpose of the distributed architecture. The implication for MCP server design: before writing any CQL, write down your tool's most common query patterns. The primary access pattern's filter column(s) become the partition key.

ScenarioWrong partition keyCorrect partition keyWhy
MCP session event logevent_id (UUID)session_id (UUID)Tools always fetch events for a session; querying by event_id is rare
Tool invocation audit loguser_id alone(user_id, month) compoundSingle-user partition would grow unbounded — spread writes across time buckets
Rate limit countertimestamp(tool_name, minute_bucket)Queries always ask "how many calls to tool X in minute Y"
Config values per tenantconfig_keytenant_idConfig is always fetched together per tenant; splitting by key fragments reads

Compound partition keys — preventing hot partitions

A single high-cardinality column partition key (e.g., user_id alone) can create hot partitions when one user generates far more activity than others. Use a compound partition key to distribute writes across time buckets:

-- (user_id, day_bucket) forces reads to specify both components
CREATE TABLE mcp_server.tool_invocations (
  user_id      uuid,
  day_bucket   date,
  invoked_at   timestamp,
  tool_name    text,
  duration_ms  int,
  status       text,
  PRIMARY KEY ((user_id, day_bucket), invoked_at)
) WITH CLUSTERING ORDER BY (invoked_at DESC)
  AND default_time_to_live = 2592000;  -- 30-day TTL

-- Query must include BOTH user_id and day_bucket
await client.execute(
  `SELECT invoked_at, tool_name, status
   FROM mcp_server.tool_invocations
   WHERE user_id = ? AND day_bucket = ?
   LIMIT 50`,
  [userId, today],
  { prepare: true }
);

The tradeoff: MCP tools that need to query across multiple days must issue one CQL query per day and merge results in application code, or use a Storage Attached Index (SAI) on user_id alone and accept the cross-partition scan cost.

Clustering columns — ordering and range queries

Clustering columns determine the physical sort order within a partition. Cassandra stores rows sorted by clustering column values, so range queries read a contiguous slice of the partition — efficient without any index beyond the partition itself.

-- Descending clustering order: newest events first without ORDER BY runtime overhead
CREATE TABLE mcp_server.mcp_events (
  session_id  uuid,
  event_time  timestamp,
  event_type  text,
  payload     text,
  PRIMARY KEY (session_id, event_time)
) WITH CLUSTERING ORDER BY (event_time DESC);

-- Efficient range query on the clustering column
await client.execute(
  `SELECT event_type, payload FROM mcp_server.mcp_events
   WHERE session_id = ?
     AND event_time >= ? AND event_time <= ?`,
  [sessionId, windowStart, windowEnd],
  { prepare: true }
);

Three clustering column constraints that catch MCP developers off-guard:

Wide-row time-series — the native Cassandra pattern for MCP event logs

The wide-row pattern stores many clustering rows under a single partition key, with time as the clustering column. This is the natural Cassandra fit for MCP tool event logs, monitoring data, and audit trails: append-heavy, partition-scoped, chronologically ordered.

-- Time-series: one partition per server per hour (caps partition size)
CREATE TABLE mcp_server.server_metrics (
  server_id    text,
  hour_bucket  timestamp,    -- floor(Date.now() / 3600000) * 3600000
  recorded_at  timestamp,
  metric_name  text,
  value        double,
  PRIMARY KEY ((server_id, hour_bucket), recorded_at, metric_name)
) WITH CLUSTERING ORDER BY (recorded_at ASC, metric_name ASC)
  AND default_time_to_live = 604800;   -- 7-day retention

function hourBucket(d: Date): Date {
  return new Date(Math.floor(d.getTime() / 3_600_000) * 3_600_000);
}

// Write: fast INSERT into the current-hour partition
await client.execute(
  `INSERT INTO mcp_server.server_metrics
   (server_id, hour_bucket, recorded_at, metric_name, value)
   VALUES (?, ?, ?, ?, ?)`,
  ['server-prod-1', hourBucket(new Date()), new Date(), 'tool_latency_p99_ms', 142.5],
  { prepare: true }
);

// Read: last hour of a specific metric
const hourAgo = hourBucket(new Date(Date.now() - 3_600_000));
const result = await client.execute(
  `SELECT recorded_at, value FROM mcp_server.server_metrics
   WHERE server_id = ? AND hour_bucket = ? AND metric_name = ?
   ORDER BY recorded_at ASC`,
  ['server-prod-1', hourAgo, 'tool_latency_p99_ms'],
  { prepare: true }
);

The hour bucket in the partition key is the key design decision. Without it, a server running for months would create an ever-growing hot partition that eventually degrades reads. Each hour bucket accumulates at most 60 × 60 × metric_count rows — well below the 10 GB partition size guideline.

Storage Attached Indexes (SAI) — secondary lookups without table duplication

SAI lets you filter on non-primary-key columns without scanning all partitions. It's specific to Keyspaces (and Cassandra 5+) and replaces the older secondary index implementation. Use it when you need a secondary access pattern that doesn't justify creating a separate denormalized table.

-- Create SAI for cross-day lookups by user_id without the day_bucket
CREATE INDEX tool_invocations_user_id_idx
  ON mcp_server.tool_invocations (user_id)
  USING 'sai';

-- Now queryable without the day_bucket partition key component
await client.execute(
  `SELECT user_id, day_bucket, invoked_at, tool_name
   FROM mcp_server.tool_invocations
   WHERE user_id = ?
   LIMIT 100`,
  [userId],
  { prepare: true }
);

-- Status lookup: find all failed tool invocations (with SAI on status column)
CREATE INDEX tool_invocations_status_idx
  ON mcp_server.tool_invocations (status)
  USING 'sai';

-- Via DDL through cassandra-driver (DDL does not support prepare:true)
await client.execute(
  `CREATE INDEX tool_invocations_status_idx
   ON mcp_server.tool_invocations (status)
   USING 'sai'`,
  [],
  { prepare: false }
);

SAI limitations: no SAI on collection columns (LIST, SET, MAP), no SAI on counter columns, and SAI writes are synchronous — the index update happens atomically with the data write, so writes cost slightly more. SAI without a partition key predicate performs a distributed scan; it is much faster than ALLOW FILTERING but slower than partition-key-scoped queries. For high-cardinality columns with low-selectivity queries (e.g., status = 'active' on a table where 90% of rows are active), SAI will still read a large fraction of the table.

Tombstones — the silent performance killer

When you DELETE a row in Cassandra, it does not immediately remove data. It writes a tombstone — a deletion marker — that tells readers to ignore the row. Tombstones accumulate until compaction removes them. Reads that encounter too many tombstones before finding live data throw TombstoneOverwhelmingException (default threshold: 100,000 tombstones per read). This is a production incident waiting to happen in MCP servers that treat Keyspaces like a cache with frequent explicit deletes.

Anti-patternWhy it creates tombstonesFix
DELETE old rows in a time-series table on each write cycleEach deleted row leaves a tombstone; compaction lags behind writesUse default_time_to_live — TTL expiry creates tombstones predictably during compaction
Setting a column to null in an UPDATENull assignment in CQL issues a cell-level tombstoneUse a sentinel value (empty string, 0) for nullable fields in hot tables
Appending to a LIST then removing elementsLIST removes create tombstones; positions are tombstoned even though new entries are appendedUse SET where order doesn't matter; for ordered logs, use separate rows
Deleting entire partitions frequently (e.g., cache eviction)Partition-level tombstone blocks reads to that partition until compactionUse short TTL on the table instead — expired data reads as not-found without tombstone accumulation

Prefer TTL-based expiry over explicit DELETEs for data with a known retention period. TTL-generated tombstones are cleaned up during compaction at a predictable rate and do not accumulate in front of live data the way delete-tombstones can. Keyspaces uses a TTL-aware compaction strategy internally — you cannot change the compaction strategy (unlike self-managed Cassandra), but this default is appropriate for TTL-heavy workloads.

Paginating large result sets with pageState

CQL has no OFFSET clause. To paginate, use the fetchSize + pageState cursor pattern from cassandra-driver. When a query matches more rows than fetchSize, the driver returns the first page and a pageState binary token. Pass the token in the next query to fetch the following page.

interface PagedResult { rows: any[]; nextPageToken: Buffer | null; }

async function queryPage(
  client: Client, cql: string, params: any[],
  pageToken: Buffer | null, pageSize = 50
): Promise<PagedResult> {
  const result = await client.execute(cql, params, {
    prepare: true,
    fetchSize: pageSize,
    pageState: pageToken ?? undefined,
  });
  return { rows: result.rows, nextPageToken: result.pageState ?? null };
}

// MCP tool: cursor-based pagination for tool invocations
export async function listInvocations(
  client: Client, userId: string, dayBucket: Date, pageToken: string | null
): Promise<{ items: any[]; nextToken: string | null }> {
  const rawToken = pageToken ? Buffer.from(pageToken, 'base64') : null;
  const { rows, nextPageToken } = await queryPage(
    client,
    `SELECT invoked_at, tool_name, status, duration_ms
     FROM mcp_server.tool_invocations
     WHERE user_id = ? AND day_bucket = ?
     ORDER BY invoked_at DESC`,
    [userId, dayBucket],
    rawToken
  );
  return {
    items: rows,
    nextToken: nextPageToken ? nextPageToken.toString('base64') : null,
  };
}

Important: pageState tokens are opaque binary blobs — do not parse them. They encode the last-seen clustering key position and are invalidated if the underlying data changes significantly (compaction, partition deletion). For long-lived pagination sessions (minutes to hours), handle QueryExecutionException from stale tokens and restart pagination from the beginning.

For the full data modeling reference, see the partition key and clustering column guide.

Part 3: TTL and Session State Management

TTL is cell-level, not row-level — this surprises everyone once

The most consequential Keyspaces TTL behavior to internalize: TTL is applied per-cell, not per-row. When you do INSERT … USING TTL 3600, Keyspaces sets the TTL on every non-key column cell in that row. If you subsequently do an UPDATE on specific columns without specifying USING TTL, those updated cells get TTL 0 (immortal), while the other cells retain their original 3600-second TTL. The result: a "zombie row" that is partially expired — the partition key is still present in the index, some columns are live (the ones you UPDATEd), and others have expired. Reads return a row with missing columns, which causes unexpected behavior in MCP tool handlers that assume all columns are present.

Two rules that eliminate zombie rows:

Table-level default TTL — the cleaner approach

For data with uniform retention, set default_time_to_live at table creation. Any INSERT or UPDATE that does not specify USING TTL inherits the table default. This avoids the zombie-row problem entirely because every write is consistently TTL-ed.

-- 7-day audit log: all rows expire in 7 days unless explicitly overridden
CREATE TABLE mcp_server.tool_audit_log (
  session_id  uuid,
  logged_at   timestamp,
  tool_name   text,
  input_hash  text,
  outcome     text,
  PRIMARY KEY (session_id, logged_at)
) WITH CLUSTERING ORDER BY (logged_at DESC)
  AND default_time_to_live = 604800;  -- 7 days in seconds

// Normal log entry — inherits 7-day TTL from table default
await client.execute(
  `INSERT INTO mcp_server.tool_audit_log
   (session_id, logged_at, tool_name, input_hash, outcome)
   VALUES (?, ?, ?, ?, ?)`,
  [sessionId, new Date(), 'run_tests', hashInput(input), 'success'],
  { prepare: true }
);

// Compliance hold — override with 90-day TTL (7776000 seconds)
await client.execute(
  `INSERT INTO mcp_server.tool_audit_log
   (session_id, logged_at, tool_name, input_hash, outcome)
   VALUES (?, ?, ?, ?, ?)
   USING TTL 7776000`,
  [sessionId, new Date(), 'deploy_production', hashInput(input), 'success'],
  { prepare: true }
);

// Immortal security event — USING TTL 0 overrides the 7-day table default
await client.execute(
  `INSERT INTO mcp_server.tool_audit_log
   (session_id, logged_at, tool_name, input_hash, outcome)
   VALUES (?, ?, ?, ?, ?)
   USING TTL 0`,
  [sessionId, new Date(), 'access_credentials', hashInput(input), 'denied'],
  { prepare: true }
);

Inspecting TTL and implementing proactive refresh

Use SELECT TTL(column_name) to retrieve remaining TTL in seconds for a specific column. Returns null for immortal cells or primary key columns. Combine with a threshold check to proactively refresh sessions before they expire under a user's feet:

async function getSessionWithTTL(client: Client, sessionId: string) {
  const result = await client.execute(
    `SELECT user_id, metadata, TTL(metadata) AS ttl_remaining
     FROM mcp_server.active_sessions
     WHERE session_id = ?`,
    [sessionId],
    { prepare: true }
  );

  if (result.rows.length === 0) return { session: null, expiresInSeconds: null };

  const row = result.rows[0];
  const remaining = row.ttl_remaining as number | null;

  // Proactively refresh if < 5 minutes remain
  if (remaining !== null && remaining < 300) {
    await client.execute(
      `UPDATE mcp_server.active_sessions USING TTL 3600
       SET metadata = ? WHERE session_id = ?`,
      [row.metadata, sessionId],
      { prepare: true }
    );
  }

  return {
    session: { userId: row.user_id, metadata: JSON.parse(row.metadata) },
    expiresInSeconds: remaining,
  };
}

Three MCP session state patterns

Pattern 1 — Short-lived tokens (simplest): set default_time_to_live and issue INSERTs with no TTL override. The token expires at a fixed horizon from issuance. No sliding-expiry logic needed. Appropriate for auth tokens, one-time-use codes, rate-limit windows.

CREATE TABLE mcp_server.auth_tokens (
  token_id  uuid,
  user_id   text,
  scopes    list<text>,
  issued_at timestamp,
  PRIMARY KEY (token_id)
) WITH default_time_to_live = 900;  -- 15-minute tokens

-- Validate: returns empty if expired
const { rows } = await client.execute(
  `SELECT user_id, scopes FROM mcp_server.auth_tokens WHERE token_id = ?`,
  [tokenId], { prepare: true }
);

Pattern 2 — Sliding expiry sessions: no default_time_to_live on the table; each UPDATE includes USING TTL N to reset the expiry window on activity. The session lives as long as there is activity within the window.

CREATE TABLE mcp_server.sliding_sessions (
  session_id  uuid,
  user_id     text,
  context     text,
  PRIMARY KEY (session_id)
  -- No default_time_to_live — TTL set per-write for sliding window
);

// Extend session on each tool call (sliding 2-hour window)
async function touchSession(client: Client, sessionId: string, context: string) {
  await client.execute(
    `UPDATE mcp_server.sliding_sessions USING TTL 7200
     SET context = ? WHERE session_id = ?`,
    [context, sessionId], { prepare: true }
  );
}

Pattern 3 — Rate-limit windows without counter tables: counter tables in Keyspaces do not support TTL (a hard constraint — CQL specification). For rate-limiting with per-window expiry, use regular rows with TTL, tracking counts as integers in a non-counter table, or use the ElastiCache Lua-atomic approach described in the ElastiCache advanced patterns guide.

Server-side timestamps — write ordering in distributed MCP deployments

Cassandra uses MVCC semantics: each write has a timestamp, and the highest timestamp wins during read. By default the timestamp is the client clock. For distributed MCP server deployments (multiple Lambda instances, multiple ECS tasks writing to the same session), clock skew between instances can cause out-of-order writes where an older value overwrites a newer one.

import { policies } from 'cassandra-driver';

// MonotonicTimestampGenerator ensures writes from one driver instance are
// always ordered correctly, even if the system clock jumps backward.
// Set at client init time — applies to all writes from this client.
const client = new Client({
  // ...other options...
  policies: {
    timestampGeneration: new policies.timestampGeneration.MonotonicTimestampGenerator(),
  },
});

// Inspect when a column was last written (microseconds since epoch)
const result = await client.execute(
  `SELECT WRITETIME(metadata) AS write_ts FROM mcp_server.active_sessions
   WHERE session_id = ?`,
  [sessionId], { prepare: true }
);
const writtenAtMs = Number(result.rows[0]?.write_ts ?? 0n) / 1000;

MonotonicTimestampGenerator handles single-instance ordering. For multi-instance deployments, combine with application-level ordering logic (last-write-wins using the highest logical version) rather than relying solely on timestamp ordering across instances with independent clocks.

PITR and TTL — the interaction that bites during incident response

Point-in-Time Recovery can restore your Keyspaces table to any second within the last 35 days. However, PITR and TTL interact in ways that surprise developers during incident response:

ScenarioBehaviorImplication
Restore to a time before a row's TTL expiredRow is restored with its original TTL intact — may expire immediately after restore if wall clock has passed the TTL windowRestoring a 1-hour-TTL session table to 2 hours ago produces mostly-empty results even after restore completes
Rows already physically compacted after TTL expiryPITR cannot restore these rows — gone from storageFor compliance audit data, use USING TTL 0 (immortal) or set TTL well beyond the 35-day PITR window
Modify TTL after enabling PITRPITR captures state including TTL valuesReducing TTL to clean up data is irreversible once rows compact

For audit data that must survive for compliance (90 days, 1 year), either use USING TTL 0 for critical rows, set default_time_to_live to exceed the longest required retention period, or export to S3 (via Kinesis Data Streams or a periodic batch job) before TTL expiry.

See the complete TTL and session state guide for tombstone management patterns for high-churn tables.

Part 4: Capacity Planning and Disaster Recovery

On-demand vs provisioned — the decision rule

Keyspaces offers two throughput modes with fundamentally different cost profiles. The rule of thumb is straightforward: start on-demand, graduate to provisioned once load is predictable.

CharacteristicOn-demand (PAY_PER_REQUEST)Provisioned
Cost modelPer-read + per-write; no idle cost beyond storageReserved RCU/WCU per second, billed whether used or not
Burst capacityInstant — absorbs any load up to 40,000 RCU/WCU per second per tableUp to 2x provisioned capacity briefly (burst); throttled beyond that
Cost at sustained high throughput2–5x more expensive than equivalent provisioned capacityPredictable; cheapest at ≥60% utilization
Capacity planning requiredNoYes — set based on P99 throughput from CloudWatch
Right for MCP serversDev/test; variable-traffic agents; event-driven toolsSteady-traffic production tools with predictable load

Start on-demand. After 2 weeks of production traffic, check CloudWatch for the P95 and P99 of ConsumedReadCapacityUnits and ConsumedWriteCapacityUnits. If utilization is steady (variance <3x between P50 and P99), switch to provisioned at 1.2× the P99 value. Mode switches are rate-limited to 4 per table per day — plan your switch window accordingly.

Capacity unit mechanics

Four capacity unit rules that affect MCP server cost more than expected:

CloudWatch monitoring — the metrics that matter

Keyspaces publishes metrics under the AWS/Cassandra namespace. Set up alarms on the throttle metrics before you need them — by the time WriteThrottleEvents is non-zero in production, MCP tool users are already experiencing errors.

MetricWhat it measuresWhen to alarm
ConsumedReadCapacityUnitsRCU consumed per secondUse for provisioned RCU target-setting; alert when consistently >80% of provisioned
ConsumedWriteCapacityUnitsWCU consumed per secondSame — use for provisioned WCU target-setting
ReadThrottleEventsRead requests throttled due to exceeding provisioned RCUAlert when >0 sustained for >1 minute — indicates under-provisioning
WriteThrottleEventsWrite requests throttled due to exceeding provisioned WCUAlert when >0 sustained for >1 minute
UserErrorsCQL errors (invalid query, type mismatch, etc.)Alert on sustained non-zero — indicates driver or schema bugs
SystemErrorsService-side errorsAlert on any non-zero — Keyspaces service issues
BillableTableSizeInBytesBilled storage bytes for the tableMonitor growth; set billing alarm to catch unbounded growth
// CloudFormation alarm for write throttling
{
  "Type": "AWS::CloudWatch::Alarm",
  "Properties": {
    "AlarmName": "keyspaces-write-throttle-mcp-prod",
    "Namespace": "AWS/Cassandra",
    "MetricName": "WriteThrottleEvents",
    "Dimensions": [
      { "Name": "Keyspace", "Value": "mcp_server" },
      { "Name": "TableName", "Value": "tool_invocations" }
    ],
    "Statistic": "Sum",
    "Period": 60,
    "EvaluationPeriods": 2,
    "Threshold": 1,
    "ComparisonOperator": "GreaterThanOrEqualToThreshold",
    "AlarmActions": ["arn:aws:sns:us-east-1:123456789012:ops-alerts"],
    "TreatMissingData": "notBreaching"
  }
}

PITR — the primary recovery mechanism for data corruption

Enable PITR from day one. It costs approximately 20% of your table storage per month (100 GB table: ~$5/month additional) and is the primary recovery mechanism for accidental data deletion, bad deployments, and data corruption from MCP tool bugs. PITR creates a new table — not an in-place restore.

import {
  UpdateTableCommand,
  RestoreTableToPointInTimeCommand,
  GetTableCommand,
} from '@aws-sdk/client-keyspaces';

// Enable PITR on an existing table
await ksClient.send(new UpdateTableCommand({
  keyspaceName: 'mcp_server',
  tableName: 'tool_invocations',
  pointInTimeRecovery: { status: 'ENABLED' },
}));

// Find the latest restorable timestamp (disaster recovery path)
const { table } = await ksClient.send(new GetTableCommand({
  keyspaceName: 'mcp_server', tableName: 'tool_invocations',
}));
const latestRestore = table?.pointInTimeRecovery?.latestRestorableTimestamp;
console.log(`Can restore up to: ${latestRestore?.toISOString()}`);

// Restore to a specific point in time (creates a new table)
await ksClient.send(new RestoreTableToPointInTimeCommand({
  sourceKeyspaceName: 'mcp_server',
  sourceTableName: 'tool_invocations',
  targetKeyspaceName: 'mcp_server',
  targetTableName: 'tool_invocations_restored_20261113',
  restoreTimestamp: new Date('2026-11-13T08:00:00Z'),
  pointInTimeRecovery: { status: 'ENABLED' },
  capacitySpecificationOverride: {
    throughputMode: 'PAY_PER_REQUEST',  // start on-demand while verifying restore
  },
}));

// Poll until restored table is ACTIVE before running verification queries
async function waitForTable(keyspace: string, table: string): Promise<void> {
  for (let attempt = 0; attempt < 30; attempt++) {
    const { table: t } = await ksClient.send(new GetTableCommand({
      keyspaceName: keyspace, tableName: table,
    }));
    if (t?.status === 'ACTIVE') return;
    await new Promise(r => setTimeout(r, 5000));
  }
  throw new Error(`Table ${keyspace}.${table} did not become ACTIVE`);
}

Important PITR operational notes:

On-demand backups — snapshots before schema migrations

On-demand backups are table snapshots taken immediately, retained indefinitely until deleted (billed at $0.10/GB/month). Use them before schema changes, MCP server deploys that modify data, and data migrations.

import {
  CreateBackupCommand,
  RestoreTableFromBackupCommand,
  DeleteBackupCommand,
} from '@aws-sdk/client-keyspaces';

// Create a pre-migration snapshot
const { backupSummary } = await ksClient.send(new CreateBackupCommand({
  keyspaceName: 'mcp_server',
  tableName: 'tool_invocations',
  backupName: 'pre-schema-migration-20261113',
  tags: [{ key: 'created-by', value: 'mcp-deploy-script' }],
}));

// Restore from backup if migration fails
await ksClient.send(new RestoreTableFromBackupCommand({
  targetKeyspaceName: 'mcp_server',
  targetTableName: 'tool_invocations_from_backup',
  backupArn: backupSummary!.backupArn!,
}));

// Delete backup when migration is confirmed successful (stop paying for it)
await ksClient.send(new DeleteBackupCommand({
  backupArn: backupSummary!.backupArn!,
}));

Service quotas and cost estimation

LimitDefaultNotes
Max tables per keyspace256Requestable increase via Service Quotas
Max partition size10 GB (soft guideline)No hard limit; larger partitions slow reads and compaction
Max row size1 MBHard limit — rows exceeding 1 MB are rejected
Max columns per table225Fixed — design wide tables carefully
On-demand throughput limit40,000 RCU and 40,000 WCU per second per tableRequestable increase; applies to on-demand mode
Capacity mode switches per table per day4 times per dayRate-limited — plan mode switches carefully
Max backups per table35Fixed; delete old backups before creating new ones
Workload typeApproximate monthly costMode recommendation
Dev/test MCP server (100 req/hour)<$1/monthOn-demand
Low-traffic production (1,000 req/hour)$3–8/monthOn-demand
Mid-traffic production (10,000 req/hour)$30–80/monthOn-demand → switch to provisioned at ~2 weeks
High-traffic production (100,000 req/hour)$150–$400/month on-demand; $50–$100 provisionedProvisioned at steady load
Storage per GB (per month)$0.25/GBUse default_time_to_live to cap data growth
PITR overhead~$0.20 per GB stored per month additionalAlways enable in production

See the full capacity modes and operations guide for complete IAM policies for multi-team Keyspaces access.

When to choose Keyspaces vs DynamoDB vs ElastiCache

Keyspaces is not the right database for every MCP server workload. Here is a decision matrix for the three most common AWS-native storage options:

Use Keyspaces whenUse DynamoDB whenUse ElastiCache when
Wide-row storage: many related rows with the same partition key (event logs, time-series metrics)Key-value or document access patterns; single-item lookups dominateSub-millisecond latency required; cache-aside read-through; session tokens with sub-second TTL precision
CQL familiarity: team already knows Cassandra; you need range queries within a partitionOperational simplicity: no driver setup, no service-specific credentials, AWS Console UI is sufficientRate limiting: Lua scripts for atomic operations; pub/sub fan-out to multiple MCP instances
High-throughput appends (write-heavy workloads) where DynamoDB single-table design becomes unwieldyAuto-scaling without thinking about partitions; global tables for multi-region active-activeL1 cache in front of Keyspaces or DynamoDB to absorb repetitive reads without paying RCU costs

For MCP server session storage specifically: DynamoDB TTL is simpler to reason about (delete within 48 hours of expiry) but Keyspaces TTL enforces expiry at read time, which means expired rows are invisible to MCP tool handlers without waiting for the background deletion. Keyspaces TTL is the stricter guarantee. For pure caching workloads (rate limiters, temporary state under a few seconds), ElastiCache remains the better fit — see the ElastiCache guide for MCP servers and the caching patterns deep-dive. For event log storage and audit trails where you need ordered range queries within a session, Keyspaces wide-row design is the natural fit. For the DynamoDB patterns equivalent, see the DynamoDB guide for MCP servers.

Related guides