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
- Two APIs, never conflate them:
@aws-sdk/client-keyspaceshandles management (keyspace creation, table DDL, PITR, backups) over HTTPS with standard SigV4.cassandra-driverhandles data (SELECT, INSERT, UPDATE, DELETE) over the CQL binary protocol at port 9142 TLS. Auth to the CQL layer uses service-specific credentials (a username/password pair scoped tocassandra.amazonaws.com) — entirely separate from your IAM API credentials. - Instantiate the driver once: connecting costs 100–500 ms for the TLS handshake and driver metadata load from
system_schema. Use a module-scope singleton; never create aClientinside a tool handler. SetlocalDataCenterto the exact AWS region string (e.g.,us-east-1) — a mismatch causesNoHostAvailableExceptioneven when the endpoint resolves. - Schema follows access patterns: the value you filter by equality goes in the partition key (
WHERE session_id = ?); the value you sort or range-query by goes in clustering columns (ORDER BY created_at DESC). Every query must include the full partition key. No OFFSET — paginate withfetchSizeandpageState. - TTL is cell-level, not row-level:
INSERT … USING TTL 3600sets expiry on all non-key cells. A subsequentUPDATEwithout TTL makes those updated cells immortal while other cells retain their original TTL. Usedefault_time_to_liveat table creation for uniform retention; override per-row withUSING TTL Nonly for exceptions. - Prefer TTL over DELETE for expiry: explicit DELETEs generate tombstones that accumulate until compaction. Tombstone-heavy reads can throw
TombstoneOverwhelmingException. For data with known retention, setdefault_time_to_liveand let TTL expiry handle cleanup at a predictable rate. - Start on-demand, graduate to provisioned:
PAY_PER_REQUESTrequires no capacity planning and absorbs any burst up to 40,000 RCU/WCU per second. After 2 weeks of production traffic, check CloudWatch forConsumedReadCapacityUnitsP95/P99. If utilization is steady (variance <3x), switch to provisioned at 1.2× P99 — 2–5x cheaper per operation at sustained load.
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.
| Operation | Package | Protocol | Auth |
|---|---|---|---|
| Create/delete keyspace, list keyspaces | @aws-sdk/client-keyspaces | HTTPS + SigV4 | Standard IAM |
| Create/alter/drop table | @aws-sdk/client-keyspaces (or CQL DDL) | HTTPS or CQL binary | IAM or service-specific |
| SELECT / INSERT / UPDATE / DELETE | cassandra-driver | CQL binary (port 9142, TLS) | Service-specific credentials |
| PITR / on-demand backups | @aws-sdk/client-keyspaces | HTTPS + SigV4 | Standard IAM |
| CloudWatch metrics | @aws-sdk/client-cloudwatch | HTTPS + SigV4 | Standard 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:
- Up to 2 service-specific credentials per IAM user — use this for zero-downtime rotation: generate credential #2, update Secrets Manager, verify new credentials work, deactivate credential #1.
- Deactivating the IAM user does NOT automatically invalidate service-specific credentials. Explicitly delete or deactivate them when revoking access.
- These are long-term credentials — rotate on a schedule using a Secrets Manager rotation Lambda.
- The IAM user still needs an IAM policy granting Keyspaces permissions — service-specific credentials handle authentication (who you are), not authorization (what you can do).
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:
localDataCenter: must match the AWS region string exactly (e.g.,us-east-1). If it doesn't match, Keyspaces returnsNoHostAvailableExceptioneven after a successful TLS handshake. This is the most common first-time setup error.- Port 9142: set it in both
contactPointsformat (suffix) andprotocolOptions.port. Setting one but not the other can cause inconsistent behavior depending on driver version. MonotonicTimestampGenerator: prevents clock-skew conflicts in multi-instance deployments (multiple Lambda instances, multiple ECS tasks). Without it, concurrent writes from instances with slightly skewed clocks can overwrite each other in unexpected order.- System keyspace access: the IAM policy must include
cassandra:Selectonarn:aws:cassandra:REGION:ACCOUNT:/keyspace/system*. The driver queriessystem_schemaandsystem_schema_mcsat connection time for metadata and prepared statement caching. Without this permission,client.connect()throws an authorization error that looks unrelated to your application tables.
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.
| Scenario | Wrong partition key | Correct partition key | Why |
|---|---|---|---|
| MCP session event log | event_id (UUID) | session_id (UUID) | Tools always fetch events for a session; querying by event_id is rare |
| Tool invocation audit log | user_id alone | (user_id, month) compound | Single-user partition would grow unbounded — spread writes across time buckets |
| Rate limit counter | timestamp | (tool_name, minute_bucket) | Queries always ask "how many calls to tool X in minute Y" |
| Config values per tenant | config_key | tenant_id | Config 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:
- Column prefix rule: you must specify earlier clustering columns in the WHERE clause before filtering on later ones. To query on
called_atwithout specifyingtool_name(the first clustering column), you need a SAI or a separate table. - Range query position: range predicates (
>=,<=,>,<) are only allowed on the last clustering column in the predicate, unless you addALLOW FILTERING. - Direction is immutable: once you define
CLUSTERING ORDER BY (event_time DESC), queries against that table cannot reverse the order at query time. If you need both newest-first and oldest-first access patterns, create two tables — a classic Cassandra trade-off.
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-pattern | Why it creates tombstones | Fix |
|---|---|---|
| DELETE old rows in a time-series table on each write cycle | Each deleted row leaves a tombstone; compaction lags behind writes | Use default_time_to_live — TTL expiry creates tombstones predictably during compaction |
Setting a column to null in an UPDATE | Null assignment in CQL issues a cell-level tombstone | Use a sentinel value (empty string, 0) for nullable fields in hot tables |
| Appending to a LIST then removing elements | LIST removes create tombstones; positions are tombstoned even though new entries are appended | Use 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 compaction | Use 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:
- Always specify
USING TTL Nin every UPDATE that touches a row with a TTL — or setdefault_time_to_liveat the table level and rely on the default. - Primary key columns (partition key and clustering columns) never expire — TTL does not apply to them. The partition key sticks around until compaction removes the tombstone after all non-key cells have expired.
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:
| Scenario | Behavior | Implication |
|---|---|---|
| Restore to a time before a row's TTL expired | Row is restored with its original TTL intact — may expire immediately after restore if wall clock has passed the TTL window | Restoring a 1-hour-TTL session table to 2 hours ago produces mostly-empty results even after restore completes |
| Rows already physically compacted after TTL expiry | PITR cannot restore these rows — gone from storage | For compliance audit data, use USING TTL 0 (immortal) or set TTL well beyond the 35-day PITR window |
| Modify TTL after enabling PITR | PITR captures state including TTL values | Reducing 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.
| Characteristic | On-demand (PAY_PER_REQUEST) | Provisioned |
|---|---|---|
| Cost model | Per-read + per-write; no idle cost beyond storage | Reserved RCU/WCU per second, billed whether used or not |
| Burst capacity | Instant — absorbs any load up to 40,000 RCU/WCU per second per table | Up to 2x provisioned capacity briefly (burst); throttled beyond that |
| Cost at sustained high throughput | 2–5x more expensive than equivalent provisioned capacity | Predictable; cheapest at ≥60% utilization |
| Capacity planning required | No | Yes — set based on P99 throughput from CloudWatch |
| Right for MCP servers | Dev/test; variable-traffic agents; event-driven tools | Steady-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:
- Read Capacity Unit (RCU): one LOCAL_QUORUM read of a row up to 4 KB. Rows larger than 4 KB consume additional RCUs (ceil(rowSize / 4096)). LOCAL_ONE reads consume 0.5 RCU each.
- Write Capacity Unit (WCU): one write of a row up to 1 KB. Rows larger than 1 KB consume additional WCUs (ceil(rowSize / 1024)).
- Lightweight transactions (LWT):
IF NOT EXISTSand conditional updates (IF status = 'pending') consume 4 WCUs, not 1. For MCP servers that use LWT for idempotency guards, this is a 4x write cost multiplier. - Large payloads in
textcolumns: storing large JSON tool payloads (10+ KB) intextcolumns burns multiple WCUs per write and multiple RCUs per read. Consider storing large payloads in S3 and keeping only the S3 key in Keyspaces.
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.
| Metric | What it measures | When to alarm |
|---|---|---|
ConsumedReadCapacityUnits | RCU consumed per second | Use for provisioned RCU target-setting; alert when consistently >80% of provisioned |
ConsumedWriteCapacityUnits | WCU consumed per second | Same — use for provisioned WCU target-setting |
ReadThrottleEvents | Read requests throttled due to exceeding provisioned RCU | Alert when >0 sustained for >1 minute — indicates under-provisioning |
WriteThrottleEvents | Write requests throttled due to exceeding provisioned WCU | Alert when >0 sustained for >1 minute |
UserErrors | CQL errors (invalid query, type mismatch, etc.) | Alert on sustained non-zero — indicates driver or schema bugs |
SystemErrors | Service-side errors | Alert on any non-zero — Keyspaces service issues |
BillableTableSizeInBytes | Billed storage bytes for the table | Monitor 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:
- PITR does not capture Storage Attached Indexes (SAI) — rebuild them on the restored table with
CREATE INDEX … USING 'sai'after restore and before redirecting traffic. - Default TTL and capacity specification are preserved from the source table unless you override them in the restore command.
- Restore to
latestRestorableTimestamp(usually within seconds of now) is the disaster recovery path for accidentally deleted tables. The table is gone but PITR has a continuous backup. - Plan the table swap procedure before you need it: verify the restored table with read queries, update your application to point to the restored table name, drop the corrupted original. This is an operational procedure — not an atomic failover.
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
| Limit | Default | Notes |
|---|---|---|
| Max tables per keyspace | 256 | Requestable increase via Service Quotas |
| Max partition size | 10 GB (soft guideline) | No hard limit; larger partitions slow reads and compaction |
| Max row size | 1 MB | Hard limit — rows exceeding 1 MB are rejected |
| Max columns per table | 225 | Fixed — design wide tables carefully |
| On-demand throughput limit | 40,000 RCU and 40,000 WCU per second per table | Requestable increase; applies to on-demand mode |
| Capacity mode switches per table per day | 4 times per day | Rate-limited — plan mode switches carefully |
| Max backups per table | 35 | Fixed; delete old backups before creating new ones |
| Workload type | Approximate monthly cost | Mode recommendation |
|---|---|---|
| Dev/test MCP server (100 req/hour) | <$1/month | On-demand |
| Low-traffic production (1,000 req/hour) | $3–8/month | On-demand |
| Mid-traffic production (10,000 req/hour) | $30–80/month | On-demand → switch to provisioned at ~2 weeks |
| High-traffic production (100,000 req/hour) | $150–$400/month on-demand; $50–$100 provisioned | Provisioned at steady load |
| Storage per GB (per month) | $0.25/GB | Use default_time_to_live to cap data growth |
| PITR overhead | ~$0.20 per GB stored per month additional | Always 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 when | Use DynamoDB when | Use 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 dominate | Sub-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 partition | Operational simplicity: no driver setup, no service-specific credentials, AWS Console UI is sufficient | Rate 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 unwieldy | Auto-scaling without thinking about partitions; global tables for multi-region active-active | L1 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
- Amazon Keyspaces for MCP servers: driver setup, auth, and CQL basics
- Amazon Keyspaces data modeling: partition keys, clustering columns, SAI
- Amazon Keyspaces TTL and session state for MCP servers
- Amazon Keyspaces capacity modes, PITR, and cost management
- DynamoDB for MCP servers: complete guide
- ElastiCache for MCP servers: complete guide
- ElastiCache advanced patterns: Lua rate limiting, pub/sub, Global Datastore
- MCP server uptime monitoring