Store one-time login codes and resend cooldowns in Redis from a Go Fiber v3 API, with Encore running Redis locally and on ElastiCache or Memorystore, or with go-redis and gofiber/storage.

Fiber is the Go web framework built on fasthttp with an Express-style API, and v3 is the current major version, with handlers that take a fiber.Ctx interface and a minimum of Go 1.26 (the Fiber tutorial covers the v3 API). Adding Redis to it is mostly about where the Redis comes from: every developer needs one on their laptop, each environment needs an ElastiCache or Memorystore cluster with TLS and auth, and the app needs a network path to a cache that only answers inside the VPC.
This guide adds Redis to a Fiber API that sends one-time login codes, limits wrong guesses and blocks rapid resends. It starts with Encore, which declares the cache in Go next to the Fiber handlers and runs it locally and in your own AWS or GCP account, then shows the same flow with go-redis, ElastiCache and the Redis storage driver for Fiber's limiter.
Encore works alongside Fiber: the routes stay Fiber handlers, and the Redis they call is a typed Go declaration in the same file. Fiber's adaptor turns a *fiber.App into a net/http handler, so Encore mounts the app in one raw endpoint with a fallback route. The caching API gives each kind of data its own keyspace, with a key pattern and an expiry.
Run in your terminal to get started locally.
The service below keeps three kinds of state in one cluster. codes holds the SHA-256 of the current code for an address for ten minutes, attempts counts wrong guesses, and cooldown is a one-minute marker written with SetIfNotExists, which maps to a single SET NX, so two quick resend requests cannot both get a new code. The cluster uses NoEviction, since a login code dropped under memory pressure looks to the user like a broken product:
// auth/auth.go
package auth
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"errors"
"fmt"
"math/big"
"net/http"
"strings"
"time"
"encore.dev"
"encore.dev/rlog"
"encore.dev/storage/cache"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/adaptor"
)
// Login codes must not be evicted early, so the cluster refuses writes
// when memory is full instead of dropping keys.
var cluster = cache.NewCluster("login", cache.ClusterConfig{
EvictionPolicy: cache.NoEviction,
})
// The SHA-256 of the current code for an email address, valid for 10 minutes.
var codes = cache.NewStringKeyspace[string](cluster, cache.KeyspaceConfig{
KeyPattern: "code/:key",
DefaultExpiry: cache.ExpireIn(10 * time.Minute),
})
// Failed verification attempts per email address.
var attempts = cache.NewIntKeyspace[string](cluster, cache.KeyspaceConfig{
KeyPattern: "attempts/:key",
DefaultExpiry: cache.ExpireIn(15 * time.Minute),
})
// Set while a resend is blocked, one code per minute per address.
var cooldown = cache.NewStringKeyspace[string](cluster, cache.KeyspaceConfig{
KeyPattern: "cooldown/:key",
DefaultExpiry: cache.ExpireIn(time.Minute),
})
const maxAttempts = 5
//encore:service
type Service struct {
handler http.HandlerFunc
}
func initService() (*Service, error) {
app := fiber.New()
app.Post("/login/code", sendCode)
app.Post("/login/verify", verifyCode)
return &Service{handler: adaptor.FiberApp(app)}, nil
}
// Fallback hands every request that no Encore endpoint matches to Fiber.
//
//encore:api public raw path=/!fallback
func (s *Service) Fallback(w http.ResponseWriter, req *http.Request) {
s.handler(w, req)
}
type codeRequest struct {
Email string `json:"email"`
Code string `json:"code"`
}
func sendCode(c fiber.Ctx) error {
var in codeRequest
if err := c.Bind().Body(&in); err != nil || !strings.Contains(in.Email, "@") {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "email is required"})
}
email := strings.ToLower(strings.TrimSpace(in.Email))
ctx := c.Context()
// SetIfNotExists is one SET NX: only the first request per minute gets through.
if err := cooldown.SetIfNotExists(ctx, email, "1"); errors.Is(err, cache.KeyExists) {
return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{"error": "wait a minute before asking for a new code"})
} else if err != nil {
return err
}
n, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
if err != nil {
return err
}
code := fmt.Sprintf("%06d", n.Int64())
if err := codes.Set(ctx, email, hash(code)); err != nil {
return err
}
if _, err := attempts.Delete(ctx, email); err != nil {
return err
}
// Send the code with your email provider here. Locally it is logged instead.
if encore.Meta().Environment.Cloud == encore.CloudLocal {
rlog.Info("login code", "email", email, "code", code)
}
return c.SendStatus(fiber.StatusAccepted)
}
func verifyCode(c fiber.Ctx) error {
var in codeRequest
if err := c.Bind().Body(&in); err != nil || in.Email == "" || len(in.Code) != 6 {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "email and a 6-digit code are required"})
}
email := strings.ToLower(strings.TrimSpace(in.Email))
ctx := c.Context()
failed, err := attempts.Get(ctx, email)
if err != nil && !errors.Is(err, cache.Miss) {
return err
}
if failed >= maxAttempts {
return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{"error": "too many attempts, request a new code"})
}
stored, err := codes.Get(ctx, email)
if errors.Is(err, cache.Miss) {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "code expired or never sent"})
} else if err != nil {
return err
}
if subtle.ConstantTimeCompare([]byte(stored), []byte(hash(in.Code))) != 1 {
if _, err := attempts.Increment(ctx, email, 1); err != nil {
return err
}
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "wrong code"})
}
// GetAndDelete makes the code single-use, even if two requests race.
if _, err := codes.GetAndDelete(ctx, email); errors.Is(err, cache.Miss) {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "code already used"})
} else if err != nil {
return err
}
_, _ = attempts.Delete(ctx, email)
// Issue your session or token here.
return c.JSON(fiber.Map{"email": email, "verified": true})
}
func hash(code string) string {
sum := sha256.Sum256([]byte(code))
return hex.EncodeToString(sum[:])
}
Running it with encore run, the first POST /login/code returns 202, a second request inside a minute returns 429, and GetAndDelete makes a correct code single-use. The Fiber adaptor does not copy the net/http request context into Fiber, so c.Context() is a background context and a client disconnect will not cancel the handler. On deploy, Encore provisions ElastiCache on AWS or Memorystore on GCP in your own account and wires the connection into the service.
A coding agent that adds, say, a per-IP limit on /login/code adds one more keyspace and the check in the same handler file, and encore run gives it a Redis to exercise the change against before anyone reviews the diff.
Best fit: Fiber APIs that keep short-lived state such as codes, sessions and limits in Redis and want the same cache on a laptop and in their own AWS or GCP account.
The hand-built version uses go-redis for the codes and the Redis driver from gofiber/storage for Fiber's limiter middleware, which keeps its counters in process memory unless you give it a Storage. Passing the same go-redis client through NewFromConnection keeps one connection pool for both:
package main
import (
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"log"
"os"
"time"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/limiter"
redisstore "github.com/gofiber/storage/redis/v3"
"github.com/redis/go-redis/v9"
)
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS_ADDR"), // ElastiCache primary endpoint:6379
Password: os.Getenv("REDIS_AUTH_TOKEN"),
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12},
})
app := fiber.New()
// Share the limiter counters across replicas by keeping them in Redis.
app.Use("/login", limiter.New(limiter.Config{
Max: 10,
Expiration: time.Minute,
Storage: redisstore.NewFromConnection(rdb),
}))
app.Post("/login/code", func(c fiber.Ctx) error {
var in struct {
Email string `json:"email"`
}
if err := c.Bind().Body(&in); err != nil {
return fiber.ErrBadRequest
}
// SET NX with a TTL: one code per address per minute.
ok, err := rdb.SetNX(c.Context(), "cooldown:"+in.Email, 1, time.Minute).Result()
if err != nil {
return err
}
if !ok {
return c.SendStatus(fiber.StatusTooManyRequests)
}
hash := sha256Hex(sixDigitCode())
if err := rdb.Set(c.Context(), "code:"+in.Email, hash, 10*time.Minute).Err(); err != nil {
return err
}
return c.SendStatus(fiber.StatusAccepted)
})
app.Post("/login/verify", verifyCode(rdb))
log.Fatal(app.Listen(":8080"))
}
func sixDigitCode() string {
var n uint32
b := make([]byte, 4)
if _, err := rand.Read(b); err != nil {
log.Fatal(err)
}
n = uint32(b[0])<<16 | uint32(b[1])<<8 | uint32(b[2])
return fmt.Sprintf("%06d", n%1000000)
}
func sha256Hex(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
func verifyCode(rdb *redis.Client) fiber.Handler {
return func(c fiber.Ctx) error {
var in struct {
Email string `json:"email"`
Code string `json:"code"`
}
if err := c.Bind().Body(&in); err != nil {
return fiber.ErrBadRequest
}
// INCR and EXPIRE in one pipeline so a crash cannot leave a counter
// without a TTL. Expire is set on every increment; Redis treats that
// as a reset of the existing expiry.
pipe := rdb.TxPipeline()
incr := pipe.Incr(c.Context(), "attempts:"+in.Email)
pipe.Expire(c.Context(), "attempts:"+in.Email, 10*time.Minute)
if _, err := pipe.Exec(c.Context()); err != nil {
return err
}
if incr.Val() > 5 {
return c.SendStatus(fiber.StatusTooManyRequests)
}
// Compare and delete atomically so a wrong guess cannot consume the code.
consume := redis.NewScript(`
local stored = redis.call("GET", KEYS[1])
if stored == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0
`)
deleted, err := consume.Run(c.Context(), rdb, []string{"code:" + in.Email}, sha256Hex(in.Code)).Int()
if err != nil {
return err
}
if deleted != 1 {
return c.SendStatus(fiber.StatusUnauthorized)
}
return c.SendStatus(fiber.StatusOK)
}
}
Locally, the TLS config has to be switched off for a plain Redis container. In AWS you create a replication group in private subnets with a subnet group and a security group that allows port 6379 from the app, and turn on in-transit encryption and an auth token, which then has to reach the app as a secret in every environment. A compact Terraform shape for the cache itself looks like this:
resource "aws_elasticache_replication_group" "login" {
replication_group_id = "fiber-login"
description = "Login codes and limiter counters"
engine = "valkey"
engine_version = "8.0"
node_type = "cache.t4g.small"
num_cache_clusters = 2
port = 6379
subnet_group_name = aws_elasticache_subnet_group.login.name
security_group_ids = [aws_security_group.redis.id]
at_rest_encryption_enabled = true
transit_encryption_enabled = true
auth_token = var.redis_auth_token
automatic_failover_enabled = true
}
The Fiber task needs REDIS_ADDR set to the primary endpoint and REDIS_AUTH_TOKEN injected from Secrets Manager, and the Redis security group should allow 6379 only from the API security group, not from the internet. For local development, run a Redis or Valkey container on 6379 without TLS and point REDIS_ADDR at localhost:6379, and leave TLSConfig unset so the same go-redis client works on a laptop and against ElastiCache. A small wrapper around redis.NewClient that sets TLSConfig only when REDIS_TLS=1 keeps one codebase for both.
Best fit: teams that already manage ElastiCache in Terraform and want direct access to every Redis command and client option.
For abuse protection on a single instance, Fiber's limiter with its default memory storage needs no Redis at all: app.Use(limiter.New(limiter.Config{Max: 10, Expiration: time.Minute})) uses c.IP() as the key and a fixed window by default. Each replica keeps its own counters, so three instances allow three times the limit and a deploy resets them, and it does nothing for data such as login codes that another instance has to read. When the service sits behind a proxy, set KeyGenerator to something stable, such as a hash of an API key, because c.IP() would otherwise be the load balancer for every request.
Best fit: a single Fiber instance that only needs a rough request limit.
Pick Encore when the Fiber app needs Redis for more than one thing and you want it declared in code, running locally with encore run and provisioned as ElastiCache or Memorystore in your own account. Pick go-redis with ElastiCache when the cache already lives in Terraform and you want the full command set and client options. The in-memory limiter fits a single instance with no shared state.
Create one Redis client at startup, for example redis.NewClient from go-redis, and call it from handlers with c.Context(). For Fiber middleware that needs shared state, such as the limiter, pass gofiber/storage/redis as the Storage option so every replica reads the same counters.
Declare a cluster with cache.NewCluster and typed keyspaces such as cache.NewStringKeyspace, mount the Fiber app in a raw endpoint with path=/!fallback through adaptor.FiberApp, and call the keyspaces from Fiber handlers. encore run provides Redis locally, and deploys get ElastiCache on AWS or Memorystore on GCP in your own account.
Not by default. The limiter keeps its counters in process memory unless you set the Storage option, so three replicas each allow the full limit. Setting Storage to a Redis store from gofiber/storage shares the counters between replicas.
Use noeviction for data that must not disappear before it expires, such as one-time codes and sessions. With an LRU policy, Redis can drop a valid code under memory pressure and the user gets a confusing expired-code error.
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.