Skip to content

Latest commit

 

History

History
462 lines (380 loc) · 18.8 KB

redis-proxy-deployment.md

File metadata and controls

462 lines (380 loc) · 18.8 KB

redis-proxy Deployment Guide

redis-proxy is a Redis-protocol reverse proxy that enables gradual migration from Redis to ElasticKV through dual-write, shadow-read comparison, and phased primary cutover.

Docker Image

Pre-built images are published to GitHub Container Registry when relevant files change on main (see path filters in the workflow):

ghcr.io/bootjp/elastickv/redis-proxy:latest
ghcr.io/bootjp/elastickv/redis-proxy:sha-<commit>

The CI workflow (.github/workflows/redis-proxy-docker.yml) builds the image automatically when files under cmd/redis-proxy/, proxy/, Dockerfile.redis-proxy, go.mod, go.sum, or the workflow file itself change.

Building locally

# Docker
docker build -f Dockerfile.redis-proxy -t redis-proxy .

# Binary
go build -o redis-proxy ./cmd/redis-proxy/

Command-Line Options

Flag Default Description
-listen :6479 Proxy listen address
-primary localhost:6379 Primary (Redis) address
-primary-db 0 Primary Redis DB number
-primary-password (empty) Primary Redis password
-secondary localhost:6380 Secondary (ElasticKV) address
-secondary-db 0 Secondary Redis DB number
-secondary-password (empty) Secondary Redis password
-primary-pool-size 128 Primary Redis backend connection pool size
-elastickv-pool-size 192 ElasticKV backend command pool size; keep the server-side ELASTICKV_REDIS_PER_PEER_CONNECTIONS above this, with headroom for dedicated PubSub connections
-secondary-write-concurrency 0 Shared maximum for all asynchronous secondary writes, including scripts. 0 derives half of the secondary backend pool size, minimum 1
-secondary-script-concurrency 0 Lua-script sublimit within -secondary-write-concurrency. 0 derives one thirty-second of the shared write limit, capped at 3, minimum 1
-secondary-blocking-replay-concurrency 0 Fallback mutating blocking-command replay sublimit. 0 uses remaining secondary backend pool capacity, capped at 32
-secondary-write-queue-size 0 Bounded queue for non-script secondary writes. 0 derives 64 * concurrency, clamped to 64..8192
-secondary-script-queue-size 0 Bounded queue for secondary Lua-script writes. 0 derives 64 * concurrency, clamped to 64..8192
-secondary-blocking-replay-queue-size 0 Bounded queue for mutating blocking-command replays. 0 derives 64 * concurrency, clamped to 64..8192
-mode dual-write Proxy mode (see below)
-secondary-timeout 30s End-to-end secondary write deadline, including queue wait
-secondary-script-timeout 5m End-to-end secondary Lua-script write deadline, including queue wait. 0 follows -secondary-timeout; the effective value must not exceed the ElasticKV Lua dispatch cap (5m)
-shadow-timeout 3s Shadow read timeout
-sentry-dsn (empty) Sentry DSN (empty = disabled)
-sentry-env (empty) Sentry environment name
-sentry-sample 1.0 Sentry sample rate
-metrics :9191 Prometheus metrics endpoint

Proxy Modes

Five modes support a phased migration strategy.

Mode Reads from Writes to Use case
redis-only Redis Redis only Transparent proxy. Route traffic through the proxy first
dual-write Redis Redis + ElasticKV Begin data sync. Populate ElasticKV
dual-write-shadow Redis (+ shadow compare from ElasticKV) Redis + ElasticKV Verify read consistency between backends
elastickv-primary ElasticKV (+ shadow compare from Redis) ElasticKV + Redis Promote ElasticKV to primary. Redis as fallback
elastickv-only ElasticKV ElasticKV only Migration complete. Decommission Redis

Recommended Migration Path

redis-only -> dual-write -> dual-write-shadow -> elastickv-primary -> elastickv-only

Monitor metrics at each stage and roll back to the previous mode if issues arise. Mode changes require a proxy restart.

Deployment Examples

Minimal (redis-only)

docker run --rm \
  -p 6379:6379 \
  ghcr.io/bootjp/elastickv/redis-proxy:latest \
  -listen :6379 \
  -primary redis.internal:6379 \
  -mode redis-only

Point your application at the proxy. Behavior is identical to connecting directly to Redis.

Dual-Write with Shadow Comparison

docker run --rm \
  -p 6379:6479 \
  -p 9191:9191 \
  ghcr.io/bootjp/elastickv/redis-proxy:latest \
  -listen :6479 \
  -primary redis.internal:6379 \
  -primary-password "${REDIS_PASSWORD}" \
  -secondary elastickv.internal:6380 \
  -elastickv-pool-size 192 \
  -secondary-write-concurrency 96 \
  -secondary-script-concurrency 3 \
  -secondary-blocking-replay-concurrency 32 \
  -mode dual-write-shadow \
  -secondary-timeout 30s \
  -secondary-script-timeout 5m \
  -shadow-timeout 3s \
  -sentry-dsn "${SENTRY_DSN}" \
  -sentry-env production \
  -metrics :9191

Docker Compose

services:
  redis-proxy:
    image: ghcr.io/bootjp/elastickv/redis-proxy:latest
    ports:
      - "6379:6479"
      - "9191:9191"
    command:
      - -listen=:6479
      - -primary=redis:6379
      - -secondary=elastickv:6380
      - -elastickv-pool-size=192
      - -secondary-write-concurrency=96
      - -secondary-script-concurrency=3
      - -secondary-blocking-replay-concurrency=32
      - -mode=dual-write-shadow
      - -metrics=:9191
    depends_on:
      - redis
      - elastickv

  redis:
    image: redis:7
    ports:
      - "6379"

  elastickv:
    image: ghcr.io/bootjp/elastickv:latest
    ports:
      - "6380"

High-availability redis-proxy (nginx TCP LB + 2 replicas)

The single-container deploy above causes a brief connection blip when the container restarts (image upgrade, config change, etc.). For operator-driven redeploys without dropping clients, put nginx's stream module in front of two redis-proxy replicas and drain them one at a time.

Assets live under deploy/redis-proxy/:

  • deploy/redis-proxy/nginx.conf -- stream-module TCP LB config.
  • deploy/redis-proxy/docker-compose.ha.yml -- two redis-proxy replicas (redis-proxy-a, redis-proxy-b) plus an nginx:1.27-alpine frontend.

Architecture

           client (redis-cli, app)
                     |
                     v  :6379 (stable)
              +---------------+
              |     nginx     |   stream {} -- hash $remote_addr consistent
              |  (stream TCP) |   passive health: max_fails=3 fail_timeout=10s
              +-------+-------+
                      |
           +----------+----------+
           v                     v
   redis-proxy-a:6379    redis-proxy-b:6379
           |                     |
           +----------+----------+
                      |
                      v
                elastickv cluster
                  (+ Redis, in
                  dual-write modes)

Nginx only exposes the client-facing port; the redis-proxy replicas are reachable only from within the compose network by service name.

Session affinity

The upstream uses hash $remote_addr consistent. This pins a given client's new connections to the same backend so that per-connection state (MULTI/EXEC, WATCH, SUBSCRIBE, Lua SELECT, etc.) lands on one replica that can actually observe it. Consistent hashing also minimises reshuffles when a backend is drained.

nginx retries the connection against the next upstream only when the TCP handshake fails (proxy_next_upstream on + proxy_next_upstream_tries 2). Once bytes have been exchanged, nginx does not replay the command on another backend -- double-executing non-idempotent Redis commands would be worse than a reconnect.

Trade-off: a client whose backend is taken offline sees its existing connection broken and must reconnect. Only new TCP sessions are steered away. This is the correct behaviour vs. silently double-sending an in-flight command.

Bring up

cd deploy/redis-proxy
# Build + start both backends and nginx.
docker compose -f docker-compose.ha.yml up -d --build

# Point the client at the nginx endpoint.
redis-cli -p 6379 PING
# PONG

Override backend wiring via env vars before docker compose up:

REDIS_PROXY_PRIMARY=redis.prod.internal:6379 \
REDIS_PROXY_SECONDARY=elastickv-1.prod.internal:6380,elastickv-2.prod.internal:6380,elastickv-3.prod.internal:6380 \
REDIS_PROXY_ELASTICKV_POOL_SIZE=192 \
REDIS_PROXY_MODE=dual-write-shadow \
  docker compose -f docker-compose.ha.yml up -d

Rolling redeploy procedure

Do one backend at a time; wait for nginx passive health to mark it down before restarting, and wait for it to come back up before touching the other replica.

cd deploy/redis-proxy

# 1. Pull the new image into the compose project.
docker compose -f docker-compose.ha.yml pull redis-proxy-a

# 2. Stop backend a. Passive health on nginx will observe max_fails
#    within ~10s (fail_timeout) on the first few failed new-connection
#    attempts and will stop sending traffic to redis-proxy-a.
#    Existing nginx->a TCP sessions terminate; clients must reconnect
#    and will land on redis-proxy-b.
docker compose -f docker-compose.ha.yml stop redis-proxy-a

# 3. Recreate with the new image.
docker compose -f docker-compose.ha.yml up -d redis-proxy-a

# 4. Verify it is serving before touching the other replica.
docker compose -f docker-compose.ha.yml exec redis-proxy-a \
    /redis-proxy --help >/dev/null    # smoke
# Or, from a host with network access to the compose network:
# redis-cli -h <redis-proxy-a-ip> -p 6379 PING

# 5. Repeat for redis-proxy-b.
docker compose -f docker-compose.ha.yml pull redis-proxy-b
docker compose -f docker-compose.ha.yml stop redis-proxy-b
docker compose -f docker-compose.ha.yml up -d redis-proxy-b

The existing scripts/rolling-update.sh is for the elastickv raft cluster, not the redis-proxy front-end; it is not involved in this sequence.

Observability

nginx writes one line per client session to /var/log/nginx/redis-proxy-access.log with this format (defined in nginx.conf):

$remote_addr [$time_local] $protocol $status $bytes_sent $bytes_received upstream=$upstream_addr session_time=$session_time

Tail it while redeploying to confirm traffic has shifted:

docker compose -f docker-compose.ha.yml exec nginx \
    tail -f /var/log/nginx/redis-proxy-access.log

Per-backend redis-proxy metrics remain on :9191 of each replica as before; scrape them individually (see the Prometheus Metrics section below).

Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis-proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: redis-proxy
  template:
    metadata:
      labels:
        app: redis-proxy
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "9191"
    spec:
      containers:
        - name: redis-proxy
          image: ghcr.io/bootjp/elastickv/redis-proxy:latest
          args:
            - -listen=:6479
            - -primary=redis:6379
            - -secondary=elastickv:6380
            - -mode=dual-write-shadow
            - -metrics=:9191
          ports:
            - containerPort: 6479
              name: redis
            - containerPort: 9191
              name: metrics
          livenessProbe:
            tcpSocket:
              port: 6479
            initialDelaySeconds: 5
            periodSeconds: 10
          readinessProbe:
            tcpSocket:
              port: 6479
            initialDelaySeconds: 3
            periodSeconds: 5
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: "1"
              memory: 512Mi

Note: The distroless base image does not include redis-cli. If you want to use the exec-based probe below, build a redis-proxy image that includes redis-cli (or another ping tool) in the same container. Otherwise, prefer the tcpSocket probes shown in the Deployment spec above or an HTTP health endpoint.

# Alternative: exec-based probe (requires redis-cli in the image)
livenessProbe:
  exec:
    command:
      - /bin/sh
      - -c
      - 'redis-cli -p 6479 PING || exit 1'
  initialDelaySeconds: 5
  periodSeconds: 10

Health Checks

The proxy does not expose an HTTP health endpoint. Use the Redis PING command to verify availability:

redis-cli -p 6479 PING
# PONG

Prometheus Metrics

Available at /metrics on the address specified by -metrics.

Key Metrics

Metric Type Description
proxy_command_total Counter Commands processed (labels: command, backend, status)
proxy_command_duration_seconds Histogram Backend command latency
proxy_primary_write_errors_total Counter Primary write errors
proxy_secondary_write_errors_total Counter Secondary write errors
proxy_primary_read_errors_total Counter Primary read errors
proxy_shadow_read_errors_total Counter Shadow read errors
proxy_divergences_total Counter Shadow read mismatches (labels: command, kind)
proxy_migration_gap_total Counter Expected mismatches from incomplete migration (labels: command)
proxy_async_drops_total Counter Async operations dropped due to backpressure
proxy_async_drops_by_queue_total{queue,reason} Counter Drops split by write/script/blocking/shadow and queue_full/expired
proxy_async_queue_depth{queue} Gauge Async operations waiting for worker capacity
proxy_async_queue_capacity{queue} Gauge Configured queue capacity
proxy_async_queue_delay_seconds{queue} Histogram Time spent waiting for worker capacity
proxy_async_workers_active{queue} Gauge Active async workers by queue
proxy_backend_pool_limit{backend} Gauge Configured connection limit for the active backend pool
proxy_backend_pool_connections{backend,state} Gauge Current total and idle go-redis connections
proxy_backend_pool_pending_requests{backend} Gauge Requests waiting for a backend connection
proxy_backend_pool_events{backend,event} Gauge Active-pool hits, misses, waits, timeouts, unusable, and stale counts
proxy_backend_pool_wait_duration_seconds{backend} Gauge Cumulative wait duration for the active backend pool
proxy_active_connections Gauge Current active client connections
proxy_pubsub_shadow_divergences_total Counter Pub/Sub shadow message mismatches (labels: kind)
proxy_pubsub_shadow_errors_total Counter Pub/Sub shadow operation errors

Recommended Alerts

groups:
  - name: redis-proxy
    rules:
      - alert: ProxyDivergenceHigh
        expr: rate(proxy_divergences_total[5m]) > 0
        for: 10m
        annotations:
          summary: "Data mismatch detected between primary and secondary"

      - alert: ProxySecondaryWriteErrors
        expr: rate(proxy_secondary_write_errors_total[5m]) > 1
        for: 5m
        annotations:
          summary: "Secondary backend write errors are elevated"

      - alert: ProxyAsyncDrops
        expr: rate(proxy_async_drops_total[5m]) > 0
        for: 5m
        annotations:
          summary: "Async goroutine limit reached; secondary may be slow"

Internal Parameters

Parameter Value Description
Redis connection pool size 128 Default go-redis pool size for Redis
ElasticKV connection pool size 192 Default per-leader command pool; regular and blocking replay pools share the server per-peer budget, while PubSub uses dedicated sockets outside the pool
ElasticKV Redis per-peer connection cap 512 Default server-side cap: two proxy replicas at pool 192, plus dedicated PubSub/shadow PubSub headroom
Dial timeout 5s Backend connection timeout
Read timeout Redis: 3s, ElasticKV: 3s Default backend read timeout. Async secondary replays override the per-call read timeout with the remaining queue deadline; blocking commands add a 10s read grace to their requested wait
Write timeout 3s Backend write timeout
Async write concurrency fallback 4096 Package fallback; the command derives a lower limit from backend pool size
Async blocking replay concurrency cap 32 Command-derived maximum for mutating blocking-command replays after normal writes reserve pool capacity
Shadow read goroutine limit 1024 Max concurrent shadow comparisons
PubSub compare window 2s Message matching window
PubSub sweep interval 500ms Expired message scan interval

Graceful Shutdown

The proxy handles SIGINT / SIGTERM for graceful shutdown:

  1. Stops accepting new connections
  2. Waits for in-flight async goroutines to complete
  3. Releases backend connection pools
  4. Flushes Sentry buffers (up to 2 seconds)

Recommended shutdown order: redis-proxy -> application -> Redis / ElasticKV.

Troubleshooting

Secondary writes are falling behind

  • Check proxy_async_queue_depth, proxy_async_queue_delay_seconds, and proxy_async_drops_by_queue_total by queue before increasing concurrency. A sustained blocking queue means BZPOP/XREAD replay work is lagging behind normal writes.
  • Check proxy_backend_pool_pending_requests and the waits/timeouts pool events. Pool waits mean concurrency is too high for the configured pool.
  • Keep ELASTICKV_REDIS_PER_PEER_CONNECTIONS at least proxy replicas sharing one client IP * -elastickv-pool-size + 128; PubSub and shadow PubSub use dedicated connections outside the command pool, and detached PubSub sockets may remain counted until cleanup. With the HA compose defaults, use at least 512. Keep -secondary-write-concurrency at or below the pool size.
  • Successful BZPOPMIN / BZPOPMAX calls are replayed to ElasticKV as an internal fast ZREM variant on the normal write queue. Regular client ZREM still keeps Redis wrong-type behavior; stale BZPOP replays avoid wide type scans. Timeout/null blocking responses are not replayed because the primary made no mutation.
  • If script drops rise while backend pool waits stay at zero, the bottleneck is server-side Lua replay or wide-column cleanup, not connection acquisition. Keep -secondary-script-concurrency low; use -secondary-script-timeout for burst backlog and profile ElasticKV before raising concurrency.
  • A sustained expired rate means secondary throughput is below ingress. Increasing queue size only delays the loss; profile ElasticKV before raising concurrency.

High divergence count

  • Also check proxy_migration_gap_total. Pre-migration missing keys are counted as gaps, not divergences.
  • In dual-write-shadow mode, inspect proxy_divergences_total labels to identify which commands are mismatched.

Pub/Sub messages missing

  • Check proxy_pubsub_shadow_divergences_total.
  • kind=data_mismatch: message received by primary but not secondary.
  • kind=extra_data: message received by secondary only.