This resume is also available in English.

6. Deploying the system12 / 14 · All columns

Columns › 6. Deploying the system › Part 39

Using Redis Well: Caching, Counters, Locks and the Pitfalls

Redis 怎麼用:快取、計數、鎖與常見陷阱

Redis is fast, but it is not the source of truth. Starting from what the shop actually uses it for, this article covers which data structure fits which job, cache-aside and invalidation, penetration, breakdown and avalanche, rate-limit counters and flash-sale stock, then big and hot keys, eviction, persistence, Cluster and go-redis pool settings, saying for each approach when it fits and when not to use it.

  • Redis
  • 快取
  • Go
  • 微服務
In this article
  1. What this article solves
  2. Step 1: What Redis is good for, and what it should not hold
  3. Step 2: Choosing a data structure
  4. Step 3: Cache-aside and delete-after-write
  5. Step 4: Penetration, breakdown and avalanche
  6. Step 5: Atomicity: single commands, transactions, Lua and pipelines
  7. Step 6: Counters and rate limiting
  8. Step 7: Pre-deducting flash-sale stock, and reconciliation
  9. Step 8: Big keys, hot keys and commands you must not use in production
  10. Step 9: Memory limits and eviction policies
  11. Step 10: Persistence, replication, Sentinel and Cluster
  12. Step 11: Connection pools, timeouts and security in go-redis
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

The previous article, “Adding Indexes Safely: Indexing Large Tables Without an Outage”, made PostgreSQL's queries use the right indexes; but some reads are simply too numerous even with an index: the product detail page is read tens of thousands of times a second while its content changes once every few hours, and in the first second of a flash sale hundreds of thousands of people want to decrement the stock of the same product. That is when everyone thinks of Redis. This article does not walk through every command; instead it answers the decisions you most often have to make when using Redis in the shop: what may go in it, which structure to use, how it breaks when things go wrong, and how to configure it so that it does not become a new source of outages.

What this article solves

The series' shop (example.com/shop, with the services api-gateway, order, payment and inventory, PostgreSQL as the database and events on NATS JetStream) already got a Redis instance in “Deploying a Whole Microservice System with Docker Compose”, used for caching, rate-limit counters and idempotency keys. After some time in production, the usual symptoms are:

  • A product's price changed, but the page still shows the old price, only for some people, and a few minutes later it is fine again.
  • The moment a popular product's cache entry expires, the database CPU jumps to full load.
  • Someone sends a flood of requests with product IDs that do not exist; the cache stops none of them and every one reaches the database.
  • Someone runs KEYS product:* in production; Redis processes nothing else for that time, and every service times out together.
  • Deleting a hash with hundreds of thousands of fields makes Redis stall; or a single key takes half of the machine's traffic.
  • After a Redis restart or a primary/replica failover, the rate-limit counters are back to zero and the flash-sale stock numbers no longer match.

This article works through, in order:

  1. What Redis is good for and what it should not hold.
  2. How to choose a data structure, and the scenario each one fits.
  3. Cache-aside, delete-after-write, and why you do not update the cache.
  4. Penetration, breakdown and avalanche, with a Go implementation you can use directly.
  5. Atomicity: single commands, transactions, Lua scripts and pipelines, and what each guarantees.
  6. Counters and rate limiting: fixed and sliding windows.
  7. Pre-deducting stock for a flash sale and reconciling it with PostgreSQL; distributed locks only briefly.
  8. Big keys, hot keys and the commands you must not use in production.
  9. Memory limits and eviction policies.
  10. Persistence, replication, Sentinel and Cluster: what you lose when something fails.
  11. Connection pools, timeouts and security settings in go-redis v9.

Tip: the Go examples use github.com/redis/go-redis/v9 (checked against the v9.23 source), and the tests run against github.com/alicebob/miniredis/v2, an in-memory Redis. Redis commands and settings follow the official documentation; details may differ between versions or in compatible implementations such as Valkey, so check against the version you actually run before going to production.

Step 1: What Redis is good for, and what it should not hold

Redis is a key-value store that keeps data in memory and executes commands one at a time on a single thread. Those two properties decide its strengths and its limits:

  • Strengths: reads and writes take microseconds to milliseconds; every command is atomic by nature (no other command can cut in while it runs); a rich set of data structures lets the server do the work (increments, rankings, set intersections); and every key can have an expiry time.
  • Limits: capacity is bounded by memory, which costs far more than disk; persistence and replication are asynchronous by default, so a crash or failover can lose the latest writes; and one slow command blocks everyone.

So the most important principle is: Redis holds derived data; the source of truth is PostgreSQL. Orders, payments, the final stock numbers and amounts are always written to the database first; when something in Redis is lost, the system must be able to rebuild it from the database or give it up safely (a rate-limit counter going back to zero just lets a few extra requests through).

api-gateway order payment inventory Redis (derived data) Product cache Rate-limit counters Flash-sale stock Idempotency keys, locks PostgreSQL Source of truth orders, payments, stock, amounts rebuild writes always go to the database first If Redis loses data, the system rebuilds or gives it up safely; it never gets money wrong

Figure: the services treat Redis as a place for derived data, and every write goes to PostgreSQL first; the contents of Redis can be rebuilt from the database.

UseExample in the shopConsequence of losing itFit for Redis?
Read cacheProduct details, category listingsA few more database queriesYes
Rate-limit countersRequests per user per minute at the api-gatewayBriefly lets more throughYes
Flash-sale stock pre-deductionLimited items reserved in Redis firstNumbers drift and must be reconciledYes, but the database must hold the exact stock
Idempotency keys, short-term dedupeIdempotency keys for payment requestsA duplicate request may run twiceOnly as a first layer; the database needs a unique constraint
Sessions, verification codesLogin sessionsUsers have to sign in againYes
Orders, payment records, balances—Money is wrong, orders vanishNo
Business events that must replayorder.placedDownstream services miss eventsNo; use NATS JetStream or Kafka

The last two rows are the most common misuse. Redis can be configured to be very durable (fsync the AOF on every write, wait for replicas to acknowledge), but that gives up its biggest advantage, and it still lacks PostgreSQL's constraints, transactions and backup tooling. Data that must never go missing belongs in a system designed for that.

Step 2: Choosing a data structure

A Redis key is always a string, and the value can be one of several types. Choose the right type and many features take a single command; choose the wrong one and you have to read the whole value back into the application, change it and write it back, which is both slow and racy.

TypeCommon commandsFitsDo not use for
StringGET, SET … EX, INCR, DECRBYA whole cached object (JSON), counters, simple flagsLarge objects where you often change one field
HashHGET, HSET, HINCRBYSeveral fields of one object, such as a cart (product ID → quantity)Data whose field count grows without bound (big keys)
ListLPUSH, RPOP, LRANGE, LTRIMThe latest N entries (recently viewed), simple first-in-first-outWork queues that need acknowledgement and redelivery
SetSADD, SISMEMBER, SINTERCollections without duplicates: users who have claimed a coupon, tagsAnything needing order or range queries
Sorted setZADD, ZRANGE, ZREMRANGEBYSCORELeaderboards, time-ordered windows (sliding-window rate limits), delayed jobsVery large sets that are read in full
StreamXADD, XREADGROUP, XACK, XAUTOCLAIMSmall internal work queues that can tolerate loss, with consumer groups and acksCross-service business events that need long retention and replay
HyperLogLogPFADD, PFCOUNTEstimating unique visitors, at most about 12 KB per key with a standard error of about 0.81%Exact numbers, or listing the members
BitmapSETBIT, GETBIT, BITCOUNTFlags indexed by contiguous integer IDs, such as daily check-insSparse or very large IDs (wastes a lot of memory)

The key judgements:

  • Read whole and write whole: a String holding JSON; often change only one or two fields: a Hash. Product details are almost always read whole, so they are a String; a cart often changes the quantity of one product, so it is a Hash with HINCRBY.
  • A List is not a reliable queue. If a consumer crashes after RPOP, that job is gone. When you need acknowledgement and redelivery, inside Redis you can use a Stream with consumer groups; for business events across services, the NATS JetStream (or Kafka) the series has been using offers persistence, replay and monitoring and fits better; see “Message Queues and Event-Driven Design”.
  • Pub/Sub does not store messages. While a subscriber is disconnected, messages are simply dropped, so it only suits notifications that may be missed, such as telling every replica to clear its local cache.
  • Give key names a structure: service-or-purpose:object:ID:version, for example product:1:v1. The version lets you switch to a new set of keys when you change the cache format, instead of dealing with old and new formats mixed together.

Step 3: Cache-aside and delete-after-write

The shop's most common cache is product details. There are several ways to do it, and the difference is "who reads and writes the database":

PatternHow it worksFitsCost and limits
Cache-asideThe application reads the cache, and only on a miss reads the database and fills the cache; on writes it updates the database, then deletes the keyRead-heavy data that can be briefly staleThe first read is slower; a few races are left for the TTL to close
Read-through/write-throughThe application only talks to a cache layer, which reads and writes the databaseWhen an existing cache layer or library does it for youRedis itself does not read your database; you have to write that layer
Write-behindWrite the cache first, then write to the database in asynchronous batchesHigh-frequency writes that may be lost, such as view countsUnflushed data is lost if the cache crashes; never for orders or amounts

The shop's default is cache-aside: it is the simplest, and on failure it falls back to the database, so a Redis outage only makes things slower, never wrong.

Service Redis PostgreSQL Read Write 1. GET product:1:v1 hit → return it 2. miss → SELECT row 3. SET … EX 600 + jitter 1. UPDATE … COMMIT 2. DEL after commit Delete, do not update: the next read loads the new value; the TTL is the last safety net

Figure: a read checks Redis first and only on a miss queries PostgreSQL and fills the cache; a write commits to the database first, then deletes the cache key.

The write path has two essentials: write the database first and touch the cache only after the commit, and delete the cache key rather than writing the new value into it. Why delete? Look at two requests changing a price at the same time:

Update the cache after writing A: UPDATE price = 100 B: UPDATE price = 120 B: SET cache = 120 A: SET cache = 100 (A was delayed) time Database 120, cache 100 wrong until the TTL expires Delete the cache after writing A: UPDATE price = 100 B: UPDATE price = 120 B: DEL cache A: DEL cache (harmless twice) time The cache is empty the next read loads 120

Figure: when the cache is updated after the write, the delayed request A writes the old value last and the cache stays wrong until the TTL expires; with deletion, the order no longer matters.

Request A updates the database to 100 first, then request B updates it to 120, so the database ends at 120. But A hits a GC pause or network delay just before writing the cache, so B writes 120 into the cache first and A then writes 100. The database says 120, the cache says 100, and it stays wrong until the TTL expires. With deletion, whichever delete comes first, the result is the same: the cache is empty, and the next read naturally loads the latest value from the database. Updating the cache also requires the writer to know exactly what the full cached object looks like; when a product's cache entry is built from several tables, that ties the writing and reading sides tightly together, whereas a delete only needs the key.

Deletion is not entirely race-free either. One case remains: a reader misses the cache and reads the old value → a writer updates the database and deletes the key → only then does the reader write the old value back into the cache. It needs "reading the database takes longer than writing the database plus deleting the key", which is unlikely, but it does happen. The common responses, in order of cost:

  1. Always set a TTL. It is the upper bound on every inconsistency: at worst the value is wrong until the TTL expires. For product details, a TTL of a few minutes is usually enough.
  2. Delayed double delete: delete once after the write, then again a few hundred milliseconds later. It covers the late write-back above, but "how much later" is a guess: too short and it does nothing, too long and the data is still stale for that period, and it adds an action that has to be scheduled. Consider it only when the TTL cannot be short and you have actually observed the problem.
  3. Trigger the delete from database changes: on top of the Outbox or CDC from “Distributed Transactions: Sagas and the Outbox Pattern”, a consumer deletes the key when it receives a "product updated" event, and failures can be retried. This also closes the gap of "the commit succeeded but the delete failed", at the cost of an extra asynchronous pipeline; it suits cases where several services cache the same data.

As for reads that need strong consistency (the price and stock at checkout, for example), do not read them from the cache; read the database. The cache exists to make the large volume of "just looking" reads cheap, not to sit in front of every read.

When not to add a cache: the data is different almost every time it is read (a low hit rate); the query is already fast enough and is merely missing an index; or reading stale data would lead to a wrong decision. Before adding a cache, make sure the database side has been tuned the way the previous article describes.

Step 4: Penetration, breakdown and avalanche

Cache-aside works well day to day; when it goes wrong, it is mostly in one of the following three shapes. The names are common in Chinese-language material; English sources usually describe the phenomenon instead, as a cache stampede or a thundering herd.

Penetration Redis An ID that does not exist PostgreSQL Every lookup misses Fixes Cache 'not found' briefly Validate the ID first Bloom filter Breakdown Redis A hot key just expired PostgreSQL Same key, many misses Fixes singleflight Mutex rebuild Logical expiry, serve stale Avalanche Redis Many keys expire at once PostgreSQL A whole batch misses Fixes Add jitter to TTLs Warm-up, limits, fallback HA, circuit breakers

Figure: penetration is lookups for data that does not exist, breakdown is a hot key expiring, avalanche is many keys expiring at once; all three send a batch of requests back to the database.

ShapeWhat happensFixesWhen you need them
PenetrationThe requested data does not exist, so the cache never hits and every request reaches the databaseCache "not found" for a short time; validate the ID format; a Bloom filterPublic endpoints where IDs can be guessed freely
BreakdownA hot key has just expired, and hundreds of requests miss and query the database at the same momentMerge requests with singleflight; rebuild under a mutex; logical expiry that serves the old valueWhen a few keys carry most of the traffic (popular products)
AvalancheMany keys expire at the same time, or Redis is entirely unavailableTTL jitter; warm-up; rate limiting and fallback; highly available RedisBatch cache fills, warm-up before a big sale, a single Redis node

“Concurrency Pitfalls: From Data Races to Overselling” already handled breakdown with singleflight. Here the three fixes are put together with Redis as the product cache the inventory service would actually use:

package cache

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"math/rand/v2"
	"time"

	"github.com/redis/go-redis/v9"
	"golang.org/x/sync/singleflight"
)

var ErrNotFound = errors.New("product not found")

type Product struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Price int64  `json:"price"` // minor currency units
}

// Loader reads a product from PostgreSQL; returns ErrNotFound when missing
type Loader func(ctx context.Context, id int64) (Product, error)

type ProductCache struct {
	rdb     *redis.Client
	load    Loader
	group   singleflight.Group
	ttl     time.Duration // base TTL
	jitter  time.Duration // add 0..jitter at random to spread expiries
	nullTTL time.Duration // the 'not found' marker lives only briefly
}

func NewProductCache(rdb *redis.Client, load Loader) *ProductCache {
	return &ProductCache{rdb: rdb, load: load,
		ttl: 10 * time.Minute, jitter: 2 * time.Minute, nullTTL: 30 * time.Second}
}

func key(id int64) string { return fmt.Sprintf("product:%d:v1", id) }

const nullMarker = "-" // never a valid JSON document

func (c *ProductCache) Get(ctx context.Context, id int64) (Product, error) {
	raw, err := c.rdb.Get(ctx, key(id)).Result()
	switch {
	case err == nil:
		if raw == nullMarker {
			return Product{}, ErrNotFound
		}
		var p Product
		if err := json.Unmarshal([]byte(raw), &p); err == nil {
			return p, nil
		}
		// cannot decode (an old format, say): treat as a miss and reload
	case errors.Is(err, redis.Nil):
		// miss
	default:
		// Redis is down: do not fill, read the database (still via singleflight so the database survives)
		return c.loadOnce(ctx, id, false)
	}
	return c.loadOnce(ctx, id, true)
}

func (c *ProductCache) loadOnce(ctx context.Context, id int64, fill bool) (Product, error) {
	v, err, _ := c.group.Do(key(id), func() (any, error) {
		// the first caller's cancellation must not fail the other waiters, but the query is still bounded
		qctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
		defer cancel()
		p, err := c.load(qctx, id)
		if errors.Is(err, ErrNotFound) && fill {
			c.rdb.Set(qctx, key(id), nullMarker, c.nullTTL) // against penetration; a failed write does not affect the reply
			return nil, err
		}
		if err != nil {
			return nil, err
		}
		if fill {
			b, _ := json.Marshal(p)
			ttl := c.ttl + time.Duration(rand.Int64N(int64(c.jitter)))
			c.rdb.Set(qctx, key(id), b, ttl)
		}
		return p, nil
	})
	if err != nil {
		return Product{}, err
	}
	return v.(Product), nil
}

// Invalidate is called after the database transaction commits: delete, never write the new value
func (c *ProductCache) Invalidate(ctx context.Context, id int64) error {
	return c.rdb.Del(ctx, key(id)).Err()
}

Each decision in this code matches one failure shape:

  • Penetration: when the database says "not found", a special value - is written to Redis and kept for only 30 seconds. After that, the same non-existent ID is answered by Redis directly. The TTL must be short because the product might be created later; the product-creation flow should also call Invalidate. If an attacker uses a different random ID each time, this does not help, and you need the ID format validation, the rate limiting from “Building an API Gateway in Go: Routing, Authentication and Rate Limiting”, or a Bloom filter (put every existing ID into a probabilistic set and reject the IDs that certainly do not exist; it can live in application memory or in a Redis module that supports it).
  • Breakdown: singleflight makes sure that within one replica only one request per key queries the database while the others wait for its result. With ten inventory replicas that is at most ten queries, which is usually enough. The query's context uses context.WithoutCancel to cut off the first caller's cancellation and then adds its own timeout; otherwise, when the first request is cancelled, every waiter fails with it.
  • Avalanche: the TTL is 10 minutes plus a random 0–2 minutes, so keys written in the same batch do not expire in the same second. When Redis itself fails, Get does not fill the cache and reads the database directly, still through singleflight, so the database is not dragged down too. At that point you also need the circuit breakers and rate limiting from “Timeouts, Retries and Circuit Breakers”: when the whole cache is gone, the database usually cannot take all the traffic, and it is better to answer some requests with "try again later".

When singleflight is not enough, there are two more options:

  • Rebuild under a (distributed) mutex: use SET lock:product:1 <token> NX PX 3000 so that only one replica in the whole cluster rebuilds, while the others wait briefly and read the cache again. This is a lock "for efficiency": if it occasionally fails, the database is queried once more, which is acceptable. The downside is higher latency for the waiting requests.
  • Logical expiry: store an expireAt field inside the value and give the Redis key itself a long TTL (or none). When a read finds a value that is "logically expired", it returns the old value to the user and lets a background job (again guarded by a lock so there is only one) rebuild it. Users always get data and latency stays flat; the cost is that people see stale data for a while, and hot data must be loaded in advance. It suits popular product pages during a big sale, not places where the price must be correct right now.

The tests (cache_test.go) use miniredis to verify this behaviour: 100 concurrent requests query the database only once; the TTL falls between 10 and 12 minutes; three lookups of a non-existent ID query the database only once; after Invalidate the new price is read; and with Redis shut down, data can still be read.

Step 5: Atomicity: single commands, transactions, Lua and pipelines

Redis executes commands one at a time on a single thread, so every command is atomic: INCR cannot have two clients both read 5 and both write back 6. The trouble starts when "several commands must hold together". Redis has four ways of grouping commands, and they guarantee completely different things:

ApproachGuaranteesDoes not guaranteeFits
PipelineSends several commands at once and reads the replies at once, saving round tripsNot atomic; other clients' commands can run in betweenWriting many independent keys in a batch
MULTI/EXECThe queued commands run back to back, with nobody else in betweenNo rollback: if one command fails, the others still take effect; no decisions based on intermediate resultsSeveral unconditional writes that must happen together
WATCH + MULTIIf a watched key changes before EXEC, the whole transaction does not run (optimistic locking)Under heavy contention it keeps retryingRead, compute in the application, write back, with few conflicts
Lua scripts (EVAL) or FunctionsThe whole script runs atomically and can read, decide and then writeThe whole Redis server processes nothing else while the script runs; writes already made are not rolled back if the script errors"Check, then modify" logic: rate limits, reservations, compare a token then delete

In practice Lua scripts are the most common. go-redis's redis.NewScript first runs the script by its SHA1 with EVALSHA, and only when the server replies NOSCRIPT (not loaded yet) does it send the whole script, so you do not have to manage loading scripts yourself. Since Redis 7 there are also Functions (FUNCTION LOAD, FCALL), which, like stored procedures, are persisted and replicated with the data; they suit several services sharing one set of scripts. For a few scripts used by a single service, EVALSHA is enough.

Rules for writing scripts:

  • Keep scripts short. While one runs, every other client is waiting; do not scan large amounts of data or loop over tens of thousands of items inside a script.
  • Pass every key the script uses through KEYS; do not build key names inside the script. On Redis Cluster the server uses KEYS to decide which node the script runs on, and those keys must be in the same slot (step 10).
  • Errors inside a script are not rolled back. Do all the checks first and write only at the end, as the reservation script below does.

Step 6: Counters and rate limiting

The api-gateway wants to limit each user to at most 10 order requests per minute. The most obvious code is:

// fragment: the problematic version
n, _ := rdb.Incr(ctx, key).Result()
if n == 1 {
	rdb.Expire(ctx, key, time.Minute) // if the process dies before this line, the key never expires
}

INCR and EXPIRE are two commands. If the service crashes or is redeployed between them, the counter has no expiry and the user is rate-limited forever. Putting both into one Lua script removes that gap. Here are fixed-window and sliding-window implementations:

package cache

import (
	"context"
	"time"

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

// Fixed window: INCR and the expiry live in one script, so no counter is left without a TTL
var fixedWindow = redis.NewScript(`
local n = redis.call("INCR", KEYS[1])
if n == 1 then
  redis.call("PEXPIRE", KEYS[1], ARGV[1])
end
return n`)

// AllowFixed lets at most limit requests through per window
func AllowFixed(ctx context.Context, rdb *redis.Client, key string, limit int64, window time.Duration) (bool, error) {
	n, err := fixedWindow.Run(ctx, rdb, []string{key}, window.Milliseconds()).Int64()
	if err != nil {
		return false, err
	}
	return n <= limit, nil
}

// Sliding window log: drop entries outside the window, then decide whether to record this one
var slidingWindow = redis.NewScript(`
local now    = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local limit  = tonumber(ARGV[3])
redis.call("ZREMRANGEBYSCORE", KEYS[1], "-inf", now - window)
if redis.call("ZCARD", KEYS[1]) >= limit then
  return 0
end
redis.call("ZADD", KEYS[1], now, ARGV[4])
redis.call("PEXPIRE", KEYS[1], window)
return 1`)

// AllowSliding needs a unique member (a request ID, say), or two requests in the same millisecond count once
func AllowSliding(ctx context.Context, rdb *redis.Client, key, member string, now time.Time, limit int64, window time.Duration) (bool, error) {
	ok, err := slidingWindow.Run(ctx, rdb, []string{key},
		now.UnixMilli(), window.Milliseconds(), limit, member).Int64()
	return ok == 1, err
}

The two windows differ at the boundary:

Fixed window (10 per minute) window 1 window 2 10 at 0:59 and 10 at 1:01 both pass → 20 in 2 seconds Sliding window (at most 10 in any 60 seconds) looking back 60 s from 1:01 already 10 → reject 0:00 1:00 2:00

Figure: a fixed window resets on the minute, letting 10 through at 0:59 and another 10 at 1:01; a sliding window allows at most 10 in any 60 seconds, so 1:01 is rejected.

ApproachHow it worksMemoryFitsNot for
Fixed window (INCR)One counter per window, reset when it expiresOne integer per userProtecting the system and preventing abuse, where letting twice as many through at a boundary is acceptableStrict quotas, such as paid API calls
Sliding window log (sorted set)Records the time of each request and looks back N secondsProportional to the limitSmall limits that must be accurate: SMS verification codes, failed sign-insLarge limits (tens of thousands per minute)
Token bucketRefills tokens at a rate, allowing short burstsTwo numbers per userShaping API traffic—

“Building an API Gateway in Go: Routing, Authentication and Rate Limiting” already implemented a token bucket inside each instance and discussed when centralised counting is actually needed. Here are three more details for centralised counting:

  • Decide in advance whether to allow or reject when Redis is unavailable. Rate limits that protect the system usually allow and raise an alert, or a Redis outage would stop the whole site from taking orders; sign-in limits that guard against brute force should reject.
  • The sliding window's member must be unique. When a sorted-set member repeats, only its score is updated, so if two requests in the same millisecond use the time as the member, they count once. The example requires the caller to pass a request ID.
  • Use a consistent time source. The example has the application pass in the current time, which makes testing easy; clock differences between replicas make the window boundary slightly fuzzy, which is acceptable for rate limiting. When you need more precision, use redis.call("TIME") inside the script to take the server's time.

The tests verify that the fixed window lets 10 of 15 requests through and that the key has an expiry; and that after 10 requests at 0:59, the sliding window still rejects at 1:01 and only allows again once the window has passed.

Step 7: Pre-deducting flash-sale stock, and reconciliation

When a limited item goes on sale, hundreds of thousands of requests arrive within a second; if they all run UPDATE … SET stock = stock - 1 on the same PostgreSQL row, that is the hot row described in “Concurrency Pitfalls: From Data Races to Overselling”: everyone queues for the same row lock and the database connection pool is exhausted in no time. That article mentioned one approach: reserve stock atomically in Redis first to turn away the requests beyond the stock, write the successful ones back to the database, and reconcile regularly. Here it is in full.

Buyer requests api-gateway rate limit Redis reserve Lua script, atomic PostgreSQL order + stock ok write failed or cancelled → release Out of stock answer 'sold out' Reconciliation job compare Redis reservations with database orders; release or fix the gaps Redis only turns away traffic beyond the stock; the exact stock lives in PostgreSQL

Figure: after rate limiting, a Redis Lua script reserves the stock; requests beyond the stock are answered at once, and only successful ones are written to PostgreSQL; failures or cancellations release the reservation, and a reconciliation job compares the two sides.

package cache

import (
	"context"
	"errors"
	"fmt"

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

var (
	ErrSoldOut      = errors.New("sold out")
	ErrNotPreloaded = errors.New("stock not preloaded")
)

// Both keys share the hash tag {sku:N}, so they land in the same slot in Redis Cluster
func stockKey(sku int64) string    { return fmt.Sprintf("{sku:%d}:stock", sku) }
func reservedKey(sku int64) string { return fmt.Sprintf("{sku:%d}:reserved", sku) }

// Returns 1 = reserved, 0 = this order already reserved, -1 = not enough stock, -2 = not preloaded
var reserve = redis.NewScript(`
if redis.call("HEXISTS", KEYS[2], ARGV[1]) == 1 then
  return 0
end
local s = redis.call("GET", KEYS[1])
if not s then
  return -2
end
local qty = tonumber(ARGV[2])
if tonumber(s) < qty then
  return -1
end
redis.call("DECRBY", KEYS[1], qty)
redis.call("HSET", KEYS[2], ARGV[1], qty)
return 1`)

// Reserve turns away requests beyond the stock at the door; successful orders still decrement stock in PostgreSQL
func Reserve(ctx context.Context, rdb *redis.Client, sku int64, orderID string, qty int64) error {
	code, err := reserve.Run(ctx, rdb, []string{stockKey(sku), reservedKey(sku)}, orderID, qty).Int64()
	if err != nil {
		return err
	}
	switch code {
	case 1, 0:
		return nil
	case -1:
		return ErrSoldOut
	default:
		return ErrNotPreloaded
	}
}

// Compensation: return the reservation when the order is cancelled or the database write fails; repeated calls return it once
var release = redis.NewScript(`
local qty = redis.call("HGET", KEYS[2], ARGV[1])
if not qty then
  return 0
end
redis.call("HDEL", KEYS[2], ARGV[1])
redis.call("INCRBY", KEYS[1], qty)
return 1`)

func Release(ctx context.Context, rdb *redis.Client, sku int64, orderID string) error {
	return release.Run(ctx, rdb, []string{stockKey(sku), reservedKey(sku)}, orderID).Err()
}

The main design points:

  • The stock must be preloaded. Before the sale opens, a scheduled job writes the sellable quantity from PostgreSQL into {sku:N}:stock. When the key does not exist, the script returns -2 rather than treating it as 0 or as unlimited, so that after a Redis restart it neither tells everyone the item is sold out nor lets everyone through.
  • Reservations are deduplicated by order ID. The {sku:N}:reserved hash records how much each order reserved. Whether the client retries after a timeout or go-redis automatically resends the same command after a dropped connection, nothing is deducted twice (step 11 explains the automatic retries). Releasing uses the same hash, so releasing twice returns the stock only once.
  • Both keys share the hash tag {sku:N}, which guarantees they land in the same slot on Redis Cluster so that the script can access both at once.
  • Redis only turns away traffic; the exact stock lives in PostgreSQL. After a successful reservation, the order service creates the order as usual, and inventory performs the real decrement in the database with a conditional UPDATE … WHERE stock >= $1 and publishes an event through the Outbox. If that database step fails, or the order is cancelled within the payment deadline, Release gives the stock back.

Why reconciliation is mandatory: Redis and PostgreSQL are two systems with no shared transaction. A service crashing after a successful reservation, a failed Release call, or Redis losing its last few writes during a failover all leave the two sides disagreeing. The reconciliation job runs every so often during the sale and once more afterwards: it reads the order IDs in reserved and compares them with the orders in the database. Reservations in Redis with no order in the database, past a grace period, are released; conversely, orders that exist in the database but not in Redis (because Redis lost the record in a failover, say) mean the Redis stock number is corrected using the database as the reference. This is the same thinking as “Reconciliation: Matching Payment Provider Statements Reliably”: consistency between two systems ultimately comes from reconciliation, not from hope.

The test has 200 goroutines compete for 50 items: exactly 50 succeed, 150 are told it is sold out, and the stock reaches zero; retrying the same order does not deduct twice; and releasing the same order twice returns only one item.

When you do not need any of this: for most products, a conditional UPDATE in PostgreSQL handles the order volume, with a single source of truth, which is much simpler. Only when measurement confirms a hot row and the flash sale is predictable is it worth paying for the complexity of reservations, releases and reconciliation.

Distributed locks get only a brief mention here: the correct way to build a lock on Redis (SET key token NX PX, a random token, a Lua compare-then-delete), the problem of a lease expiring without the holder knowing, and the debate around fencing tokens and Redlock are covered fully in “Idempotency and Distributed Locks”. The conclusion: Redis locks are fine "for efficiency", such as the cache rebuild in step 4; where correctness matters (payments, the final stock numbers), rely on database constraints and idempotency, not on a Redis lock alone. The reservation script above is atomic by itself and needs no extra lock.

Step 8: Big keys, hot keys and commands you must not use in production

Redis processes commands on a single thread, so one slow command makes every client wait. Slow commands are mostly caused by big keys, hot keys and commands that scan the whole keyspace.

Big keys: a single key whose value is large (a string of several MB, say), or a collection with very many elements (a hash with hundreds of thousands of fields). The problems:

  • Commands that read the whole thing, such as HGETALL, SMEMBERS and LRANGE 0 -1, take time proportional to the element count; everyone else waits meanwhile, and the network moves a lot of data at once.
  • Deleting it with DEL takes time just to free the memory. Delete big keys with UNLINK, which hands the freeing to a background thread.
  • In a Cluster, a big key can live only on one node, which unbalances memory between nodes and slows down slot migration.

The remedy is to split: a hash like a cart is small anyway; if a collection grows without bound (for example "every user who has claimed a coupon"), split it into several keys by date or by a hash of the ID, or move it back to the database. Read collections in batches with HSCAN, SSCAN and ZSCAN.

Hot keys: a few keys carry most of the traffic, such as the stock key of a flash-sale item or the home page's recommendation list. In a Cluster, a given key always lands on the same node, so no number of extra nodes will spread that key's traffic. Options:

  • Add a very short local cache in the application (say 1–5 seconds). For data that is the same for everyone, like the home page recommendations, ten replicas each caching it brings Redis reads down to a dozen or so per second.
  • Make copies: write home:recommend as eight copies, home:recommend:0 to :7, and pick one at random when reading, spreading them across slots and nodes; the cost is eight writes per update.
  • Write-heavy hot keys (flash-sale stock) cannot be copied; the only option is the rate limiting in front, bringing traffic down to what Redis can handle.

How to find them:

# Scan the whole keyspace for the keys with the most elements per type (uses SCAN internally; -i pauses between every 100 SCANs)
redis-cli -h redis.internal --bigkeys -i 0.1

# Find the biggest keys by memory use
redis-cli -h redis.internal --memkeys -i 0.1

# Find hot keys: only works when maxmemory-policy is an LFU policy (allkeys-lfu, volatile-lfu)
redis-cli -h redis.internal --hotkeys

# How much memory one key uses (bytes)
redis-cli -h redis.internal MEMORY USAGE 'product:1:v1'

# Recent slow commands
redis-cli -h redis.internal SLOWLOG GET 10

--bigkeys and --memkeys both scan with SCAN, so they do not block the server for long, but they still add load; run them on a replica or off-peak. --hotkeys relies on the LFU access-frequency counters, so it does not work when the eviction policy is not LFU; for routine hot-key monitoring you can also count accesses per key in the application.

Commands you must not use in production:

  • KEYS pattern: walks the whole keyspace in one go, taking time proportional to the total number of keys; the official documentation's example is about 40 milliseconds to scan a million keys on an entry-level laptop, but with tens of millions of keys, or during a busy peak, every other command queues for that time and the large reply fills the network. To list keys, use SCAN cursor MATCH pattern COUNT n and walk through in many steps; it may return duplicate keys, which the application must handle. More fundamentally, do not depend on "listing every matching key": when you need a group of keys, remember them in a separate Set.
  • FLUSHALL, FLUSHDB: one command wipes all the data.
  • HGETALL, SMEMBERS, LRANGE 0 -1 on big keys: for the reasons above.
  • MONITOR: sends every command to the monitoring client, noticeably slowing the server under heavy traffic; only for brief debugging.

These commands are best forbidden at the permission level, which step 11 does with ACLs.

Step 9: Memory limits and eviction policies

All Redis data lives in memory, so you must set maxmemory. On 64-bit systems it defaults to 0, meaning no limit: the data keeps growing until the machine runs out of memory and the operating system kills the process, or it starts swapping and becomes extremely slow.

What happens at the limit is decided by maxmemory-policy:

PolicyBehaviourFits
noeviction (default)Nothing is evicted; commands that add data return an error; reads work as normalData that must not be deleted silently: stock reservations, queues, idempotency keys
allkeys-lruEvicts the least recently used keys among all keys (approximate LRU)A pure cache where some data is read far more than the rest; the default choice for a cache without a special reason
allkeys-lfuEvicts the least frequently used keys among all keys (approximate LFU)A pure cache whose popular data stays stable; also makes --hotkeys usable
volatile-lru/volatile-lfuEvicts only among keys that have a TTLOne Redis instance mixing cache entries (with a TTL) and data that must not be evicted (without)
volatile-ttlEvicts the keys with the shortest remaining TTL among those that have oneWhen the application can express importance through TTLs
allkeys-random/volatile-randomEvicts at randomWhen every key is accessed with roughly equal likelihood

The official documentation also lists policies that only exist in newer versions (such as LRM, which evicts by the time of last modification); check that your version supports them before using them.

How to choose:

  • For a pure cache, use allkeys-lru or allkeys-lfu. Anything in a cache can be rebuilt, so an eviction is just one more miss.
  • For data that "must not silently disappear", such as stock reservations, queues and idempotency keys, use noeviction and monitor memory use. A failed write will at least be noticed; an evicted key raises no error at all and only shows up one day as a reconciliation that does not add up.
  • Better still, keep the two uses apart in separate Redis instances: the cache instance can evict freely, while the other uses noeviction with persistence enabled. When they are mixed, the volatile-* policies require every cache key to have a TTL and every important key to have none; forget it in one place and the wrong thing gets evicted. Also, when no key has a TTL, the volatile-* policies behave like noeviction.
  • Do not set maxmemory to all of the machine's memory. With persistence or replication enabled, Redis needs extra buffers, and RDB snapshots and AOF rewrites fork a child process; under heavy writes, copy-on-write briefly increases memory use. Leave some headroom for them.
# An instance dedicated to caching
maxmemory 4gb
maxmemory-policy allkeys-lfu

The metrics to watch are all in INFO: the ratio of used_memory to maxmemory; a steadily rising evicted_keys (keys evicted), which means memory is short and the hit rate will fall with it; keyspace_hits and keyspace_misses, from which you compute the hit rate; and a high expired_keys with a low hit rate, which may mean the TTLs are too short.

Step 10: Persistence, replication, Sentinel and Cluster

This step answers one question: when Redis fails, what do you lose?

There are two kinds of persistence, and both can be on at once:

OptionHow it worksLost on a crashFits
NoneMemory onlyEverythingA pure cache that warms up again from the database after a restart
RDBPer configuration (for example save 60 1000), periodically forks a child to write a snapshotEvery write since the last snapshot, usually several minutesBackups, fast restarts
AOFAppends every write command to a log; appendfsync decides how often to fsyncAbout one second with everysec (the default); least with always, but it is slowData whose loss causes trouble, such as stock reservations and idempotency keys

With both enabled, a restart restores from the AOF because it is more complete. In Compose the series turned persistence off on the cache Redis (--save '' --appendonly no) because it only holds caches and counters; the instance holding stock reservations should enable AOF with appendfsync everysec and sit on a persistent disk. Even then, remember that "losing at most about a second" is still losing, which is why the reconciliation above is needed.

Replication is asynchronous. The primary replies "OK" to the client and only then sends the command to its replicas. If the primary crashes in that gap and a replica is promoted to primary, those writes are gone. The WAIT command can wait for a given number of replicas to acknowledge, but it only lowers the probability of loss; it does not turn Redis into a strongly consistent system. This is also why “Idempotency and Distributed Locks” says a Redis lock can fail during a failover.

There are two high-availability architectures:

ArchitectureWhat it doesFitsWatch out for
Single node + replicasOne primary, several replicas, manual failoverDevelopment, caches that can tolerate minutes of downtimeA failed primary needs a human
SentinelSeveral Sentinel processes watch the primary and, once enough of them agree, promote a replica automatically; clients ask the Sentinels for the current primaryData that fits on one machine, with automatic failoverAt least three Sentinels on different machines; the client must support Sentinel
ClusterData is split into 16384 slots spread over several primaries, each with its own replicasWhen the data or the write volume exceeds one machineRestrictions on multi-key operations; only database 0; the client must support Cluster

With a managed cloud service (AWS ElastiCache, for example), failover is handled for you, but the trade-offs above remain: a failover causes brief connection errors, asynchronous replication can still lose the last writes, and the application must still retry and cope.

go-redis has a client for each: redis.NewClient (single node), redis.NewFailoverClient (Sentinel, with MasterName and SentinelAddrs) and redis.NewClusterClient (Cluster). They all implement the redis.UniversalClient interface; if the application code depends on that interface, each environment can use a different deployment.

Cluster slots and hash tags are where most problems appear when moving from a single node to a Cluster:

slot = CRC16(key) mod 16384; with {…} in the key only the part inside is hashed Node A slot 0–5460 Node B slot 5461–10922 Node C slot 10923–16383 {sku:7}:stock slot 11147 {sku:7}:reserved slot 11147 cart:42 slot 15749 order:42 slot 8691 Only keys in one slot can share an MGET, MULTI or Lua script; cart:42 with order:42 returns CROSSSLOT

Figure: a key's slot is decided by its CRC16; with braces only the part inside them is hashed, so the two keys starting with {sku:7} are in the same slot.

Each key's slot is CRC16(key) mod 16384. The server only allows keys from the same slot in one multi-key command, one MULTI transaction or one Lua script; otherwise it returns a CROSSSLOT error, even if the two slots happen to be on the same node. To put related keys in the same slot, use a hash tag: when a key contains {…}, only the part inside the first pair of braces is hashed. In step 7, {sku:7}:stock and {sku:7}:reserved both hash only sku:7, so the reservation script can work on both at once.

Hash tags have a cost too: all keys with the same tag live on the same node. If you add {users} to every user's data, you squeeze it all into one slot, the Cluster loses its point, and you create big and hot keys. The tag's scope should be exactly "the group that must be operated on atomically together", usually one object's ID.

Also, some clients (including recent versions of go-redis's ClusterClient) use the command routing information the server provides to split reads such as MGET by slot, send them separately and merge the results. The program does not get an error, but the result is no longer read at a single point in time; transactions and Lua scripts cannot be split like that and must follow the same-slot rule.

Step 11: Connection pools, timeouts and security in go-redis

Finally, the client settings. Redis itself is fast; most latency problems are in the client: a pool that is too small, timeouts that are too long, or timeouts that never take effect.

package cache

import (
	"time"

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

func NewClient(addr, user, pass string) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     addr,
		Username: user, // an ACL user, not default
		Password: pass,
		// TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12}, // enable across networks

		DialTimeout:           500 * time.Millisecond,
		ReadTimeout:           200 * time.Millisecond, // a cache slower than the database is pointless
		WriteTimeout:          200 * time.Millisecond,
		ContextTimeoutEnabled: true, // apply the request context's deadline to reads and writes

		PoolSize:        50,                     // normal connections per replica
		MaxActiveConns:  60,                     // hard cap; without it, busy periods can exceed PoolSize
		MinIdleConns:    5,                      // kept warm so a cold start does not dial all at once
		PoolTimeout:     300 * time.Millisecond, // how long to wait when the pool is full
		ConnMaxIdleTime: 5 * time.Minute,        // shorter than the server's timeout

		MaxRetries: 1, // resend once after a dropped connection; see the text for non-idempotent work
	})
}

The reasoning behind each setting:

  • Timeouts must be much shorter than the database's. The cache exists to be faster than the database; a cache lookup that waits three seconds to time out is already slower than querying the database directly. Set read and write timeouts to a few hundred milliseconds and treat a timeout as a miss, falling back to the database (which is exactly how Get in step 4 handles Redis errors). Several defaults, such as ReadTimeout, have changed between versions, so write them out explicitly rather than relying on the defaults.
  • ContextTimeoutEnabled: true. By default go-redis does not apply the context's deadline to network reads and writes; it only uses ReadTimeout/WriteTimeout. Once it is on, the HTTP request's remaining time (the timeout budget from “Timeouts, Retries and Circuit Breakers”) actually limits the Redis call.
  • PoolSize is the number of connections each replica normally keeps; MaxActiveConns is the hard cap (without it, the connection count can exceed PoolSize when busy). The caps of all replicas added together must stay below Redis's maxclients, the same calculation as for database connections in “database/sql, Transactions and Connection Pools in Go”. PoolTimeout is how long to wait when the pool is full; keep it short so congestion fails fast instead of queueing requests. Recent go-redis versions also have a separate pool for pipelines (PipelinePoolSize), which must be counted in the total.
  • ConnMaxIdleTime must be shorter than the server's timeout setting and the idle timeouts of network devices in between (load balancers, NAT), or the client picks up a connection the other side has already closed.
  • Be careful with automatic retries of non-idempotent commands. go-redis resends a command after errors such as a dropped connection, but the command may in fact already have run on the server. Resending GET is harmless; resending INCR or DECRBY counts twice. A rate-limit counter counting one extra is acceptable; for operations that must not double-count, such as stock, either make the script itself idempotent (step 7 deduplicates by order ID) or set MaxRetries to -1 to turn retries off (note that 0 means "use the default", not "off").

Security settings. Redis is designed on the assumption that it runs inside a trusted network and ships with little protection by default; large numbers of Redis instances exposed to the internet without a password have been compromised. At a minimum:

  1. Do not expose it. bind only to internal network interfaces, and let the firewall or a Kubernetes NetworkPolicy allow only the services that need it (“Microservice Security: Authentication, Authorisation, Secrets and Supply Chain”). Keep protected-mode yes.
  2. One ACL user per service, with only the keys and commands it needs, and disable the default user, or at least give it a password. Older versions only had requirepass, one shared password; since Redis 6, ACLs let you apply least privilege.
  3. Use TLS across networks. Redis has to be built with TLS support and configured with tls-port, tls-cert-file, tls-key-file and tls-ca-cert-file; the client sets TLSConfig. Managed services usually offer it as an option.
  4. Forbid dangerous commands. Use the ACL -@dangerous to take FLUSHALL, KEYS, CONFIG, DEBUG and similar commands away from the application users. The older way is rename-command in the configuration file to rename or disable them; ACLs are clearer and can differ per user.
  5. Keep passwords in secret management, not in configuration files or images; pass the password to redis-cli through the REDISCLI_AUTH environment variable rather than -a (which stays in the shell history and the process list).
# inventory service: only the product cache and stock keys, may run scripts, no dangerous commands
redis-cli -h redis.internal --user admin --askpass \
  ACL SETUSER inventory on '>replace-with-a-password-from-secret-management' \
  '~product:*' '~{sku:*' '+@read' '+@write' '+@scripting' '+@connection' '-@dangerous'

ACL rules apply from left to right, so -@dangerous goes last and removes the dangerous commands from the categories granted before it. Before going live, run the service's integration tests with this user to make sure no needed command is missing; when a permission error appears, ACL LOG records which command or key was refused.

Common pitfalls

  • Treating Redis as the source of truth: orders, payments or balances exist only in Redis and the latest writes are lost after a failover or restart. Redis holds derived data; the truth is in PostgreSQL.
  • Cache entries without a TTL: no inconsistency has an upper bound, and memory only grows. Every cache key needs a TTL, with random jitter.
  • Updating the cache after a write instead of deleting it: two concurrent writes update the cache in the opposite order and the old value stays until the TTL expires. Delete after writing, and only after the commit.
  • Caching only data that exists: non-existent IDs reach the database every time. Cache "not found" briefly, and add ID validation and rate limiting.
  • No protection when a hot key expires: hundreds of requests go back to the source at once. Use singleflight, a mutex rebuild or logical expiry.
  • INCR and EXPIRE as two commands: a crash between them leaves a counter that never expires. Put them in one Lua script.
  • Assuming MULTI/EXEC rolls back: if one command fails, the others still take effect; when you need to check before writing, use Lua.
  • Lua scripts that do too much: the whole Redis server stops while a script runs. Scripts should do only the necessary checks and writes.
  • Using KEYS in production: the more keys, the longer the stall, with every other command queued. Use SCAN, or keep the keys you need in a Set, and forbid KEYS with ACLs.
  • Deleting big keys with DEL and reading them with HGETALL: both cause stalls. Split them, delete with UNLINK, read in batches with HSCAN.
  • No maxmemory: the process is killed once memory runs out. Set a limit and choose the eviction policy by use.
  • Mixing caches and data that must not be evicted in an allkeys-* instance: stock reservations are silently evicted. Use separate instances, or at least noeviction.
  • Multi-key operations on Cluster without hash tags: scripts and transactions return CROSSSLOT. Give related keys the same tag, but do not make the tag so broad that it becomes a hot spot.
  • Client timeouts longer than the database's: when Redis slows down, every request is stuck. Keep timeouts short, turn on ContextTimeoutEnabled, and fall back to the database on a timeout.
  • Automatic retries of non-idempotent operations: stock is deducted twice. Deduplicate inside the script by a business ID, or turn retries off.
  • Redis exposed to the internet, or every service sharing the default user: it gets compromised or all the data gets deleted by mistake. Internal network, ACLs, TLS, and dangerous commands forbidden.

Key takeaways

  • Redis is for derived data that can be rebuilt or given up: caches, counters, reservations, short-term dedupe; orders, payments and business events belong in PostgreSQL and NATS JetStream.
  • Choose the data structure by access pattern: a String for whole reads and writes, a Hash for individual fields, a sorted set for rankings and time windows; a List is not a reliable queue, and Pub/Sub does not store messages.
  • Cache-aside is the default: write the database first and delete the cache key after the commit; the TTL bounds every inconsistency; reads that need strong consistency go to the database.
  • Stop penetration with short-lived "not found" entries and validation; breakdown with singleflight, a mutex rebuild or logical expiry; avalanche with TTL jitter, warm-up, rate limiting and fallback.
  • Every command is atomic; for "check, then modify", use a Lua script; a pipeline only saves round trips, and MULTI does not roll back.
  • A counter's increment and its expiry belong in one script; a fixed window is simple but lets extra traffic through at the boundary, and a sliding window is accurate but its memory grows with the limit.
  • Flash-sale reservations let Redis turn away traffic beyond the stock, with the order ID making reservations and releases idempotent; the exact stock is in the database, and the two are reconciled regularly.
  • Find and split big and hot keys; do not use KEYS or FLUSHALL in production, and forbid them with ACLs.
  • Always set maxmemory; use allkeys-lru or allkeys-lfu for a pure cache, and noeviction on a separate instance for data that must not disappear.
  • Persistence and replication can both lose the last writes; Cluster only allows multi-key operations within one slot, and hash tags keep related keys together.
  • In go-redis, keep timeouts short and explicit, let the context take effect, and size the pool by the number of replicas; keep Redis on the internal network with one least-privilege ACL user per service.

References

  • Key eviction (official Redis documentation): the unlimited 64-bit maxmemory default, eviction policies and volatile-* behavior, used in step 9.
  • Redis persistence (official Redis documentation): RDB and AOF, and losing up to about one second with appendfsync everysec, used in step 10.
  • Redis replication (official Redis documentation): asynchronous replication by default and WAIT, used in step 10.
  • Redis cluster specification (official Redis documentation): the 16384 slots, hash tags and multi-key limits, used in steps 7 and 10.
  • Transactions (official Redis documentation): MULTI/EXEC not supporting rollbacks, as noted in step 5.
  • Scripting with Lua (official Redis documentation): EVAL, EVALSHA and the script cache, behind the Lua scripts in steps 5 to 7.
  • KEYS (official Redis documentation): the official warning against KEYS in production, used in step 8.
  • ACL (official Redis documentation): per-user permissions and -@dangerous, used for the security setup in step 11.

Next

The cache took the bulk of the "just looking" reads off PostgreSQL, but some reads can never be cached: they need data much fresher than a cache can offer, or their query conditions vary too much to cache at all. As those reads keep growing, the usual next step is to send reads to the database's read-only replicas. The next article, “PostgreSQL Read/Write Splitting: Replication Lag, Routing and What to Watch For”, explains where replication lag comes from, which queries may go to a replica, how to handle reading right after a write, and how the application should react when a replica falls behind or fails.