search
HomeDatabaseRedisWhat are the situations of Redis blocking?

Command blocking

Using inappropriate commands causes client blocking:

  • keys *: Get all key operations;

  • Hgetall: Returns the sum of all fields in the hash table;

  • smembers: Returns all members in the set;

These commands The time complexity is O(n), and sometimes the entire table is scanned. As n increases, the time complexity will increase and the client will be blocked.

SAVE blocking

Everyone knows that when Redis takes an RDB snapshot, it will call the system function fork() and create a child thread to complete the writing of temporary files, and the triggering condition is save configuration in the configuration file.

When our configuration is reached, the bgsave command will be triggered to create a snapshot. This method will not block the main thread, while manually executing the save command will be executed in the main thread, BlockingMain thread.

Synchronous persistence

When Redis records AOF logs directly, if there are a large number of write operations and is configured for synchronous persistence

appendfsync always

That is, every time a data change occurs, It is recorded to disk immediately. Because writing to disk is time-consuming and has poor performance, it sometimes blocks the main thread.

AOF rewriting

  • fork creates a sub-thread to rewrite the file. When executing the BGREWRITEAOF command, the Redis server will maintain an AOF Rewrite buffer, which records all write commands executed by the server during the creation of a new AOF file by the child thread.

  • When the child thread completes the work of creating a new AOF file, the server will append all the contents in the rewrite buffer to the end of the new AOF file, so that the new AOF file saves The database state is consistent with the existing database state.

  • Finally, the server replaces the old AOF file with the new AOF file to complete the AOF file rewriting operation.

Blocking occurs during step 2. When writing new data in the buffer to a new file, blocking will occur.

AOF log

The logging of AOF does not record the log before executing the command like the relational database (to facilitate fault recovery), but uses the method of executing the command first and then recording the log.

The reason is that AOF logging will not perform syntax checking on commands, which can reduce additional checking overhead and will not block the execution of the current command, but may cause blocking to the next operation. risk.

This is because the AOF log is also executed in the main thread. If the disk writing pressure is high when writing the log file to the disk, the disk writing will be very slow, which will lead to Subsequent operations cannot be performed.

Big Key Problem

Big key does not mean that the value of the key is very large, but that the value corresponding to the key is very large.

The blocking problems caused by large keys are as follows:

  • Client timeout blocking: Since Redis execution commands are single-threaded, it will be more time-consuming to operate large keys. , then Redis will be blocked. From the perspective of the client, there will be no response for a long, long time.

  • Causes network congestion: each time you obtain a large key, the network traffic generated is large. If the size of a key is 1 MB and the number of visits per second is 1000, then 1000MB will be generated per second. traffic, which is catastrophic for servers with ordinary Gigabit network cards.

  • Blocking the worker thread: If you use del to delete a large key, the worker thread will be blocked, making it impossible to process subsequent commands.

Find big key

When we use the --bigkeys parameter that comes with Redis to find the big key, it is best to choose the slave node Execute this command on the master node, because when executed on the master node, it will block the master node.

  • We can also use the SCAN command to find big keys;

  • In order to identify big keys, you need to first ensure that Redis uses RDB persistence. And analyze the corresponding RDB file. There are ready-made tools on the Internet:

    • redis-rdb-tools: A tool written in Python language to analyze the RDB snapshot file of Redis

    • This tool is called rdb_bigkeys and is written in Go language. It can be used to analyze Redis' RDB snapshot files and has higher performance.

Delete large key

The essence of the deletion operation is to release the memory space occupied by the key-value pair.

Releasing memory is only the first step. In order to manage memory space more efficiently, when the application releases memory,

the operating system needs to insert the released memory block into a linked list of free memory blocks , for subsequent management and redistribution. This process itself takes a certain amount of time and will blockthe application currently releasing memory.

So, if a large amount of memory is released at once, the operation time of the free memory block linked list will increase, which will accordingly cause the blocking of the Redis

main thread. If the main thread is blocked, All other requests may timeout, and more and more timeouts will cause Redis connections to be exhausted and various exceptions to occur.

When deleting large keys, it is recommended to use batch deletion and asynchronous deletion.

Clear the database

Clearing the database is the same as deleting bigkey above. Flushdb and flushall also involve deleting and releasing all key-value pairs, which are also the blocking points of Redis.

Cluster expansion

Redis cluster can dynamically expand and shrink nodes. This process is currently in a semi-automatic state and requires manual intervention.

When expanding or shrinking, data migration is required. In order to ensure the consistency of migration, Redis all migration operations are synchronous operations.

When performing migration, Redis at both ends will enter a blocking state of varying lengths. For small keys, this time can be ignored, but if the memory usage of the key is too large, serious Sometimes, a failover within the cluster will be triggered, causing unnecessary switching.

The above is the detailed content of What are the situations of Redis blocking?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis: Understanding NoSQL ConceptsRedis: Understanding NoSQL ConceptsApr 21, 2025 am 12:04 AM

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)