Guide · Amazon Keyspaces · TTL · Session State · MCP Server Tools
Amazon Keyspaces TTL and Session State for MCP Servers
Amazon Keyspaces has built-in TTL (time-to-live) support that makes it a natural fit for MCP server session state, rate-limit counters, and any data with a natural expiry horizon. Unlike DynamoDB TTL (which deletes rows in the background within 48 hours of expiry), Keyspaces TTL enforces expiry at read time — a row past its TTL is returned as not-found even if it has not yet been physically deleted. This guide covers per-row TTL, table-level default TTL, TTL inspection, server-side timestamps, the interaction between TTL and point-in-time recovery, and tombstone management for high-TTL workloads.
TL;DR
Set default_time_to_live at table creation for data with uniform retention (e.g., 24-hour session tokens). Override per-row with USING TTL N in INSERT/UPDATE for data that needs variable expiry. TTL is specified in seconds. A row with TTL 0 never expires; use USING TTL 0 to explicitly mark a row as immortal (overrides table default). Inspect remaining TTL with SELECT TTL(column_name). Server-side timestamps (USING TIMESTAMP) control write ordering for concurrent updates — the highest timestamp wins, regardless of clock order. Keyspaces PITR can restore data before TTL expiry, but cannot restore already-expired-and-compacted rows — keep this in mind when setting aggressive TTL on data you might need to audit.
Per-row TTL with USING TTL
Add USING TTL N to any INSERT or UPDATE statement to set an expiry on the written row. N is in seconds. The row (or updated cells) expire and become invisible at the read layer exactly N seconds after the write timestamp.
// INSERT with 1-hour TTL — typical for MCP session tokens
await client.execute(
`INSERT INTO mcp_server.active_sessions
(session_id, user_id, created_at, metadata)
VALUES (?, ?, ?, ?)
USING TTL 3600`,
[sessionId, userId, new Date(), JSON.stringify(meta)],
{ prepare: true }
);
// UPDATE with TTL — refreshes the expiry window on activity ("sliding expiry")
await client.execute(
`UPDATE mcp_server.active_sessions
USING TTL 3600
SET metadata = ?, last_active = ?
WHERE session_id = ?`,
[JSON.stringify(newMeta), new Date(), sessionId],
{ prepare: true }
);
The UPDATE form implements a sliding expiry: each activity update resets the 1-hour window. This is the correct pattern for MCP session tokens that should expire only after a period of inactivity.
Important TTL behaviors to know:
- Cell-level TTL: CQL TTL is applied per-cell, not per-row. If you INSERT with TTL 3600 and then UPDATE specific columns without a TTL, those updated columns get TTL 0 (immortal). The other columns retain their original TTL. This can leave zombie rows that are partially expired — readable but with missing columns.
- Primary key columns never expire: TTL does not apply to partition key or clustering column cells. These are the row's identity — expiring them would leave orphaned data. TTL on INSERT expiries the entire non-key data; the key cells linger until compaction removes the tombstone.
- Counter tables: TTL is not supported on counter tables in Keyspaces.
Table-level default TTL
Set default_time_to_live at table creation for uniform retention. Any INSERT or UPDATE that does not specify USING TTL inherits the table default. Use this for audit logs, event streams, and time-series data where all rows have the same retention horizon.
-- Create table with 7-day default TTL (all rows expire in 7 days unless 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
Via the management SDK:
import { CreateTableCommand } from '@aws-sdk/client-keyspaces';
await ksClient.send(new CreateTableCommand({
keyspaceName: 'mcp_server',
tableName: 'tool_audit_log',
schemaDefinition: {
allColumns: [
{ name: 'session_id', type: 'uuid' },
{ name: 'logged_at', type: 'timestamp' },
{ name: 'tool_name', type: 'text' },
{ name: 'input_hash', type: 'text' },
{ name: 'outcome', type: 'text' },
],
partitionKeys: [{ name: 'session_id' }],
clusteringKeys: [{ name: 'logged_at', orderBy: 'DESC' }],
},
capacitySpecification: { throughputMode: 'PAY_PER_REQUEST' },
defaultTimeToLive: 604800, // 7 days
}));
Overriding the default TTL
// Row with no TTL override — inherits table default (7 days)
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 }
);
// Row that must be retained longer (compliance hold) — override with 90-day TTL
await client.execute(
`INSERT INTO mcp_server.tool_audit_log
(session_id, logged_at, tool_name, input_hash, outcome)
VALUES (?, ?, ?, ?, ?)
USING TTL 7776000`, // 90 days
[sessionId, new Date(), 'deploy_production', hashInput(input), 'success'],
{ prepare: true }
);
// Row that must never expire (audit of a security event) — USING TTL 0 disables expiry
await client.execute(
`INSERT INTO mcp_server.tool_audit_log
(session_id, logged_at, tool_name, input_hash, outcome)
VALUES (?, ?, ?, ?, ?)
USING TTL 0`, // immortal — overrides the 7-day table default
[sessionId, new Date(), 'access_credentials', hashInput(input), 'denied'],
{ prepare: true }
);
Inspecting TTL at read time
Use SELECT TTL(column_name) to retrieve the remaining TTL in seconds for a specific column. Returns null if the column has no TTL (either immortal or key column), and 0 if the column has already expired (but the row hasn't been compacted yet — this is rare to observe in practice).
const result = await client.execute(
`SELECT session_id, TTL(metadata) AS remaining_ttl, metadata
FROM mcp_server.active_sessions
WHERE session_id = ?`,
[sessionId],
{ prepare: true }
);
if (result.rows.length === 0) {
// Row not found — either never existed or already expired
return null;
}
const row = result.rows[0];
const remainingSeconds = row.remaining_ttl;
if (remainingSeconds !== null && remainingSeconds < 300) {
// Less than 5 minutes remaining — refresh the session
await refreshSessionTTL(client, sessionId);
}
Build a TTL-aware session accessor for MCP tools:
async function getSessionWithTTL(
client: Client,
sessionId: string
): Promise<{ session: Session | null; expiresInSeconds: number | null }> {
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];
return {
session: { userId: row.user_id, metadata: JSON.parse(row.metadata) },
expiresInSeconds: row.ttl_remaining,
};
}
Server-side timestamps — write ordering
Cassandra uses MVCC semantics: each write has a timestamp, and the highest timestamp wins during read. By default, the timestamp is the client clock at write time. For distributed MCP server deployments (multiple Lambda instances, multiple ECS tasks writing concurrently), clock skew between instances can cause out-of-order writes where an older value overwrites a newer one.
Use USING TIMESTAMP N (N in microseconds since epoch) to control write ordering explicitly:
// Write with explicit server-generated timestamp for deterministic ordering
const writeMicros = BigInt(Date.now()) * 1000n; // milliseconds to microseconds
await client.execute(
`UPDATE mcp_server.active_sessions
USING TTL 3600 AND TIMESTAMP ?
SET metadata = ?, last_active = ?
WHERE session_id = ?`,
[writeMicros, JSON.stringify(newMeta), new Date(), sessionId],
{ prepare: true }
);
The cassandra-driver also supports setting the default timestamp policy at the client or query level, which is cleaner for high-concurrency workloads:
import { policies } from 'cassandra-driver';
// Use monotonic timestamps generated by the driver (avoids client-clock skew)
const client = new Client({
// ...other options...
policies: {
timestampGeneration: new policies.timestampGeneration.MonotonicTimestampGenerator(),
},
});
// All writes from this client use monotonically increasing timestamps
// — no need for USING TIMESTAMP in individual queries
MonotonicTimestampGenerator ensures that writes from a single driver instance are always ordered correctly, even if the system clock jumps backward. For multi-instance deployments, combine with application-level ordering logic (e.g., last-write-wins using the highest logical version) rather than relying on timestamp ordering across instances.
WRITETIME — inspecting write timestamps
// See when a column was written (in 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;
MCP session state patterns
Three common session state patterns for MCP servers, ordered by complexity:
Pattern 1 — Short-lived tokens (simplest)
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; no extension possible
-- Issue a token
await client.execute(
`INSERT INTO mcp_server.auth_tokens (token_id, user_id, scopes, issued_at)
VALUES (?, ?, ?, ?)`, // inherits 15-min TTL from table default
[types.Uuid.random(), userId, ['read:code', 'write:tests'], new Date()],
{ prepare: true }
);
// Validate a token (returns nothing 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
CREATE TABLE mcp_server.sliding_sessions (
session_id uuid,
user_id text,
context text,
PRIMARY KEY (session_id)
-- No default_time_to_live — TTL is set per-write to implement 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 counters (note: not counter tables)
-- Use regular rows + TTL to track rate limit windows
-- (Counter tables do not support TTL — use this pattern instead)
CREATE TABLE mcp_server.rate_buckets (
tool_name text,
user_id text,
minute_key bigint, -- floor(epochMs / 60000)
call_count counter,
PRIMARY KEY ((tool_name, user_id), minute_key)
);
-- Note: counter tables cannot have TTL — manage old rows via scheduled DELETE
-- or use a separate non-counter table with per-row TTL and USING TTL 120 (2-min window)
PITR and TTL interaction
Amazon Keyspaces Point-in-Time Recovery (PITR) enables restoring a table to any second within the last 35 days. However, PITR and TTL interact in ways that surprise developers:
| Scenario | Behavior | Implication for MCP developers |
|---|---|---|
| Restore to a time before a row's TTL expired | Row is restored with its original TTL intact — it may expire immediately after restore if the TTL has already elapsed relative to wall clock | Restoring a 1-hour-TTL session table to 2 hours ago will produce mostly-empty results even after restore completes |
| Restore to a time before the table was created | Not possible — PITR only covers the table's lifetime | PITR cannot recover data from before the table existed |
| Rows already physically compacted after TTL expiry | PITR cannot restore these rows — they are gone from storage | For compliance audit data, use USING TTL 0 (immortal) or set a very long TTL well beyond the PITR window |
| Modify TTL after enabling PITR | PITR captures the state including TTL values | Reducing TTL to clean up data is irreversible once rows compact |
For MCP server audit logs 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.
Tombstone management for high-TTL-churn tables
When many rows expire by TTL within a short window (e.g., all 1-hour session tokens written in a burst expiring together), compaction must process a large number of tombstones. This is typically not a problem in Keyspaces because AWS manages compaction internally, but there are limits and observable effects:
- Reads against a partition with many expired tombstones may be slower than expected until the next compaction pass clears them.
- Keyspaces by default uses a TTL-aware compaction strategy that prioritizes cleaning up expired data. You cannot change the compaction strategy in Keyspaces (unlike self-managed Cassandra), but this default is appropriate for TTL-heavy workloads.
- If you use
SELECT COUNT(*)on a TTL-heavy table, the count includes rows with tombstones that have not yet been compacted — the count may be higher than the number of live rows. - For tables where every row has a TTL (pure cache tables, session tables), consider partitioning by time bucket so that entire partitions expire together. Keyspaces can drop an entire partition more efficiently than processing tombstones cell by cell.
-- Partition by token_hour so entire partitions are dropped by compaction
-- rather than accumulating individual tombstones
CREATE TABLE mcp_server.burst_sessions (
token_hour timestamp, -- floor(epochMs / 3600000) * 3600000
session_id uuid,
user_id text,
context text,
PRIMARY KEY (token_hour, session_id)
) WITH default_time_to_live = 3600; -- 1 hour; entire hour-bucket partitions expire together
Related guides
- Amazon Keyspaces for MCP servers: driver setup, auth, and CQL basics
- Amazon Keyspaces data modeling: partition keys, clustering columns, SAI
- Amazon Keyspaces capacity modes, PITR, and cost management
- ElastiCache caching patterns for MCP servers: cache-aside, write-through, TTL
- MCP server uptime monitoring