惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

aimingoo的专栏
aimingoo的专栏
Engineering at Meta
Engineering at Meta
有赞技术团队
有赞技术团队
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
Vercel News
Vercel News
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
IT之家
IT之家
MongoDB | Blog
MongoDB | Blog
Y
Y Combinator Blog
B
Blog
The GitHub Blog
The GitHub Blog
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Stack Overflow Blog
Stack Overflow Blog
C
Check Point Blog
Microsoft Azure Blog
Microsoft Azure Blog
D
DataBreaches.Net
I
InfoQ
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
腾讯CDC
H
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
[System Design] Chapter 2: Flash Sale Engine - Solving Ov...
Tuấn Anh · 2026-06-24 · via DEV Community

← Series hub
← PrevNext →

Chapter 2: Flash Sale Engine - The Mystery Behind Redis and Hot Keys

Flash Sale events are the ultimate stress test for system architecture. When an iPhone is sold for $1, millions of users will smash the "Buy Now" button in the exact same millisecond. If this massive spike hits a MySQL database directly, the system will instantly crash due to Row Locks and Deadlocks.

1. The Hot Key Problem and Two-Tier Caching

A highly discounted product is known as a Hot Key.
Many developers mistakenly believe that "just putting inventory in Redis" solves everything. However, a single Redis node has Network Bandwidth and CPU limits (typically maxing out at ~100k Ops/sec). One million clicks on a single key will saturate the network interface card (NIC) of that Redis node.

Shopee's Solution: Multi-Level Caching

  • Tier 1 (Local Cache): Built directly into the RAM of the Golang Application Servers (using tools like sync.Map or BigCache). This local cache only stores a boolean flag: "Is the item still in stock?". It has a TTL of just 1-2 seconds but successfully blocks 90% of useless traffic from hitting the network once the item is sold out.
  • Tier 2 (Distributed Cache - Redis): Only when the Local Cache reports that the item is available does the request proceed to the Redis cluster.

2. Preventing Overselling with Atomic Lua Scripts

When a user buys an item, the system must deduct the inventory. But if you use standard commands: Read stock (GET) -> Check if > 0 -> Write new stock (SET), you will face a critical Race Condition. Two parallel threads might both read a stock value of 1, both decrement it, and result in selling two items when only one existed (Overselling).

The Solution: Shopee wraps the inventory deduction logic inside Lua Scripts running natively within Redis. Because Redis is fundamentally single-threaded, executing a Lua script acts as an Atomic Transaction—no other requests can interrupt it mid-execution.

-- Example Lua Script for Inventory Deduction
local stock_key = KEYS[1]
local stock = tonumber(redis.call('GET', stock_key))

if stock and stock > 0 then
    redis.call('DECR', stock_key)
    return 1 -- Purchase Successful
else
    return 0 -- Out of Stock
end

Fail Fast: Thanks to this mechanism, if the Lua script returns 0, the request is immediately rejected and the user sees an "Out of Stock" message. This RAM-level operation takes mere microseconds.

3. Inventory Sharding

For mega-campaigns, a single Hot Key on a single Redis Node is still too risky. Shopee employs Inventory Sharding.
If there are 1,000 iPhones, they do not store the number 1,000 in a single key iphone_stock. Instead, they slice it into 10 shards: iphone_stock_1 to iphone_stock_10. Each key holds 100 items and is distributed across 10 different physical Redis Nodes.

A load balancer or router randomly routes incoming user traffic to one of those 10 keys, instantly dividing the massive system pressure by 10.

sequenceDiagram
    participant User
    participant App as Golang Server<br/>(Local Cache)
    participant Redis as Redis Cluster<br/>(Sharded)
    participant Worker as Kafka Worker

    User->>App: Click "Buy Now"
    Note over App: Check Local Cache.<br/>Block if Out of Stock
    App->>Redis: Route to shard (e.g. stock_3)
    Note over Redis: Execute Atomic Lua Script
    Redis-->>App: If 0: Return Error
    Redis-->>Worker: If 1: Push Order Event to Queue
    Worker-->>User: Process Order Asynchronously

Developer Takeaway: RAM and caching are your strongest weapons against heavy traffic. However, do not blindly rely on a Distributed Cache. Combine it with Local Caches on the App Server to save network bandwidth, and always use Lua Scripts to guarantee data consistency when handling sensitive numbers like inventory or wallet balances.


References & Further Reading

{{< author-cta >}}


This post was originally published on my blog at Chapter 2: Flash Sale Engine - Solving Overselling and Hot Keys.

Hi, I'm Lê Tuấn Anh (vesviet) 👋
I am a Senior Go Backend Architect & Distributed Systems Engineer with 17+ years of experience building high-traffic platforms (25M+ requests/month).
If you enjoyed this deep-dive, let's connect on LinkedIn or explore my consulting services at tanhdev.com/hire.