Skip to main content

Redis · OpenTelemetry · Tutorial

Redis Latency Monitoring: From SLOWLOG to Client Spans

Redis says a GET took 4 microseconds; your service says 40 ms. How to measure both sides, read SLOWLOG and LATENCY DOCTOR, and find the blocking command.

aiAxonIQ Team, Engineering at aiAxonIQ

Nov 20, 20269 min read

A Redis GET executes in a few microseconds. The service calling it reports a p99 of 40 ms for the same command. Both numbers are correct, and the distance between them is where most Redis performance problems live. Redis latency monitoring has to measure both sides: what the server spends executing commands, and what the client waits for in total. This guide covers the server-side tools Redis ships with, the metrics worth exporting, client spans from OpenTelemetry, the usual causes of a slow Redis, and the alerts that catch them.

Client-side and server-side latency are different numbers

Server-side latency is the time Redis spends executing a command. Client-side latency is everything the application waits for: borrowing a connection from the pool, serializing the request, the network round trip, queueing behind other commands inside Redis, execution, sending the reply, and parsing it. The server only sees one slice of that.

The queueing part is what makes Redis different from most databases. Commands execute on a single main thread. I/O threads, available since Redis 6, can take over reading from and writing to sockets, but execution stays serial. So when one client runs a command that takes 200 ms, every other client waits behind it. Their own commands still execute in microseconds, so their server-side numbers look perfect, while their client-side latency jumps by up to 200 ms. One slow command, thousands of slow requests.

Before reading anything else, get a baseline from redis-cli:

# Round-trip latency of PING from this host, in milliseconds
redis-cli -h redis-primary --latency

# The same, as a new sample line every 15 seconds
redis-cli -h redis-primary --latency-history -i 15

# Run ON the Redis host: latency the kernel or hypervisor adds
# before Redis even runs (test duration in seconds)
redis-cli --intrinsic-latency 100

Intrinsic latency is a floor that no Redis setting can lower. On a noisy virtual machine it can be several milliseconds, and it is worth knowing before you spend a day tuning commands.

SLOWLOG: commands that took long to execute

The slow log records commands whose execution time exceeded slowlog-log-slower-than, in microseconds. The default is 10000 (10 ms), which is an eternity for Redis, and slowlog-max-len keeps only the last 128 entries. Most production setups lower the threshold and raise the length:

CONFIG SET slowlog-log-slower-than 1000
CONFIG SET slowlog-max-len 1024

SLOWLOG GET 1
1) 1) (integer) 4021
   2) (integer) 1795012345
   3) (integer) 182340
   4) 1) "KEYS"
      2) "session:*"
   5) "10.0.3.17:52144"
   6) "reindex-worker"

Each entry has an ID, a Unix timestamp, the execution time in microseconds, the command and its arguments (trimmed to 32 arguments and 128 characters each by default), the client address and the client name. That last field is empty unless clients call CLIENT SETNAME, so make every service set it: "reindex-worker" is far more useful at 3 a.m. than an ephemeral port.

Two limits matter. The slow log measures execution only, not network or queueing time, so a client stuck behind a slow command never appears in it; only the command that blocked it does. And it is a ring buffer, so entries disappear under load. Poll it, or track the entry ID, rather than looking only when someone complains. CONFIG SET changes are also lost on restart unless you run CONFIG REWRITE or update redis.conf.

The latency monitor: LATENCY LATEST and LATENCY DOCTOR

The slow log only knows about commands. Redis also stalls for reasons that are not commands at all, and the latency monitor records those. It is off by default (latency-monitor-threshold 0). The threshold is in milliseconds:

CONFIG SET latency-monitor-threshold 50

LATENCY LATEST
1) 1) "fork"
   2) (integer) 1795012990
   3) (integer) 412
   4) (integer) 655
2) 1) "command"
   2) (integer) 1795012345
   3) (integer) 182
   4) (integer) 182

LATENCY LATEST returns one row per event type: its name, the time of the latest spike, the latest duration and the maximum seen, both in milliseconds. The event names point at the cause. command and fast-command are slow commands (the second covers O(1) and O(log N) commands, which should never be slow). fork is the fork for an RDB snapshot or AOF rewrite. aof-fsync-always, aof-write and its variants are disk writes for persistence. expire-cycle and eviction-cycle are the background work of expiring keys and evicting under maxmemory.

LATENCY HISTORY fork shows the recent samples for one event, and LATENCY DOCTOR turns everything recorded into a plain-language report with advice, such as checking transparent huge pages when forks are slow. LATENCY RESET clears it after a fix, so the next reading is about the new state.

INFO commandstats and latencystats

For trends rather than incidents, use the per-command counters in INFO:

INFO commandstats
cmdstat_get:calls=91822344,usec=118374512,usec_per_call=1.29,rejected_calls=0,failed_calls=0
cmdstat_hgetall:calls=402117,usec=95501223,usec_per_call=237.50,rejected_calls=0,failed_calls=0

INFO latencystats
latency_percentiles_usec_get:p50=1.003,p99=3.007,p99.9=12.031
latency_percentiles_usec_hgetall:p50=98.303,p99=2015.231,p99.9=8126.463

commandstats gives call counts and total execution time per command; usec_per_call is a lifetime average. latencystats, added in Redis 7.0, gives percentiles per command, and is controlled by latency-tracking (on by default) and latency-tracking-info-percentiles (p50, p99 and p99.9 by default). In the example, HGETALL has a median under 0.1 ms and a p99 of 2 ms: a few very large hashes are hiding in that command.

Both are cumulative since the server started or since CONFIG RESETSTAT. A p99 over three months of uptime barely moves when today gets worse. LATENCY HISTOGRAM, also from Redis 7.0, returns the raw cumulative bucket counts per command, and a histogram is the format that lets a metrics system compute percentiles over a recent window from the difference between two scrapes.

Common causes of Redis latency

Big keys and O(N) commands

Most slow commands are fine commands applied to the wrong data. HGETALL, SMEMBERS and LRANGE key 0 -1 are cheap on a 20-field hash and very expensive on one with two million fields. Deleting a big key is slow too, because DEL frees memory synchronously: use UNLINK, or set lazyfree-lazy-user-del yes so DEL behaves the same way. Find big keys with redis-cli --bigkeys or --memkeys, which walk the keyspace with SCAN, preferably against a replica, and check a specific key with MEMORY USAGE.

Then there are commands that are O(N) by design. KEYS scans the whole keyspace and should never run in production; use SCAN and deny KEYS to application users with an ACL rule such as -keys. FLUSHALL and FLUSHDB without ASYNC, SORT and wide ZRANGE calls belong on the same watch list. Lua scripts and functions run atomically, so a slow script blocks everything for its whole duration; it appears in the slow log as EVALSHA or FCALL.

Fork for RDB snapshots and AOF rewrites

To write a snapshot or rewrite the AOF, Redis forks. The fork copies the page tables of the process, which takes longer as the dataset grows, and the main thread is paused while it happens. INFO stats reports the last one as latest_fork_usec. Transparent huge pages make the copy-on-write that follows much more expensive; Redis logs a warning at startup when they are enabled, and the usual fix is echo never > /sys/kernel/mm/transparent_hugepage/enabled. If fork spikes line up with your latency spikes, consider taking snapshots on a replica instead of the primary.

Disk, swap and the network

With appendfsync always, every write waits for the disk. The default everysec is far cheaper, but a slow or saturated disk can still stall writes, which shows up as aof-write-pending-fsync events. If the host swaps, a command that touches a swapped-out page waits for the disk too; check the Swap: lines in /proc/<pid>/smaps for the Redis process, and make sure maxmemory leaves headroom for the fork. On the client side, cross-zone round trips, an exhausted connection pool and large replies all add latency that Redis never sees. Many keys created with the same TTL also expire together, which shows up as expire-cycle: add jitter to TTLs.

Exporting the metrics: redis_exporter or the Collector

Two common ways get these numbers into a metrics system. The Prometheus redis_exporter exposes most of INFO plus several of the sources above:

  • redis_commands_total and redis_commands_duration_seconds_total, by cmd, from commandstats
  • redis_latency_percentiles_usec, a summary by cmd, from latencystats
  • redis_commands_latencies_usec, a histogram by cmd built from LATENCY HISTOGRAM
  • redis_slowlog_length, redis_slowlog_last_id and redis_last_slow_execution_duration_seconds
  • redis_latency_spike_duration_seconds by event_name, from LATENCY LATEST
  • redis_latest_fork_usec, redis_connected_clients, redis_blocked_clients and redis_memory_used_bytes

The histogram is the most useful of these, because it gives a windowed p99 per command. Its buckets are in microseconds:

# p99 execution time per command over the last 5 minutes, in microseconds
histogram_quantile(0.99,
  sum by (le, cmd) (rate(redis_commands_latencies_usec_bucket[5m])))

# Average execution time per command, in seconds
rate(redis_commands_duration_seconds_total[5m])
  / rate(redis_commands_total[5m])

If you already run the OpenTelemetry Collector, the contrib redis receiver reads INFO on an interval. Per-command metrics are optional and off by default:

receivers:
  redis:
    endpoint: redis-primary:6379
    collection_interval: 15s
    password: ${env:REDIS_PASSWORD}
    metrics:
      redis.cmd.latency:
        enabled: true
      redis.cmd.calls:
        enabled: true
      redis.cmd.usec:
        enabled: true

Default metrics include redis.clients.connected, redis.clients.blocked, redis.commands.processed, redis.memory.used and redis.latest_fork. redis.cmd.latency reports the latencystats percentiles as a gauge with cmd and percentile attributes, which means it inherits their lifetime view. Neither tool ships the slow log entries themselves, so if you want the arguments and client names in your log search, poll SLOWLOG GET from a small job and emit each new entry as a structured log line.

Client spans: the latency your users feel

Server metrics never include the network, the pool or the queueing. Client spans do. OpenTelemetry instrumentation exists for the common clients: @opentelemetry/instrumentation-ioredis and @opentelemetry/instrumentation-redis for Node.js, opentelemetry-instrumentation-redis for redis-py, and Jedis, Lettuce and Redisson in the Java agent. Each command becomes a CLIENT span inside the request trace, with attributes from the Redis semantic conventions:

  • db.system.name = redis (older instrumentations emit db.system)
  • db.operation.name: the command, such as GET or HSET
  • db.namespace: the database index as a string, such as 0
  • db.query.text: the command in CLI syntax with values redacted, for example HMSET myhash field1 ? field2 ?
  • server.address and server.port: which node, which matters with replicas and clusters
  • db.response.status_code: the error prefix on failure, such as WRONGTYPE or CLUSTERDOWN

The conventions say query text should not be collected unless it is sanitized, and Redis arguments often contain session tokens and email addresses, so check what your instrumentation records before you enable full arguments. Pipelines usually produce one span for the whole batch, with db.operation.name set to PIPELINE or prefixed with it, so per-command time inside a pipeline is not visible from the client.

Put the two views side by side, per command, and the diagnosis mostly falls out:

  • Client p99 high, server p99 low, slow log empty: the time is outside Redis. Look at the network path, pool wait time and client CPU or garbage collection.
  • Every command, every service, slow at the same moment, with one slow log entry: a blocking command. The slow log entry is the culprit; the client spans are its victims.
  • Spikes that line up with `fork` in `LATENCY LATEST`: persistence. Check latest_fork_usec and transparent huge pages.
  • Server p99 of one command creeping up over weeks: a key is growing. Find it with --bigkeys and change the data model.

Alerts that catch Redis latency

Page on what users feel and open tickets for the causes:

  • Page: p99 duration of Redis client spans per service and per command, over 5 to 10 minutes, against a threshold derived from the latency budget of the calling endpoint.
  • Ticket: increase(redis_slowlog_last_id[10m]) > 0 for new slow log entries. The ID keeps counting even when the ring buffer is full, unlike redis_slowlog_length.
  • Ticket: redis_latest_fork_usec above a few hundred milliseconds, and any redis_latency_spike_duration_seconds for fork or aof-* events.
  • Ticket: redis_blocked_clients rising, connected clients approaching maxclients, or memory approaching maxmemory with evictions climbing.

Redis latency monitoring with aiAxonIQ

In aiAxonIQ, Database Monitoring records each Redis call as a span with its command, duration and outcome, inside the distributed trace, with P50, P95 and P99 latency per database and per operation, and a jump from a slow call to the full trace and its logs. Server metrics from redis_exporter, sent with Prometheus remote_write, or from the Collector redis receiver over OTLP, sit on the same dashboards as the spans, with alerts on either. For services you cannot instrument, axonIQzerocode reconstructs Redis transactions from socket traffic with eBPF, so legacy binaries report the same signals. If your stack pairs Redis with a relational database, the same approach for the other half is in our guide to PostgreSQL slow query monitoring.

Put this into practice with aiAxonIQ Database Monitoring.

More articles