Guide · Amazon Keyspaces · Data Modeling · MCP Server Tools
Amazon Keyspaces Data Modeling for MCP Servers — Partition Keys, Clustering Columns, SAI
Cassandra data modeling is different from relational or key-value modeling. The access pattern drives the schema design, not the other way around. For MCP server tools, the most common question is: "how do I structure data so I can query it efficiently given the tool input?" This guide covers the core mechanics — partition key choice, clustering columns for ordering and range queries, wide-row patterns for time-series tool logs, Storage Attached Indexes for secondary lookups, tombstone accumulation pitfalls, and paginating large result sets with pageState.
TL;DR
Design your Keyspaces schema around your MCP tool's read access pattern. Put the value you filter by equality in the partition key (WHERE session_id = ?). Put values you sort or range-query by in clustering columns (ORDER BY created_at DESC). Every CQL query must include the full partition key — there is no table scan without ALLOW FILTERING (which is expensive). For secondary lookups (find all sessions for a user, not a specific session), create a Storage Attached Index (SAI) on the user_id column. Avoid deleting individual cells or using collections with heavy churn — these generate tombstones that slow reads and must be compacted. Paginate large results with fetchSize and pageState from cassandra-driver.
Partition key design — the fundamental constraint
In Cassandra (and therefore Keyspaces), all data for a given partition key value is stored together on the same node. A CQL WHERE clause without the full partition key is either rejected or requires ALLOW FILTERING — a full cluster scan. This is not a limitation you work around — it is the data model's core design assumption: define partitions by how you will query.
| 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 partition key with a single high-cardinality column (like user_id) can create hot partitions if one user generates far more data than others. Use a compound partition key to distribute writes:
-- Compound partition key: (user_id, day_bucket)
CREATE TABLE mcp_server.tool_invocations (
user_id uuid,
day_bucket date, -- partition by user AND calendar day
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
Querying requires both partition key components:
-- Must provide BOTH user_id AND day_bucket
await client.execute(
`SELECT * FROM mcp_server.tool_invocations
WHERE user_id = ? AND day_bucket = ?
ORDER BY invoked_at DESC
LIMIT 50`,
[userId, today],
{ prepare: true }
);
This means your MCP tool must include the day bucket in its query. For tools that need to query across multiple days, issue one query per day and merge results in application code — or use an 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, which makes range queries (WHERE created_at > ? AND created_at < ?) efficient because they read a contiguous range of the sorted partition data.
-- Descending order: most recent events first without ORDER BY 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);
-- Range query on the clustering column
await client.execute(
`SELECT * FROM mcp_server.mcp_events
WHERE session_id = ?
AND event_time >= ? AND event_time <= ?`,
[sessionId, windowStart, windowEnd],
{ prepare: true }
);
Multi-column clustering keys enable composite ordering:
-- Sort by tool_name ASC then timestamp DESC within each session
CREATE TABLE mcp_server.tool_calls (
session_id uuid,
tool_name text,
called_at timestamp,
result text,
PRIMARY KEY (session_id, tool_name, called_at)
) WITH CLUSTERING ORDER BY (tool_name ASC, called_at DESC);
-- Query: all calls to 'search_code' in a session, newest first
await client.execute(
`SELECT * FROM mcp_server.tool_calls
WHERE session_id = ? AND tool_name = ?`,
[sessionId, 'search_code'],
{ prepare: true }
);
Important constraints on clustering column queries:
- You must specify earlier clustering columns in the WHERE clause before filtering on later ones (column prefix rule). To query on
called_atwithout specifyingtool_name, you need a separate table or SAI. - Range queries (
>=,<=,>,<) are allowed only on the last clustering column in the predicate, unless you useALLOW FILTERING. - You cannot mix
ASCandDESCdirections within a single query — ordering must follow the table'sCLUSTERING ORDER BY.
Wide-row pattern for time-series tool data
The wide-row pattern stores many rows for a single partition key, with time as the clustering column. This is the native Cassandra pattern for append-heavy workloads like MCP tool event logs, monitoring data, and audit trails.
-- Wide-row time-series: one partition per MCP server instance per hour
CREATE TABLE mcp_server.server_metrics (
server_id text,
hour_bucket timestamp, -- rounded to hour: new Date(Math.floor(Date.now() / 3600000) * 3600000)
recorded_at timestamp, -- exact timestamp — clustering column
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
The hour bucket in the partition key caps partition size. Each hour bucket for one server accumulates at most 60 * 60 * metric_count rows — typically well under the 10 GB partition size limit. Without the bucket, a server running for months would create an ever-growing hot partition.
function hourBucket(date: Date): Date {
return new Date(Math.floor(date.getTime() / 3_600_000) * 3_600_000);
}
// Write a metric data point
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 the last hour of latency for a server
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 }
);
Storage Attached Indexes (SAI) — secondary lookups
Amazon Keyspaces supports Storage Attached Indexes (SAI), which allow filtering on non-primary-key columns without scanning all partitions. SAI is specific to Keyspaces (and Cassandra 5+) and replaces the older secondary index implementation. It is not materialized views — there is no separate table.
Use SAI when:
- You need to find records by a column that is not in the partition key (e.g., find all tool_invocations where status = 'failed')
- The column has reasonable cardinality — very low-cardinality columns (true/false, 2–3 enum values) may read large portions of the table on each query
- The table is not write-heavy enough for the index maintenance overhead to matter
-- Create SAI on user_id for cross-day lookups without day_bucket
CREATE INDEX tool_invocations_user_id_idx
ON mcp_server.tool_invocations (user_id)
USING 'sai';
-- Now you can query without the day_bucket partition key component
-- (Keyspaces performs a distributed scan using the SAI)
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 }
);
SAI creation via the management SDK:
import { CreateTableCommand } from '@aws-sdk/client-keyspaces';
// SAI is specified at table creation time in the SDK
// or via CQL DDL after creation using cassandra-driver
await client.execute(
`CREATE INDEX tool_invocations_status_idx
ON mcp_server.tool_invocations (status)
USING 'sai'`,
[],
{ prepare: false } // DDL does not support prepare
);
SAI limitations
- SAI queries without a partition key equality predicate perform a distributed scan — they are slower than partition-key-scoped queries but much faster than
ALLOW FILTERING. - No SAI on collection columns (LIST, SET, MAP).
- No SAI on counter columns.
- SAI index updates are synchronous with the write — no eventual-consistency lag, but writes cost slightly more.
- Keyspaces does not support materialized views — SAI is the alternative for query flexibility.
Tombstones — the silent performance killer
When you DELETE a row in Cassandra, it does not remove data immediately. It writes a tombstone — a deletion marker — that tells readers to ignore the row. Tombstones accumulate until compaction removes them. If reads encounter too many tombstones before finding live data, Cassandra throws a TombstoneOverwhelmingException (default threshold: 100,000 tombstones per read).
MCP server patterns that generate heavy tombstones:
| 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 too, but predictably during compaction |
Updating a column to null | Setting a column to null in CQL issues a cell-level tombstone | Use a sentinel value (empty string, 0) instead of null for nullable fields in hot tables |
| Appending to a LIST collection then removing elements | LIST removes create tombstones; LIST appends create new entries but old positions are tombstoned | Use SET instead of LIST where order does not matter; for ordered append-only logs, use separate rows |
| Deleting entire partitions frequently (e.g., cache eviction) | Partition-level tombstone blocks all reads to that partition until compaction | Use short TTL on the table instead; expired data reads as not-found without tombstone accumulation visible to readers |
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 explicit-delete tombstones can.
Paginating large result sets with pageState
When a CQL query matches more rows than fetchSize, cassandra-driver returns the first page and a pageState token. Pass the token in the next query to fetch the following page. This is the correct way to implement pagination in Keyspaces MCP tools — do not use OFFSET (CQL has no OFFSET clause).
import { types } from 'cassandra-driver';
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: list tool invocations with cursor-based pagination
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 attempt to 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), validate that tokens are still valid by handling the QueryExecutionException that Keyspaces returns for stale tokens, and restart pagination from the beginning.
Query patterns reference
| Access pattern | Schema strategy | CQL pattern |
|---|---|---|
| Fetch by entity ID (most common) | Entity ID as partition key | WHERE entity_id = ? |
| Fetch N most recent events for entity | Entity ID partition, timestamp clustering DESC | WHERE entity_id = ? LIMIT N |
| Fetch events in time range for entity | Entity ID partition, timestamp clustering | WHERE entity_id = ? AND ts >= ? AND ts <= ? |
| Find entities by secondary attribute | SAI on secondary column | WHERE secondary_col = ? (with SAI) |
| Paginate through all events | Entity + time bucket partition, SAI optional | fetchSize + pageState cursor |
| High-cardinality fan-out (all events globally) | Time bucket only as partition | Avoid — creates hot partition; use Kinesis or separate analytics system |