Updated Nov 25, 20267 min read

Set Up ElastiCache Redis Without Terraform

What an ElastiCache Redis or Valkey cluster needs on AWS, from subnet groups and security groups to TLS, auth and failover, how the console and CLI paths compare with Terraform, and how to get a cache in your own AWS account from keyspaces declared in code.

Illustration for Set Up ElastiCache Redis Without Terraform

ElastiCache is the managed Redis and Valkey service on AWS, and teams reach for it once a database starts carrying session data, rate limits or the results of slow upstream calls.

Creating the cluster takes minutes, but it also needs a subnet group, security group rules, TLS, an auth token and a second Redis for local development, since the cluster cannot be reached from a laptop. This guide covers those pieces and then sets up the same cache from code.

What does ElastiCache need on AWS?

PieceWhy it is needed
Private subnets in two or more Availability ZonesElastiCache nodes live in your VPC with no public endpoint
Cache subnet groupTells ElastiCache which subnets it may place nodes in
Security groupAllows port 6379 only from the application's security group
Replication groupThe primary and replicas, node type, engine and version
Encryption and authIn-transit TLS, at-rest encryption, and an auth token or RBAC users
Multi-AZ and automatic failoverPromotes a replica when the primary fails
Client configurationThe primary endpoint, TLS settings and credentials in every service

The subnet group docs cover the networking step, and the in-transit encryption docs explain that clients must connect with TLS once it is on, which is also a precondition for using an auth token. RBAC replaces the single token with users and access strings, at the cost of another set of resources to manage.

What are the options besides Terraform?

The console wizard creates a working cluster in a few minutes, and it is hard to repeat the same choices for staging and production a month later. The AWS CLI makes the steps scriptable:

~
$ aws elasticache create-cache-subnet-group \ --cache-subnet-group-name app-cache \ --cache-subnet-group-description "App cache" \ --subnet-ids subnet-0a1b2c3d subnet-4e5f6a7b$ aws elasticache create-replication-group \ --replication-group-id app-cache \ --replication-group-description "App cache" \ --engine valkey --cache-node-type cache.t4g.medium \ --num-cache-clusters 2 --automatic-failover-enabled --multi-az-enabled \ --cache-subnet-group-name app-cache --security-group-ids sg-0c1d2e3f \ --transit-encryption-enabled --at-rest-encryption-enabled

The script still assumes a VPC, subnets and a security group that exist already, it does not update a cluster whose settings drift, and the endpoint and credentials have to reach each service by hand, as the create-replication-group reference makes clear from its long list of options. CloudFormation and CDK describe the same resources in another format, and the Terraform resource has the same shape, so none of these removes the second Redis that local development needs.

How does Encore set up ElastiCache?

Encore brings infrastructure from code, so the cache is declared in the service that uses it, as a cluster with typed keyspaces, and Encore provisions ElastiCache for Redis in your own AWS account when you deploy, or Memorystore on GCP, as the AWS infrastructure docs describe. Under encore run the same cluster is an in-memory Redis implementation, so there is no container to start and no endpoint to configure.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop --example=hello-world$ cd shop && mkdir catalog

Declare the cache and use it

The catalog service below puts a five-minute cache in front of a slow upstream catalog and adds a fixed-window rate limit per API key, with both keyspaces on one cluster:

// catalog/catalog.go package catalog import ( "context" "encoding/json" "errors" "fmt" "net/http" "time" "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/storage/cache" ) // A Redis cluster: ElastiCache on AWS, Memorystore on GCP, in-memory under `encore run`. var cluster = cache.NewCluster("catalog-cache", cache.ClusterConfig{ EvictionPolicy: cache.AllKeysLRU, }) type Product struct { SKU string `json:"sku"` Name string `json:"name"` PriceCents int `json:"price_cents"` } // Cached copies of products from the slow upstream catalog, kept for five minutes. var products = cache.NewStructKeyspace[string, Product](cluster, cache.KeyspaceConfig{ KeyPattern: "product/:key", DefaultExpiry: cache.ExpireIn(5 * time.Minute), }) // Requests per API key in the current minute, for a fixed-window rate limit. var requests = cache.NewIntKeyspace[string](cluster, cache.KeyspaceConfig{ KeyPattern: "requests/:key", DefaultExpiry: cache.ExpireIn(time.Minute), }) const limitPerMinute = 60 // lookupAPIKey resolves a token to a stable principal. In production this is a // database or secret-backed lookup, never a pass-through of the raw token. var lookupAPIKey = func(token string) (auth.UID, bool) { return "", false } //encore:authhandler func AuthHandler(ctx context.Context, token string) (auth.UID, error) { id, ok := lookupAPIKey(token) if !ok { return "", &errs.Error{Code: errs.Unauthenticated, Message: "unknown API key"} } return id, nil } //encore:api auth method=GET path=/products/:sku func GetProduct(ctx context.Context, sku string) (*Product, error) { uid, ok := auth.UserID() if !ok { return nil, &errs.Error{Code: errs.Unauthenticated, Message: "missing auth"} } // Fail closed if the limiter is unavailable, and count by the resolved principal. n, err := requests.Increment(ctx, string(uid), 1) if err != nil { return nil, err } if n > limitPerMinute { return nil, &errs.Error{Code: errs.ResourceExhausted, Message: "rate limit exceeded"} } prod, err := products.Get(ctx, sku) if err == nil { return &prod, nil } if !errors.Is(err, cache.Miss) { return nil, err } prod, err = loadProduct(ctx, sku) if err != nil { return nil, err } if err := products.Set(ctx, sku, prod); err != nil { return nil, err } return &prod, nil } // loadProduct calls the upstream catalog; tests replace it. var loadProduct = func(ctx context.Context, sku string) (Product, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://catalog.internal.example.com/products/"+sku, nil) if err != nil { return Product{}, err } resp, err := http.DefaultClient.Do(req) if err != nil { return Product{}, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return Product{}, fmt.Errorf("catalog returned %d", resp.StatusCode) } var prod Product err = json.NewDecoder(resp.Body).Decode(&prod) return prod, err }
// catalog/catalog_test.go package catalog import ( "context" "testing" "encore.dev/beta/auth" "encore.dev/beta/errs" ) func TestGetProductCachesAndLimits(t *testing.T) { calls := 0 loadProduct = func(ctx context.Context, sku string) (Product, error) { calls++ return Product{SKU: sku, Name: "Enamel mug", PriceCents: 1200}, nil } lookupAPIKey = func(token string) (auth.UID, bool) { if token == "test-key" { return "acct_1", true } return "", false } ctx := auth.WithContext(context.Background(), "acct_1", nil) for i := 0; i < limitPerMinute; i++ { if _, err := GetProduct(ctx, "MUG-1"); err != nil { t.Fatalf("request %d: %v", i+1, err) } } if calls != 1 { t.Fatalf("upstream called %d times, want 1", calls) } _, err := GetProduct(ctx, "MUG-1") if errs.Code(err) != errs.ResourceExhausted { t.Fatalf("request over the limit: got %v, want ResourceExhausted", err) } }

encore test ./... runs the test against a fresh in-memory cache for each test, and encore run serves the endpoint locally, so the cache hit, the limit and the resource_exhausted error can be checked with curl before anything is deployed. The caching docs describe the other keyspace types, such as lists and sets, and the eviction policies a cluster can use.

To deploy, connect your AWS account as described in Connect your cloud account and push. Encore creates the ElastiCache cluster in private subnets, with its security group and credentials, and gives the catalog service access to it, so the endpoint and token never appear in configuration files.

A coding agent asked to cache another lookup adds a keyspace with its own KeyPattern in the same change, and Encore rejects a pattern that conflicts with an existing one before the code runs.

Best fit: Teams that want Redis on AWS for caching and rate limits, declared by the services that use it, with the same cache running in tests and on a laptop.

Which approach should you use?

Use Terraform or CloudFormation when a platform team runs shared ElastiCache clusters for many applications and owns their sizing and upgrades. Use Encore when the cache belongs to the application, and you want each new keyspace to ship with the code that reads it and run locally without a container.

Frequently asked questions

What do I need to create an ElastiCache Redis cluster?

A VPC with private subnets, a cache subnet group listing them, a security group that allows port 6379 from the application's security group, and the replication group itself with a node type, engine version and the number of replicas. Production setups add in-transit and at-rest encryption, an auth token or RBAC users, Multi-AZ and automatic failover.

Can I connect to ElastiCache from my laptop?

Not directly. ElastiCache has no public endpoint and is reached from inside its VPC, so local development usually runs a separate Redis or Valkey in Docker, and debugging the deployed cluster goes through a bastion host, a VPN or Session Manager port forwarding.

Should I use Redis or Valkey on ElastiCache?

Valkey is the open source fork of Redis that AWS supports on ElastiCache, it speaks the same protocol, and AWS prices Valkey nodes below Redis OSS nodes of the same type according to the ElastiCache pricing page. Existing Redis clients work with both.

How do I get ElastiCache in my own AWS account with no Terraform?

With Encore you declare a cache cluster and typed keyspaces in the service code. Deploying to your AWS account provisions ElastiCache for Redis with the networking and access it needs, and encore run uses an in-memory Redis implementation locally, so no Docker container is needed for the cache.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders