How to Track Redis Key Changes Using MONITOR, Keyspace Events, and AOF Files
This article explains various methods to monitor Redis key changes—including using the MONITOR command, configuring keyspace event notifications, and parsing AOF files with optional timestamps—detailing their setup, advantages, limitations, and practical code examples for accurate change tracking in production environments.
Background : When debugging or troubleshooting Redis in development or production, it is often necessary to view how specific keys change over time to verify data consistency with business flows. This requires a way to review the commands that modify those keys.
Using MONITOR : The redis-cli monitor command streams every command processed by a Redis instance. The output can be redirected to a file for later analysis. While MONITOR provides the most precise command execution times and captures all command types (including reads), it significantly impacts CPU performance and should only be run briefly in production, and on each instance in a clustered environment.
Keyspace Event Notifications : Redis can publish notifications for key events via its Pub/Sub system. By configuring notify-keyspace-events (e.g., config set notify-keyspace-events AKE ), keyspace or key-event messages are sent to a channel such as __keyspace@0__:mykey . Clients can subscribe with PSUBSCRIBE __keyspace@0__:${keyPattern} to receive change events for specific keys or patterns. The article outlines handling of create, update, and delete events, and warns about CPU overhead and potential inaccuracy when keys change rapidly.
Disabling Event Notifications : After monitoring is complete, the configuration should be cleared ( config set notify-keyspace-events '' ) to avoid unnecessary resource consumption.
AOF Files : Redis persists write commands in an Append‑Only File (AOF). Prior to Redis 7.0, the AOF does not store timestamps, making it impossible to know when a command was executed. Starting with Redis 7.0, timestamps can be enabled ( config set aof-timestamp-enabled yes ), which adds lines like #TS:1661161652 before command entries.
Parsing AOF : The article provides a Java example that reads an AOF file, extracts command, key, value, and optional timestamp, and builds a list of RedisKeyUpdateRecord objects. The code snippet is wrapped in ... tags to preserve formatting.
public class RedisKeyChangeTest {
@Test
public void scanAof() {
String localFilePath = "/data/redis.aof"; // aof file path
long currentLine = 1;
try (FileReader fileReader = new FileReader(new File(localFilePath));
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
List
redisRecordList = new ArrayList<>();
List
tempRedisRecords = new ArrayList<>();
String str;
while ((str = bufferedReader.readLine()) != null) {
currentLine++;
if (str.startsWith("*")) {
RedisKeyUpdateRecord redisRecord = new RedisKeyUpdateRecord();
StringBuffer values = new StringBuffer();
String s = str.replaceFirst("\\*", "");
Integer paramNum = Integer.valueOf(s);
for (int i = 0; i < 2 * paramNum; i++) {
String s1 = bufferedReader.readLine();
currentLine++;
if (i % 2 == 0) continue;
if (i == 1) {
redisRecord.setCommand(s1);
} else if (i == 3) {
redisRecord.setKey(s1);
} else {
if (i == 5) {
values.append(s1);
} else {
values.append(" ");
values.append(s1);
}
}
}
redisRecord.setValue(values.toString());
redisRecordList.add(redisRecord);
tempRedisRecords.add(redisRecord);
}
if (str.startsWith("#TS:")) {
String timestamp = str.replace("#TS:", "");
Long updateTime = Long.valueOf(timestamp);
Timestamp time = new Timestamp(updateTime * 1000);
tempRedisRecords.forEach(r -> r.setUpdateTime(time));
tempRedisRecords.clear();
log.info("save redis key record, currentLine:{}", currentLine);
}
}
} catch (Exception e) {
log.error("save redis key record error, execute currentLine:{}", currentLine, e.getMessage());
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class RedisKeyUpdateRecord {
private String command;
private String key;
private String value;
private Timestamp updateTime;
}
}Solution Comparison : The article compares four approaches—MONITOR, keyspace event notifications, AOF (pre‑7.0), and AOF (7.0+)—highlighting trade‑offs in operational complexity, impact on performance, and accuracy. MONITOR offers the most detail but high overhead; keyspace events provide real‑time notifications with moderate overhead; AOF parsing is low‑impact but limited to write commands, with timestamps only available from Redis 7.0 onward.
Additional Details : The article also includes a brief overview of the MONITOR command’s history, its implementation in Redis source code, and how it integrates with the server’s client monitoring list.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.