Amazon Elasticache
AWSOfficialPublished by AWS
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Medium risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The Amazon ElastiCache skill provides a structured, modular approach to managing in-memory data stores on AWS. It guides developers through the entire lifecycle of ElastiCache and Valkey, from initial requirements gathering and provisioning to complex data modeling, AI-driven vector search, and operational monitoring. The skill enforces best practices for connection safety, security, and infrastructure-as-code, ensuring reliable performance for caching, session management, and GenAI workloads.
What it does
- Assesses workload requirements to recommend optimal ElastiCache configurations.
- Automates provisioning and connectivity setup for serverless and node-based clusters.
- Provides implementation patterns for common use cases like cache-aside, session stores, and rate limiting.
- Supports advanced AI workloads including semantic caching, RAG, and vector similarity search.
- Delivers operational diagnostics for performance tuning, cost optimization, and troubleshooting.
- Manages migration paths from self-managed Redis or between different deployment models.
When to use it
- When you need to reduce database load or improve API response times with an in-memory cache.
- When implementing AI agent memory, RAG retrieval, or semantic caching for LLM applications.
- When migrating existing Redis workloads to a managed AWS environment.
- When troubleshooting performance issues like high latency, replication lag, or memory pressure.
- When setting up secure, production-ready caching infrastructure using IaC.
Advantages
- Standardizes deployment and operational patterns across development teams.
- Ensures compliance with security best practices like TLS and IAM authentication.
- Reduces configuration errors through automated input validation and tagging.
- Provides clear guidance on engine selection and version-specific feature availability.
- Simplifies complex tasks like cross-region migration and vector search setup.
Usage examples
- “I need to speed up my RDS database. Should I use ElastiCache?”
- The agent will initiate the requirements sub-skill to analyze your workload, stack, and latency needs, then provide a recommendation on whether ElastiCache is the right fit.
- “How do I set up a Valkey cluster for vector search?”
- The agent will route to the genai sub-skill, verify you are using a node-based Valkey 8.2+ cluster, and provide the necessary configuration and code to enable vector similarity search.
- “My cache hit rate is low and latency is spiking. Can you help me troubleshoot?”
- The agent will activate the monitoring sub-skill to analyze your metrics, identify potential hot keys or memory imbalance, and suggest specific remediation steps.
- “Help me migrate my self-managed Redis to ElastiCache.”
- The agent will guide you through the migration sub-skill, performing preflight checks and validating your source configuration for a zero-downtime cutover.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/aws/amazon-elasticache/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip amazon-elasticache.zip -d .agents/skills
Documentation by AWS
ElastiCache
A modular ElastiCache toolkit organized as a registry of sub-skills. Each sub-skill handles one domain of ElastiCache work. The router below matches user intent to the right sub-skill, then loads only the references needed for that sub-skill.
How this skill works
Match the user's request against the semantic categories in the registry below. Match on meaning, not exact wording ("help me figure out which data structures to use" matches
data-modelingeven without the word "pattern").Disambiguation: If the user's intent matches multiple sub-skills, apply these rules in order:
If
.elasticache/requirements.jsonexists withinfrastructure.endpointset, prefermonitoringordata-modeling(the user has an existing cache).If no cache exists (no requirements.json or no endpoint), prefer
requirements.If still ambiguous, ask one clarifying question: "Are you looking to set up something new, or troubleshoot something existing?"
Check the Guardrails section before recommending an engine or deployment model.
Read
references/{sub-skill-id}/instructions.mdfor the matched sub-skill. If the file is not found at a relative path, check your prompt or environment for the skill directory absolute path and retry with{skill-directory}/references/{sub-skill-id}/instructions.md.If the request spans multiple sub-skills, execute them in pipeline order.
If a sub-skill requires upstream context (engine, deployment model, endpoint) not yet in session memory, route to the upstream sub-skill first.
If no sub-skill matches, activate
requirementsfirst.If a script or CLI call fails, show the error to the user and suggest a specific fix before retrying.
Sub-skill registry
Each entry has: an ID (directory name under references/), a domain description, semantic categories for matching, and upstream/downstream dependencies.
| ID | Name | Domain | Semantic Categories | Upstream | Downstream |
|---|---|---|---|---|---|
requirements | Solution Fit | Gathers workload, stack, scale, latency, persistence, and budget through workspace scan + structured interview. Decides whether ElastiCache is the right service and hands off with a routing recommendation. | I need a cache, speed up my app, reduce database load, lower Bedrock cost, should I use ElastiCache, what's best for my workload, evaluating cache options, ElastiCache vs X, Valkey vs X, vague new workload | — | setup, data-modeling, genai, monitoring, migration |
setup | Create and Connect | Provisioning, connectivity, security, authentication, IaC, deployment choice. Gets the user to a working cache with least friction. Covers engine selection, serverless vs node-based, VPC, TLS, RBAC/IAM, jump-host/SSM tunnels, CLI/SDK/CFN/CDK/Terraform starters. | create a cache, set up ElastiCache, provision, Valkey cluster, connect Lambda/ECS/EKS/EC2, VPC, security groups, TLS, RBAC, IAM auth, jump host, SSM tunnel, CloudFormation, CDK, Terraform, engine selection, serverless vs node-based, backup, snapshot, restore, export | requirements (optional) | data-modeling, genai, monitoring |
data-modeling | Application Patterns | Picks data structures, key schema, TTL strategy, invalidation approach, and client code for non-AI patterns: cache-aside, session store, rate limiting, leaderboards, counters, pub/sub, streams, shopping carts, job queues, activity feeds. | session store, rate limiting, leaderboard, cache-aside, query caching, counters, streams, pub/sub, shopping cart, job queue, activity feed, key schema, TTL, invalidation, data structures | setup (cache must exist) | monitoring |
genai | AI and Vector Workloads | Classifies request into Mode 1 (plain cache), Mode 2 (semantic response cache), or Mode 3 (full vector search). Selects Valkey and forces node-based Valkey 8.2 or above (recommend 9.0) when server-side vector similarity is needed. Covers semantic caching, agent memory, RAG retrieval, recommendation, personalization, conversation/session persistence for AI agents, and framework wiring (Strands, mem0, LangChain). | semantic cache, RAG, agent memory, conversational memory, vector search, embeddings, recommendation, personalization, Bedrock latency, Bedrock cost, LLM caching, Strands, mem0, LangChain, conversation history, AI session store, embedding provider, framework integration | setup (cache must exist) | monitoring |
monitoring | Operate and Observe | Diagnoses performance, cost, and reliability using metrics first, then recommends the smallest change. Covers dashboards, alarms, log delivery, cost reporting, event routing, troubleshooting high CPU / memory / replication lag / connection spikes / low hit rate / hot keys / big keys / slot imbalance / latency spike root cause. | cache is slow, cost too high, hit rate low, high CPU, memory pressure, replication lag, connection spikes, dashboards, alarms, CloudWatch, cost comparison, troubleshoot, hot key, uneven shard load, one node pinned, big key, memory bloat, which key is biggest, keyspace distribution, prefix analysis, cost attribution by tenant, memory imbalance, one shard full, slot memory skew, latency spike, slow command incident, root cause for latency bump | — | setup, migration |
migration | Engine and Platform Migration | Selects the migration path and sequences preflight, validation, cutover, and rollback. Covers self-managed Redis → ElastiCache, Redis OSS → Valkey, node-based ↔ serverless, version upgrades. Hard validate-before-migrate gate. | migrate, Redis OSS to Valkey, self-managed to ElastiCache, node-based to serverless, serverless to node-based, engine upgrade, version upgrade, zero-downtime cutover, rollback | — | setup, monitoring |
Pipeline order
Sub-skills run independently, but common multi-step journeys follow these pipelines:
requirements→setup→ (data-modeling|genai) →monitoringmigration→setup→monitoringmonitoring→setup|migration(if metrics indicate)
State handoff: requirements.json
.elasticache/requirements.json is the single source of truth for cross-sub-skill state. Each sub-skill reads it at start and writes its section after completing work. Read before writing; merge, do not overwrite.
| Section | Owner | Key fields |
|---|---|---|
| top-level | requirements | engine, deployment_model, region, runtime, patterns, use_case, vpc_id, subnet_ids, security_group_ids |
infrastructure | setup | cache_name, resource_id, engine_version, topology, endpoint, port, auth_model, tls, client_library, execution_path, access_mode, tunnel_instance_id, embedding_provider, embedding_model, embedding_dim, embedding_module |
genai | genai | mode, mode_2_path, framework |
migration | migration | source_type, source_host, migration_path, cutover_status |
Ownership note:
deployment_modelis set byrequirementsduring initial interview.migrationmay update it after an engine or deployment model switch (e.g., node-based to serverless).
requirements.json should include "schema_version": 1 and "last_updated": "<ISO timestamp>" at the top level. Every sub-skill that writes to requirements.json must update last_updated. If last_updated is older than 7 days, warn the user that cached state may be stale.
requirements.json tracks one active cache. If the user works with multiple caches in the same project, confirm which cache is active before reading or writing state.
When a sub-skill needs upstream context (engine, endpoint, auth model), check requirements.json first. If the field is null or the file does not exist, route to the upstream sub-skill.
Global rules (apply to every sub-skill)
Execution path. Use AWS CLI, SDK (boto3), CloudFormation, or CDK as the primary path for control-plane work. Use valkey-py as the primary path for data-plane work.
Response depth. Summary (2-3 sentences) for "should I" or "which" questions. Standard (recommendation + config + code + next steps) by default. Expert (full decision matrix with alternatives, cost, security caveats) for "why" or "compare all" questions. Escalate on user request; never downgrade unprompted.
Session memory. Track region, VPC, engine, deployment model, auth model, compute runtime, and language. Carry forward across sub-skills. Do not re-ask. If the user overrides a value, update it everywhere. Inferred values (from workspace scan or IaC) must be re-confirmed before high-risk decisions (engine, deployment model, security posture); low-risk inferences (language, framework, region) can be used as defaults silently.
Source priority. Always answer from skill-local files first (sub-skill references, then
scripts/). Do not fetch external documentation or web search unless the local files cannot answer the query. When local files are insufficient, fall back to official AWS docs: https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/ for features and https://aws.amazon.com/elasticache/pricing/ for pricing. Never invent price points or version constraints. If the user references a Valkey or Redis version, feature, or pricing tier not covered in local files, fall back to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/ before answering. Do not extrapolate from local content that may be outdated.Freshness disclaimer. When outputting pricing, version constraints, or feature availability, include a one-line disclaimer: "For current pricing see https://aws.amazon.com/elasticache/pricing/. For current feature availability see https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/."
Connection safety. Never create a Valkey/Redis client at module level (top of file, import time). Initialize connections inside a function or on first use. Module-level connections crash applications that import the module before the cache is reachable.
Code environment. Use
python3(notpython) in all commands and shebangs. Do not generatepip installorpytestcommands in application code. Prefer the agent's file-writing tool over shell redirection for writing files.Input validation (write operations only). Before running any create, modify, or delete CLI command or SDK call that uses user-provided values (cache name, region, subnet IDs, security group IDs, VPC ID, KMS key, snapshot name), validate them with
scripts/input_validator.py. Runpython3 scripts/input_validator.py cache_name=<val> region=<val> ...or importvalidate_allas a library. Skip validation for read-only operations (describe, list) where bad input is harmless.Resource tagging (always apply on resource creation). When creating any cache (
create-serverless-cache,create-replication-group,create-cache-cluster), ALWAYS include these tags:--tags Key=managed_by,Value=aws-skills Key=skill,Value=elasticache Key=skill_version,Value=1.0.0 Key=created_by,Value=elasticache-skill Key=generation_model,Value={your-model-id}Example:
--tags Key=managed_by,Value=aws-skills Key=skill,Value=elasticache Key=skill_version,Value=1.0.0 Key=created_by,Value=elasticache-skill Key=generation_model,Value=claude-sonnet-4-20250514Set
generation_modelto your own model identifier. Include these tags even if the user does not mention tagging. If the user provides additional tags, append these to their tags rather than replacing them.
Reference loading
Load additional references only when the current turn's answer requires them.
On-demand pointers (not preloaded; fetch when the trigger applies):
references/shared-ux/production-readiness.md— when the user asks if their cache is ready for production, or after setup completes and the user wants to go to productionreferences/shared-ux/action-safety.md— before any destructive action (risk levels, never-auto-execute list)references/shared-ux/error-remediation.md— when the user hits a specific ElastiCache error code (MOVED, CROSSSLOT, CLUSTERDOWN, MULTI/EXEC+IAM, etc.)references/shared-foundation/boundary-doc.md— when the user asks what this skill coversreferences/shared-foundation/attribution.md— when generating CLI commands, SDK code, or IaC templatesreferences/shared-foundation/architecture-diagrams.md— when the user asks for architecture diagrams or visual referencereferences/shared-runtime/lambda.md— when connecting from Lambda (cold start gotchas, IAM auth code, lazy init)references/shared-runtime/ecs.md— when connecting from ECS (SIGTERM shutdown, connection pool drain, task definition)references/shared-runtime/eks.md— when connecting from EKS (IRSA, service mesh bypass, SecurityGroupPolicy CRD)references/shared-runtime/api-gateway.md— when integrating with API Gateway (no direct path, caching layers comparison)references/shared-runtime/rds-acceleration.md— when caching RDS/Aurora queries (thundering herd, stampede protection, invalidation)references/shared-runtime/secret-injection.md— when the user asks about credential management per compute platformreferences/shared-security/encryption-defaults.md— when adding encryption to an existing unencrypted cluster (TLS two-step migration, at-rest immutability)references/shared-security/config-guardrails.md— when the user wants continuous compliance monitoring (AWS Config rules, custom Lambda rules)references/shared-security/vpc-patterns.md— when debugging port/security-group issues (port 6380 serverless reader, anti-patterns)
Folder convention:
references/contains 10 folders. 6 match the sub-skills (requirements,setup,data-modeling,genai,monitoring,migration) and are routing destinations. The 4shared-*folders (shared-foundation,shared-ux,shared-security,shared-runtime) are cross-cutting material loaded on demand, not routing destinations.
Guardrails
| Priority | Rule |
|---|---|
| CRITICAL | Vector search MUST use node-based Valkey 8.2 or above. Serverless does NOT support vector search. Never suggest serverless for vector search. Apply this regardless of which sub-skill activates. |
| CRITICAL | Do not invent price points or version constraints. Use scripts/price_calculator.py and current AWS docs when precision matters. |
| HIGH | Do not recommend Memcached when the user needs persistence, replication, RBAC or IAM auth, sorted sets, streams, pub/sub, or vector search. |
| HIGH | Do not assume local laptop access works directly. ElastiCache is VPC-centric; explain VPC, tunnel, or jump-host access when needed. |
| STANDARD | Do not trigger on every generic Redis mention. Trigger when the user is clearly asking about AWS, managed caching, migration, connectivity, pricing, operations, or AWS service integration. |
| STANDARD | For ambiguous "cache" requests inside AWS contexts, activate this skill and start with requirements. |
Product truths
ElastiCache Serverless deploys in under a minute and removes infrastructure management.
Valkey serverless pricing is 33% lower than other supported engines; node-based Valkey pricing is 20% lower.
Serverless caches have in-transit encryption always enabled (cannot be disabled).
IAM auth is available for all ElastiCache Valkey versions (7.2 is the baseline Valkey version on ElastiCache) and Redis OSS 7.0+.
Valkey version ladder: 7.2 (baseline), 8.0 (20% more data per node (capacity improvement), per-slot metrics), 8.1 (Bloom filters, COMMANDLOG, SET IFEQ, 20% less memory via new hash table (efficiency improvement)), 8.2 (vector search), 9.0 (recommended default for new clusters). Recommend Valkey 9.0 for new clusters unless a specific feature dictates otherwise.
Vector search is available for Valkey 8.2 or above on node-based clusters (recommend 9.0).
Global Datastore is available for node-based clusters only. It does not support IPv6 or Local Zones. Global Datastore supports AUTH and RBAC. Cross-region failover must be promoted manually (no autofailover across regions). At-rest encryption must be enabled on all clusters in the Global Datastore, but each cluster can use a separate KMS key per region.
Online migration from self-managed Redis to ElastiCache requires: (source) AUTH must not be enabled,
protected-modeset tono, replication and administrative commands must not be renamed (e.g.,sync,psync,info,config,command,cluster); (target) encryption in-transit disabled, Multi-AZ enabled, engine version Redis OSS 5.0.6+ or Valkey 7.2+, not part of a Global Datastore, data tiering disabled. Shard counts must match between source and target. All source Redis instances must use the same port. Online migration is not supported for serverless caches (node-based targets only). Seereferences/migration/topology-validation.mdfor the full checklist.
Files
- ATTRIBUTION.mdAdded by AutoGineer924 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer67 B
- SKILL.md17.8 KiB
- assets/examples/sample_commandstats.csv882 B
- assets/examples/sample_input_simple.csv449 B
- references/data-modeling/command-availability.md6.1 KiB
- references/data-modeling/common-patterns.md8.6 KiB
- references/data-modeling/instructions.md9.9 KiB
- references/data-modeling/memcached-recipe.md5.2 KiB
- references/data-modeling/recipe-gallery.md8.2 KiB
- references/genai/agent-memory.md5.9 KiB
- references/genai/elasticache-search.md16.9 KiB
- references/genai/embedding-providers.md8.6 KiB
- references/genai/framework-guide.md4.9 KiB
- references/genai/instructions.md9.7 KiB
- references/genai/rag-retrieval.md9.3 KiB
- references/genai/semantic-cache.md8.9 KiB
- references/genai/session-store.md6.4 KiB
- references/migration/auth-migration.md14.4 KiB
- references/migration/feature-comparison.md10.9 KiB
- references/migration/global-datastore-operations.md8.0 KiB
- references/migration/instructions.md14.8 KiB
- references/migration/rollback-procedures.md16.9 KiB
- references/migration/self-managed-migration.md14.6 KiB
- references/migration/sizing-assessment.md6.8 KiB
- references/migration/topology-validation.md8.1 KiB
- references/migration/upgrade-patching.md13.2 KiB
- references/migration/valkey-migration-guide.md13.5 KiB
- references/monitoring/alarm-packs.md8.4 KiB
- references/monitoring/big-key-hunter.md6.8 KiB
- references/monitoring/client-tuning-and-diagnostics.md11.8 KiB
- references/monitoring/cloudwatch-dashboards.md7.7 KiB
- references/monitoring/cost-reporting.md11.9 KiB
- references/monitoring/event-routing.md9.5 KiB
- references/monitoring/hot-key-detection.md10.8 KiB
- references/monitoring/instructions.md8.8 KiB
- references/monitoring/key-space-distribution-by-prefix.md6.8 KiB
- references/monitoring/log-delivery.md7.9 KiB
- references/monitoring/slot-memory-imbalance-detection.md6.7 KiB
- references/monitoring/slow-log-cross-signal-diagnosis.md8.5 KiB
- references/monitoring/troubleshooting.md17.9 KiB
- references/requirements/instructions.md9.9 KiB
- references/setup/auth-model-selector.md3.3 KiB
- references/setup/cluster-topology.md3.6 KiB
- references/setup/connection-guide.md6.4 KiB
- references/setup/connectivity-diagnostics.md6.9 KiB
- references/setup/create-secure-cache.md8.4 KiB
- references/setup/engine-selection.md2.1 KiB
- references/setup/iac-best-practices.md7.3 KiB
- references/setup/iac-reference.md6.2 KiB
- references/setup/iam-policies.md2.7 KiB
- references/setup/instructions.md8.6 KiB
- references/setup/serverless-vs-node.md12.7 KiB
- references/setup/service-quotas.md2.9 KiB
- references/shared-foundation/architecture-diagrams.md8.0 KiB
- references/shared-foundation/attribution.md3.7 KiB
- references/shared-foundation/boundary-doc.md4.9 KiB
- references/shared-runtime/api-gateway.md5.4 KiB
- references/shared-runtime/ecs.md7.5 KiB
- references/shared-runtime/eks.md10.5 KiB
- references/shared-runtime/lambda.md10.1 KiB
- references/shared-runtime/rds-acceleration.md12.6 KiB
- references/shared-runtime/secret-injection.md14.1 KiB
- references/shared-security/config-guardrails.md8.0 KiB
- references/shared-security/encryption-defaults.md4.2 KiB
- references/shared-security/vpc-patterns.md2.8 KiB
- references/shared-ux/action-safety.md9.8 KiB
- references/shared-ux/error-remediation.md12.1 KiB
- references/shared-ux/production-readiness.md5.5 KiB
- scripts/collect_metrics.shScript5.2 KiB
- scripts/command_classifier.pyScript6.2 KiB
- scripts/find_tunnel_host.pyScript7.2 KiB
- scripts/generate_dashboards.pyScript27.1 KiB
- scripts/input_validator.pyScript10.6 KiB
- scripts/migration_preflight.pyScript19.5 KiB
- scripts/price_calculator.pyScript14.4 KiB
- scripts/pricing.pyScript20.2 KiB
- scripts/security_audit.pyScript19.5 KiB
- scripts/serverless_estimator.pyScript28.4 KiB
- scripts/start_tunnel.pyScript11.7 KiB
- scripts/test_connection.pyScript13.3 KiB
- scripts/validate_references.pyScript10.6 KiB
scripts/pricing.py
"""
ElastiCache pricing loader.
Fetches live pricing from the AWS Bulk Pricing API (public, no auth required).
Caches locally to avoid repeated downloads. Refreshes if cache is older than 7 days.
Source: https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonElastiCache/current/index.json
Also accepts an optional local CSV for offline or override use.
Supports On-Demand and Reserved Node pricing (1-year and 3-year terms with
No Upfront, Partial Upfront, and All Upfront purchase options). Reserved pricing
is extracted from the bulk pricing JSON terms.Reserved section.
"""
import csv
import json
import os
import sys
import time
import urllib.request
from typing import Dict, Optional, Tuple
BULK_PRICING_URL = "https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonElastiCache/current/index.json"
CACHE_MAX_AGE_SECONDS = 7 * 24 * 3600 # 7 days
_CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".pricing_cache")
_CACHE_FILE = os.path.join(_CACHE_DIR, "elasticache_pricing.json")
def _cache_is_fresh() -> bool:
"""Check if local cache exists and is younger than CACHE_MAX_AGE_SECONDS."""
if not os.path.exists(_CACHE_FILE):
return False
age = time.time() - os.path.getmtime(_CACHE_FILE)
return age < CACHE_MAX_AGE_SECONDS
def _fetch_and_cache() -> dict:
"""Fetch bulk pricing JSON from AWS and cache locally."""
os.makedirs(_CACHE_DIR, exist_ok=True)
print("Fetching live ElastiCache pricing from AWS...", file=sys.stderr)
try:
req = urllib.request.Request(BULK_PRICING_URL)
with urllib.request.urlopen(req, timeout=60) as resp:
raw = resp.read()
except Exception as e:
raise RuntimeError(
"Failed to fetch pricing from {}. Error: {}. "
"Check network connectivity or provide a local pricing CSV.".format(BULK_PRICING_URL, e)
)
data = json.loads(raw)
parsed = _parse_bulk_pricing(data)
parsed["fetched_at"] = time.time()
with open(_CACHE_FILE, "w") as f:
json.dump(parsed, f)
print(" Pricing cached at: {}".format(_CACHE_FILE), file=sys.stderr)
return parsed
def _load_cache() -> dict:
"""Load parsed pricing from local cache."""
with open(_CACHE_FILE, "r") as f:
return json.load(f)
def _parse_bulk_pricing(data: dict) -> dict:
"""Parse the AWS bulk pricing JSON into our compact format.
Extracts:
- On-demand node-based hourly rates by (region, instance_type, engine)
- Reserved node-based rates by (region, instance_type, engine, lease, purchase_option)
- Serverless storage rates by (region, engine)
- Serverless ECPU rates by (region, engine)
- Extended Support surcharges by (region, engine, year)
"""
products = data.get("products", {})
terms = data.get("terms", {}).get("OnDemand", {})
reserved_terms = data.get("terms", {}).get("Reserved", {})
node_pricing = {} # "region|instance_type|engine" -> $/hr
serverless_storage = {} # "region|engine" -> $/GB-hr
serverless_ecpu = {} # "region|engine" -> $/ECPU
extended_support = {} # "region|instance_type|engine|year" -> $/node-hr
reserved_pricing = {} # "region|instance_type|engine|lease|purchase" -> {"hourly": $, "upfront": $}
node_memory = {} # "instance_type" -> GB (float)
for sku, product in products.items():
attrs = product.get("attributes", {})
family = product.get("productFamily", "")
region = attrs.get("regionCode", "")
if not region:
continue
# Skip Outpost and non-standard location types
if attrs.get("locationType", "") != "AWS Region":
continue
# Get the on-demand price and unit for this SKU
price_info = _get_od_price_with_unit(sku, terms)
if price_info is None:
continue
price_per_unit, unit = price_info
if price_per_unit <= 0:
continue
if family == "Cache Instance":
instance_type = attrs.get("instanceType", "")
engine = _normalize_engine(attrs.get("cacheEngine", ""))
usagetype = attrs.get("usagetype", "")
# Extended Support entries live under "Cache Instance" family
# but have "ExtendedSupport" in the usagetype
if "ExtendedSupport" in usagetype:
if not engine or not instance_type or unit != "Hrs":
continue
years = _parse_extended_support_years(usagetype)
for year in years:
key = "{}|{}|{}|{}".format(region, instance_type, engine, year)
extended_support[key] = price_per_unit
elif instance_type and engine and unit == "Hrs":
key = "{}|{}|{}".format(region, instance_type, engine)
node_pricing[key] = price_per_unit
# Extract memory from product attributes (e.g., "103.68 GiB")
if instance_type not in node_memory:
mem_str = attrs.get("memory", "")
mem_gb = _parse_memory_gib(mem_str)
if mem_gb > 0:
node_memory[instance_type] = mem_gb
elif family == "ElastiCache Serverless":
engine = _normalize_engine(attrs.get("cacheEngine", ""))
operation = attrs.get("operation", "")
usagetype = attrs.get("usagetype", "")
if "Snapshot" in operation or "Backup" in usagetype:
continue
if not engine:
continue
key = "{}|{}".format(region, engine)
unit_lower = unit.lower()
if "gb-hour" in unit_lower or "CachedData" in usagetype:
serverless_storage[key] = price_per_unit
elif "processingunit" in unit_lower or "ProcessingUnits" in usagetype:
serverless_ecpu[key] = price_per_unit
# Parse Reserved terms for node-based instances
_valid_purchase_options = {"No Upfront", "Partial Upfront", "All Upfront"}
for sku, offers in reserved_terms.items():
product = products.get(sku)
if not product or product.get("productFamily") != "Cache Instance":
continue
attrs = product.get("attributes", {})
if attrs.get("locationType", "") != "AWS Region":
continue
if "ExtendedSupport" in attrs.get("usagetype", ""):
continue
region = attrs.get("regionCode", "")
instance_type = attrs.get("instanceType", "")
engine = _normalize_engine(attrs.get("cacheEngine", ""))
if not (region and instance_type and engine):
continue
for offer_id, offer in offers.items():
ta = offer.get("termAttributes", {})
purchase_option = ta.get("PurchaseOption", "")
if purchase_option not in _valid_purchase_options:
continue # skip legacy "Heavy Utilization"
lease = ta.get("LeaseContractLength", "") # "1yr" or "3yr"
hourly = 0.0
upfront = 0.0
for dim in offer.get("priceDimensions", {}).values():
try:
price = float(dim.get("pricePerUnit", {}).get("USD", "0"))
except (ValueError, TypeError):
continue
unit = dim.get("unit", "")
if unit == "Hrs":
hourly = price
elif unit == "Quantity":
upfront = price
key = "{}|{}|{}|{}|{}".format(
region, instance_type, engine, lease, purchase_option
)
reserved_pricing[key] = {"hourly": hourly, "upfront": upfront}
return {
"node_pricing": node_pricing,
"serverless_storage": serverless_storage,
"serverless_ecpu": serverless_ecpu,
"extended_support": extended_support,
"reserved_pricing": reserved_pricing,
"node_memory": node_memory,
}
def _get_od_price_with_unit(sku: str, terms: dict) -> Optional[Tuple[float, str]]:
"""Extract on-demand price and unit for a SKU from the terms section."""
sku_terms = terms.get(sku, {})
for offer in sku_terms.values():
dimensions = offer.get("priceDimensions", {})
for dim in dimensions.values():
try:
price = float(dim.get("pricePerUnit", {}).get("USD", "0"))
unit = dim.get("unit", "")
return (price, unit)
except (ValueError, TypeError):
continue
return None
def _parse_extended_support_years(usagetype: str) -> list:
"""Extract year tiers from an Extended Support usagetype string.
AWS usagetype format:
- "USE1-ExtendedSupportYr1_Yr2-NodeUsage:cache.r7g.large" -> years 1 and 2 (same rate)
- "USE1-ExtendedSupportYr3-NodeUsage:cache.r7g.large" -> year 3+
Returns a list of year strings, e.g. ["1", "2"] or ["3"].
"""
ut = usagetype.lower()
if "yr1_yr2" in ut:
return ["1", "2"]
if "yr3" in ut:
return ["3"]
if "yr1" in ut and "yr2" not in ut:
return ["1"]
if "yr2" in ut and "yr1" not in ut:
return ["2"]
# Fallback: generic extended support mention without year
if "extendedsupport" in ut.replace("-", "").replace("_", ""):
return ["1"]
return []
def _normalize_engine(engine_str: str) -> str:
"""Normalize engine name from bulk pricing to our standard names."""
eng = engine_str.lower().strip()
if "valkey" in eng:
return "valkey"
if "redis" in eng:
return "redis"
if "memcached" in eng:
return "memcached"
return eng
def _parse_memory_gib(mem_str: str) -> float:
"""Parse memory string like '103.68 GiB' into a float GB value."""
if not mem_str:
return 0.0
try:
parts = mem_str.strip().split()
return float(parts[0])
except (ValueError, IndexError):
return 0.0
class PricingLoader:
"""Load and look up ElastiCache pricing.
Priority:
1. Local CSV (if provided) - for offline or override use
2. Live AWS bulk pricing (fetched and cached locally for 7 days)
"""
def __init__(self, pricing_csv: Optional[str] = None):
self._serverless_storage: Dict[Tuple[str, str], float] = {}
self._serverless_ecpu: Dict[Tuple[str, str], float] = {}
self._node_od: Dict[Tuple[str, str, str], float] = {}
self._extended_support: Dict[Tuple[str, str, str, str], float] = {} # (region, itype, engine, year)
self._reserved: Dict[Tuple[str, str, str, str, str], dict] = {} # (region, itype, engine, lease, purchase) -> {"hourly", "upfront"}
self._node_memory: Dict[str, float] = {} # instance_type -> GB
if pricing_csv and os.path.exists(pricing_csv):
self._load_csv(pricing_csv)
elif pricing_csv:
raise FileNotFoundError(
"Pricing CSV not found: {}".format(pricing_csv)
)
else:
self._load_live()
def _load_live(self):
"""Load pricing from AWS bulk pricing (cached locally)."""
if _cache_is_fresh():
data = _load_cache()
else:
data = _fetch_and_cache()
for key, price in data.get("node_pricing", {}).items():
parts = key.split("|")
if len(parts) == 3:
region, itype, engine = parts
self._node_od[(region, itype, engine)] = price
for key, price in data.get("serverless_storage", {}).items():
parts = key.split("|")
if len(parts) == 2:
region, engine = parts
self._serverless_storage[(region, engine)] = price
for key, price in data.get("serverless_ecpu", {}).items():
parts = key.split("|")
if len(parts) == 2:
region, engine = parts
self._serverless_ecpu[(region, engine)] = price
for key, price in data.get("extended_support", {}).items():
parts = key.split("|")
if len(parts) == 4:
region, itype, engine, year = parts
self._extended_support[(region, itype, engine, year)] = price
for key, price_info in data.get("reserved_pricing", {}).items():
parts = key.split("|")
if len(parts) == 5:
region, itype, engine, lease, purchase = parts
self._reserved[(region, itype, engine, lease, purchase)] = price_info
self._node_memory = data.get("node_memory", {})
def _load_csv(self, path: str):
"""Load pricing from a local CSV."""
with open(path, newline="") as f:
for row in csv.DictReader(f):
family = row.get("Product Family", "")
region = row.get("Region Code", "")
engine = row.get("Cache Engine", "").lower()
term = row.get("TermType", "")
try:
price = float(row.get("PricePerUnit", "0"))
except (ValueError, TypeError):
continue
if price <= 0 or not region:
continue
if family == "Cache Instance" and term == "OnDemand":
itype = row.get("Instance Type", "")
if itype and row.get("Unit") == "Hrs":
self._node_od[(region, itype, engine)] = price
elif family == "ElastiCache Serverless":
unit = row.get("Unit", "")
operation = row.get("Operation", row.get("operation", ""))
if "Snapshot" in operation or unit == "GB-months":
continue
unit_lower = unit.lower()
if "gb-hour" in unit_lower:
self._serverless_storage[(region, engine)] = price
elif "processingunit" in unit_lower:
self._serverless_ecpu[(region, engine)] = price
# CSV loader only supports on-demand node and serverless pricing.
# Reserved pricing, Extended Support surcharges, and node memory data
# are only available from the live bulk pricing API.
if not self._reserved:
print(
"Note: CSV pricing does not include Reserved Instance or Extended Support data. "
"Use live pricing (omit --pricing-csv) for full coverage.",
file=sys.stderr,
)
def get_serverless_storage_rate(self, region: str, engine: str) -> float:
"""Get serverless storage rate in $/GB-hour."""
eng = engine.lower()
key = (region, eng)
if key in self._serverless_storage:
return self._serverless_storage[key]
raise ValueError(
"No serverless storage pricing found for region={}, engine={}. "
"Available: {}".format(region, eng, self._list_serverless_regions(eng))
)
def get_serverless_ecpu_rate(self, region: str, engine: str) -> float:
"""Get serverless ECPU rate in $ per single ECPU."""
eng = engine.lower()
key = (region, eng)
if key in self._serverless_ecpu:
return self._serverless_ecpu[key]
raise ValueError(
"No serverless ECPU pricing found for region={}, engine={}. "
"Available: {}".format(region, eng, self._list_serverless_regions(eng))
)
def get_node_hourly_rate(self, region: str, instance_type: str, engine: str = "valkey") -> float:
"""Get node on-demand hourly rate."""
eng = engine.lower()
key = (region, instance_type, eng)
if key in self._node_od:
return self._node_od[key]
raise ValueError(
"No node pricing found for region={}, instance_type={}, engine={}".format(
region, instance_type, eng
)
)
def get_node_monthly_rate(self, region: str, instance_type: str, engine: str = "valkey") -> float:
"""Get node on-demand monthly rate (hourly x 730 hours)."""
return self.get_node_hourly_rate(region, instance_type, engine) * 730
def get_extended_support_rate(self, region: str, instance_type: str, engine: str, year: str = "1") -> float:
"""Get Extended Support surcharge in $/node-hour for the given year tier.
Year tiers: '1' and '2' (same rate, from Yr1_Yr2), '3' (higher rate, from Yr3).
"""
eng = engine.lower()
key = (region, instance_type, eng, str(year))
if key in self._extended_support:
return self._extended_support[key]
raise ValueError(
"No Extended Support pricing found for region={}, instance_type={}, engine={}, year={}. "
"This may mean Extended Support pricing is not published for this combination.".format(
region, instance_type, eng, year
)
)
def has_extended_support_pricing(self) -> bool:
"""Check if any Extended Support pricing was loaded."""
return len(self._extended_support) > 0
def get_node_memory_gb(self, instance_type: str) -> float:
"""Get memory capacity in GB for a node type. Returns 0 if unknown."""
return self._node_memory.get(instance_type, 0.0)
def get_all_node_memory(self) -> dict:
"""Get the full instance_type -> memory_gb mapping."""
return dict(self._node_memory)
def _list_serverless_regions(self, engine: str) -> str:
"""List regions that have serverless pricing loaded for an engine."""
regions = sorted(set(
r for (r, e) in self._serverless_storage if e == engine
))
if len(regions) > 5:
return ", ".join(regions[:5]) + " and {} more".format(len(regions) - 5)
return ", ".join(regions) if regions else "none loaded"
# --- Reserved pricing methods ---
def get_reserved_rate(
self, region: str, instance_type: str, engine: str = "valkey",
lease_length: str = "1yr", purchase_option: str = "No Upfront",
) -> dict:
"""Get reserved pricing for a node.
Returns {"hourly": float, "upfront": float}.
- "No Upfront": upfront=0, hourly=full reserved rate
- "All Upfront": upfront=lump sum, hourly=0
- "Partial Upfront": upfront=partial lump sum, hourly=reduced rate
"""
eng = engine.lower()
key = (region, instance_type, eng, lease_length, purchase_option)
if key in self._reserved:
return self._reserved[key]
raise ValueError(
"No reserved pricing found for region={}, instance_type={}, engine={}, "
"lease={}, purchase={}".format(region, instance_type, eng, lease_length, purchase_option)
)
def get_reserved_effective_monthly(
self, region: str, instance_type: str, engine: str = "valkey",
lease_length: str = "1yr", purchase_option: str = "No Upfront",
) -> float:
"""Get effective monthly cost for a reserved node.
Amortizes upfront payment over the term and adds the recurring hourly cost.
Formula: (upfront / term_months) + (hourly * 730)
"""
rate = self.get_reserved_rate(region, instance_type, engine, lease_length, purchase_option)
term_months = 12 if lease_length == "1yr" else 36
monthly = (rate["upfront"] / term_months) + (rate["hourly"] * 730)
return round(monthly, 2)
def list_reserved_options(
self, region: str, instance_type: str, engine: str = "valkey",
) -> list:
"""List all available reserved pricing options for a node.
Returns a list of dicts with lease_length, purchase_option,
hourly, upfront, and effective_monthly.
"""
eng = engine.lower()
results = []
for (r, it, e, lease, purchase), rate in self._reserved.items():
if r == region and it == instance_type and e == eng:
term_months = 12 if lease == "1yr" else 36
effective = round(
(rate["upfront"] / term_months) + (rate["hourly"] * 730), 2
)
results.append({
"lease_length": lease,
"purchase_option": purchase,
"hourly": rate["hourly"],
"upfront": rate["upfront"],
"effective_monthly": effective,
})
results.sort(key=lambda x: x["effective_monthly"])
return results
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python, Needs Node.js
Security
What our scanner noticed· Medium risk
- References to credential files
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- AWS
- Publisher
- AWS (Official)
- Source
- aws/agent-toolkit-for-aws · skills/specialized-skills/database-skills/amazon-elasticache · commit 0a218f8
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by AWS.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download amazon-elasticache.zip