[KongchangAI]
· 3 min read· 1,692 words

Redis High-Concurrency in Practice: Flash Sale Overselling and Cache Issues Explained

Redis High-Concurrency in Practice: Flash Sale Overselling and Cache Issues Explained

Breaks down flash sale overselling, caching, and distributed locks from a Redis inventory deduction case, and extends to multi-Agent engineering.

Based on Bilibili creator Teacher Zhuge's public lesson, the article starts from a minimal SpringBoot code snippet that reads Redis inventory and decrements it by one, revealing that flash sale overselling stems from non-atomic inventory deduction. It then discusses the performance limits of single-machine locks, the necessity of Redis distributed locks, and countermeasures for cache penetration and breakdown. Another section migrates high-concurrency architecture ideas to multi-Agent AI engineering, using Redis for communication caching and distributed locks for task idempotency.

In e-commerce flash sale scenarios, high concurrency often brings a series of thorny problems, and Redis, as the core component for caching and inventory deduction, directly determines system stability through how it is used. Recently, Bilibili creator Teacher Zhuge, in a public lesson, started from a minimal inventory deduction case and gradually broke down the high-frequency pitfalls in the flash sale order placement flow, including overselling, cache penetration/breakdown, distributed locks, and more, extending to multi-Agent AI engineering practice. This article is based on the course content and, combined with multi-source analysis, sorts out the key issues and solution approaches.

Seeing Overselling in a Single Line of Code: The Inventory Trap Under Concurrency

At the start of the course, Teacher Zhuge showed a SpringBoot endpoint that simulates reading the inventory value from Redis (default 300), checks whether it is greater than 0, then decrements it by 1 and writes it back. The code logic looks correct, but once concurrent requests execute at the same time, the problem is immediately exposed: multiple requests read 300 at the same time, each decrements by 1 and writes back 299, so the inventory is ultimately reduced by only 1, but multiple products were actually sold, causing overselling.

Give the teacher a thumbs up

This case intuitively explains the essence of overselling—inventory deduction is not an atomic operation. In flash sale scenarios, similar to JD.com's rush purchase pages, instantaneous traffic can reach tens of thousands of QPS, and this simple "read-modify-write" pattern is bound to fail. Teacher Zhuge emphasized that this is one of the most typical pitfalls in high-frequency scenarios and also the starting point for the subsequent increasingly complex discussion.

Later I will gradually make it more and more complex

Atomic Operations and Redis Single Commands

The root cause of the overselling problem is that the three steps of "read-modify-write" are not atomic. Redis provides several single-command atomic operations that can bypass distributed locks to perform safe deductions: DECR/INCR atomically add or subtract when the key exists and return the new value, but they cannot determine whether the result after deduction is negative; DECRBY works the same way. A more reliable approach is to first initialize inventory with SETNX, then combine a Lua script to package "check whether inventory is sufficient" and "deduct" into a single atomic execution unit—Redis does not insert other commands while executing a Lua script, so it is naturally atomic. The SpringBoot code demonstrated in the course lacks exactly this layer of encapsulation, causing multiple requests under concurrency to read the same inventory value. Understanding the atomicity boundaries of single commands and Lua scripts is the underlying capability that should be mastered before introducing distributed locks.

Can Locking Solve Overselling? The Trade-off Between Performance and Deadlocks

When facing overselling, most developers' first reaction is to add a lock. The course mentioned using JDK built-in synchronized or ReentrantLock. Indeed, in a single-machine environment, synchronization locks can ensure that only one thread executes the deduction logic at a time, thereby avoiding overselling. But Teacher Zhuge immediately raised a question: in high-concurrency scenarios, will locking bring performance problems?

Then the following logic

The answer is yes. Lock granularity, waiting time, and context switching can all become bottlenecks, especially when lock contention is intense, throughput drops sharply. More seriously, if locks are used improperly (such as locks not being released or inconsistent lock ordering), deadlocks may also be triggered. In addition, single-machine locks cannot handle distributed deployment; when multiple service instances deduct inventory at the same time, overselling still occurs. Therefore, distributed locks become an inevitable choice, and Redis is a common tool for implementing distributed locks.

Key Points for Implementing Redis Distributed Locks

Using Redis to implement distributed locks centers on the command SET key value NX PX timeout: NX ensures success only when the key does not exist (that is, the lock is acquired), and PX sets an expiration time for the lock to avoid the lock never being released after the holder crashes. But these two points alone are not enough; two classic problems must be solved: the first is "accidentally deleting someone else's lock"—when releasing the lock, compare the value first (usually a UUID identifying the holder) before deleting, and the comparison and deletion must use a Lua script to ensure atomicity; the second is "the lock expires but the business is not finished"—a watchdog mechanism can periodically renew the lock, and Redisson's RLock encapsulates this logic. In addition, the reentrancy of locks and the controversy around Redlock also need to be considered. The course emphasizes that distributed locks are an inevitable choice, and when selecting a solution, whether to build a lightweight script in-house or directly introduce Redisson depends on the team's trade-off between maintainability and feature completeness.

Cache Penetration and Breakdown: Two Other Hidden Dangers Under High Concurrency

In addition to overselling, the course also focused on cache penetration and cache breakdown. Cache penetration refers to querying data that does not exist, causing requests to fall directly to the database; it can usually be solved with a Bloom filter or by caching null values. Cache breakdown refers to the moment a hot key expires, when a large number of requests flood into the database; it can be mitigated with a mutex lock or a never-expire strategy. Combining the actual scenario of JD.com's flash sale page, Teacher Zhuge explained the trigger conditions and response plans for these problems, and pointed out that Redis configuration optimization in high-concurrency scenarios (such as connection pooling and persistence strategies) cannot be ignored either.

Is it 299?

Multi-source analysis shows that different technical bloggers share a consensus on solutions to cache problems: Bloom filters and mutex locks are mainstream methods, but in specific implementation, some recommend using Redisson, while others suggest building lightweight solutions in-house. Teacher Zhuge's course is more practice-oriented, emphasizing choosing appropriate solutions based on business characteristics rather than blindly applying them.

Distinguishing Bloom Filters from Cache Avalanche

A Bloom filter is a probabilistic data structure with extremely high space efficiency. It uses a bit array plus multiple hash functions to determine "whether an element may exist": if it returns "does not exist," then it definitely does not exist; if it returns "exists," a false positive is possible. It is suitable for front-line interception in cache penetration scenarios, blocking large numbers of requests that query non-existent keys from the database, at the cost of a certain false positive rate and no support for deleting elements. It is also necessary to note the difference between cache breakdown and cache avalanche: breakdown is the instantaneous impact caused by the invalidation of a single hot key, while avalanche is a large number of keys expiring at the same time or Redis going down entirely; the latter needs comprehensive treatment through measures such as adding random offsets to expiration times, multi-level caching, and rate limiting with degradation. The three have different causes, and their response strategies cannot be used interchangeably.

Multi-Agent AI Engineering: A New Battleground for Backend Development

Another major section of the course is multi-Agent intelligent agent development. As AI applications deepen, backend systems need to support multiple Agents working collaboratively, which imposes new requirements on concurrency handling, task scheduling, and state management. Combining his own experience at Vipshop and JD.com, Teacher Zhuge shared how to migrate high-concurrency architecture ideas to multi-Agent scenarios, for example using Redis as a cache layer for communication between Agents, or using distributed locks to ensure idempotency of task execution. Although this part was not covered in much detail in the original material, as a highlight of the course, it provides backend developers with a new perspective.

Idempotency and State Management in Multi-Agent Collaboration

Multi-Agent systems usually have an orchestrator split tasks among multiple sub-Agents for parallel execution and then aggregate the results, which is structurally highly similar to the flash sale flow: both involve concurrent competition, repeated execution, and state consistency problems. There are two keys to engineering implementation. The first is idempotency—Agent tasks may be triggered repeatedly due to retries or timeouts, so distributed locks or unique task IDs are needed to ensure that the same task is executed only once and side effects do not accumulate. The second is state management—intermediate results and session context between Agents require shared storage, and Redis's string, hash, and Stream structures can respectively serve as cache, state snapshots, and message queues. Migrating the ideas of "atomicity, idempotency, and state isolation" from high-concurrency systems can significantly reduce the complexity of multi-Agent orchestration.

Summary and Recommendations

This public lesson starts from a small case and progresses layer by layer, covering the most common pitfalls in flash sale systems. For backend developers, understanding the essence of overselling, mastering the correct use of distributed locks, and being familiar with response strategies for cache problems are the basic skills for building high-concurrency systems. At the same time, multi-Agent AI engineering, as an emerging direction, deserves continuous attention. Teacher Zhuge also provided interview materials and books, suitable for systematic gap-filling. Overall, the course content is highly practical and suitable for developers with some Java foundation who hope to go deeper into the high-concurrency field.

One-line Summary

Breaks down flash sale overselling, caching, and distributed locks from a Redis inventory deduction case, and extends to multi-Agent engineering.

Paragraph Summary

The article is based on a public lesson by Bilibili creator Teacher Zhuge. Starting from a minimal SpringBoot code snippet that reads Redis inventory and decrements it by one, it reveals that the essence of flash sale overselling is non-atomic inventory deduction. It then discusses layer by layer: although single-machine synchronized or ReentrantLock can prevent overselling, performance is limited under high concurrency and cannot handle distributed deployment, so Redis distributed locks must be introduced; it also supplements the difference between cache penetration and cache breakdown and response methods such as Bloom filters and mutex locks. Another section of the course migrates high-concurrency architecture ideas to multi-Agent AI engineering, using Redis for communication caching and distributed locks to ensure task idempotency. The overall content is highly practical and suitable for developers with some Java foundation who hope to go deeper into the high-concurrency field.

#Redis high concurrency#flash sale overselling#distributed locks#cache penetration#cache breakdown#multi-Agent AI engineering
Share:

Related articles