AWS ElastiCache · 2026-11-12 · ElastiCache advanced arc
AWS ElastiCache Advanced Patterns for MCP Servers: Lua Rate Limiting, Caching Patterns, Pub/Sub, and Global Datastore
Beyond basic session storage, MCP servers need ElastiCache to do harder things: enforce per-user rate limits atomically without race conditions, serve hot data from memory without stampedes on cache expiry, broadcast configuration changes to every running server instance in real time, and survive regional outages without a full cold-start rebuild. This guide synthesizes four advanced ElastiCache patterns — Lua-atomic rate limiting, cache-aside and write-through with stampede prevention, Pub/Sub fan-out with cluster mode constraints, and Global Datastore cross-region replication — into a production playbook you can follow end-to-end.
TL;DR
- Rate limiting: never use
INCR+EXPIREas separate commands — the two-command sequence has a race condition. UseEVALwith a Lua script that does both atomically. Use sorted sets for sliding-window accuracy; token buckets for burst-friendly limits. Cache compiled scripts withSCRIPT LOAD+EVALSHAon hot paths. In cluster mode, all keys in a singleEVALmust share a hash tag likerl:fixed:{user:abc}:tool. - Caching patterns: cache-aside for read-heavy data, write-through for data where staleness is unacceptable. Add TTL jitter (
base + Math.random() * jitter) to spread expiry of batch-loaded keys. Prevent thundering herds with aSET lockKey 1 NX PX 5000mutex and an atomic Lua check-and-delete release. Setvolatile-lrueviction and always provide a fallback TTL even when you plan to invalidate explicitly. - Pub/Sub: use a dedicated subscriber connection — a subscribed connection cannot run
GET,SET, orPUBLISH. ioredis auto-resubscribes after reconnect, but messages during the disconnect window are permanently lost (at-most-once). In cluster mode, Pub/Sub is shard-local — prefix all channel names with{pubsub}to force them to a single shard. - Global Datastore: one writable primary region, up to two read-only secondary regions, replication lag typically under 100 ms. Writes from secondary regions are proxied to the primary — this adds 50–150 ms cross-region round trip to every write. Failover requires explicit
FailoverGlobalReplicationGroupCommand. All groups in a Global Datastore must share the same AUTH token; rotate all simultaneously.
Pattern 1: Lua-atomic rate limiting
MCP server tools that call LLMs, hit external APIs, or run expensive database queries need rate limiting to prevent abuse and control cost. The naive approach — INCR key then EXPIRE key — has a race condition: two concurrent callers both read zero, both increment, and neither sets expiry correctly, so the key may never expire. The correct approach uses Lua scripting: ElastiCache executes a Lua script atomically in a single server round-trip, making the check-increment-expire sequence indivisible.
See the full ElastiCache rate limiting guide for complete implementations. The three algorithms you need:
Fixed window counter
Resets at exact time boundaries (every 60 seconds). Cheapest on memory — one integer key per user per tool. The Lua script increments the counter and sets the TTL only on the first call in a window:
const FIXED_WINDOW_SCRIPT = `
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local count = redis.call('INCR', key)
if count == 1 then
redis.call('EXPIRE', key, window)
end
local ttl = redis.call('TTL', key)
return { count, ttl }
`;
// Key format: hash tag ensures cluster-mode co-location
// All keys for the same user hash to the same slot
const key = `rl:fixed:{user:${userId}}:${toolName}`;
const [count, ttl] = await redis.eval(
FIXED_WINDOW_SCRIPT, 1, key,
String(limitPerWindow), String(windowSeconds),
) as [number, number];
Fixed window edge case: at the boundary between windows, a user can make 2× their limit in a short burst — limit calls just before the window resets and limit more immediately after. If this matters for your use case, use a sliding window.
Sliding window with sorted sets
A sliding window measures the last N seconds from now, not from the start of the current window. It prevents the double-burst problem but uses more memory — one sorted set entry per request rather than a single integer:
const SLIDING_WINDOW_SCRIPT = `
local key = KEYS[1]
local now = tonumber(ARGV[1])
local window_ms = tonumber(ARGV[2])
local limit = tonumber(ARGV[3])
local entry_id = ARGV[4]
redis.call('ZREMRANGEBYSCORE', key, 0, now - window_ms)
local count = redis.call('ZCARD', key)
if count < limit then
redis.call('ZADD', key, now, entry_id)
redis.call('PEXPIRE', key, window_ms + 1000)
return { 1, count + 1, limit - count - 1 }
else
return { 0, count, 0 }
end
`;
const now = Date.now();
const entryId = `${now}-${Math.random().toString(36).slice(2, 8)}`;
const key = `rl:slide:{user:${userId}}:${toolName}`;
const [allowed, count, remaining] = await redis.eval(
SLIDING_WINDOW_SCRIPT, 1, key,
String(now), String(windowMs), String(limit), entryId,
) as [number, number, number];
Memory tradeoff: each request within the window occupies one sorted set entry (~80 bytes). At 100 requests/minute/user with a 60-second window, peak memory per active user is about 8 KB. For high-volume tools where fixed-window burst is acceptable, the integer counter is an order of magnitude cheaper.
Token bucket for burst-friendly limits
Token bucket allows short bursts up to capacity tokens while enforcing a long-term refill rate. A user who has been idle accumulates tokens (up to capacity) and can spend them in a burst. This maps well to MCP tools called interactively — a user who hasn't made a request in 10 minutes should be able to run a batch of tools immediately without being rate-limited on the first few:
const TOKEN_BUCKET_SCRIPT = `
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2]) -- tokens per second
local now = tonumber(ARGV[3]) -- current time (float seconds)
local requested = tonumber(ARGV[4]) -- tokens to consume
local bucket = redis.call('HMGET', key, 'tokens', 'last_refill')
local tokens = tonumber(bucket[1])
local last_refill = tonumber(bucket[2])
if tokens == false or last_refill == false then
tokens = capacity
last_refill = now
end
local elapsed = now - last_refill
tokens = math.min(capacity, tokens + elapsed * refill_rate)
last_refill = now
if tokens >= requested then
tokens = tokens - requested
redis.call('HSET', key, 'tokens', tokens, 'last_refill', last_refill)
redis.call('EXPIRE', key, math.ceil(capacity / refill_rate) + 60)
return { 1, math.floor(tokens) }
else
redis.call('HSET', key, 'tokens', tokens, 'last_refill', last_refill)
redis.call('EXPIRE', key, math.ceil(capacity / refill_rate) + 60)
return { 0, math.floor(tokens), math.ceil((requested - tokens) / refill_rate) }
end
`;
The TTL inside the script uses math.ceil(capacity / refillRate) + 60 — with capacity 20 and refillRate 0.5 tokens/second, that is ceil(40) + 60 = 100 seconds. A fully-depleted bucket refills within the TTL window, preventing the key from expiring while a bucket still has theoretical capacity.
EVALSHA — avoiding script re-compilation overhead
Every EVAL call sends the full Lua script text across the network and forces ElastiCache to parse and compile it. On hot paths (thousands of tool calls per minute), this adds measurable latency. Load scripts once at startup and use EVALSHA on each call:
const scriptShas: Record<string, string> = {};
async function loadRateLimitScripts(): Promise<void> {
scriptShas.fixedWindow = await redis.script('LOAD', FIXED_WINDOW_SCRIPT);
scriptShas.slidingWindow = await redis.script('LOAD', SLIDING_WINDOW_SCRIPT);
scriptShas.tokenBucket = await redis.script('LOAD', TOKEN_BUCKET_SCRIPT);
}
async function checkRateLimitFast(key: string, limit: number, window: number) {
try {
return await redis.evalsha(scriptShas.fixedWindow, 1, key, String(limit), String(window));
} catch (err: any) {
if (err.message?.includes('NOSCRIPT')) {
// ElastiCache flushes script cache on node restart or failover
await loadRateLimitScripts();
return redis.evalsha(scriptShas.fixedWindow, 1, key, String(limit), String(window));
}
throw err;
}
}
Always catch NOSCRIPT errors. ElastiCache flushes the script cache on node restarts and primary/replica failovers. After a cluster failover, the new primary has not seen your scripts — EVALSHA returns NOSCRIPT No matching script. Please use EVAL until you reload.
Layering per-user, per-tool, and global limits
Most production MCP servers need multiple independent limits applied in sequence. Run checks in parallel since they touch independent keys; return the most user-friendly error when any fires:
async function enforceRateLimits(userId: string, toolName: string): Promise<void> {
const [userResult, toolResult, globalResult] = await Promise.all([
checkRateLimitFast(`rl:fixed:{user:${userId}}:*`, 100, 60),
checkRateLimitFast(`rl:fixed:{user:${userId}}:tool:${toolName}`, 10, 60),
checkRateLimitFast(`rl:fixed:{global}:all`, 10_000, 60),
]);
if (!userResult.allowed) {
throw Object.assign(new Error(`Rate limit: ${userResult.count}/100 per minute`),
{ code: 'RATE_LIMIT_USER', retryAfter: userResult.ttl });
}
if (!toolResult.allowed) {
throw Object.assign(new Error(`Tool rate limit exceeded for ${toolName}`),
{ code: 'RATE_LIMIT_TOOL', retryAfter: toolResult.ttl });
}
if (!globalResult.allowed) {
// Don't expose global limit details to users — log internally
throw Object.assign(new Error('Service temporarily at capacity'),
{ code: 'RATE_LIMIT_GLOBAL', retryAfter: globalResult.ttl });
}
}
Always return X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, and Retry-After (on 429) in response headers so callers can implement exponential backoff intelligently. Decide upfront whether to fail-open (allow requests when Redis is unavailable) or fail-closed. For user-facing MCP tools, fail-open with an alert is safer than taking down the entire service during a brief Redis hiccup. For cost-sensitive operations like paid LLM API calls, fail-closed with a circuit breaker is correct.
Pattern 2: Caching patterns — cache-aside, write-through, and stampede prevention
MCP server tools that query the same data repeatedly — user profiles, feature flags, product catalogs, LLM context embeddings — spend most of their latency budget on database round trips. ElastiCache eliminates repeat queries by keeping hot data in memory. The challenge is not adding a Redis call: it is choosing the right pattern so cached data stays correct when the source changes, peak traffic does not cause stampedes on expiry, and expired entries rebuild quickly. See the full ElastiCache caching patterns guide for implementations.
Cache-aside (lazy loading)
Cache-aside is the most common pattern for MCP tools. On a cache miss, the application fetches from the database, writes to cache, and returns the value. Only keys that are actually read end up in memory.
async function getUserProfile(userId: string): Promise<UserProfile | null> {
const cacheKey = `user:profile:${userId}`;
const cached = await redis.get(cacheKey);
if (cached !== null) return JSON.parse(cached);
const item = await ddb.send(new GetCommand({
TableName: process.env.USERS_TABLE!,
Key: { userId },
}));
if (!item.Item) {
// Cache negative result — prevents stampede on non-existent keys
await redis.set(cacheKey, 'null', 'EX', 60);
return null;
}
const ttl = 600 + Math.floor(Math.random() * 60); // 10 min + jitter
await redis.set(cacheKey, JSON.stringify(item.Item), 'EX', ttl);
return item.Item as UserProfile;
}
Negative caching: cache 'null' for keys that do not exist in the database. Without it, every lookup for a deleted or never-created userId hits the database — an easy vector for cache bypass attacks or wasted queries for churned accounts.
TTL jitter: Math.floor(Math.random() * 60) adds up to 60 seconds of random spread. If you load 10,000 user profiles at startup with a base TTL of 600 seconds, all 10,000 would expire simultaneously without jitter — causing 10,000 concurrent database queries. Jitter spreads expiries across a 60-second window.
Write-through caching
Write-through updates cache synchronously on every database write. The cache always reflects the latest state — there is no stale window. Use it when reads and writes are balanced and stale data is unacceptable (financial balances, permissions):
async function updateUserProfile(userId: string, updates: Partial<UserProfile>): Promise<UserProfile> {
const updated = { ...(await getUserProfile(userId))!, ...updates };
// Write database first (source of truth)
await ddb.send(new PutCommand({ TableName: process.env.USERS_TABLE!, Item: updated }));
// Write cache synchronously
const ttl = 600 + Math.floor(Math.random() * 60);
await redis.set(`user:profile:${userId}`, JSON.stringify(updated), 'EX', ttl);
return updated;
}
async function deleteUserProfile(userId: string): Promise<void> {
await ddb.send(new DeleteCommand({ TableName: process.env.USERS_TABLE!, Key: { userId } }));
// Explicit DEL — do not let stale data linger until TTL expiry
await redis.del(`user:profile:${userId}`);
}
Always call explicit DEL on hard deletes. If you delete a database record but rely on TTL expiry for the cache, MCP tools return data for deleted users until the TTL fires.
TTL strategy by data volatility
TTL selection is a business decision disguised as a technical one. Too short — you evict items before they are reused. Too long — users see stale data. Use volatility as your guide:
| Data type | Change frequency | Recommended TTL | Notes |
|---|---|---|---|
| Exchange rates, real-time metrics | Every few seconds | 10–30 seconds | Cache to absorb burst reads between upstream fetches |
| Inventory levels, prices | Minutes | 60–300 seconds | Accept brief staleness; pair with write-through on explicit updates |
| User preferences, profile | Hours | 600–1800 seconds | Jitter ±10% to spread expirations |
| Product catalog, documentation | Daily | 3600–86400 seconds | Invalidate explicitly on content publish events |
| Feature flags | Rare, explicit | 300 seconds max + explicit invalidation | Always invalidate on flag change — never rely solely on TTL |
| LLM embeddings for search | Never (content hash) | No TTL (persistent) or 7+ days | Key by content hash; never expires unless content changes |
Always set a fallback TTL even when you plan to use explicit invalidation. If the invalidation event is lost (message queue failure, deploy race), the fallback TTL bounds the staleness window.
Thundering herd prevention with mutex lock
When a popular cache key expires, every concurrent request that finds the cache empty races to rebuild it — all hitting the database simultaneously. For a key serving 500 requests/second, the expiry moment generates 500 database queries in a 1-millisecond window. The standard solution is a short-lived mutex lock:
const LOCK_TTL_MS = 5000; // lock expires if holder crashes
const WAIT_POLL_MS = 50;
const MAX_WAIT_MS = 3000;
async function getWithMutex<T>(
cacheKey: string,
buildValue: () => Promise<T>,
cacheTTL: number,
): Promise<T> {
const cached = await redis.get(cacheKey);
if (cached !== null) return JSON.parse(cached);
const lockKey = `lock:${cacheKey}`;
const lockValue = `${Date.now()}-${Math.random()}`;
const acquired = await redis.set(lockKey, lockValue, 'PX', LOCK_TTL_MS, 'NX');
if (acquired === 'OK') {
try {
const value = await buildValue();
const ttl = cacheTTL + Math.floor(Math.random() * Math.floor(cacheTTL * 0.1));
await redis.set(cacheKey, JSON.stringify(value), 'EX', ttl);
return value;
} finally {
// Atomic check-and-delete: only release lock we still own
await redis.eval(
`if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end`,
1, lockKey, lockValue,
);
}
}
// Another caller holds lock — poll until cache is populated
const deadline = Date.now() + MAX_WAIT_MS;
while (Date.now() < deadline) {
await new Promise(r => setTimeout(r, WAIT_POLL_MS));
const result = await redis.get(cacheKey);
if (result !== null) return JSON.parse(result);
}
// Fallback: bypass cache if wait timed out
console.warn(`[cache] mutex wait timeout for ${cacheKey}`);
return buildValue();
}
Lock release atomicity: the Lua check-and-delete prevents releasing a lock you no longer own. If your process took longer than LOCK_TTL_MS to build the value, the lock has already expired and another process may have acquired it. Without the atomic check, you delete someone else's lock and trigger another thundering herd.
Cache warming at startup
Cold cache = every request misses until the cache fills — a traffic spike on startup drives maximum database load at the worst possible moment. For predictable hot keys (top N users, global config, feature flags), pre-warm the cache during deployment before traffic shifts to the new instance. Use ioredis pipeline() to batch all SET commands into a single TCP round trip — warming 1,000 entries with individual SET calls at 0.3 ms/call takes 300 ms; with pipeline the same 1,000 entries take 2–5 ms:
async function warmCache(): Promise<void> {
const pipeline = redis.pipeline();
const flags = await fetchAllFeatureFlags();
for (const [key, value] of Object.entries(flags)) {
pipeline.set(`flag:${key}`, JSON.stringify(value), 'EX', 300);
}
const topUsers = await fetchTopUsers(1000);
for (const user of topUsers) {
const ttl = 600 + Math.floor(Math.random() * 60);
pipeline.set(`user:profile:${user.userId}`, JSON.stringify(user), 'EX', ttl);
}
await pipeline.exec();
console.log(`[cache] warmed ${Object.keys(flags).length + topUsers.length} entries`);
}
Tag-based invalidation
When a database record changes, you need to invalidate every cached key that derived its value from that record. Product pages cache SEO snippets, user views, related-items lists — all derived from the same product record. Tag-based invalidation tracks which cache keys belong to a logical tag, so a single product update invalidates all of them atomically via a Lua script:
const INVALIDATION_SCRIPT = `
local tag_key = KEYS[1]
local keys = redis.call('SMEMBERS', tag_key)
if #keys > 0 then redis.call('DEL', unpack(keys)) end
redis.call('DEL', tag_key)
return #keys
`;
// Register key under tag at write time
await redis.pipeline()
.set(cacheKey, JSON.stringify(value), 'EX', ttl)
.sadd(tagKey, cacheKey)
.expire(tagKey, ttl + 60)
.exec();
// Invalidate all keys for a product in one operation
const deleted = await redis.eval(INVALIDATION_SCRIPT, 1, `tag:product:${productId}`) as number;
For eviction policy, use volatile-lru (not allkeys-lru) in your ElastiCache parameter group. It only evicts keys that have a TTL set — protecting configuration constants and static lookup tables without TTL from memory-pressure eviction, while correctly managing session and cache keys that always have a TTL.
Pattern 3: Pub/Sub fan-out for real-time MCP events
MCP server tools often need to broadcast updates to multiple subscribers — a tool completion event that multiple UI sessions should receive, a feature flag change that all running MCP instances should apply immediately, or a cache invalidation signal that every server in a fleet should act on. Redis Pub/Sub provides a lightweight real-time messaging channel with sub-millisecond delivery to connected subscribers. See the full ElastiCache Pub/Sub guide for all patterns.
Dedicated subscriber connection
Once a connection enters subscribe mode (SUBSCRIBE or PSUBSCRIBE), it can only run subscribe-family commands: SUBSCRIBE, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PING, and QUIT. Any other command (GET, SET, PUBLISH) returns ERR Command not allowed in subscribe mode. You must use a separate connection for all regular Redis operations:
import Redis from 'ioredis';
// Regular connection for GET/SET/PUBLISH/all normal operations
const redis = new Redis({
host: process.env.ELASTICACHE_PRIMARY_ENDPOINT,
port: 6379, tls: {}, password: process.env.ELASTICACHE_AUTH_TOKEN,
});
// Dedicated connection for subscriptions only
const subscriber = new Redis({
host: process.env.ELASTICACHE_PRIMARY_ENDPOINT,
port: 6379, tls: {}, password: process.env.ELASTICACHE_AUTH_TOKEN,
lazyConnect: true,
retryStrategy(times) { return Math.min(times * 100, 5000); },
reconnectOnError(err) { return err.message.includes('READONLY'); },
});
subscriber.on('message', (channel, message) => handleMessage(channel, message));
subscriber.on('ready', () => {
// ioredis auto-resubscribes to previous channels — no manual re-subscribe needed
console.log('[pubsub] connection ready');
});
await subscriber.connect();
await subscriber.subscribe('tool:completions', 'config:updates');
ioredis stores the list of subscribed channels in memory and re-runs the subscription commands automatically after each reconnection. The gap between disconnect and reconnect is a message loss window — there is no replay. Messages published while the connection was down are permanently gone.
SUBSCRIBE vs PSUBSCRIBE
SUBSCRIBE channel matches exact channel names. PSUBSCRIBE pattern matches glob patterns (tool:*:complete, user:*:events). Pattern subscriptions are more flexible but have higher CPU cost on the server because every publish checks all active patterns against every registered pattern. With 1,000 subscribers each using PSUBSCRIBE tool:*:complete and 10,000 messages/second, pattern matching runs 10 million times per second. Use exact SUBSCRIBE when you can enumerate the channels; fall back to PSUBSCRIBE only when channel names are dynamically generated and unpredictable at subscribe time.
// SUBSCRIBE — fires 'message' event
subscriber.on('message', (channel, message) => {
console.log('exact match:', channel, message);
});
await subscriber.subscribe('tool:search:complete', 'config:feature-flags');
// PSUBSCRIBE — fires 'pmessage' event (pattern + matched channel + message)
subscriber.on('pmessage', (pattern, channel, message) => {
console.log('pattern match:', pattern, '→', channel, message);
});
await subscriber.psubscribe('tool:*:complete', 'user:*:event');
Three production fan-out patterns
Pattern A — Broadcast to all server instances (config updates): publish to a single channel; every MCP server instance subscribes and updates its local in-memory config. No request required from each instance:
// Publisher (admin service or deployment script)
await redis.publish('config:reload', JSON.stringify({
version: '2026-11-12-001',
featureFlags: { newSearchAlgorithm: true },
}));
// Every MCP server instance subscribes and hot-reloads
subscriber.on('message', (channel, message) => {
if (channel === 'config:reload') {
configStore.update(JSON.parse(message));
}
});
Pattern B — Per-user event delivery: user-scoped channels like user:${userId}:events ensure only the MCP server instance handling that user's session subscribes — avoids fanning out to all instances. Always unsubscribe in the session cleanup handler to prevent memory leaks:
await subscriber.subscribe(`user:${userId}:events`);
subscriber.on('message', (channel, message) => {
const event = JSON.parse(message);
if (event.type === 'tool_complete') {
wsSession.send(JSON.stringify(event));
}
});
// CRITICAL: unsubscribe when session ends
wsSession.on('close', async () => {
await subscriber.unsubscribe(`user:${userId}:events`);
});
Pattern C — Cache invalidation broadcast: publish a cache-invalidation message; every server instance deletes the key on receipt. Simpler than tag-based invalidation for cases where every instance caches the same keys:
await redis.publish('cache:invalidate', JSON.stringify({ key: `product:seo:p-456:en` }));
subscriber.on('message', (channel, message) => {
if (channel === 'cache:invalidate') {
const { key } = JSON.parse(message);
redis.del(key);
localCache?.delete(key);
}
});
Cluster mode: Pub/Sub is shard-local
ElastiCache cluster mode distributes keys and channels across multiple shards. A message published to a channel only reaches subscribers on the same shard as the publisher. If your publisher connects to shard A and your subscriber connects to shard B, the subscriber never receives the message. The common workaround is to prefix all Pub/Sub channel names with a fixed hash tag like {pubsub} — this forces all channels to hash to the same slot, keeping them on a single shard. The tradeoff: that shard handles all Pub/Sub load, so it can become a hotspot. For moderate pub/sub volume this is acceptable; for high-volume fan-out, consider a dedicated non-clustered ElastiCache node for Pub/Sub:
// All these channels hash to the same shard (hash of "pubsub")
const configChannel = `{pubsub}:config:reload`;
const cacheInvalidate = `{pubsub}:cache:invalidate`;
const userEventPrefix = `{pubsub}:user:`; // per-user: `{pubsub}:user:${userId}`
// PSUBSCRIBE does NOT work across cluster shards — use SUBSCRIBE with exact names
// or accept single-shard restriction with hash tag
Pub/Sub vs Redis Streams: choosing the right primitive
| Characteristic | Pub/Sub | Redis Streams |
|---|---|---|
| Persistence | No — ephemeral, fire-and-forget | Yes — persisted in sorted log |
| Delivery | At-most-once (missed if not subscribed) | At-least-once with ACK |
| Replay | No | Yes — read from any position |
| Consumer groups | No | Yes — competing consumers |
| Cluster mode | Shard-local (workaround: hash tag) | Key-routed |
| Use for | Real-time notifications, config broadcast, cache invalidation | Job queues, audit logs, event sourcing, durable fan-out |
Use Pub/Sub when you are broadcasting to online listeners, message loss during reconnect is tolerable, and you want zero persistence overhead. Use Streams when subscribers may be offline, you need replay, or message acknowledgment is required.
Pattern 4: Global Datastore for multi-region MCP deployments
MCP servers deployed across multiple AWS regions face a common problem: how do you share session state, rate limit counters, and configuration between regions without introducing a cross-region round trip on every request? ElastiCache Global Datastore solves this with an active-passive architecture: one primary region accepts all writes and replicates asynchronously to up to two secondary regions at under 1 second of lag. MCP servers in secondary regions read locally (sub-millisecond), and writes travel to the primary region. See the full ElastiCache Global Datastore guide for the complete setup and failover procedure.
When Global Datastore makes sense
- Multi-region session state: users who roam between regions can hit their session in any region without a cross-region DB query.
- Read-heavy global cache: product catalogs, feature flags, and configuration read thousands of times per second in every region but updated rarely can be served locally in each region.
- Disaster recovery: if your primary region (us-east-1) goes down, you have a warm Redis replica in us-west-2 with <1 second of data lag, ready to promote without a cold-start rebuild.
- Rate limiting with regional fairness: rate limit counters written to the primary can be read in secondary regions — a user who exhausts their limit in us-east-1 is blocked in eu-west-1 within ~1 second of lag.
Do not use Global Datastore when: you need writes to succeed locally in every region (Global Datastore is active-passive, not active-active), you are using ElastiCache for Valkey (Global Datastore supports ElastiCache for Redis only), or your workload is write-heavy from multiple regions (all writes cross the inter-region link to the primary, adding 50–150 ms per write).
Architecture: creating the Global Datastore
A Global Datastore consists of one primary replication group (one region, reads and writes) and up to two secondary replication groups (read-only; writes are accepted but proxied to the primary region):
import {
ElastiCacheClient,
CreateGlobalReplicationGroupCommand,
CreateReplicationGroupCommand,
} from '@aws-sdk/client-elasticache';
// Step 1: Create Global Datastore from existing primary replication group
const primaryClient = new ElastiCacheClient({ region: 'us-east-1' });
const { GlobalReplicationGroup } = await primaryClient.send(
new CreateGlobalReplicationGroupCommand({
GlobalReplicationGroupIdSuffix: 'mcp-prod', // becomes 'ldgnf-mcp-prod' with auto-prefix
PrimaryReplicationGroupId: 'mcp-cache-primary',
GlobalReplicationGroupDescription: 'MCP server session + rate limit cache',
}),
);
// Step 2: Add secondary replication group in eu-west-1
// (create an empty group in eu-west-1, then associate it)
const euClient = new ElastiCacheClient({ region: 'eu-west-1' });
await euClient.send(new CreateReplicationGroupCommand({
ReplicationGroupId: 'mcp-cache-eu',
ReplicationGroupDescription: 'MCP cache EU secondary',
GlobalReplicationGroupId: GlobalReplicationGroup!.GlobalReplicationGroupId,
CacheNodeType: 'cache.r7g.large', // must match primary node type
NumCacheClusters: 2, // 1 primary + 1 replica within EU
}));
The GlobalReplicationGroupId is prefixed by AWS with a 5-character identifier (e.g. ldgnf-mcp-prod) — you cannot control this prefix. Use the Suffix parameter to make the ID recognizable in CloudWatch and CloudTrail logs.
Connecting MCP servers to their regional endpoint
Each replication group has its own cluster endpoint. MCP servers in a region connect to their local replication group endpoint — not to the Global Datastore ID or the primary endpoint in another region. Reads are served locally (fast). Writes appear to succeed locally in secondary regions but are proxied to the primary region, adding ~100 ms round-trip latency:
// Same code in both regions — ELASTICACHE_ENDPOINT is different per-region deploy config
const redis = new Redis({
host: process.env.ELASTICACHE_ENDPOINT, // regional cluster endpoint
port: 6379, tls: {}, password: process.env.ELASTICACHE_AUTH_TOKEN,
});
// Reads: served locally in each region (sub-millisecond)
const session = await redis.get(`session:${sessionId}`);
// Writes: appear to succeed locally in secondary regions,
// but are proxied to us-east-1 primary — adds ~100ms in eu-west-1
await redis.set(`session:${sessionId}`, JSON.stringify(sessionData), 'EX', 3600);
For MCP server use cases where session writes happen once (login) and reads happen many times (every tool call), this write-proxy tradeoff is favorable. For write-heavy workloads where every request writes, benchmark the write-proxy latency against your SLO before adopting Global Datastore.
Monitoring replication lag
The key metric for Global Datastore health is GlobalDatastoreReplicationLag in CloudWatch — the time in milliseconds between when data is written to the primary and when it appears in secondaries. Under normal conditions this is under 100 ms. Spikes above 1,000 ms indicate network issues between regions or a secondary under heavy load:
async function getReplicationLag(globalReplicationGroupId: string): Promise<number> {
const cw = new CloudWatchClient({ region: 'us-east-1' });
const now = new Date();
const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
const { Datapoints } = await cw.send(new GetMetricStatisticsCommand({
Namespace: 'AWS/ElastiCache',
MetricName: 'GlobalDatastoreReplicationLag',
Dimensions: [{ Name: 'GlobalReplicationGroupId', Value: globalReplicationGroupId }],
StartTime: fiveMinutesAgo, EndTime: now,
Period: 60, Statistics: ['Maximum'],
}));
return Math.max(...(Datapoints ?? []).map(d => d.Maximum ?? 0));
}
// Alert if replication lag exceeds 2 seconds — well before it affects failover RPO
const lagMs = await getReplicationLag('ldgnf-mcp-prod');
if (lagMs > 2000) {
console.error(`[global-datastore] ALERT: replication lag ${lagMs}ms`);
}
Set a CloudWatch alarm on GlobalDatastoreReplicationLag > 5000 (5 seconds) to trigger an operational review before lag grows large enough to affect failover RPO. Under normal conditions the metric is under 100 ms — a spike to 2,000 ms is an early warning.
Failover: promoting a secondary region
If the primary region is unavailable, promote a secondary replication group to become the new primary. The promotion takes 2–5 minutes. After promotion, the old primary becomes a secondary (if it recovers) and must be re-added manually:
import { FailoverGlobalReplicationGroupCommand } from '@aws-sdk/client-elasticache';
// From eu-west-1 (the region you want to promote to primary)
const euClient = new ElastiCacheClient({ region: 'eu-west-1' });
await euClient.send(new FailoverGlobalReplicationGroupCommand({
GlobalReplicationGroupId: 'ldgnf-mcp-prod',
PrimaryRegion: 'eu-west-1',
PrimaryReplicationGroupId: 'mcp-cache-eu',
}));
RPO (Recovery Point Objective): approximately equal to the replication lag at the moment of failure — typically under 1 second, never zero. Any writes committed to the primary after the last replicated entry are permanently lost. For MCP server session data, losing 1 second of writes means users may need to re-authenticate — acceptable for most applications.
Connection updates after failover: your MCP servers in eu-west-1 were already connected to the eu-west-1 endpoint — no connection string change needed. MCP servers in us-east-1 that were connected to the old primary will get connection errors during failover; ioredis will reconnect automatically once the old cluster stabilizes or you re-route DNS to the new primary endpoint.
Global Datastore constraints
| Constraint | Detail |
|---|---|
| Engine | ElastiCache for Redis only. Not supported for ElastiCache for Valkey or Memcached. |
| Minimum Redis version | Redis 5.0.6 or later |
| Data tiering | Not supported — r6gd instances (NVMe SSD tiering) cannot be used in Global Datastore |
| Number of secondary regions | Maximum 2 secondary replication groups |
| AUTH token | All replication groups in the Global Datastore must use the same AUTH token. Rotate all simultaneously. |
| Deletion order | Remove secondaries first (DisassociateGlobalReplicationGroupCommand), then delete primary. Attempting to delete primary first fails with InvalidGlobalReplicationGroupStateFault. |
| Billing | Each replication group (primary + each secondary) is billed separately. Cross-region data transfer costs are additional. |
Combined failure mode reference
| Error | Pattern | Cause | Fix |
|---|---|---|---|
NOSCRIPT No matching script | Rate limiting | EVALSHA after ElastiCache node restart flushed script cache | Catch NOSCRIPT, re-run SCRIPT LOAD, retry with new SHA |
CROSSSLOT Keys in request don't hash to the same slot | Rate limiting, caching | Multi-key Lua EVAL in cluster mode with keys in different slots | Use hash tags like rl:fixed:{user:abc}:tool |
| Rate counter never resets; key persists forever | Rate limiting | INCR + EXPIRE race: process crashed between the two calls | Use Lua EVAL to make increment + expire atomic |
| 500+ concurrent DB queries on cache expiry | Caching | Thundering herd: popular key expired, every request misses simultaneously | Mutex lock with SET NX PX; probabilistic XFetch alternative |
| Stale data served after record deletion | Caching | Cache-aside: relying on TTL expiry instead of explicit DEL on delete | Always call redis.del(cacheKey) in delete path |
ERR Command not allowed in subscribe mode | Pub/Sub | Running GET/SET/PUBLISH on the subscriber connection | Use a dedicated Redis connection for non-subscribe commands |
| Subscriber never receives messages in cluster mode | Pub/Sub | Publisher and subscriber connected to different shards | Prefix all channels with {pubsub} hash tag to force same shard |
| Memory leak: too many subscriptions | Pub/Sub | Not calling UNSUBSCRIBE when WebSocket sessions end | Always unsubscribe in session cleanup handler |
| Writes from eu-west-1 succeed but add ~100ms latency | Global Datastore | Writes from secondary regions are proxied to primary across regions | Accept latency for write-once/read-many; not suitable for write-heavy workloads |
InvalidGlobalReplicationGroupStateFault on delete | Global Datastore | Attempting to delete primary while secondary members are still associated | Disassociate secondaries first, then delete the Global Datastore shell, then regional groups |
| AUTH token rotation breaks all sessions simultaneously | Global Datastore | Using SET strategy directly instead of ROTATE then SET | Always use ROTATE strategy first to open dual-token window; deploy app; then SET to finalize |
Related guides
- ElastiCache rate limiting: Lua scripts, sliding window, token bucket
- ElastiCache caching patterns: cache-aside, write-through, TTL strategy, stampede prevention
- ElastiCache Pub/Sub: real-time fan-out, channel patterns, reconnect handling
- ElastiCache Global Datastore: cross-region replication, failover, multi-region sessions
- AWS ElastiCache Redis for MCP Servers: VPC Networking, AUTH Security, Session State, and Cluster Mode
- ElastiCache for Redis: VPC setup, parameter groups, ioredis connection
- ElastiCache cluster mode: hash slots, MOVED/ASK redirects, CROSSSLOT
- ElastiCache auth token, TLS, zero-downtime ROTATE rotation, RBAC
- AWS RDS for MCP Servers: RDS Proxy, IAM Auth, Multi-AZ Failover
- AWS Lambda for MCP Servers: cold starts, streaming, provisioned concurrency