Redis fundamentals and the Go client
What Redis is, keys and expiry, INCR and EXPIRE, how a pipeline batches commands, and how to create a go-redis client and call it with a context and a timeout.
Learning outcomes
- Explain what Redis is and why a shared counter needs it once there are several API instances.
- Use INCR, EXPIRE and TTL and say what each returns.
- Design a key such as rl:{key}:{windowStart}.
- Create a go-redis v9 client, call a command with a context, and close the client.
- Explain the difference between a plain pipeline and a transaction pipeline at a high level.
Why a rate limiter needs Redis
The rate limiter you built earlier works inside one Go process. It stores counters in a map, protects shared state with a mutex, and uses an injected clock to decide when a window starts or a token becomes available.
That is sufficient when one API process handles every request. It stops being sufficient when the backend runs multiple instances.
Imagine deploying two copies of your API behind a load balancer. A load balancer distributes incoming requests across available servers. The same user might send one request to instance A and the next request to instance B.
Each process has its own memory. A map inside instance A is not shared with instance B. If both instances independently enforce a limit of 10 requests per minute, the user could make 10 requests to each instance and receive 20 requests in total.
This is the problem of distributed state: multiple processes need to read and update the same piece of information consistently.
A rate limit counter must live somewhere that all API instances can access. Redis provides that shared location.


What Redis is
Redis is an in-memory data structure server. It runs as a separate process, accepts commands over a network connection, and stores data in memory.
A data structure server provides operations on values rather than requiring every application to implement storage and synchronization itself. Redis supports strings, hashes, lists, sets, sorted sets, streams, and other data structures.
For this week's rate limiter, we mainly need Redis strings and a few commands that operate on integer values stored in those strings.
The architecture looks like this:
- Your Go API receives an HTTP request.
- The rate limiter constructs a Redis key for the request's identity and time window.
- The Go API sends a command to Redis.
- Redis updates the shared counter and returns the result.
- The API decides whether to allow the request or return HTTP 429.
Redis is a separate service, not a Go package embedded into your application. Every API instance connects to the same Redis server or Redis deployment.
Why keep counters in memory?
Redis is designed for fast access to data held in memory. A counter update does not require your API to read and rewrite a row in MySQL. Redis handles the operation directly.
Redis can also persist data to disk, but persistence is not important for the rate limiter counters in this course. A counter only matters for its current time window. Once that window ends, its count is no longer useful.
If Redis restarts and loses an unfinished counter, a user might temporarily receive a fresh allowance. That is a trade-off to understand, not a reason to make rate limiting depend on durable database storage.
Redis is not a replacement for MySQL. MySQL remains the durable source of truth for application data such as users, restaurants, orders, and payments. Redis is useful for fast, shared state such as counters, cache entries, and short-lived coordination data.
Run Redis locally
The course repository already includes Docker Compose configuration from lesson 1.2. From the repository root, start the services:
docker compose up -dThe -d flag runs the containers in the background. Check their status:
docker compose psYou should see the Redis container running. The exact service name and port mapping depend on the repository's Compose configuration. In the examples below, Redis is reachable at localhost:6379.
Open a Redis command-line client:
docker compose exec redis redis-cliIf your Compose service has a different name, substitute that service name. You can also use a locally installed redis-cli if it is configured to connect to the same host and port.
You are now interacting directly with Redis. Commands are entered into the Redis prompt, not into your Go program.
Test the connection
Start with:
PINGRedis should reply:
PONGPING is a simple health check. It confirms that the client can reach the Redis server and that Redis can respond.
Store and retrieve a value
Redis stores strings as key-value pairs. A key identifies a value.
SET greeting "hello"
GET greetingThe first command stores the value hello under the key greeting. The second retrieves it.
Redis replies with:
OK
"hello"You can delete the value:
DEL greetingDEL removes the specified key. It returns the number of keys that were removed.
Increment a counter
A Redis string can also represent an integer. The INCR command increments that integer:
INCR requests
INCR requests
GET requestsThe two increments return 1 and 2, and GET requests returns "2".
An important property of INCR is that it creates a missing key with an initial value of zero before incrementing it. Therefore, the first INCR on a missing key creates the key with value 1.
You do not need to issue a separate SET requests 0 command before using it.
Redis commands are individually atomic. An atomic command is executed as one indivisible operation from the perspective of other clients. Two clients incrementing the same key will not overwrite each other's increments.
This matters when multiple API instances update the same rate limit counter concurrently.
Give a key an expiry
A counter should not live forever. The time to live (TTL) of a key is the amount of time remaining before Redis automatically deletes it.
Use EXPIRE to set a lifetime in seconds:
EXPIRE requests 60
TTL requestsThe first command sets the key to expire after 60 seconds. The second reports the remaining lifetime. The returned value will be at most 60 and will decrease as time passes.
Redis uses two special TTL values:
-1means the key exists but has no expiry.-2means the key does not exist.
Try these cases:
SET permanent "value"
TTL permanent
TTL missing-keyThe first TTL returns -1, while the second returns -2.
Delete the keys you created:
DEL requests permanentInspect keys while developing
You can inspect keys with:
KEYS *This returns every key in the selected Redis database. It is convenient while experimenting locally, but you should not use KEYS in production.
KEYS scans the keyspace as one operation. On a large database, it can take a long time and block Redis from processing other commands while it runs. A production application should not depend on enumerating every key.
For interactive inspection, SCAN is a safer alternative because it iterates through keys in batches. Your rate limiter should not need to enumerate keys at all.
Designing a Redis fixed-window counter
Recall the fixed-window algorithm from lesson 1.9. A fixed window divides time into intervals of a known duration. Every request within one interval increments the same counter.
For a 60-second window, the first interval might cover timestamps from 12:00:00 through 12:00:59. The next interval starts at 12:01:00.
The application needs to calculate the start of the current window. If the current Unix timestamp is 1700000042 and the window is 60 seconds, the window start is:
1700000042 - (1700000042 % 60) = 1700000040A Unix timestamp is the number of seconds elapsed since 00:00:00 UTC on 1 January 1970. Truncating the timestamp to a window boundary gives every request in the same interval the same window start.
For a user with identity user:42, we can construct this Redis key:
rl:{key}:{windowStart}For example:
rl:user:42:1700000040The prefix rl identifies rate limiter keys. Colons separate the logical parts of the key, making it easier to inspect and understand. Redis treats the entire string as one key. Colons do not create nested objects or directories.
The window start is part of the key for an important reason: each time window must have an independent counter.
If you used only rl:user:42, the same counter would continue across window boundaries. You would need extra logic to determine whether its stored count belonged to the current interval. Including the window start makes the identity of the counter explicit.
The key lifecycle is straightforward:
- The first request in a window increments the key from zero to one.
- The key receives an expiry corresponding to the window duration.
- Further requests in that window increment the same key.
- When the expiry elapses, Redis removes the key.
- A request in the next window uses a different key.


Set expiry only once
There is a subtle detail when incrementing a counter repeatedly.
Suppose every request runs both INCR and EXPIRE 60. The expiry is reset to 60 seconds on every request. This creates a sliding expiry rather than an expiry tied to the original window. A continuously active user could keep the key alive beyond the end of the intended window.
Redis 7 supports the NX option for EXPIRE:
EXPIRE requests 60 NXNX means that Redis sets the expiry only if the key does not already have an expiry. The first request can establish the lifetime, and later requests will not extend it.
You can try it in the Redis prompt:
SET demo-counter 1
EXPIRE demo-counter 60 NX
TTL demo-counter
EXPIRE demo-counter 120 NX
TTL demo-counter
DEL demo-counterThe second EXPIRE does not replace the existing expiry. The remaining TTL continues to decrease.
This is useful for a fixed-window counter because the window's lifetime should not be extended by later requests.
Connect Go to Redis
Your Go API needs a Redis client library to send commands and interpret responses. The course uses go-redis, a widely used Go client for Redis.
From the backend directory, add the dependency:
go get github.com/redis/go-redis/v9The /v9 suffix identifies the module's major version. Go treats it as part of the import path, so use the same path in your source files.
Create a Redis client with redis.NewClient:
package main
import (
"github.com/redis/go-redis/v9"
)
func newRedisClient() *redis.Client {
return redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
}redis.Options configures the connection. Addr is the Redis server address. For local development, localhost:6379 is a common default. In a containerized deployment, the address may instead use the Redis Compose service name and port.
The returned *redis.Client is safe for concurrent use by multiple goroutines. You do not need to create a separate client for every HTTP request or protect the client itself with a mutex.
The client owns a connection pool. A connection pool maintains reusable network connections so requests do not need to establish a brand-new TCP connection for every Redis command.
This is different from your rate limiter's in-memory map. The map contains application state and needs synchronization. The Redis client manages its own concurrent connection handling.
Execute a command with a context
Every Redis operation should receive a context. The context allows the caller to cancel the operation or impose a deadline.
Here is a small program that connects to Redis, increments a counter, and prints the result:
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/redis/go-redis/v9"
)
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
defer rdb.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
value, err := rdb.Incr(ctx, "example-counter").Result()
if err != nil {
log.Fatal(err)
}
fmt.Println(value)
}Incr sends the Redis INCR command. Its Result() method returns two values: the integer result and an error.
The context has a one-second deadline. If the operation cannot complete within that time, the client can stop waiting and return an error.
defer rdb.Close() closes the client and its connections when the program exits. In a long-running API, create the client during application startup and close it during application shutdown. Do not create and close a Redis client for every HTTP request.
Result and Val
go-redis command methods return command objects. You can retrieve their results in two common ways:
value, err := rdb.Incr(ctx, "example-counter").Result()Or:
value := rdb.Incr(ctx, "example-counter").Val()Result() returns both the value and the error. Use it when the operation can fail and your application needs to respond appropriately.
Val() returns only the value. It is convenient when you deliberately do not need to inspect the error, but ignoring Redis errors in a rate limiter is usually a mistake.
For example, if Redis is unavailable and your code silently treats a failed increment as zero, it might accidentally allow every request. The later exercise introduces an explicit fallback policy. For now, always inspect the error.
Understand redis.Nil
Redis can return a special error when a command expects a value but the requested key does not exist.
go-redis represents this response with redis.Nil. It is different from a network failure or a Redis server error.
For example:
value, err := rdb.Get(ctx, "missing-key").Result()
if err == redis.Nil {
fmt.Println("key does not exist")
} else if err != nil {
log.Printf("Redis error: %v", err)
} else {
fmt.Println(value)
}The branches have different meanings:
redis.Nilmeans the requested key was missing.- Any other non-nil error means the command failed for another reason, such as a connection problem or timeout.
- A nil error means the command succeeded.
Do not compare every Redis error to redis.Nil. A missing key is often an expected condition, while a timeout is an operational failure that may require logging, fallback behavior, or a rejected request.
For INCR, a missing key is not an error because Redis creates it automatically. For GET, a missing key produces redis.Nil.
Keep Redis calls within the request budget
Your HTTP handlers already receive a request context through r.Context(). Lesson 1.17 introduced deriving a shorter timeout from that context.
This matters because Redis is a network dependency. Even though Redis is fast under normal conditions, it can become slow or unreachable because of network issues, server overload, or connection problems.
Imagine every incoming request waits several seconds for Redis. Your API can accumulate blocked handler goroutines, consume resources, and become unresponsive.
A short Redis timeout limits how long one request waits for the dependency.
For a rate limiter, a starting timeout might be 50 milliseconds:
func incrementCounter(
rdb *redis.Client,
requestCtx context.Context,
key string,
) (int64, error) {
ctx, cancel := context.WithTimeout(requestCtx, 50*time.Millisecond)
defer cancel()
return rdb.Incr(ctx, key).Result()
}The child context inherits cancellation from the request context. If the client disconnects or the request is cancelled, the Redis operation can be cancelled too. The 50-millisecond deadline also ensures that this particular call does not wait indefinitely.
This timeout is an example, not a universal production value. The right value depends on your latency budget, network environment, and Redis deployment. Measure actual latency before choosing one.
Avoid using context.Background() inside every handler for Redis calls. Doing so discards the request's cancellation and deadline. Use the request context as the parent.
Two Redis commands and the cost of a network round trip
A fixed-window counter needs two operations:
- Increment the counter.
- Set its expiry if it does not already have one.
You could issue them as separate calls:
func incrementAndExpireSeparately(
ctx context.Context,
rdb *redis.Client,
key string,
windowSeconds time.Duration,
) (int64, error) {
count, err := rdb.Incr(ctx, key).Result()
if err != nil {
return 0, err
}
_, err = rdb.ExpireNX(ctx, key, windowSeconds).Result()
if err != nil {
return 0, err
}
return count, nil
}The first call sends INCR and waits for its response. Only after receiving that response does the application send EXPIRE NX.
Each request therefore requires two network round trips. A network round trip is the time taken to send a command to Redis and receive its response.
Even if each Redis command takes very little time to execute, network latency can dominate the total duration. If your API is in another container or on another machine, the network cost becomes more noticeable.
There is another issue to think about: the two commands are separate operations. What happens if the first command succeeds but the second command fails? What if another request arrives between them?
We will address these questions in the next lesson.
Batch commands with a pipeline
A pipeline lets the client send several Redis commands together and read their replies together.
Instead of waiting for the response to INCR before sending EXPIRE, the client queues both commands and sends them as a batch.
Here is the same counter operation using a plain pipeline:
func incrementAndExpireWithPipeline(
ctx context.Context,
rdb *redis.Client,
key string,
windowSeconds time.Duration,
) (int64, error) {
pipe := rdb.Pipeline()
incrCmd := pipe.Incr(ctx, key)
expireCmd := pipe.ExpireNX(ctx, key, windowSeconds)
_, err := pipe.Exec(ctx)
if err != nil {
return 0, err
}
if err := incrCmd.Err(); err != nil {
return 0, err
}
if err := expireCmd.Err(); err != nil {
return 0, err
}
return incrCmd.Val(), nil
}The pipeline queues the two commands. Exec sends the queued commands and collects their responses. The incrCmd and expireCmd objects let you inspect the results of their respective commands.
This can reduce network overhead because the client does not need to wait for each individual response before sending the next command.
However, a pipeline does not make the commands atomic as a group. Atomicity means an operation is observed as one indivisible unit. Redis still executes the individual commands, and another client may execute commands between them.
A pipeline is a performance mechanism, not a transaction.
There is also an important error-handling detail. Exec can return an error, and individual queued commands have their own errors. Check both rather than assuming that a successful-looking command value proves the entire batch succeeded.
Think about the failure cases
Consider what happens in each variant:
- The separate-call version increments the key, but the connection fails before the expiry is set.
- The pipeline sends both commands, but another request executes between them.
- Redis executes one command successfully but reports an error for another command.
- A request is cancelled while the client is waiting for the pipeline response.
What happens to the counter? Can it remain without an expiry? Could a key live longer than the intended window? Does the returned count still represent the operation you expect?
Do not try to solve these cases by adding more commands to the pipeline. The next lesson covers Redis transactions, Lua scripts, and failure handling. Those tools provide the stronger execution guarantees needed for a correct shared counter.
Configure Redis for the course tests
The course's Redis integration tests use an environment variable named TEST_REDIS_ADDR.
This separates the Redis address used by tests from the address used by your local API configuration. Your code can read the environment variable and use it to construct the client.
For example:
package ratelimit
import (
"os"
"github.com/redis/go-redis/v9"
)
func newTestRedisClient() *redis.Client {
addr := os.Getenv("TEST_REDIS_ADDR")
if addr == "" {
addr = "localhost:6379"
}
return redis.NewClient(&redis.Options{
Addr: addr,
})
}This is a small test-oriented example. Your production API should have an explicit configuration path rather than silently depending on test environment variables.
The Redis integration tests are marked with the redis build tag. A build tag is a condition that controls whether Go includes particular files when compiling a package.
Run the ordinary tests with:
go test ./...Run the Redis integration tests with:
TEST_REDIS_ADDR=localhost:6379 go test -tags redis ./...The Redis service must be running and reachable at the configured address. If the tests run inside a container, localhost refers to that container itself, not necessarily the Redis container. Use the appropriate service address for that environment.
The redis build tag keeps integration tests separate from the default test run. This is useful because unit tests should remain fast and should not require a running Redis service.
What you should understand before the next lesson
You now have the basic pieces needed to use Redis from Go:
- Redis is a separate in-memory data structure server that multiple API instances can share.
INCRcreates a missing counter at one and returns its new value.EXPIREassigns a lifetime, whileTTLreports the remaining lifetime.EXPIRE NXsets an expiry only when the key does not already have one.- A fixed-window key includes both the request identity and the window start.
- A go-redis client is safe for concurrent use and manages a connection pool.
- Redis calls should use request-derived contexts with short timeouts.
- A pipeline batches commands to reduce network round trips, but does not make them atomic as a group.
The two counter implementations in this lesson are intentionally incomplete as production designs. The next lesson explains how to make the increment-and-expiry operation safe under concurrent requests and partial failures.
Knowledge assessment
An API runs on four instances, each enforcing a rate limit of 100 requests using a local Go map. What is the main problem?
Practical applications
- Exercise 1.22: Redis fixed-window limiter. Use a shared Redis counter, construct keys from the request identity and window start, set expiry, and integrate Redis with the limiter's failure behavior.
- Optional exercise 1.26: Build on the Redis counter and fixed-window concepts when implementing an additional rate limiting algorithm.
- Optional exercise 1.29: Apply Redis command execution techniques to a more advanced rate limiter implementation.
References
Everything above is explained on this page; these are where it comes from (Redis 7, go-redis v9).