search
HomeDatabaseRedisHow Redis saves memory

How Redis saves memory

May 31, 2023 pm 08:04 PM
redis

First of all, this application that reversely checks user UID through picture ID has the following requirements:

  • The query speed must be fast enough

  • All data must be stored in the memory, preferably an EC2 high-memory model (17GB or 34GB, 68GB is too wasteful)

  • Support persistence ization, so that there is no need to warm up after the server is restarted

First of all, they rejected the database storage solution, and they maintained the KISS principle (Keep It Simple and Stupid), because this application does not use It does not have the update function, transaction function, related query and other awesome functions of the database, so there is no need to choose and maintain a database for these unused functions.

So they chose Redis. Redis is an in-memory database that supports persistence. All data is stored in memory (forget VM), and the simplest implementation is to use the String structure of Redis. A key-value store will do. Like this:

SET media:1155315 939
GET media:1155315
> 939

Among them, 1155315 is the picture ID and 939 is the user ID. We use each picture ID as the key and the user uid as the value to save it as a key-value pair. Then they conducted a test and stored the data according to the above method. 1,000,000 data will use 70MB of memory, and 300,000,000 photos will use 21GB of memory. Compared with the budget of 17GB, it is still overspending.

(NoSQLFan: In fact, we can see an optimization point here. We can remove the same media in front of the key value and only store the numbers. This will reduce the length of the key and reduce the memory overhead of the key value [ Note: The key value of Redis will not be converted from string to number, so what is saved here is only the overhead of the 6 bytes of media:]. After experiments, the memory usage will be reduced to 50MB, and the total memory usage is 15GB , it meets the needs, but subsequent improvements of Instagram are still necessary)

So the developers of Instagram asked Pieter Noordhuis, one of the developers of Redis, about the optimization plan, and the reply was to use the Hash structure. The specific method is to segment the data and use a Hash structure to store each segment. Since the Hash structure will compress and store a single Hash element when it is less than a certain number, it can save a lot of memory. This does not exist in the above String structure. The "hash-zipmap-max-entries" parameter in the configuration file controls a certain number. After experiments by developers, when hash-zipmap-max-entries is set to 1000, the performance is better. After exceeding 1000, the HSET command will cause the CPU consumption to become very large.

So they changed the plan and stored the data in the following structure:

HSET "mediabucket:1155" "1155315" "939"
HGET "mediabucket:1155" "1155315"
> "939"

By taking the first four digits of the 7-digit picture ID as the key value of the Hash structure, it ensures that each Hash internal It only contains 3-digit keys, which is 1,000.

After conducting another experiment, it was found that only 16MB of memory was consumed for every 1,000,000 keys. Total memory usage has also been reduced to 5GB, which meets application requirements.

(NoSQLFan: Similarly, we can still optimize here. The first is to change the key value of the Hash structure into a pure number, so that the key length is reduced by 12 bytes. The second is to change the key value in the Hash structure. The subkey value becomes three digits, which reduces the overhead by 4 bytes, as shown below. After experimentation, the memory usage will be reduced to 10MB, and the total memory usage is 3GB)

HSET "1155" "315" "939"
HGET "1155" "315"
> "939"

The above is the detailed content of How Redis saves memory. 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: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

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 Article

Hot Tools

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools