Overview

A Redis Cluster with six nodes (three primaries, three replicas) is not a read-scaled system out of the box. By default, all reads go to the primary of the slot that owns the key. The replicas exist for failover, not for load distribution. If your API issues 50,000 GET commands per second, all 50,000 go to the three primary nodes. The replicas idle while the primaries saturate.

Two complementary patterns address this. Read replicas route eligible reads to replica nodes using REPLICA_PREFERRED (Lettuce) or SLAVE_PREFERRED (Jedis). The read load spreads across both primary and replica shards at the cost of replica lag — replicas are asynchronously replicated and may lag the primary by 1–20 ms under normal conditions and 100–500 ms under a primary CPU spike. Near-cache moves a subset of frequently read, slowly changing data into the application pod’s own memory, eliminating the Redis network hop entirely for those reads — at the cost of a client-side invalidation protocol and additional JVM heap.

The two patterns are not interchangeable. Use read replicas for data that must be consistent across all pods within the replica lag window and whose staleness budget is measured in milliseconds. Use near-cache for data where staleness can be measured in seconds and where the read-to-write ratio is so high that eliminating the network hop pays for the heap overhead.

The use cases that benefit share one shape: reference data read at very high frequency during a predictable peak. In payments, that means exchange-rate reads during a settlement window (60-second staleness budget), routing tables such as BIC directories around a cut-off (24-hour staleness acceptable), and limit-matrix pre-checks before authorisation (30-second budget set by internal controls). In retail it is price and promotion lookups during a flash sale; in telecoms, tariff and plan lookups during a billing run. The examples below use the payments case because its staleness budgets are the strictest.

Redis Cluster replication is asynchronous by default

Unlike synchronous replication in a traditional RDBMS, Redis replication is asynchronous: the primary acknowledges a write before the replica has persisted it. WAIT numreplicas timeout forces a synchronous acknowledgement but adds latency proportional to replica count and network RTT. For settlement-critical writes (payment state, authorisation decisions), use WAIT 1 50 (wait for one replica, 50 ms timeout) and fall back gracefully if the replica count is not met. Never use WAIT for high-frequency reference-data writes — the latency overhead eliminates the caching benefit.

Replica Lag Budget

Every read-replica and near-cache strategy requires an explicit replica lag budget for each data type: the maximum acceptable difference between what a replica returns and what the primary holds. This is not a Redis configuration parameter — it is a business requirement that must be signed off by the data owner before you route reads to replicas or near-cache.

Replica lag has two components. Replication lag is the delay between a write completing on the primary and the replica applying that write. Under normal conditions with a well-provisioned primary, this is 1–5 ms. Under primary CPU saturation (common during settlement windows, flash sales or batch runs when write throughput spikes), it can reach 100–500 ms. Near-cache lag is the TTL you set on the Caffeine L1 cache, which determines how stale the in-JVM copy can be before it expires and is refreshed from Redis.

Data typeAcceptable lagRead strategyBusiness / regulatory constraint
Account balanceZero — always primaryPRIMARY onlyMust reflect the last committed transaction; any staleness is a correctness error and, in regulated sectors, a compliance finding
Payment authorisation stateZero — always primaryPRIMARY onlyIdempotency checks must read from primary; a stale replica read may allow a duplicate payment
Exchange rates60 secondsNear-cache (60 s TTL) → REPLICA_PREFERREDSettlement runs in fixed daily windows; 60-second staleness acceptable within a session
BIC/IBAN routing table24 hoursNear-cache (1 h TTL) → REPLICA_PREFERREDSWIFT BIC changes published at day start; 24-hour staleness standard industry practice
Limit matrix30 secondsREPLICA_PREFERRED (no near-cache)Limit changes by ops must propagate within 30 s; near-cache introduces additional lag beyond replica lag
Product configuration5 minutesNear-cache (5 min TTL) → REPLICA_PREFERREDNo real-time requirement; product changes go through a release pipeline with hours of lead time
Account balances must NEVER be read from a replica or near-cache

The most dangerous misapplication of read replicas in any balance-bearing system is routing balance reads to replicas to reduce primary load. A replica serving a balance read during a settlement window may lag by 100–500 ms — enough time for a debit to have cleared on the primary but not yet propagated to the replica. The API serves a pre-debit balance. The customer sees incorrect available funds. In a regulated payments business, serving a stale balance that leads to an incorrect payment decision is a material compliance event; in retail, the equivalent is overselling stock you do not have. Configure your Lettuce routing explicitly to never use REPLICA_PREFERRED for balance cache keys.

Read-Replica Topology

A Redis Cluster with read replicas has two read modes, controlled per-connection or per-command in Lettuce: MASTER (primary only, default), SLAVE (replica only — not recommended; fails if replica unavailable), MASTER_PREFERRED (primary preferred, falls back to replica), SLAVE_PREFERRED (deprecated name), and REPLICA_PREFERRED (replica preferred, falls back to primary when no replica is available).

For a peak-load API, the topology decision is: use REPLICA_PREFERRED at the connection level for a dedicated read connection factory, and use MASTER for the write and balance-read connection factory. Never use a single connection factory with alternating read modes — the per-request mode switching in Lettuce introduces routing inconsistencies under connection pool pressure.

RedisTopologyConfig.javajava
@Configuration
public class RedisTopologyConfig {

    @Value("${spring.data.redis.cluster.nodes}")
    private List<String> clusterNodes;

    // Primary connection factory: all writes + balance reads.
    // ReadFrom.MASTER ensures zero replica lag for correctness-critical keys.
    @Bean
    @Primary
    public LettuceConnectionFactory primaryConnectionFactory() {
        RedisClusterConfiguration config = new RedisClusterConfiguration(clusterNodes);
        config.setMaxRedirects(3);

        LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
            .readFrom(ReadFrom.MASTER)   // PRIMARY only: balances, payment state
            .commandTimeout(Duration.ofMillis(200))
            .build();

        return new LettuceConnectionFactory(config, clientConfig);
    }

    // Replica-preferred connection factory: reference data reads.
    // REPLICA_PREFERRED falls back to primary if no replica is available.
    @Bean
    @Qualifier("replicaConnectionFactory")
    public LettuceConnectionFactory replicaConnectionFactory() {
        RedisClusterConfiguration config = new RedisClusterConfiguration(clusterNodes);
        config.setMaxRedirects(3);

        LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
            .readFrom(ReadFrom.REPLICA_PREFERRED) // replicas for ref data
            .commandTimeout(Duration.ofMillis(200))
            .build();

        return new LettuceConnectionFactory(config, clientConfig);
    }

    // Separate RedisTemplate for reference-data reads via replica connection.
    // Balance and payment-state reads use the @Primary (master) template.
    @Bean
    @Qualifier("replicaRedisTemplate")
    public RedisTemplate<String, Object> replicaRedisTemplate(
            @Qualifier("replicaConnectionFactory") LettuceConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }
}

Near-Cache Pattern

A near-cache is a client-side, process-local cache that sits in front of a distributed cache. The name comes from Hazelcast, which uses it as a first-class feature; the concept applies equally to Caffeine sitting in front of Redis. What distinguishes a near-cache from a generic L1 cache is its invalidation protocol: when the backing distributed cache changes a value, the near-cache in every client must be notified so it can evict its stale copy.

Without invalidation, a near-cache with a 60-second TTL means every pod can serve a value that is up to 60 seconds stale — regardless of how many times that value was updated in Redis during those 60 seconds. With Redis keyspace notifications as the invalidation signal, the near-cache entry is evicted within milliseconds of the Redis key being updated, and the next read repopulates from the (now fresh) replica. This reduces effective staleness from “up to TTL” to “replica lag + keyspace notification delivery latency” — typically 5–30 ms total.

The trade-off for near-cache is JVM heap consumption and the operational overhead of enabling Redis keyspace notifications. For exchange rates (200 entries, ~500 bytes each), the heap cost is 100 KB per pod — negligible. For a limit matrix (5,000 entries, ~1 KB each), it is 5 MB per pod — still acceptable. For account balances, near-cache is never appropriate regardless of size, as described above.

NearCacheConfig.javajava
@Configuration
public class NearCacheConfig {

    // Near-cache for exchange rates: 60-second TTL, max 200 entries.
    // Coherence via Redis keyspace notifications (see NearCacheInvalidationListener).
    @Bean("exchangeRateNearCache")
    public Cache exchangeRateNearCache() {
        com.github.benmanes.caffeine.cache.Cache<String, ExchangeRate> cache =
            Caffeine.newBuilder()
                .maximumSize(200)
                .expireAfterWrite(60, TimeUnit.SECONDS)
                .recordStats()
                .build();
        return new CaffeineCache("exchange-rates-near", cache);
    }

    // Near-cache for BIC/IBAN routing: 1-hour TTL, max 10,000 entries.
    @Bean("bicRoutingNearCache")
    public Cache bicRoutingNearCache() {
        com.github.benmanes.caffeine.cache.Cache<String, BicRouting> cache =
            Caffeine.newBuilder()
                .maximumSize(10_000)
                .expireAfterWrite(1, TimeUnit.HOURS)
                .recordStats()
                .build();
        return new CaffeineCache("bic-routing-near", cache);
    }
}

// Invalidation listener: evicts near-cache entries on Redis keyspace notifications.
@Component
public class NearCacheInvalidationListener implements MessageListener {

    private final Cache exchangeRateNearCache;
    private final Cache bicRoutingNearCache;
    private final MeterRegistry registry;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = new String(message.getBody(), StandardCharsets.UTF_8);
        if (key.startsWith("exchange-rates::")) {
            exchangeRateNearCache.evict(key.substring(16));
            registry.counter("near_cache.invalidations",
                "cache", "exchange-rates").increment();
        } else if (key.startsWith("bic-routing::")) {
            bicRoutingNearCache.evict(key.substring(13));
            registry.counter("near_cache.invalidations",
                "cache", "bic-routing").increment();
        }
    }
}

Spring Data Redis Routing

The cleanest way to route reads to replicas in a Spring application is a dual-template pattern: one RedisTemplate wired to the MASTER connection factory, one wired to the REPLICA_PREFERRED factory. Services inject the correct template at the class level using @Qualifier. This is explicit and easily audited — the choice of replica vs. primary is visible in the service constructor, not buried in a framework configuration that can be misread.

Avoid configuring REPLICA_PREFERRED at the application-wide level in application.yaml. That approach makes it easy to accidentally route balance reads to replicas when a new service is created without awareness of the dual-template pattern. Explicit injection of the correct template at the service layer is safer.

ExchangeRateService.javajava
@Service
public class ExchangeRateService {

    private final Cache nearCache;        // Caffeine L1
    private final RedisTemplate<String, ExchangeRate> replicaTemplate; // REPLICA_PREFERRED
    private final ExchangeRateRepository repository; // DB fallback

    public ExchangeRateService(
            @Qualifier("exchangeRateNearCache") Cache nearCache,
            @Qualifier("replicaRedisTemplate") RedisTemplate<String, ExchangeRate> replicaTemplate,
            ExchangeRateRepository repository) {
        this.nearCache = nearCache;
        this.replicaTemplate = replicaTemplate;
        this.repository = repository;
    }

    public ExchangeRate getRate(String currencyPair) {
        // 1. Near-cache (Caffeine, in-JVM): <1 µs, staleness = TTL (60 s)
        Cache.ValueWrapper cached = nearCache.get(currencyPair);
        if (cached != null) return (ExchangeRate) cached.get();

        // 2. Redis replica read: ~1 ms, replica lag budget 60 s
        String redisKey = "exchange-rates::" + currencyPair;
        ExchangeRate rate = replicaTemplate.opsForValue().get(redisKey);
        if (rate != null) {
            nearCache.put(currencyPair, rate); // populate near-cache
            return rate;
        }

        // 3. Database fallback: ~20 ms, refreshes both Redis and near-cache
        rate = repository.findByCurrencyPair(currencyPair)
            .orElseThrow(() -> new RateNotFoundException(currencyPair));
        replicaTemplate.opsForValue().set(redisKey, rate,
            Duration.ofMinutes(5)); // write to Redis primary (via primary connection)
        nearCache.put(currencyPair, rate);
        return rate;
    }
}
replicaTemplate.opsForValue().set() still writes to the primary

Despite using the REPLICA_PREFERRED connection factory, write commands (SET, DEL, HSET, etc.) are always routed to the primary shard. Redis replicas are read-only by default (replica-read-only yes in redis.conf). Sending a write to a replica returns READONLY error; Lettuce re-routes writes to the primary automatically. The dual-template pattern is therefore about read routing, not write routing — writes always go to primaries regardless of the connection’s ReadFrom setting.

Hazelcast Near Cache

Hazelcast IMDG provides a built-in Near Cache feature for maps that removes the need to implement a separate Caffeine + Redis keyspace notification stack. Hazelcast manages the coherence protocol internally: when a primary map entry changes, Hazelcast sends invalidation messages to all client Near Cache instances subscribed to that map. This is the preferred near-cache implementation when the application already uses Hazelcast for distributed state — the coherence protocol is battle-tested and the configuration is declarative.

When the application uses Redis (not Hazelcast) as the distributed cache, the Caffeine + keyspace notification pattern described above is the equivalent. Do not introduce Hazelcast solely for Near Cache when Redis is already the distributed cache — the operational overhead of running two distributed data systems for the same workload rarely pays off.

hazelcast.yamlyaml
hazelcast-client:
  cluster-name: integration-prod
  network:
    cluster-members:
      - hz-node-0.hazelcast-svc.integration.svc.cluster.local:5701
      - hz-node-1.hazelcast-svc.integration.svc.cluster.local:5701
      - hz-node-2.hazelcast-svc.integration.svc.cluster.local:5701

  near-caches:
    # Near Cache for exchange rates: 200 entries, 60-second TTL.
    # Invalidation mode INVALIDATE: coherence via Hazelcast cluster events.
    exchange-rates:
      in-memory-format: OBJECT       # deserialized; faster than BINARY for read-heavy
      invalidate-on-change: true     # coherence: evict on remote update
      time-to-live-seconds: 60
      max-idle-seconds: 120
      eviction:
        eviction-policy: LFU
        max-size-policy: ENTRY_COUNT
        size: 200
      local-update-policy: INVALIDATE # invalidate near-cache on write (not update)
      preloader:
        enabled: true
        store-interval-seconds: 600  # persist near-cache keys to disk every 10 min
        store-initial-delay-seconds: 120

    bic-routing:
      in-memory-format: OBJECT
      invalidate-on-change: true
      time-to-live-seconds: 3600   # 1 hour near-cache TTL
      eviction:
        eviction-policy: LFU
        max-size-policy: ENTRY_COUNT
        size: 10000
      local-update-policy: INVALIDATE

Peak-Window API Patterns

Many read-heavy APIs face a predictable peak: a payment scheme’s settlement window, a retailer’s flash sale, a broker’s market open, a utility’s month-end billing run. During that window the volume of balance or stock pre-checks, rate or price lookups, and routing queries spikes significantly above the daily baseline. Near-cache and read-replica topologies are most valuable during this window precisely because two loads occur together: high read throughput and high write throughput (settlement confirmations or orders updating account state). The read-replica pattern offloads the reference-data reads from primaries that are simultaneously absorbing settlement writes.

Five patterns hold up in production during such windows:

  1. Separate read and write connection pools

    Use two connection pool configurations: a write pool (default: 10 connections per node, timeout 200 ms) targeting primaries, and a read pool (default: 20 connections per node, timeout 150 ms) targeting replicas via REPLICA_PREFERRED. The read pool is larger because reference-data reads are more numerous and shorter-lived than writes. Tune pool sizes based on the connection count observed in redis-cli CLIENT LIST during a peak-window load test.

  2. Preheat the near-cache before the peak window opens

    Settlement sessions, scheduled sales and batch runs open at a known time. Schedule a cache-warm job 10 minutes before the window opens to populate the near-cache for exchange rates and BIC routing tables. This ensures the near-cache is fully populated before the spike hits, eliminating DB fallback reads during the window. The warm job reads from Redis replicas, not from the database — it only touches the DB if the Redis near-cache is cold (e.g., after a Redis cluster failover).

  3. Promote replicas during primary failover without routing stale balance reads

    When a Redis primary fails, Redis Sentinel or Redis Cluster promotes a replica to primary. During the promotion (typically 10–30 seconds), the near-cache TTLs provide continuity for reference data reads. For balance and payment-state reads, implement a circuit breaker: if the primary is unavailable and the read-from-replica fallback is not configured for that key type, return a 503 rather than serving a potentially stale balance. A 503 is recoverable; a stale balance that authorises an overdraft is not.

  4. Monitor replica lag explicitly during the peak window

    Instrument the Lettuce connection factory to emit redis.replica.lag.ms metrics for each replica node. Alert when lag exceeds 100 ms — that is the threshold at which limit-matrix reads from replicas start producing values that have missed recent limit-change operations. If lag exceeds 100 ms on any replica, temporarily switch that key type back to primary-only reads and alert the operations team.

  5. ISO 20022 pacs.008 enrichment: near-cache for BIC/LEI resolution

    SWIFT MT-to-MX migration requires BIC-to-LEI resolution at message transformation time. The ISO 20022 BIC/LEI resolution table is a classic near-cache candidate: 10,000–50,000 entries, updated once per business day at the SWIFT open time, read on every international payment. The same reasoning applies to any per-message enrichment lookup, such as SKU-to-supplier or postcode-to-region mapping. Configure a 1-hour near-cache TTL with Hazelcast invalidate-on-change: true. The near-cache eliminates the Redis hop for every enrichment operation, cutting p99 enrichment latency from 2 ms to <0.1 ms at 10,000 pacs.008 messages per hour.

Monitoring & Observability

Near-cache and read-replica topologies introduce two failure modes that standard Redis monitoring does not catch: replica lag drift and near-cache divergence. Both require dedicated metrics and alert thresholds.

MetricSourceAlert thresholdWhat it means
redis.replica.lag.msINFO replication → master_repl_offset delta>100 msReplica is falling behind; ref-data reads may be stale beyond the lag budget
near_cache.hits / near_cache.missesCaffeine stats() via MicrometerHit rate <80% for exchange-ratesNear-cache is undersized or TTL is too short; reads are falling through to Redis
near_cache.invalidationsCustom counter on keyspace notification receipt>100/s sustained for >5 minHigh write rate on ref-data keys; near-cache TTL is likely too long
redis.connected_slavesINFO replication< expected replica countA replica is down; REPLICA_PREFERRED falls back to primary, increasing primary load
lettuce.command.latency.p99Lettuce Micrometer integration>10 ms on replica readsReplica is overloaded or the network path to the replica is degraded
ReplicaLagMonitor.javajava
// Publishes replica lag as a Micrometer gauge for each Redis Cluster replica.
// Scraped by Prometheus; alert in Alertmanager when lag exceeds 100ms.
@Component
public class ReplicaLagMonitor {

    private final RedisClusterCommands<String, String> clusterCommands;
    private final MeterRegistry registry;

    @Scheduled(fixedDelay = 5000) // every 5 seconds
    public void collectReplicaLag() {
        clusterCommands.clusterNodes().stream()
            .filter(node -> node.is(RedisClusterNode.NodeFlag.REPLICA))
            .forEach(replica -> {
                Properties info = clusterCommands.info("replication");
                String lagStr = info.getProperty("master_link_status");
                String offsetDelta = info.getProperty("master_repl_offset");
                if (offsetDelta != null) {
                    Gauge.builder("redis.replica.lag.ms",
                        () -> estimateLagMs(offsetDelta))
                        .tag("host", replica.getUri().getHost())
                        .register(registry);
                }
            });
    }

    private double estimateLagMs(String offsetDelta) {
        // Approximate: 1 byte/µs throughput on a typical 10 Gbps intra-rack link.
        // Replace with actual measurement from master_last_io_seconds_ago if available.
        long delta = Long.parseLong(offsetDelta);
        return delta / 1_000.0; // bytes to microseconds to milliseconds
    }
}

Failure Modes

Near-cache divergence during Redis Cluster failover

When a Redis primary fails and a replica is promoted, there is a 10–30 second window during which the new primary may not have the last few writes that the old primary received before crashing. If those writes were limit changes or exchange rate updates, the pods’ near-caches hold the last value from the keyspace notification they received. After promotion, the new primary is now “authoritative” with slightly older data. The near-cache entries are still valid according to their TTL, but the near-cache TTL countdown started from the last keyspace notification — not from the promotion event. If your near-cache TTL is 60 seconds and the failover took 20 seconds, pods may serve near-cache entries for up to 40 more seconds based on data that was current before the failover but is now stale relative to the promoted primary. For exchange rates with a 60-second business staleness budget, this is acceptable. For limit matrices with a 30-second budget, the overlap is a risk. Mitigation: on detection of a Redis Cluster topology change (ClusterTopologyChangedEvent in Lettuce), flush all near-caches immediately to force re-fetch from the new primary.

REPLICA_PREFERRED fallback during replica unavailability increases primary load

When a replica is unavailable (failover in progress, replica pod restarted in OpenShift), Lettuce’s REPLICA_PREFERRED falls back to the primary for all reads that would have gone to that replica. At 50,000 reference-data reads per second normally distributed across primaries and replicas, losing one of three replicas during a peak window can increase primary read load by 30–50%. If the primary is already near its throughput limit due to settlement writes, this additional read load can push it into CPU saturation, increasing replication lag on the remaining replicas — which further reduces their read-availability, creating a feedback loop. Mitigation: size primaries for the scenario of all replicas being unavailable simultaneously. This is a worst-case sizing exercise, not a normal-operation sizing. For workloads tied to a settlement window or scheduled sale, the worst case occurs precisely during the peak.

Keyspace notifications missed during Redis restart cause stale near-caches

Redis keyspace notifications are fire-and-forget: they are not persisted and are not retransmitted on reconnect. If a pod’s Redis subscription is interrupted (pod restart, network partition, Redis restart), it misses all keyspace notifications that were published during the interruption. The pod’s near-cache continues to hold the pre-interruption values until they expire by TTL. For exchange rates with a 60-second TTL, the maximum staleness after a 30-second interruption is 60 seconds — the same as a normal TTL expiry. Mitigation: on reconnect, flush the near-cache for all caches that use keyspace notification coherence. Implement a RedisConnectionStateListener that flushes on reconnection. The flush causes a brief miss storm to Redis; this is acceptable if the pod’s readiness probe suppresses traffic during the warm period.

Steps to Deploy Near-Cache and Read-Replica Topology

  1. Build a data-classification table with lag budgets

    For every entity that will be cached, document: staleness budget (seconds), read strategy (PRIMARY / REPLICA_PREFERRED / near-cache), near-cache TTL if applicable, invalidation mechanism, and sign-off from the data owner. Get this signed off before writing a line of code. The sign-off prevents teams from quietly routing balance reads to replicas when caching a new entity type.

  2. Configure dual Lettuce connection factories

    Create a MASTER factory (primary only) and a REPLICA_PREFERRED factory. Wire them to separate RedisTemplate beans annotated with @Qualifier. Never configure REPLICA_PREFERRED at the application-level spring.data.redis property level — that makes it too easy for new services to inherit the replica routing without understanding the lag implications.

  3. Enable Redis keyspace notifications with minimal scope

    Run CONFIG SET notify-keyspace-events Kgx (keyevent + generic + expired-without-string) on the cache Redis Cluster — this is narrower than KEA and reduces CPU overhead significantly. Verify that DELETE and EXPIRE events are being published for the keys used by the near-cache. Load-test the notification throughput at peak write rate to confirm the Redis node CPU does not exceed 60% with notifications enabled.

  4. Implement near-cache with Caffeine and a keyspace invalidation listener

    Configure per-cache Caffeine specs (maximumSize, expireAfterWrite). Implement RedisMessageListenerContainer subscribed to __keyevent@0__:del and __keyevent@0__:expired. Add a RedisConnectionStateListener that flushes all near-caches on reconnect. Test: write a key to Redis, observe the near-cache entry evict within 50 ms on all pods.

  5. Add replica-lag and near-cache hit-rate metrics

    Implement the ReplicaLagMonitor scheduled bean. Expose Caffeine stats via Micrometer. Add a custom counter for keyspace notification receipt latency (time between Redis publish and application receipt). Create Alertmanager rules: lag > 100 ms (severity: warning), lag > 500 ms (severity: critical), near-cache hit rate < 80% (severity: warning).

  6. Implement the ClusterTopologyChangedEvent flush

    Register a Lettuce ClusterTopologyChangedEvent listener. On topology change (primary failover, replica added/removed), flush all near-caches that use keyspace notification coherence. Log the flush event with the topology change details. This handles the near-cache divergence risk during failover described in the failure modes section.

  7. Load test at peak-window scale before go-live

    Run a load test at 1.5x peak-window RPS. Verify replica lag stays below 20 ms under write load. Verify near-cache hit rates stay above 95% for exchange rates and 98% for BIC routing. Verify that a simulated primary failover (stop the Redis primary pod) triggers the near-cache flush and does not route balance reads to the promoted replica.