Redis atomicity, transactions, Lua and failure handling

Why INCR then EXPIRE must not be split, how MULTI/EXEC and a Lua script make steps atomic, how EVALSHA caches a script, and how to fail open with an in-memory fallback and a single log line.

Learning outcomes

  • Explain what goes wrong when INCR and EXPIRE are sent separately.
  • Use a go-redis TxPipeline with INCR and EXPIRE NX and say what MULTI/EXEC does and does not roll back.
  • Explain what a Lua script gives you and how EVALSHA and NOSCRIPT work.
  • Set a short timeout, fall back to an in-memory limiter, and log the first failure once.
  • State the consequences of failing open.

Why Redis operations need stronger guarantees

In lesson 1.20, you used Redis to store a fixed-window rate limit counter. The basic operation involved two commands:

  1. INCR increments the counter.
  2. EXPIRE NX assigns an expiry if the key does not already have one.

You also saw that a plain pipeline can send both commands together, reducing network round trips.

There is still a correctness problem to solve. Sending two commands together does not guarantee that they execute as one indivisible operation. If the first command succeeds but the second does not, the counter can be left in an invalid state.

This lesson introduces three ways to execute related Redis commands:

  • A transaction, which executes a queued group of commands without other clients interleaving.
  • A Lua script, which runs conditional logic atomically inside Redis.
  • A fallback strategy, which keeps the API available when Redis cannot be reached.

These mechanisms solve different problems. Choosing the right one requires understanding exactly what guarantees each provides.

The failure between INCR and EXPIRE

Consider this implementation from the previous lesson:

go
func incrementAndExpire(
	ctx context.Context,
	rdb *redis.Client,
	key string,
	window time.Duration,
) (int64, error) {
	count, err := rdb.Incr(ctx, key).Result()
	if err != nil {
		return 0, err
	}

	_, err = rdb.ExpireNX(ctx, key, window).Result()
	if err != nil {
		return 0, err
	}

	return count, nil
}

The code looks reasonable, but the two commands are independent network operations.

Imagine Redis successfully executes INCR. The counter becomes 1. Before the application can send or complete EXPIRE NX, the connection drops.

The counter now exists without an expiry.

A key without an expiry remains in Redis until something explicitly deletes it. Every future request increments the same counter. The fixed window never resets because the key never disappears.

A timeout can create the same uncertainty. Your application might stop waiting for a response even though Redis has already executed the command.

Show two timelines: in the first, INCR succeeds but the connection drops before EXPIRE, leaving a counter with no TTL; in the second, MULTI queues INCR and EXPIRE NX and EXEC runs both without another client interleaving.Show two timelines: in the first, INCR succeeds but the connection drops before EXPIRE, leaving a counter with no TTL; in the second, MULTI queues INCR and EXPIRE NX and EXEC runs both without another client interleaving.

A plain pipeline does not eliminate this failure. It reduces network round trips, but it does not make the commands atomic as a group. Redis still executes the individual commands, and a failure can leave the application uncertain about which commands took effect.

There is another mistake worth avoiding: running EXPIRE key 60 on every request. That resets the expiry to 60 seconds each time. A continuously active user can keep extending the key's lifetime. The counter then behaves like a sliding expiry instead of a fixed window.

We need a way to ensure that the increment and initial expiry are executed together, without resetting an existing expiry.

Redis transactions with MULTI and EXEC

A Redis transaction groups multiple commands so Redis executes them sequentially without commands from other clients being interleaved between them.

Redis provides two main commands for this:

  • MULTI begins a transaction.
  • EXEC executes the commands queued after MULTI.

When Redis receives commands after MULTI, it queues them instead of executing them immediately. When it receives EXEC, it runs the queued commands in order and returns their results.

For example, in redis-cli:

redis
MULTI
INCR rl:user:42:1700000000
EXPIRE rl:user:42:1700000000 60 NX
EXEC

The two commands are queued and then executed together when EXEC is received.

Other clients cannot insert their commands between the queued INCR and EXPIRE NX operations. This is the guarantee we need for the fixed-window counter.

Use TxPipeline in go-redis

The go-redis client provides TxPipeline() to execute commands through a Redis transaction.

Here is the fixed-window operation using it:

go
func incrementAndExpireTransaction(
	ctx context.Context,
	rdb *redis.Client,
	key string,
	window time.Duration,
) (int64, error) {
	pipe := rdb.TxPipeline()

	incrCmd := pipe.Incr(ctx, key)
	expireCmd := pipe.ExpireNX(ctx, key, window)

	_, 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 important difference is TxPipeline() instead of Pipeline().

The client queues both commands and executes them using Redis transaction semantics. Exec sends the transaction and returns the results. The individual command objects let you inspect the result or error of each command.

ExpireNX is important here. It sets the expiry only if the key does not already have one. The first request in a window establishes the expiry. Later requests increment the counter without extending that expiry.

This example assumes Redis 7 or later, which supports the NX option for EXPIRE.

What a Redis transaction does not guarantee

A Redis transaction is not the same as a SQL transaction. In particular, it does not provide rollback of commands that have already executed.

Suppose a transaction contains three commands:

  1. INCR succeeds.
  2. A command executes and returns a runtime error.
  3. Another command succeeds.

Redis does not undo the successful commands just because one command failed at runtime. The transaction executes its queued commands in order, and each command produces its own result.

There are two distinct kinds of errors to understand:

  • A queue-time error occurs when Redis cannot queue a command, for example because the command syntax is invalid. Redis can abort the transaction before execution.
  • A runtime error occurs when a queued command is executed but fails. Other queued commands are still processed, and successful operations are not rolled back.

A transaction also does not provide conditional logic between commands. You cannot inspect the result of INCR inside the transaction and then decide whether to execute another command based on that result. The commands are queued before EXEC runs.

That is why EXPIRE NX is useful. Redis itself checks whether an expiry already exists when executing the command. You do not need to read the increment result and make a decision in Go.

Lua scripts for conditional atomic operations

Transactions are useful when you already know the commands that need to run. Sometimes you need more than a fixed sequence.

For example, a token bucket requires several related operations:

  1. Read the stored token count.
  2. Calculate how much time has passed.
  3. Refill tokens, up to the bucket's capacity.
  4. Decide whether the request can be accepted.
  5. Update the token count and last-refill timestamp.

The decision in step 4 depends on the results of the earlier steps. A transaction cannot express this kind of conditional logic between queued commands.

Redis supports server-side scripting with Lua. Lua is a small scripting language that Redis embeds so applications can execute custom logic on the Redis server.

A Lua script runs as one atomic operation from the perspective of other Redis clients. While a script is executing, Redis does not interleave commands from other clients with its execution.

This lets the script read values, make decisions, and write updates as one operation.

Understand KEYS and ARGV

A Redis Lua script receives two important collections:

  • KEYS contains the Redis keys passed to the script.
  • ARGV contains additional arguments passed to the script.

Use KEYS for the Redis keys the script accesses. Use ARGV for values such as limits, window durations, or refill rates.

Inside the script, redis.call() executes a Redis command and returns its result to Lua.

For example:

lua
local count = redis.call("INCR", KEYS[1])

if count == 1 then
    redis.call("EXPIRE", KEYS[1], ARGV[1])
end

return count

This script implements a fixed-window counter:

  • It increments the key supplied in KEYS[1].
  • If the resulting count is 1, it sets the expiry using the duration supplied in ARGV[1].
  • It returns the count to the caller.

The condition is evaluated inside Redis. No other client can run a command between the increment and expiry operations.

Unlike a transaction, the script can make a decision based on the result of an earlier command.

This example uses the same first-increment rule as the transaction example. It assumes that the key is created and managed by this script. If an earlier bug has already left a key without an expiry, a later increment will not repair it because the count will be greater than one.

Run a Lua script from Go

go-redis provides redis.NewScript to define a script and execute it.

Here is a complete example of the fixed-window script and its Go call:

go
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/redis/go-redis/v9"
)

const fixedWindowScript = `
local count = redis.call("INCR", KEYS[1])

if count == 1 then
    redis.call("EXPIRE", KEYS[1], ARGV[1])
end

return count
`

func main() {
	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})
	defer rdb.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	script := redis.NewScript(fixedWindowScript)

	key := "rl:user:42:1700000000"
	windowSeconds := int64(60)

	result, err := script.Run(
		ctx,
		rdb,
		[]string{key},
		windowSeconds,
	).Int64()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result)
}

redis.NewScript creates a reusable script object. Run executes it using the supplied context, Redis client, keys, and arguments.

The []string{key} slice becomes the script's KEYS collection. The windowSeconds argument becomes ARGV[1].

The script returns a Redis integer, which go-redis converts through Int64().

This example is an alternative implementation for learning. Exercise 1.22 uses the transaction approach, not this Lua implementation.

EVAL, EVALSHA and script caching

Redis can execute a Lua script directly with the EVAL command. The command sends the script text to Redis, along with the number of keys, the keys, and the arguments.

Sending the complete script text repeatedly is unnecessary. Redis supports loading a script and referring to it by its SHA1 hash, a fixed-length identifier calculated from the script contents.

The process is:

  1. SCRIPT LOAD sends the script to Redis and stores it in Redis's script cache.
  2. Redis returns the script's SHA1 hash.
  3. EVALSHA executes the cached script using that hash instead of sending the full script again.

The script cache belongs to the Redis server. If Redis restarts, the cache can be empty even though your Go application still knows the script hash.

In that case, Redis returns the NOSCRIPT error because it does not recognize the requested hash.

go-redis handles this pattern through redis.NewScript and Run. It tries EVALSHA first. If Redis reports NOSCRIPT, the client falls back to EVAL, sending the script text so Redis can execute it.

This is why you should generally use redis.NewScript rather than manually implementing script loading and hash management.

Keep scripts short

Lua scripts execute atomically, but that guarantee has a cost.

Redis processes commands on its main execution thread. While a script is running, Redis cannot process other client commands. A long-running script can therefore delay unrelated requests.

Keep scripts short and predictable. Avoid loops over large collections, expensive computations, or operations whose execution time grows with the number of users or keys.

For our rate limiter, a script that performs a few reads, calculations, and writes is appropriate. A script that scans thousands of keys to rebuild rate limit state is not.

Choosing between pipelines, transactions and Lua

These mechanisms are related, but they do not offer the same guarantees.

PropertyPlain pipelineTxPipelineLua script
Batches commandsYesYesExecutes one script
Prevents other clients from interleavingNoYes, during EXECYes, during script execution
Supports conditional logic between operationsNoNoYes
Reduces network round tripsYesYesYes
Rolls back earlier successful commands after a runtime errorNoNoNo general rollback guarantee
Best useIndependent commands where batching is enoughKnown command sequence that must not interleaveConditional multi-step logic

Use a plain pipeline when commands are independent and you mainly want to reduce network overhead.

Use a transaction when you know the commands in advance and need them to execute without other clients interleaving.

Use Lua when later operations depend on the results of earlier operations and the entire decision must happen atomically on the Redis server.

For the fixed-window counter in exercise 1.22, a transaction with INCR and EXPIRE NX is sufficient. For a Redis token bucket, where the refill and admission decision require conditional logic, Lua is a better fit.

What happens when Redis is unavailable?

Even with correct Redis commands, Redis can become unreachable.

Possible causes include:

  • The Redis container or server has stopped.
  • A network connection has failed.
  • Redis is overloaded and cannot respond within the request's deadline.
  • The connection pool cannot establish a usable connection.
  • The request context has been cancelled.

Your rate limiter must decide what the API should do when it cannot reach Redis.

There are two broad policies:

  • Fail open: allow the request to continue using an alternative mechanism.
  • Fail closed: reject the request because the rate limit could not be checked.

For this course's general API rate limiter, we use fail open with an in-memory fallback.

Fail open with an in-memory fallback

A fail-open fallback means that when Redis fails, the API continues serving requests using a local rate limiter instead of rejecting every request.

The local fallback can be the FixedWindow implementation you already built. It stores counters in the current process and protects its shared state with a mutex.

The high-level behavior is:

  1. Calculate the current fixed-window key.
  2. Try to increment the shared Redis counter with a short timeout.
  3. If Redis succeeds, compare the returned count with the configured limit.
  4. If Redis fails, log the failure once and use the local FixedWindow.
  5. Return the fallback decision.

The timeout should be short. For this course, use 50 milliseconds as the starting value.

Show a request calling Allow, then a Redis operation under a 50 millisecond timeout; on success return the Redis counter decision, and on error log once and use the in-memory FixedWindow fallback, with either path returning an allow or reject decision to the request.Show a request calling Allow, then a Redis operation under a 50 millisecond timeout; on success return the Redis counter decision, and on error log once and use the in-memory FixedWindow fallback, with either path returning an allow or reject decision to the request.

Structure the Redis limiter

The Redis-backed limiter needs to hold its Redis client, limit configuration, window duration, timeout, fallback limiter, and logging state.

The sync.Once value ensures that the Redis failure warning is logged only once, rather than once for every request while Redis remains unavailable.

go
package ratelimit

import (
	"log/slog"
	"sync"
	"time"

	"github.com/redis/go-redis/v9"
)

type RedisFixedWindow struct {
	rdb      *redis.Client
	limit    int
	size     time.Duration
	timeout  time.Duration
	fallback *FixedWindow
	logOnce  sync.Once
	logger   *slog.Logger
}

func NewRedisFixedWindow(
	rdb *redis.Client,
	limit int,
	size time.Duration,
) *RedisFixedWindow {
	return &RedisFixedWindow{
		rdb:     rdb,
		limit:   limit,
		size:    size,
		timeout: 50 * time.Millisecond,
		logger:  slog.Default(),
	}
}

This shows the structure and constructor shape. The constructor still needs to initialize the fallback with the appropriate local fixed-window configuration from your existing implementation. The complete assembled limiter is part of exercise 1.22.

Understand the Allow method

The Allow method follows the same fixed-window calculation you used in lesson 1.20.

Its responsibilities are:

  1. Get the current time.
  2. Truncate it to the configured window size.
  3. Build a key such as rl:user:42:1700000000.
  4. Derive a short timeout context from the request context.
  5. Run INCR and EXPIRE NX through TxPipeline.
  6. If Redis succeeds, compare the returned count with the configured limit.
  7. If Redis fails, log once and ask the fallback limiter for a decision.

The transaction part has the same shape you saw earlier:

go
pipe := r.rdb.TxPipeline()

incrCmd := pipe.Incr(ctx, redisKey)
expireCmd := pipe.ExpireNX(ctx, redisKey, r.size)

_, err := pipe.Exec(ctx)

You must inspect the execution and individual command errors before treating the returned count as valid.

The fallback branch uses the local limiter:

go
r.logOnce.Do(func() {
	r.logger.Warn("Redis rate limiter unavailable, using local fallback")
})

return r.fallback.Allow(key)

The sync.Once value is safe to use across concurrent requests. Only the first caller executes the function. Later calls skip it.

The example is deliberately a piece of the method, not a complete implementation. You still need to assemble the context handling, key calculation, command error checks, and return decision in the exercise.

Understand the consequences of fail open

Fail open preserves availability, but it weakens the rate limit.

The fallback counter exists only inside one process. If your API has four instances and all four fall back independently, each can allow the full configured limit.

For example, if the limit is 100 requests per minute, four instances could collectively allow approximately 400 requests during that period.

There are two more consequences:

  • The fallback counters are lost when an API process restarts.
  • If Redis executes a command but the response is lost or arrives after the timeout, the application cannot know whether the counter was incremented. Falling back locally may mean that the request is counted in both Redis and the local limiter.

A timeout does not prove that Redis did not execute the command. It only means the client did not receive a successful response within the allowed time.

These trade-offs are acceptable for a general availability-oriented rate limiter in this course, but they are not appropriate for every security decision.

When fail closed is the right choice

Consider a login endpoint that limits password attempts.

If Redis becomes unavailable and the API switches to independent local counters, an attacker can distribute attempts across multiple API instances. The effective limit becomes much higher, weakening protection against password guessing.

For security-critical limits such as login attempts, fail closed may be the correct policy. If the API cannot verify the limit, it rejects or temporarily blocks the request rather than allowing an unchecked attempt.

The policy depends on what the limit protects:

  • General API traffic may favor availability and fail open.
  • Login attempts and other abuse-sensitive operations may favor security and fail closed.
  • Payment and account operations may need a carefully designed policy based on their risk and failure modes.

Do not apply one failure policy to every endpoint without considering its consequences.

Test the fallback and shared Redis state

A Redis-backed limiter needs tests for both normal operation and Redis failure.

The course provides two important integration tests.

Test that two instances share one counter

TestW1B7_RedisWindowCountsAcrossInstances creates two limiter instances that use the same Redis service.

The test sends requests through both instances and checks that they count against the same shared window.

This verifies an important property: the counter belongs to Redis, not to an individual Go process or limiter object.

If each limiter accidentally used a local map instead, both could independently allow the full limit.

Test fail open when Redis is down

TestW1B7_FailsOpenWhenRedisIsDown points the Redis client at an address where no Redis server is listening.

The limiter attempts the Redis operation, receives a connection error, and uses its in-memory fallback.

The test checks that Allow continues returning decisions according to the fallback rather than rejecting every request merely because Redis is unavailable.

You can reproduce the idea manually by configuring a Redis client with an unused local port:

go
rdb := redis.NewClient(&redis.Options{
	Addr: "127.0.0.1:6399",
})
defer rdb.Close()

Make sure no Redis service is listening on that port. The connection will fail, allowing you to exercise the fallback path.

The test should not depend on a specific network error string. Different operating systems and network conditions can report connection failures differently. Check the behavior of the limiter instead.

Avoid logging on every failed request

When Redis is down, every request may trigger the fallback. Logging a warning for every failure can create a large volume of repetitive logs and make useful operational events harder to find.

Use sync.Once to emit the first warning only:

go
var logOnce sync.Once

func logRedisFailure(logger *slog.Logger) {
	logOnce.Do(func() {
		logger.Warn("Redis unavailable, using local rate limit fallback")
	})
}

This is process-local logging state. If you run multiple API instances, each instance can log its own first failure. That is expected.

The fallback should also remain concurrency-safe. The existing FixedWindow implementation must protect its internal map and counters because multiple HTTP handler goroutines may call Allow at the same time.

Summary

You now understand the guarantees and trade-offs behind Redis-backed rate limiting:

  • Separate INCR and EXPIRE calls can leave a key without a TTL if the second operation fails.
  • A plain pipeline reduces network round trips but does not prevent other clients from interleaving commands.
  • TxPipeline uses MULTI/EXEC so queued commands execute without interleaving.
  • Redis transactions do not roll back successful commands after runtime errors and cannot perform conditional logic between queued commands.
  • Lua scripts provide conditional multi-step atomic logic inside Redis.
  • redis.NewScript().Run() uses EVALSHA and falls back to EVAL when Redis returns NOSCRIPT.
  • A fail-open fallback keeps the API available but makes limits process-local and weaker.
  • Security-sensitive limits may need to fail closed instead.

The important engineering decision is not simply choosing the fastest Redis command. It is choosing the weakest mechanism that still provides the correctness guarantees your operation needs.

Knowledge assessment

Question 1 of 5

Separate INCR and EXPIRE NX calls are used to maintain a fixed-window Redis counter. Why can this leave a counter that never resets, and does a plain pipeline solve the problem?

Pick an answer, then say how sure you are.

Practical applications

  • Exercise 1.22: Redis fixed-window limiter that fails open. Implement RedisFixedWindow using TxPipeline, EXPIRE NX, a short context timeout, and a concurrency-safe in-memory fallback. Verify shared counting across instances and behavior when Redis is unavailable.
  • Optional exercise 1.29: Token bucket in Redis with Lua and EVALSHA. Use a Redis Lua script to perform conditional token refill and request admission atomically, and execute it through go-redis script support.

References

Everything above is explained on this page; these are where it comes from (Redis 7, go-redis v9).

Finished Lesson 1.21?