Detailed explanation of Redis production environment configuration
In actual production environments, in order to ensure the stability and high performance of Redis, we often need to make a series of optimizations to the default configuration. This blog post will take an optimized Redis configuration file as an example to explain in detail from multiple aspects such as basic network settings, persistence, replication, memory management, AOF persistence, performance tuning, and monitoring restrictions.
Here is a sample configuration file with detailed notes:
Configuration file example
##################### # Redis configuration optimization file# Suitable for production environments##################### # Bind the address, allow all IP access, and it is recommended to change the production environment to intranet IPbind 192.168.1.1 # Protect mode, it is recommended to enable (yes) to enhance securityprotected-mode yes # Listen to the portport 6379 # TCP connection queue sizetcp-backlog 511 # Connection timeout (0 means no timeout)timeout 0 # TCP keep-alive time (seconds), it is recommended to set it to be larger to avoid the connection being accidentally disconnected by the firewall.tcp-keepalive 300 # Backend rundaemonize yes # Process PID file pathpidfile /data/redis/redis_6379.pid # Log level (debug | verbose | notice | warning)loglevel notice # Log file path (null value indicates output to standard output)logfile "/data/app/redis/logs/" # Number of databases (default 16, adjusted according to business needs)databases 16 # Show Redis startup logo (shutdown to reduce log interference)always-show-logo no
Basic network and process management
bind and protected-modeSpecified in the configuration file
bind 192.168.1.1
, only this IP is allowed to access the Redis service. For production environments, it is recommended to use intranet IP to limit access. Turn on at the same timeprotected-mode
(Protected Mode), which can prevent unauthorized access.Port and connection settingsuse
port 6379
Set the Redis listening port,tcp-backlog
The length of the connection queue is set.timeout 0
Indicates that the idle connection is not automatically disconnected, andtcp-keepalive 300
Maintain long connection activity and avoid intermediate devices (such as firewalls) being disconnected due to idle timeout.Background operation and loggingpass
daemonize yes
Make Redis run in the background and define the PID file path (pidfile
) and log file path and log level. These settings help manage processes and troubleshoot problems.
RDB persistent configuration
Redis provides RDB persistence method, which can save memory data to disk regularly. The following optimizations are made for RDB in the configuration file:
##################### # RDB persistence##################### # Block writes when RDB fails to avoid data corruptionstop-writes-on-bgsave-error yes # Enable RDB data compressionrdbcompression yes # Enable RDB data verificationrdbchecksum yes # RDB file namedbfilename # Close RDB to delete synchronous files to prevent mistaken deletionrdb-del-sync-files no # RDB file storage directory, it is recommended to set it to SSD diskdir /data/app/redis/data/
Data integrity protectionuse
stop-writes-on-bgsave-error yes
, Once an error occurs in RDB persistence, stop the write operation to prevent data inconsistency.Data compression and verificationTurn on
rdbcompression
andrdbchecksum
It can effectively reduce the size of RDB files and ensure data integrity through verification.File storage directoryStore RDB files in
/data/app/redis/data/
, it is recommended to deploy on SSD for higher I/O performance.
Copy (master-slave synchronization) settings
In high availability architectures, master-slave replication is a common method. The following settings are made for the copy function in the configuration file:
##################### # Copy (master-slave synchronization)##################### # Allow replicas to still provide read-only service when disconnecting the main libraryreplica-serve-stale-data yes # Replica Node Read-only Modereplica-read-only yes # Turn off disk-free synchronization (default is used)repl-diskless-sync no # No disk synchronization delayrepl-diskless-sync-delay 5 # Turn off disk-free loadingrepl-diskless-load disabled # Keep the default TCP nodelay configurationrepl-disable-tcp-nodelay no # Replica priority (the smaller the easier it is to become the main library)replica-priority 100
Replica service availability
replica-serve-stale-data yes
It allows the replica to continue to provide read-only services when it is disconnected from the main library to ensure that the business is not interrupted.Synchronization methodDisk synchronization is used by default, through adjustment
repl-diskless-sync-delay
To control the delay and maintain the stability of data transmission.Master selection strategyConfiguration
replica-priority
, the lower the value, the more likely it is to be elected as a new master library when the master library fails.
Memory management
Memory management is a core part of Redis performance, and flexible memory management strategies are provided in the configuration file:
##################### # Memory Management##################### # The default memory is not limited, and can be adjusted according to business needs.maxmemory 0 # If you do not evict data, you can change to allkeys-lrumaxmemory-policy noeviction # Turn off lazy deletion to avoid extra CPU overheadlazyfree-lazy-eviction no # Turn off lazy expirationlazyfree-lazy-expire no # Turn off lazy deletionlazyfree-lazy-server-del no # Close the lazy copy cleaningreplica-lazy-flush no # Close OOM Adjustmentoom-score-adj no # Enable only when OOM protectionoom-score-adj-values 0 200 800
Memory limits and policies
maxmemory 0
Indicates that the default unlimited memory is suitable for environments with sufficient memory resources; at the same time, it is setmaxmemory-policy noeviction
, means that the data will not be evicted when the memory reaches the upper limit. In actual production, you can choose according to business needs such asallkeys-lru
Such as an expulsion strategy.Lazy deletionTurning off various lazy delete functions (lazyfree-* configurations) can reduce CPU overhead, but may make the delete operation more synchronously executed and need to be traded down based on business scenarios.
AOF persistence
AOF (Append Only File) is another persistence solution for Redis that can provide higher data security. The AOF is set as follows in the configuration file:
##################### # AOF Persistence##################### # Enable AOF persistenceappendonly yes # AOF file nameappendfilename "" # Synchronize once per second, a compromise between performance and securityappendfsync everysec # Whether to turn off synchronization during rewritingno-appendfsync-on-rewrite no # The proportion of triggering AOF rewriteauto-aof-rewrite-percentage 100 # Minimum size to trigger AOF rewriteauto-aof-rewrite-min-size 64mb # Allow truncated AOF to loadaof-load-truncated yes # AOF is compatible with RDB headers, reducing restart timeaof-use-rdb-preamble yes
Data security and performanceTurn on
appendonly yes
And useappendfsync everysec
, strike a balance between data security and performance; synchronizing AOF files once a second can significantly reduce the risk of data loss.Automatic rewriteConfiguration
auto-aof-rewrite-percentage
andauto-aof-rewrite-min-size
, ensuring that the AOF file does not increase without limit, while using incremental rewrite to reduce performance losses during rewrite.Compatibility and recoveryEnable
aof-use-rdb-preamble
The RDB header data can be used to speed up loading speed and improve recovery efficiency during restart.
Performance optimization settings
In order to obtain better response speed in high concurrency environments, Redis also made a series of performance tuning in the configuration file:
##################### # Performance optimization##################### # Turn up the Hz frequency to increase the response speedhz 50 # Dynamic adjustment Hzdynamic-hz yes # AOF incremental synchronization during rewritingaof-rewrite-incremental-fsync yes # RDB incremental synchronization during savingrdb-save-incremental-fsync yes # Enable jemalloc thread-optimized memory managementjemalloc-bg-thread yes
Hz frequencyThe default event processing frequency (hz) is raised to 50 times/sec, and dynamic adjustment is enabled to ensure that it can still respond to client requests quickly when load fluctuates.
Incremental synchronizationEnable incremental synchronization for AOF rewrite and RDB save can effectively reduce the pressure on disk I/O and improve overall performance.
Memory allocation optimizationEnable jemalloc background threads (
jemalloc-bg-thread yes
) Further optimize memory allocation and release, suitable for high concurrency scenarios.
Restrictions and monitoring
To detect problems in a timely manner and prevent unexpected situations, Redis provides a series of monitoring and restrictions:
##################### # Restrictions and monitoring##################### # Slow query threshold (microseconds)slowlog-log-slower-than 10000 # Slow query log maximum numberslowlog-max-len 128 # Turn off delay monitoringlatency-monitor-threshold 0 # Close key event notificationnotify-keyspace-events "" # No limit for ordinary clientsclient-output-buffer-limit normal 0 0 0 # Replica Node Limitclient-output-buffer-limit replica 256mb 64mb 60 # PubSub Limitationsclient-output-buffer-limit pubsub 32mb 8mb 60
Slow query logBy setting
slowlog-log-slower-than 10000
(in microseconds) to record commands with execution time of more than 10 milliseconds help to locate performance bottlenecks.Client output bufferBuffer size limits are set for ordinary clients, replication nodes and PubSub modules respectively to prevent abnormal situations (such as client blocking) from causing memory surges.
Other parameters
Finally, some additional parameters are defined in the configuration file, such as RDB saving conditions and TCP-related parameters, to further refine the behavior of Redis:
##################### #Other parameters##################### # RDB Trigger Conditionsave 900 1 300 10 60 10000 # TCP connection queue sizetcp-backlog 511 # TCP Keep-alive time (seconds)tcp-keepalive 300
These parameters can fine-tune the data storage frequency, network connection queue, etc. according to specific business scenarios, thereby achieving a balance between performance and reliability.
Complete configuration
######################################### # Redis configuration optimization file# Suitable for production environments######################################### # Bind the address, allow all IP access, and it is recommended to change the production environment to intranet IPbind 192.168.1.1 # Protect mode, it is recommended to enable (yes) to enhance securityprotected-mode yes # Listen to the portport 6379 # TCP connection queue sizetcp-backlog 511 # Connection timeout (0 means no timeout)timeout 0 # TCP keep-alive time (seconds), it is recommended to set it to be larger to avoid the connection being accidentally disconnected by the firewall.tcp-keepalive 300 # Backend rundaemonize yes # Process PID file pathpidfile /data/app/redis/redis_6379.pid # Log level (debug | verbose | notice | warning)loglevel notice # Log file path (null value indicates output to standard output)logfile "/data/redis/logs/" # Number of databases (default 16, adjusted according to business needs)databases 16 # Show Redis startup logo (shutdown to reduce log interference)always-show-logo no ######################################### # RDB persistence######################################### # Block writes when RDB fails to avoid data corruptionstop-writes-on-bgsave-error yes # Enable RDB data compressionrdbcompression yes # Enable RDB data verificationrdbchecksum yes # RDB file namedbfilename # Close RDB to delete synchronous files to prevent mistaken deletionrdb-del-sync-files no # RDB file storage directory, it is recommended to set it to SSD diskdir /data/app/redis/data/ ######################################### # Copy (master-slave synchronization)######################################### # Allow replicas to still provide read-only service when disconnecting the main libraryreplica-serve-stale-data yes # Replica Node Read-only Modereplica-read-only yes # Turn off disk-free synchronization (default is used)repl-diskless-sync no # No disk synchronization delayrepl-diskless-sync-delay 5 # Turn off disk-free loadingrepl-diskless-load disabled # Keep the default TCP nodelay configurationrepl-disable-tcp-nodelay no # Replica priority (the smaller the easier it is to become the main library)replica-priority 100 ######################################### # Memory Management######################################### # The default memory is not limited, and can be adjusted according to business needs.maxmemory 0 # If you do not evict data, you can change to allkeys-lrumaxmemory-policy noeviction # Turn off lazy deletion to avoid extra CPU overheadlazyfree-lazy-eviction no # Turn off lazy expirationlazyfree-lazy-expire no # Turn off lazy deletionlazyfree-lazy-server-del no # Close the lazy copy cleaningreplica-lazy-flush no # Close OOM Adjustmentoom-score-adj no # Enable only when OOM protectionoom-score-adj-values 0 200 800 ######################################### # AOF Persistence######################################### # Enable AOF persistenceappendonly yes # AOF file nameappendfilename "" # Synchronize once per second, a compromise between performance and securityappendfsync everysec # Whether to turn off synchronization during rewritingno-appendfsync-on-rewrite no # The proportion of triggering AOF rewriteauto-aof-rewrite-percentage 100 # Minimum size to trigger AOF rewriteauto-aof-rewrite-min-size 64mb # Allow truncated AOF to loadaof-load-truncated yes # AOF is compatible with RDB headers, reducing restart timeaof-use-rdb-preamble yes ######################################### # Performance optimization######################################### # Turn up the Hz frequency to increase the response speedhz 50 # Dynamic adjustment Hzdynamic-hz yes # AOF incremental synchronization during rewritingaof-rewrite-incremental-fsync yes # RDB incremental synchronization during savingrdb-save-incremental-fsync yes # Enable jemalloc thread-optimized memory managementjemalloc-bg-thread yes ######################################### # Restrictions and monitoring######################################### # Slow query threshold (microseconds)slowlog-log-slower-than 10000 # Slow query log maximum numberslowlog-max-len 128 # Turn off delay monitoringlatency-monitor-threshold 0 # Close key event notificationnotify-keyspace-events "" # No limit for ordinary clientsclient-output-buffer-limit normal 0 0 0 # Replica Node Limitclient-output-buffer-limit replica 256mb 64mb 60 # PubSub Limitationsclient-output-buffer-limit pubsub 32mb 8mb 60 ######################################### #Other parameters######################################### # RDB Trigger Conditionsave 900 1 300 10 60 10000 # TCP connection queue sizetcp-backlog 511 # TCP Keep-alive time (seconds)tcp-keepalive 300
Summarize
This blog post analyzes a Redis configuration file optimized for production environments in detail. By reasonably setting network parameters, persistence policies, replication mechanisms, memory management and performance tuning, Redis can maintain stable and efficient operation in high concurrency and large data volume scenarios.
During actual deployment, various parameters should be adjusted appropriately based on their own hardware conditions and business characteristics. For environmental security, data reliability and performance optimization, it is recommended to refer to official documents and community best practices to continuously improve and tune configurations.
This is the article about the stand-alone configuration of Redis6.2.6 production environment. For more related Redis configuration content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!