As we know, Redis is an in-memory key-value store database. If our data is stored in our host memory (RAM), how can we restore all values from the last state of our system in case of system reboot or power outages?
Redis provides two options for persisting our data. The first is by creating a snapshot and the second is by appending each write action into a file. The second is also called the append-only-file (AOF) method. Applying those options is as trivial as updating several lines of the Redis configuration file.
Redis performs snapshotting with certain rules by default. Enabling the auto-snapshot method with different rules is done by configuring the following lines in the /etc/redis/redis.conf
file.
save 300 10
save 30 1000
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
dir /var/lib/redis
The line save 300 10
means snapshot will be automatically updated in the background if at least 10 writes have occurred within 300 seconds. The line save 30 1000
means it will be updated for at least 1000 writes within 30 seconds.
Snapshotting is also run by Redis automatically when it is shutting down gracefully. We can also run BGSAVE
or SAVE
command on Redis client. The BGSAVE
command will run snapshotting process by initiating a fork of the main Redis thread so it won't block Redis to accept any writes from the client. Auto-snapshotting is also run this way. But, we need to consider the available memory of our host for performing this action because current values in our database will be buffered in memory before they can be written in the RDB file. Meanwhile, the SAVE
command is run on the main thread so it will block Redis from accepting any write.
Append-only mode works differently, it captures any writes and appends them into the appendonly.aof
file. Several configuration options are as follows.
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite yes
The appendfsync
parameter has three options: always
, everysec
, and no
. The everysec
option won't make Redis appends each of the new writes directly as it happens but Redis will aggregate them and append them one time on every second. Appending process can also be triggered by running the BGREWRITEAOF
command on the Redis client.
Database replication is also very trivial as Redis support it on its core. When we have a primary/master Redis instance, we can deploy another Redis instance and assign it as a replica/slave of the primary one. In the replica server configuration, we can add a parameter replicaof <masterhost> <port>
. By default, the replica is read-only. We can add a parameter replica-read-only no
if we want to enable writing on the replica. But, it is only for ephemeral or temporary data because the stored values will be rewritten when the replica resync with the primary one.
Comments
Post a Comment