Oct 23, 20265 min read

How to Have an AI Agent Add a Redis Cache to a Go API on AWS

Asking Claude Code or Cursor to add caching gets you a Redis client in minutes. Here is what else it takes on AWS, and how Encore turns the cache into part of the application.

A slow endpoint is one of the most common things people hand to a coding agent, and "add a Redis cache" is the usual answer. The code is short and the agent will write it correctly.

The open questions are about everything around it: which cluster the code talks to, how that cluster is reached from the service, and what happens when many requests miss the cache at once, the problem known as a cache stampede.

This guide goes through both routes on AWS for a Go API that caches product lookups.

The two routes at a glance

QuestionWith Encorego-redis and ElastiCache by hand
What the agent writesA cluster and a typed keyspace, used in the endpointClient setup and JSON encoding
Local developmentencore run gives you a working cacheA local Redis you start and configure
AWS resourcesElastiCache Redis, provisioned on deployA cluster and its network setup, created by you
Connection detailsWired by Encore per environmentAn address variable set in every environment
Who touches AWSEncore's IAM roleWhoever applies the infrastructure change

The hand-built route: go-redis and ElastiCache

A typical agent-written cache with go-redis reads an address from the environment and handles misses and encoding itself:

var rdb = redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDR")}) func CachedProduct(ctx context.Context, id int64, load func(context.Context, int64) (*Product, error)) (*Product, error) { key := fmt.Sprintf("product/%d", id) raw, err := rdb.Get(ctx, key).Bytes() if err == nil { var p Product if err := json.Unmarshal(raw, &p); err == nil { return &p, nil } } else if !errors.Is(err, redis.Nil) { return nil, err } p, err := load(ctx, id) if err != nil { return nil, err } data, _ := json.Marshal(p) return p, rdb.Set(ctx, key, data, 10*time.Minute).Err() }

The code is fine, and the work it implies sits outside the repo. Amazon ElastiCache clusters live inside a VPC, so the cluster needs a subnet group in the same network as the service and a security group that admits the service's traffic. Then REDIS_ADDR has to be set for staging and production, and a local Redis is needed for development. The eviction policy matters too: Redis only evicts keys under memory pressure according to the policy you configure, and the wrong one turns a full cache into write errors.

An agent can draft each of those pieces, but applying them means AWS permissions, and the code change alone gives the reviewer no sign that the infrastructure exists.

Encore: the cache as part of the application

Encore

Encore combines an open source SDK, where the application declares the infrastructure it uses, with a platform that provisions that infrastructure in your own AWS account. A cache is a cluster and a typed keyspace, using Encore's caching package:

package catalog import ( "context" "errors" "time" "encore.dev/storage/cache" ) var cluster = cache.NewCluster("catalog-cache", cache.ClusterConfig{ EvictionPolicy: cache.AllKeysLRU, }) var products = cache.NewStructKeyspace[int64, Product](cluster, cache.KeyspaceConfig{ KeyPattern: "product/:key", DefaultExpiry: cache.ExpireIn(10 * time.Minute), }) //encore:api public method=GET path=/products/:id/cached func GetCached(ctx context.Context, id int64) (*Product, error) { cached, err := products.Get(ctx, id) if err == nil { return &cached, nil } else if !errors.Is(err, cache.Miss) { return nil, err } product, err := Get(ctx, id) if err != nil { return nil, err } if err := products.Set(ctx, id, *product); err != nil { return nil, err } return product, nil }

The keyspace is typed, so the agent cannot write a string where a product belongs, and the key pattern and expiry live next to the code that uses them. The eviction policy is part of the declaration instead of a setting on a cluster somewhere else.

Under encore run the cache works locally with no setup, and Postgres starts locally for the Get call behind it. On deploy, Encore provisions ElastiCache Redis in your account, inside the VPC it creates for the app, and connects the service to it. Node types and replica counts are configured per environment, not in the code.

An agent connected to the local MCP server can call the endpoint twice and read both traces to confirm the second request is served from the cache. Its diff is limited to Go code, and cloud access sits with Encore's IAM role, not the agent.

Good to know

A cache does not protect against a stampede by itself, because if a hot key expires under heavy load, many requests can call Get at once. For a handful of hot keys, a short in-process lock per key or a staggered expiry is usually enough. At larger scale, Facebook's memcache paper describes leases, which let one client refill a missing key while the others wait.

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

Run in your terminal to get started locally.

How to choose

  • Encore when you want the agent's cache change to carry its own infrastructure, so the pull request includes everything needed to run it on AWS.
  • go-redis with ElastiCache when the cluster already exists and is shared with other systems, and the service only needs a client and an address.

Frequently asked questions

How do I get an AI agent to add a Redis cache to my Go API on AWS?

With Encore, ask the agent to declare a cache cluster and a typed keyspace with cache.NewCluster and cache.NewStructKeyspace, and use it in the endpoint. encore run gives you a working cache locally, and on deploy Encore provisions ElastiCache Redis in your AWS account. Without Encore, the agent writes go-redis code against a REDIS_ADDR variable, and someone provisions ElastiCache with its network setup and wires the endpoint into each environment.

What should be cached in a backend API?

Reads that are expensive and tolerate slightly stale data, such as product details or computed aggregates. Set an expiry on every key so stale entries age out, and keep the database as the source of truth.

Does the agent need AWS access to create the cache?

Not with Encore. The agent changes Go code, and cloud access sits with Encore's IAM role, not the agent. Cluster sizing is set per environment, outside the code the agent edits.

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