Skip to content
quboliu
Go back

Repost · Bilingual

How to Scale a System from 0 to 10 million+ Users如何将系统从零扩展到一千万乃至更多用户

Area: 分布式系统Edit page

Scaling is a complex topic, but after working at big tech on services handling millions of requests and scaling my own startup (AlgoMaster.io) from scratch, I’ve realized that most systems evolve through a surprisingly similar set of stages as they grow.

系统扩展是个复杂的话题。我曾在大型科技公司负责处理数百万次请求的服务,也从零开始把自己的创业项目 AlgoMaster.io 做大。这些经历让我发现,大多数系统在成长中都会经过一系列相似得出奇的阶段。

The key insight is that you should not over-engineer from the start. Start simple, identify bottlenecks, and scale incrementally.

我体会最深的是,别在起步时就过度设计。先从简单的方案做起,找到瓶颈,再逐步扩展。

In this article, I’ll walk you through 7 stages of scaling a system from zero to 10 million users and beyond. Each stage addresses the specific bottlenecks that show up at different growth points. You’ll learn what to add, when to add it, why it helps, and the trade-offs involved.

本文将带你走过系统扩展的七个阶段,从零用户一直到一千万乃至更多。每个阶段都应对特定增长节点上出现的瓶颈。我们会看清楚该加什么、什么时候加、为什么有用,以及要为此付出什么代价。

Whether you’re building an app or website, preparing for system design interviews, or just curious about how large-scale systems work, understanding this progression will sharpen they way you think about architecture.

无论你在做应用或网站、准备系统设计面试,还是好奇大规模系统如何运作,弄懂这段演进过程,都能帮你更准确地判断架构该怎么选。

Disclaimer: The user ranges and numbers mentioned in this article are approximate and intended to illustrate a scaling journey. Actual thresholds will vary depending on your product, workload characteristics, and traffic patterns.

说明:文中的用户区间和各项数字都是近似值,用于说明扩展过程。实际阈值取决于产品、负载特征和流量模式。


Stage 1: Single Server (0-100 Users)第一阶段:单台服务器(0~100 名用户)

When you’re just starting out, your first priority is simple: ship something and validate your idea. Optimizing too early at this stage wastes time and money on problems you may never face.

刚起步时,最优先的事很简单:把产品做出来,验证想法。过早优化会把时间和金钱花在可能永远不会出现的问题上。

The simplest architecture puts everything on a single server: your web application, database, and any background jobs all running on the same machine.

最简单的架构把所有东西都放在一台服务器上:Web 应用、数据库和所有后台任务共用一台机器。

用户访问同一台服务器上的 Web 应用、数据库和后台任务。

This is how Instagram started. When Kevin Systrom and Mike Krieger launched the first version in 2010, 25,000 people signed up on day one.

They didn’t over-engineer upfront. With a small team and a simple setup, they scaled in response to real demand, adding capacity as usage grew, rather than building for hypothetical future traffic.

Instagram 就是这样起步的。Kevin Systrom 和 Mike Krieger 在 2010 年发布第一个版本,第一天就有 25,000 人注册。

他们没有预先设计一套复杂架构。团队小,系统也简单,容量跟着实际用量增长,不为设想中的未来流量提前建设。

What This Architecture Looks Like这套架构长什么样

In practice, a single-server setup means:

单台服务器上通常运行着以下组件:

All of these run on one virtual machine. Your cloud provider bill might be $20-50/month for a basic VPS (DigitalOcean Droplet, AWS Lightsail, Linode).

这些组件都跑在一台虚拟机上。基础款 VPS(DigitalOcean Droplet、AWS Lightsail 或 Linode)的云服务账单可能是每月 20~50 美元。

Why This Works for Early Stage为什么它适合早期

At this stage, simplicity is your biggest advantage:

在这个阶段,简单是你最大的优势:

The Trade-offs You’re Making选择单机要接受哪些取舍

This simplicity comes with trade-offs you accept knowingly:

这种简单也有代价,选择它时就要心中有数:

Single-server trade-offs, their impact, and why they are tolerable at first.

取舍影响为什么现阶段可以接受
单点故障服务器宕机,应用随之离线用户少,及时修复即可
资源争用数据库与应用争用 CPU 和内存流量低,尚不会产生明显争用
无法水平扩展不容易增加服务器流量低且可预测
部署导致停机上线新代码必须重启用户可能察觉不到短暂中断

When to Move On什么时候该往前走

You’ll know it’s time to evolve when you notice these signs:

出现以下迹象时,就该考虑调整架构了:

At some point, the server starts to struggle under the weight of doing everything. That’s when it’s time for your first architectural split.

当一台服务器开始扛不住所有工作时,就到了第一次拆分架构的时候。


Stage 2: Separate Database (100-1K Users)第二阶段:独立部署数据库(100~1,000 名用户)

As traffic grows, your single server starts struggling. The web application and database compete for the same CPU, memory, and disk I/O. A single heavy query can spike latency and slow down every API response.

流量增长后,单机开始吃紧。Web 应用和数据库争用 CPU、内存和磁盘 I/O。一条开销大的查询就可能让延迟骤升,把所有 API 响应都拖慢。

The first scaling step is simple: separate the database from the application server.

扩展的第一步很简单:把数据库和应用服务器分开。

用户访问应用层,Web 应用再访问独立的数据层。

This two-tier architecture gives you several immediate benefits:

这种两层架构会立刻带来几项好处:

Managed Database Services托管数据库服务

At this stage, most teams use a managed database like Amazon RDS, Google Cloud SQL, Azure Database, or Supabase (I use Supabase at algomaster.io).

大多数团队在这个阶段会选用托管数据库,例如 Amazon RDS、Google Cloud SQL、Azure Database 或 Supabase。我自己在 algomaster.io 上用的就是 Supabase。

Managed services typically handle:

托管服务通常会接手这些工作:

The cost difference between self-hosting and managed is usually small once you factor in engineering time. A managed PostgreSQL instance might cost $50–$100/month more than a raw VM, but it can save hours of maintenance every week. Those hours are better spent shipping features.

把工程师的时间也算进去,自建与托管的成本差距通常不大。一个托管的 PostgreSQL 实例可能比单租虚拟机每月多花 50~100 美元,却能每周节省好几个小时的维护时间。把这些时间用来交付功能更划算。

The main reasons to self-manage a database are:

选择自管数据库通常出于以下原因:

For most teams, managed services are the right choice until your database bill grows into the thousands of dollars per month.

对大多数团队来说,在数据库账单涨到每月数千美元之前,托管服务通常是合适的选择。

Connection Pooling连接池

One often-overlooked improvement at this stage is connection pooling. Each database connection consumes resources:

在这个阶段,连接池是一个经常被忽略的改进点。每条数据库连接都会消耗资源:

Opening a new connection is expensive too. Between the TCP handshake, SSL negotiation, and database authentication, you can add 50–100 ms of overhead per request.

新建连接的代价也不低。TCP 握手、SSL 协商和数据库身份验证加起来,可能让每个请求多花 50~100 毫秒。

A connection pooler like PgBouncer (for PostgreSQL) keeps a small set of database connections open and reuses them across requests.

连接池工具会保持少量数据库连接处于打开状态,让多个请求复用它们。PostgreSQL 的 PgBouncer 就是一个例子。

三个应用实例通过同一个 PgBouncer 连接池访问 PostgreSQL。

With 1,000 users, you might have 100 concurrent connections hitting your API. Without pooling, that’s 100 database connections consuming resources. With pooling, 20-30 actual database connections can efficiently serve those 100 application connections through connection reuse.

服务 1,000 名用户时,API 可能同时接到 100 条连接。不设连接池,就有 100 条数据库连接在消耗资源。借助连接复用,20~30 条实际的数据库连接就能有效服务这 100 条应用连接。

Connection pooling modes:

连接池有几种工作模式:

Most applications work best with transaction pooling, which often improves connection efficiency by 3–5x.

对多数应用,事务级池化最合适,连接使用效率往往能提高到原来的 3~5 倍。

Network Latency Considerations网络延迟也要算进去

Separating the database introduces network latency. When app and database were on the same machine, “network” latency was essentially zero (loopback interface). Now every query adds 0.1-1ms of network round-trip time.

单独部署数据库会引入网络延迟。应用和数据库在同一台机器上时,走的是回环接口,“网络”延迟几乎为零。现在每次查询会多出 0.1~1 毫秒的网络往返时间。

For most applications, this is negligible. But if your code makes hundreds of database queries per request (an anti-pattern, but common), this latency adds up. The solution isn’t to put them back on the same machine, but to optimize your query patterns:

对多数应用,这点时间可以忽略。但如果每个请求要查询数据库几百次(这是一种常见的反模式),延迟就会累积。此时应优化查询方式,不必把应用和数据库搬回同一台机器:

With the database on its own server, you’ve bought yourself room to grow. But you’ve also created a new single point of failure: the application server is now the weak link. What happens when it goes down, or when it simply can’t keep up with demand?

把数据库放到单独的服务器上,为继续增长腾出了空间,但也使应用服务器成了新的单点。它宕机了怎么办?如果它只是不够快,跟不上请求量,又怎么办?


Stage 3: Load Balancer + Horizontal Scaling (1K-10K Users)第三阶段:负载均衡与水平扩展(1,000~1 万名用户)

Your separated architecture handles load better now, but you’ve introduced a new problem: your single application server is now a single point of failure. If it crashes, your entire application goes down. And as traffic grows, that one server can’t keep up.

拆分后的架构更能应付负载,但现在唯一的应用服务器成了单点故障源。它一旦崩溃,整个应用就会离线。流量持续增长,它迟早也会跟不上。

The next step is to run multiple application servers behind a load balancer.

下一步是在负载均衡器后面运行多台应用服务器。

负载均衡器把请求分发给三台应用服务器,三者共用数据库。

The load balancer sits in front of your servers and distributes incoming requests across them. If one server fails, the load balancer detects this (via health checks) and routes traffic only to healthy servers. Users experience no downtime when a single server fails.

负载均衡器位于服务器前方,负责把进入系统的请求分配给各台服务器。如果一台服务器发生故障,负载均衡器会通过健康检查发现,并只向健康的服务器转发流量。用户不会因为单台服务器故障而遭遇停机。

The load balancer needs to decide which server handles each request. Common algorithms include: Round Robin, Weighted Round Robin, Least Connections, IP Hash, and Random.

负载均衡器要决定每个请求由哪台服务器处理。常见算法有轮询、加权轮询、最少连接、按 IP 哈希和随机分配。

Most teams start with Round Robin (simple, works well for most cases) and switch to Least Connections if they have requests with varying processing times.

大多数团队先用轮询:它简单,也适用于大多数情况。如果各个请求的处理时间差别很大,再换成最少连接。

Modern load balancers operate at different layers:

现代负载均衡器可以工作在不同的网络层:

For most web applications, Layer 7 load balancing is preferable because it enables:

对多数 Web 应用,七层负载均衡更合适,因为它支持:

Vertical vs Horizontal Scaling垂直扩展与水平扩展

Before adding more servers, you might ask: why not just get a bigger server? This is the classic vertical vs horizontal scaling trade-off.

增加服务器之前,你可能会问:为什么不直接换一台更强的机器?这正是垂直扩展与水平扩展之间的经典取舍。

Vertical scaling means moving to a larger server. It works well early on and usually requires no code changes. But you eventually run into two problems: hard hardware limits and rapidly increasing costs.

垂直扩展是换用规格更高的服务器。它在早期效果很好,通常不用改代码。但最后会遇到两个问题:硬件有上限,成本也会迅速上升。

Bigger machines are priced non-linearly, so doubling CPU or memory can cost 3–4x more. And even the largest instances have a ceiling.

大机器的价格并不随规格线性增长。CPU 或内存翻倍,成本可能变成原来的 3~4 倍。而且再大的实例也有上限。

Horizontal scaling means adding more servers. It is harder at first because your application must be stateless, so any server can handle any request. But it gives you effectively unlimited capacity and built-in redundancy. If one server fails, the system keeps running.

水平扩展则是增加服务器数量。起步更难,因为应用必须无状态,才能让任意一台服务器处理任意请求。作为回报,容量几乎可以持续扩展,同时也有了冗余:坏一台,系统照样运行。

The Session Problem会话问题

This is where horizontal scaling gets tricky. If a user logs in and their session lives in Server 1’s memory, what happens when the next request lands on Server 2? From the app’s perspective, the session is missing, so the user looks logged out.

水平扩展的棘手之处在这里。用户登录后,会话存在服务器 1 的内存中。如果下一次请求落到服务器 2,会怎样?它找不到会话,于是会把用户当成已经退出登录。

This is the stateful server problem, and it’s the biggest obstacle to horizontal scaling.

这就是有状态服务器问题,也是水平扩展最大的障碍。

There are two common ways to handle it:

常见的处理办法有两种。

1. Sticky Sessions (Session Affinity)1. 粘性会话(会话亲和性)

The load balancer routes all requests from the same user to the same server, typically using a cookie or IP hash.

负载均衡器把同一用户的所有请求转发到同一台服务器,通常用 Cookie 或 IP 哈希来决定去向。

Pros:

优点:

Cons:

缺点:

2. External Session Store2. 外部会话存储

Move session data out of the application servers into a shared store like Redis or Memcached.

把会话数据移出应用服务器,放入 Redis 或 Memcached 等共享存储。

负载均衡器后的三台应用服务器共用 Redis 会话存储和数据库。

Now any server can handle any request because session data is centralized. This is the pattern most large-scale systems use. The added latency of a Redis lookup (sub-millisecond) is negligible compared to the flexibility it provides.

会话集中存放后,任何一台服务器都能处理任何请求。这是大多数大型系统采用的做法。查一次 Redis 增加的延迟通常不到一毫秒,与这种灵活性相比几乎可以忽略。

You can now handle more traffic and survive server failures. But as your user base grows, you’ll notice something: no matter how many application servers you add, they’re all hammering the same database. The database is becoming your next bottleneck.

现在系统既能承载更多流量,又能经受服务器故障。但用户继续增长时,你会发现,无论加多少应用服务器,它们都在访问同一个数据库。数据库正成为下一个瓶颈。


Stage 4: Caching + Read Replicas + CDN (10K-100K Users)第四阶段:缓存、只读副本与 CDN(1 万~10 万名用户)

With 10,000+ users, a new bottleneck emerges: your database. Every request hits the database, and as traffic grows, query latency increases. The database that handled 100 QPS (queries per second) fine starts struggling at 1,000 QPS.

超过 1 万名用户后,新的瓶颈出现在数据库。每个请求都要访问数据库,流量一大,查询延迟就上升。原来能轻松处理 100 QPS(每秒查询数)的数据库,到了 1,000 QPS 就开始吃力。

Read-heavy applications (which most are, with read-to-write ratios of 10:1 or higher) suffer especially hard.

对以读为主的应用,影响尤其明显。大多数应用都属于这一类,读写比通常达到 10∶1,甚至更高。

This stage introduces three complementary solutions: caching, read replicas, and CDNs. Together, they can reduce database load by 90% or more.

这个阶段可以引入三种互补的手段:缓存、只读副本和 CDN。三者配合,有望将数据库负载降低 90% 甚至更多。

Caching Layer缓存层

Most web applications follow the 80/20 rule: 80% of requests access 20% of the data. A product page viewed 10,000 times doesn’t need 10,000 database queries. The user’s profile that loads on every page view doesn’t need to be fetched fresh each time.

多数 Web 应用符合二八定律:80% 的请求访问 20% 的数据。一张商品详情页被浏览 1 万次,用不着查数据库 1 万次。每次打开页面都会加载的用户资料,也不必次次重新查询。

Caching stores frequently accessed data in memory for near-instant retrieval. While database queries take 1-100ms, cache reads take 0.1-1ms.

缓存把频繁访问的数据放在内存里,读取时几乎不用等。数据库查询要 1~100 毫秒,读缓存只要 0.1~1 毫秒。

旁路缓存命中时约 0.5 毫秒返回;未命中时查询数据库(约 10 毫秒),并把结果写入缓存。

The most common caching pattern is cache-aside (also called lazy loading):

最常见的是旁路缓存(cache-aside,也称惰性加载):

  1. Application checks the cache first

    应用先查缓存。

  2. If data exists (cache hit), return it immediately

    如果数据存在(缓存命中),就立即返回。

  3. If not (cache miss), query the database

    如果不存在(缓存未命中),就查询数据库。

  4. Store the result in cache for future requests (with TTL)

    将结果写入缓存,并设置生存时间(TTL),供后续请求使用。

  5. Return the data

    返回数据。

Redis and Memcached are the standard choices here. Redis is more feature-rich (supports data structures like lists, sets, sorted sets; persistence; pub/sub; Lua scripting), while Memcached is simpler and slightly faster for pure key-value caching.

常见选择是 Redis 和 Memcached。Redis 功能更丰富,支持列表、集合、有序集合等数据结构,也支持持久化、发布订阅和 Lua 脚本。Memcached 更简单,纯键值缓存场景下速度略快。

Most teams choose Redis because the additional features are useful (using sorted sets for leaderboards, lists for queues, etc.), and the performance difference is negligible.

大多数团队选择 Redis,因为有序集合可以做排行榜,列表可以做队列,这些额外功能很实用,而两者的性能差异可以忽略。

What to Cache什么适合缓存

Not everything should be cached. Good cache candidates include:

并非所有数据都值得缓存。以下是合适的候选项:

Cache candidates with example TTLs and the reason for caching each data type.

数据类型生存时间(TTL)原因
用户资料5~15 分钟每页都会加载,数据很少变化
商品列表1~5 分钟读取量大,可以容忍短时间的旧数据
API 响应1~60 秒减少昂贵的计算
数据库查询结果视情况而定避免重复执行昂贵的查询
会话数据30 分钟每个已通过身份验证的请求都需要
限流计数器1 分钟访问量大,对精确度的要求较低

Poor cache candidates:

以下数据不太适合缓存:

Cache Invalidation缓存失效

The hardest part of caching isn’t adding it, it’s keeping it accurate. When underlying data changes, cached data becomes stale. This is famously one of the “two hard problems in computer science.”

加缓存不难,难的是让缓存一直准确。底层数据发生变化,缓存里的值就会过时。这正是人们常说的“计算机科学中的两大难题”之一。

Common strategies include:

常用策略包括:

Five cache update and invalidation strategies compared.

策略工作方式取舍
TTL(生存时间)数据在 N 秒后自动过期实现简单,但 TTL 窗口内可能读到旧数据
直写(Write-Through)数据库更新时立即更新缓存缓存始终最新,写入延迟增加
回写(Write-Behind)先更新缓存,之后异步写数据库写入快;缓存故障可能导致数据丢失
旁路缓存并主动失效数据变化时删除缓存键可精确控制;下一次读取无法命中
事件驱动监听数据库变更,据此使缓存失效精确,但需要变更数据捕获(CDC)等事件基础设施

Most systems start with TTL-based expiration (set cache to expire after 5-60 minutes) and add explicit invalidation for data where staleness causes problems. For example:

多数系统先采用 TTL 过期策略,让缓存项在 5~60 分钟后过期;如果某类数据一旦过时就会造成问题,再对它显式执行失效操作。例如:

def update_user_profile(user_id, new_data):
    # Update database
    db.update("users", user_id, new_data)
    # Invalidate cache
    cache.delete(f"user:{user_id}")

The next read will miss the cache and fetch fresh data from the database.

下一次读取将无法命中缓存,于是会从数据库取回最新数据。

Read Replicas只读副本

Even with caching, some requests will still hit the database, especially writes and cache misses. Read replicas help by distributing read traffic across multiple copies of the database.

即使用了缓存,仍有请求需要访问数据库,尤其是写入和缓存未命中的读取。只读副本可以把读流量分摊给多个数据库副本。

两台应用服务器写主库,并从两个异步更新的只读副本读取数据。

The primary database handles all writes. Changes are then replicated (usually asynchronously) to one or more read replicas. Your application sends read queries to replicas and keeps the write workload on the primary, which reduces contention and improves overall throughput.

所有写入都由主库处理,再把变更复制到一个或多个只读副本,通常采用异步复制。应用把读查询发给副本,写请求留给主库,既能减少资源争用,又能提高总体吞吐量。

Replication Lag复制延迟

One important consideration is replication lag. Since replication is often asynchronous (for performance), replicas might be milliseconds to seconds behind the primary.

需要留意的是复制延迟。为提高性能,复制往往异步进行,从库可能落后主库几毫秒到几秒钟。

For most applications, this is acceptable. If a social media feed is a second behind, most users will not notice. But some flows require stronger consistency.

多数应用可以接受这种延迟。社交媒体的信息流晚一秒出现,大多数用户不会察觉。但有些流程需要更强的一致性。

A common failure mode is read-your-writes consistency:

常见问题是无法保证读到自己的写入:

A user updates their profile and refreshes immediately. If that read lands on a replica that has not caught up, they see old data and assume the update failed.

用户更新个人资料后立刻刷新。如果这次读取落到了尚未追上主库的副本,用户看到的还是旧资料,便以为更新失败了。

Solutions:

可以这样处理:

  1. Read from primary after writes: For a short window (N seconds) after a write, route that user’s reads to the primary.

    写后读主库。写入后的一小段时间(N 秒)内,把该用户的读请求发往主库。

  2. Session-level consistency: Track the user’s last write timestamp and only read from replicas that have caught up past that point.

    会话级一致性。记录用户最后一次写入的时间戳,只从已经同步到该时间点或更晚的副本读取。

  3. Explicit read-from-primary: For critical reads (viewing just-updated data), always hit the primary.

    明确指定读主库。查看刚更新的数据等关键读取,始终访问主库。

Most frameworks have built-in support for read/write splitting. For example, Rails (ActiveRecord), Django, and Hibernate can route reads to replicas and writes to the primary automatically.

许多框架内置了读写分离支持。例如 Rails(ActiveRecord)、Django 和 Hibernate,都可以自动把读取发往副本、写入发往主库。

Content Delivery Network (CDN)内容分发网络(CDN)

Static assets like images, CSS, JavaScript, and videos rarely change and don’t need to hit your application servers at all. They’re also the largest files you serve, which makes them expensive in both bandwidth and compute if you serve them directly.

图片、CSS、JavaScript、视频等静态资源很少变化,根本不必请求应用服务器。它们往往也是站点提供的最大文件,直接提供这些文件既占带宽,也耗计算资源。

A CDN solves this by caching static assets on globally distributed servers called edge locations (or points of presence).

CDN 把静态资源缓存在分布于全球的服务器上。这些服务器所在的位置称为边缘节点,也叫接入点(PoP)。

东京用户距本地 CDN 节点约 50 毫秒;只在缓存未命中时,节点才访问约 300 毫秒外的美国东部源站。

Here’s what happens when a user in Tokyo requests an image:

假设东京的一位用户请求一张图片:

Popular CDNs include Cloudflare (strong free tier), AWS CloudFront, Fastly, and Akamai.

常见的 CDN 有 Cloudflare(免费套餐很实用)、AWS CloudFront、Fastly 和 Akamai。

With caching, read replicas, and a CDN in place, your system can handle steady growth. The next challenge is spiky traffic. A viral post, a marketing campaign, or even the difference between 3 AM and 3 PM can create 10x traffic variation. At that point, manually adjusting capacity stops working.

有了缓存、只读副本和 CDN,系统足以应付平稳增长。下一道难题是流量尖峰。一篇爆红的帖子、一次营销活动,甚至凌晨三点和下午三点的差别,都可能让流量相差十倍。此时再手动调整容量就行不通了。


Stage 5: Auto-Scaling + Stateless Design (100K-500K Users)第五阶段:自动伸缩与无状态设计(10 万~50 万名用户)

At 100K+ users, traffic patterns become less predictable. You might have:

用户超过 10 万后,流量模式越发难以预测。你可能会遇到:

At this point, manually adding and removing servers is no longer viable. You need infrastructure that reacts automatically.

此时手动增减服务器已经不可行。基础设施需要能够自动响应负载变化。

This stage focuses on auto-scaling (automatically adjusting capacity) and ensuring your application is truly stateless (servers can be added or removed freely without data loss or user impact).

这个阶段要解决两件事:自动伸缩,也就是自动调整容量;以及让应用真正无状态,使服务器能自由增减,既不丢数据,也不影响用户。

Stateless Architecture无状态架构

For auto-scaling to work, your application servers must be interchangeable. Any request can go to any server. Any server can be terminated without losing data. A new server can start handling requests immediately.

自动伸缩的前提是应用服务器可以互换。任一请求都能发给任一服务器。任一服务器被终止,都不会丢失数据。新服务器一就绪,就应当能处理请求。

伸缩组将会话与缓存放在 Redis,文件与媒体放在对象存储,主数据放在数据库。

When a new server joins the cluster, it typically:

新服务器加入集群时,通常会:

  1. Starts the application

    启动应用。

  2. Registers with the load balancer (or gets discovered)

    向负载均衡器注册,或由服务发现机制找到它。

  3. Connects to Redis, database, and other shared services

    连接 Redis、数据库和其他共享服务。

  4. Immediately starts handling requests

    开始处理请求。

When a server is removed:

移除服务器时,过程如下:

  1. Load balancer stops sending new requests

    负载均衡器停止向它发送新请求。

  2. In-flight requests complete (graceful shutdown)

    等待正在处理的请求完成,即优雅关闭。

  3. Server terminates

    终止服务器。

No data is lost, because nothing important is stored locally.

重要数据都没有保存在本地,因此不会丢失。

Auto-Scaling Strategies自动伸缩策略

Auto-scaling adjusts capacity based on metrics. The scaling system continuously monitors metrics and adds or removes servers based on thresholds.

自动伸缩系统会持续监控指标,根据阈值增加或移除服务器,从而调整容量。

Most teams start with CPU-based scaling. It’s simple, works for most workloads, and is easy to reason about. Add queue-depth scaling for background job workers.

大多数团队从基于 CPU 使用率的伸缩开始。它简单,适用于多数负载,也容易理解。对执行后台任务的工作进程,可以再按队列深度进行伸缩。

Scaling Parameters伸缩参数

When configuring auto-scaling, you’ll set these parameters:

配置自动伸缩时,需要设置以下参数:

Minimum instances: 2       # Always running, even at zero traffic
Maximum instances: 20      # Cost ceiling and resource limit
Scale-up threshold: 70%    # CPU percentage to trigger scale-up
Scale-down threshold: 30%  # CPU percentage to trigger scale-down
Scale-up cooldown: 3 min   # Wait time after scaling up before next action
Scale-down cooldown: 10 min # Wait time after scaling down
Instance warmup: 2 min     # Time for new instance to become fully operational

Important considerations:

有几点值得注意:

JWT for Stateless Authentication用 JWT 做无状态身份验证

At this scale, many teams move from session-based to token-based authentication using JWTs (JSON Web Tokens). With session-based auth, every request requires a session store lookup. With JWTs, authentication state is contained in the token itself.

到了这个规模,许多团队会把基于会话的身份验证改为基于令牌的验证,使用 JWT(JSON Web Token)。基于会话时,每次请求都要查询会话存储;使用 JWT 时,验证身份所需的状态包含在令牌本身中。

A JWT has three parts:

JWT 由三部分组成:

Header.Payload.Signature

eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjM0NTZ9.signature_here

The payload contains claims like user ID, roles, and expiration. The signature ensures the token wasn’t tampered with. Any server can verify the signature using a shared secret key without querying a database.

载荷中包含用户 ID、角色、过期时间等声明。签名用于确认令牌未被篡改。任何服务器都可以用共享密钥验证签名,无须查询数据库。

Trade-offs with JWTs:

JWT 的取舍如下:

A common pattern is short-lived access tokens (for example, 15 minutes) plus long-lived refresh tokens (for example, 7 days). That limits how long a compromised or stale token can be used.

常见做法是搭配使用短期访问令牌(例如 15 分钟)和长期刷新令牌(例如 7 天),以限制泄露或已经过时的访问令牌还能使用多久。

At this point, your application tier scales elastically. Traffic spikes and more servers spin up. Traffic drops and they spin down.

至此,应用层已经能弹性伸缩:流量猛增,就启动更多服务器;流量下降,就撤掉部分服务器。

But a new ceiling is coming: the database can only handle so many writes, the monolith becomes harder to change safely, and some operations are too slow to run synchronously. That’s when you bring in the heavy machinery.

但新的上限正在逼近:数据库能承受的写入量有限,单体应用越来越难安全修改,还有些操作慢到不适合同步执行。这时才轮到更复杂的手段上场。


Stage 6: Sharding + Microservices + Message Queues (500K-1M Users)第六阶段:分片、微服务与消息队列(50 万~100 万名用户)

With 500K+ users, you’ll hit new ceilings that the previous optimizations can’t solve:

用户超过 50 万后,之前的优化手段已经无法突破一些新的上限:

This is where the heavy machinery comes in: database sharding, microservices, and asynchronous processing (message queues).

这时才需要更重的工具:数据库分片、微服务和借助消息队列进行的异步处理。

Database Sharding数据库分片

Read replicas solved read scaling, but writes all still go to one primary database. At high volume, this primary becomes the bottleneck. You’re limited by what one machine can handle in terms of:

只读副本解决了读取扩展的问题,但所有写入仍然要经过一个主库。数据量上来后,主库就成了瓶颈。以下几项都受单台机器能力的限制:

Sharding splits your data across multiple databases based on a shard key. Each shard holds a subset of the data and handles both reads and writes for that subset.

分片依据分片键,将数据分散到多个数据库。每个分片只存放其中一部分数据,并负责这部分数据的读写。

分片路由器将 A~H、I~P、Q~Z 三组用户分别路由到三个分片。

Sharding Strategies分片策略

Hash, range, directory, and geographic sharding compared, including the hash expression.

策略工作方式优点缺点
哈希分片hash(user_id) % num_shards数据在各分片间分布均匀添加分片需要迁移数据,所有数据重新计算哈希
范围分片1 至 100 万号用户在分片 1,100 万至 200 万号在分片 2实现简单,分片内部可做范围查询某些区间更活跃时负载不均
目录分片通过查找表将每个键映射到一个分片最灵活,可单独迁移某个键查找表可能成为瓶颈,并增加延迟
地理分片美国用户在分片 1,欧盟用户在分片 2延迟低,便于满足数据驻留要求分布可能不均,用户跨区域迁移时处理复杂

Consistent hashing is a popular improvement over simple hash-based sharding. Instead of hash(key) % num_shards, you place keys on a ring. When you add a new shard, only keys adjacent to its position move, not all keys. This means adding a fourth shard moves ~25% of data instead of ~75%.

一致性哈希是对简单哈希分片的一种常见改进。与直接按 hash(key) % num_shards 分片相比,一致性哈希将键放在环上。新增分片时,只移动与该位置相邻的键。例如,加入第四个分片时,需要迁移的数据约为 25%,而简单哈希分片约为 75%。

When to Shard什么时候该分片

Sharding is a one-way door. Once you shard:

分片是个难以逆转的决定。一旦分片:

Before sharding, exhaust these options:

分片之前,应当先试尽以下办法:

  1. Optimize queries: Add missing indexes, rewrite slow queries, denormalize where helpful

    优化查询。补齐缺失的索引,重写慢查询,在确有收益时做反规范化。

  2. Vertical scaling: Upgrade to a bigger database server (more CPU, RAM, faster SSDs)

    垂直扩展。升级数据库服务器,增加 CPU 和内存,换更快的 SSD。

  3. Read replicas: If read-heavy, add replicas to handle reads

    只读副本。读多写少时,增加副本分担读流量。

  4. Caching: Reduce load on database by caching frequently accessed data

    缓存。缓存频繁访问的数据,减轻数据库负载。

  5. Archival: Move old data to cold storage (separate database, object storage)

    归档。把旧数据迁移到冷存储,例如单独的数据库或对象存储。

  6. Connection pooling: Reduce connection overhead

    连接池。减少连接管理的开销。

Only shard when you’re truly write-bound and a single node physically cannot handle your throughput, or when your dataset exceeds what fits on one machine.

只有在确认瓶颈是写入、单节点确实无法承担所需吞吐量,或者数据集大到单机装不下时,才应分片。

Microservices微服务

As the product and team grow, a monolith becomes harder to evolve safely. Common signals you might benefit from microservices:

产品和团队不断成长时,想稳妥地修改单体应用会越来越难。下面这些现象意味着微服务可能帮得上忙:

Microservices split the application into independent services that communicate over the network.

微服务将应用拆成独立的服务,通过网络通信。

API 网关把客户端请求路由到用户、订单、通知、搜索和支付服务,各服务使用各自的数据库、队列或搜索引擎。

Each service:

每个服务都具备以下特征:

The trade-off is a big jump in operational complexity. The safest approach is to start with one extraction: pick the service with the cleanest boundaries and the clearest independent scaling needs. Avoid splitting into dozens of services upfront.

代价是运维复杂度大幅上升。最稳妥的是先拆出一个服务:选边界最清楚、也最需要独立扩展的那一个。不要一开始就拆成几十个服务。

Message Queues and Async Processing消息队列与异步处理

Not everything needs to happen synchronously in the request path. When a user places an order, some steps must complete immediately, while others can happen in the background.

并非所有工作都要在请求路径上同步完成。以用户下单为例,有些步骤必须当场完成,另一些则可以交给后台。

Must be synchronous:

必须同步完成:

Can be asynchronous:

可以异步完成:

Message queues like Kafka, RabbitMQ, or SQS decouple producers from consumers. The order service publishes an event like OrderPlaced, and downstream systems consume it independently.

Kafka、RabbitMQ、SQS 等消息队列可以把生产者与消费者解耦。订单服务发布一个事件,例如 OrderPlaced,各个下游系统可以独立消费它。

订单和用户服务向消息队列发布事件,邮件、分析、仓储和推荐服务分别消费。

Benefits of async processing:

异步处理带来的好处包括:

A common real-world pattern is “do the write now, do the heavy work later.”

现实中经常采用的模式是:“先完成写入,耗时的工作留到后面。”

For example, in social apps, creating a post is usually a fast write and an immediate success response. Expensive work like fan-out, indexing, notifications, and feed updates happens asynchronously, which is why you sometimes see small delays in like counts or feed propagation.

比如社交应用创建帖子时,通常只做一次快速写入,就立即返回成功响应。扇出分发、建立索引、发送通知、更新信息流等开销大的工作随后异步执行。因此,点赞数更新、帖子出现在其他人的信息流中,有时都会稍有延迟。

At this point, your architecture can handle massive scale within a single region. But your users aren’t all in one place, and neither should your infrastructure be.

到这里,架构已经能在单个区域承载很大的规模。但用户不会全都集中在一个地方,基础设施也不该如此。

Once you have users across continents, latency becomes noticeable, and a single datacenter becomes a single point of failure for your entire global user base.

一旦用户遍布多个大洲,网络延迟就会变得明显,而唯一的数据中心也会成为影响全球所有用户的单点故障源。


Stage 7: Multi-Region + Advanced Patterns (1M-10M+ Users)第七阶段:多区域部署与进阶架构模式(100 万~1,000 万及以上用户)

With millions of users worldwide, new challenges emerge:

在全球拥有数百万用户时,新的挑战接踵而来:

This stage covers multi-region deployment, advanced caching, and specialized patterns like CQRS.

这个阶段会讨论多区域部署、进阶缓存策略,以及 CQRS 等专用架构模式。

Multi-Region Architecture多区域架构

Deploying to multiple geographic regions achieves two main goals:

在多个地理区域部署主要有两个目标:

  1. Lower latency: Users connect to nearby servers. Tokyo users hit Tokyo servers (20ms) instead of US servers (200ms).

    降低延迟。用户连接附近的服务器。例如东京用户访问东京服务器只要 20 毫秒,访问美国服务器则要 200 毫秒。

  2. Disaster recovery: If one region fails, others continue serving traffic. True high availability.

    灾难恢复。一个区域出现故障时,其他区域仍能接收流量,实现真正的高可用。

全球 DNS 将用户路由到三个区域;美国东部主库将数据异步复制到亚太和欧洲西部的副本。

There are two main approaches:

主要有两种做法。

Active-Passive (Primary-Secondary)主备模式(Active-Passive)

One region (primary) handles all writes. Other regions serve reads and can take over if the primary fails.

一个区域作为主区域,处理所有写入。其他区域提供读取服务,并可在主区域故障时接管。

Pros:

优点:

Cons:

缺点:

Active-Active多活模式(Active-Active)

All regions handle both reads and writes. This requires solving the hard problem: what happens when users in US and EU update the same record simultaneously?

所有区域都能读写。这样就必须解决一个难题:美国用户和欧洲用户同时修改同一条记录,会发生什么?

Pros:

优点:

Cons:

缺点:

Most companies start with active-passive. Active-active requires solving distributed consensus problems and accepting eventual consistency.

大多数公司先采用主备模式。采用多活架构,既要解决分布式共识问题,也要能接受最终一致性。

CAP Theorem at Global Scale全球规模下的 CAP 定理

The CAP theorem becomes very real at global scale. It states that a distributed system can only provide two of three guarantees:

在全球规模下,CAP 定理会变成切实的工程约束。它指出,一个分布式系统无法同时提供以下三项保证:

Since network partitions between regions are inevitable (undersea cables get cut, cloud providers have outages), you’re really choosing between consistency and availability during a partition.

区域间的网络分区不可避免,例如海底光缆被切断,或云服务商出现故障。因此真正要做的选择是:发生分区期间,保一致性还是保可用性?

Most global systems choose eventual consistency for most operations:

对多数操作,大多数全球系统选择最终一致性:

Only operations where inconsistency causes real problems (payments, inventory decrements, financial transactions) require strong consistency, and those might route to a primary region.

只有在数据不一致会引发实际问题的地方,例如支付、扣减库存、金融交易,才需要强一致性。这些操作可以路由到主区域。

CQRS PatternCQRS 模式

As systems grow, read and write patterns diverge significantly:

随着系统增长,读写两条路径的需求会显著分化:

CQRS (Command Query Responsibility Segregation) separates these concerns entirely.

CQRS(命令查询职责分离)将这两类职责彻底分开。

CQRS 将写入端的验证与规范化数据库同查询端的反规范化数据库分开,投影服务消费事件并更新读库。

The write side uses a normalized schema optimized for data integrity and transactional guarantees. The read side uses denormalized views optimized for query performance. Events synchronize the two.

写入端采用规范化的数据库模式,针对数据完整性和事务保证进行优化;读取端使用反规范化的视图,针对查询性能优化。两端通过事件保持同步。

Real-world example: Twitter’s timeline architecture.

现实中的例子是 Twitter 的时间线架构。

CQRS adds complexity but enables:

CQRS 增加了复杂度,但也让以下做法成为可能:

Advanced Caching Patterns进阶缓存策略

At global scale, caching becomes more sophisticated:

在全球规模下,缓存也会用得更精细。

Multi-Tier Caching多级缓存

逐级未命中时,请求从本地内存依次转向 Redis 集群、CDN 边缘节点,最后到源站数据库。

Latency, size, and use cases for three cache tiers and the origin database.

层级类型延迟容量使用场景
L1应用内存小于 0.1 毫秒小,GB 级热点数据、请求范围内的数据
L2分布式缓存(Redis)0.5~2 毫秒中等,数十至数百 GB共享数据、会话
L3CDN 边缘10~50 毫秒大,TB 级静态内容、API 响应
源站数据库10~100 毫秒非常大权威数据

Cache Warming缓存预热

When a new cache server starts (or cache expires after maintenance), the first requests face cache misses, causing latency spikes and origin load. Cache warming pre-populates caches before traffic arrives:

新的缓存服务器刚启动,或维护之后缓存已过期时,最先到达的请求会连续遇到缓存未命中,导致延迟飙升、源站负载增加。缓存预热则在流量到来之前填入数据:

Netflix pre-warms edge caches with popular content before peak hours. When evening viewing starts, the most-watched shows are already cached at edge locations.

Netflix 会在高峰时段到来之前,把热门内容预先放入边缘缓存。晚间观众打开电视时,最受欢迎的节目已经缓存在边缘节点。

Write-Behind (Write-Back) Caching异步回写缓存(Write-Behind / Write-Back)

For write-heavy workloads, write to cache first and asynchronously persist to database:

对写入密集的负载,可以先写缓存,再异步持久化到数据库:

  1. Write goes to cache (immediate return to user)

    写入先到缓存,用户立即得到响应。

  2. Cache acknowledges write

    缓存确认写入。

  3. Background process flushes writes to database periodically

    后台进程定期将写入刷新到数据库。

This reduces write latency dramatically but introduces risk: if the cache fails before flushing, writes are lost. Use only when:

这会显著降低写入延迟,但也带来风险:缓存若在刷新前发生故障,这些写入就会丢失。只在以下条件下使用:

You’ve now built a globally distributed system that handles millions of users with low latency worldwide. But the journey doesn’t end here. At truly massive scale, even the best off-the-shelf solutions start showing their limits.

至此,你已搭建起一个全球分布式系统,能以较低延迟服务世界各地的数百万用户。但这条路还没到头。规模再往上,即使最好的现成方案也会逐渐显出局限。


Beyond 10 Million Users超过一千万用户之后

At 10 million users and beyond, you enter territory where off-the-shelf solutions don’t always work. Companies at this scale often build custom infrastructure tailored to their specific access patterns. The problems become unique to your workload.

用户数达到一千万乃至更多时,现成方案未必处处适用。这一规模的公司经常会按自身访问模式定制基础设施。系统遇到的问题开始取决于它自己特有的负载。

Specialized Data Stores专用数据存储

No single database handles all access patterns well. The concept of “polyglot persistence” means using different databases for different use cases:

没有一个数据库能擅长所有访问模式。“多元持久化”(polyglot persistence)指的就是为不同场景选用不同的数据库:

应用按数据类型使用七种存储,例如 PostgreSQL 存事务数据、Redis 存会话与缓存、ClickHouse 做分析。

Database choices and their strengths for eight different data types.

数据类型数据库或存储选择选择原因
事务数据PostgreSQL、MySQL、CockroachDBACID 保证、熟悉的 SQL、成熟的工具
缓存与会话Redis、Memcached亚毫秒级延迟,多种数据结构
全文搜索Elasticsearch、OpenSearch、Meilisearch倒排索引、相关性评分、分面搜索
时间序列TimescaleDB、InfluxDB、Prometheus针对按时间顺序写入、降采样和数据保留做了优化
图关系Neo4j、Amazon Neptune、Dgraph高效遍历,在关系上做模式匹配
媒体与文件S3、GCS、Azure Blob便宜、持久、可持续扩展的对象存储
分析ClickHouse、BigQuery、Snowflake列式存储、快速聚合、支持极大规模
大规模键值数据DynamoDB、Cassandra、ScyllaDB各种规模下延迟可预测,支持水平扩展

Each database is optimized for specific access patterns. Using PostgreSQL for time-series data works but is inefficient. Using Elasticsearch for transactions is possible but dangerous.

每种数据库都针对特定访问模式做了优化。用 PostgreSQL 存时间序列数据也能工作,但效率不高;用 Elasticsearch 处理事务也许做得到,却有风险。

Custom Solutions at Scale大规模系统中的定制方案

At extreme scale, some companies build custom infrastructure because their requirements go beyond what general-purpose systems can deliver:

到了极大规模,有些公司的需求超出了通用系统能提供的能力,它们因此开始自建基础设施:

These aren’t options you’ll reach for initially, but they illustrate that scaling is an ongoing journey, not a destination. The architecture that works at 1 million users is rarely the one you’ll want at 100 million.

起步时用不到这些方案,但这些例子说明,扩展是持续的过程。适合 100 万用户的架构,很少会是一亿用户时仍想采用的架构。

Edge Computing边缘计算

The next frontier is pushing computation closer to users. Instead of all logic running in centralized data centers, edge computing runs code at CDN edge locations worldwide:

下一个方向是让计算更靠近用户。边缘计算把代码放到世界各地的 CDN 边缘节点执行,无须把所有逻辑都集中在数据中心:

Edge computing represents a fundamental shift: instead of “request → CDN → origin → CDN → response”, many requests become “request → edge → response” with the edge having enough compute capability to handle the logic.

边缘计算改变了请求的路径。过去是“请求 → CDN → 源站 → CDN → 响应”;当边缘已有足够算力来执行逻辑时,许多请求可以简化成“请求 → 边缘 → 响应”。

Now that we’ve covered the full progression from a single server to global-scale infrastructure, an important question remains: how do you know when to take each step? Scaling too early wastes resources; scaling too late causes outages.

从单台服务器到全球基础设施,整个演进过程已经讲完。还有一个重要问题:怎么判断何时该迈出哪一步?扩展过早会浪费资源,过晚则会导致故障。


Summary总结

Scaling a system from zero to millions of users follows a predictable progression. Each stage solves problems that emerge at specific thresholds:

从零用户扩展到数百万用户,系统通常会经历一系列可预期的阶段。每个阶段都为了解决达到某一规模后出现的问题:

User ranges, architecture changes, and main benefits across all seven scaling stages.

阶段用户数主要变化主要收益
10~100单台服务器承载所有组件快速上线,验证想法
2100~1,000将数据库与应用服务器分离资源隔离,独立扩展
31,000~1 万负载均衡,水平扩展增加冗余,承载更多流量
41 万~10 万缓存、只读副本、CDN减轻数据库负载,加快读取
510 万~50 万自动伸缩,状态外置自动应对流量尖峰
650 万~100 万分片、微服务、消息队列扩展写入能力,团队独立交付
7100 万~1,000 万及以上多区域、CQRS、专用存储改善全球访问性能,支持灾难恢复

Key Principles to Remember值得记住的原则

  1. Start simple: Don’t optimize for problems you don’t have yet. A single server is fine until it isn’t.

    从简单开始。别优化还没遇到的问题。一台服务器能胜任时,就先用一台。

  2. Measure first: Identify the actual bottleneck before adding infrastructure. CPU-bound problems need different solutions than I/O-bound ones.

    先测量。增添基础设施前,先找到真正的瓶颈。CPU 受限和 I/O 受限的问题,需要不同的解决办法。

  3. Stateless servers are the prerequisite: You can’t horizontally scale or auto-scale until your servers hold no local state.

    无状态服务器是前提。要水平扩展或自动伸缩,服务器首先不能依赖本地保存的状态。

  4. Cache aggressively: Most data is read far more often than written. Caching gives you 10-100x performance improvement for read-heavy workloads.

    充分利用缓存。多数数据被读取的次数远多于被写入的次数;对读密集型负载,缓存可以把性能提高到原来的 10~100 倍。

  5. Async when possible: Not everything needs to happen in the request path. Email sending, analytics, notifications can all be queued.

    能异步就异步。并非所有工作都要放在请求路径上。发送邮件、做分析、发通知,都可以排队处理。

  6. Shard reluctantly: Database sharding is a one-way door with significant complexity. Exhaust other options first.

    谨慎分片。数据库分片很难回头,也会大幅增加复杂度。先试尽其他选择。

  7. Accept trade-offs: Perfect consistency and availability don’t coexist during network partitions. Know which operations truly need strong consistency.

    接受取舍。发生网络分区时,严格一致性与可用性不能兼得。要清楚哪些操作确实需要强一致性。

  8. Complexity has costs: Every component you add is a component that can fail, needs monitoring, requires expertise to operate.

    复杂度有代价。每增加一个组件,就多了一个可能出故障、需要监控、也需要专业知识才能运维的环节。

The path to scale isn’t about implementing everything at once. It’s about understanding which problems emerge at each stage and applying the right solutions at the right time.

扩展系统并不要求一次实现所有机制,而是要看懂各阶段会冒出哪些问题,再在合适的时候选用相应的办法。

The best architecture is the simplest one that meets your current needs, with a clear path to evolve when those needs change.

最好的架构,是能满足当前需求的最简单方案,同时也能在需求改变时沿清晰的路径演进。

Thank you so much for reading. If you found it valuable, consider subscribing for more such content every week. If you have any questions or suggestions, please email me your comments or feel free to improve it.

感谢阅读。如果你觉得本文有帮助,可以订阅,每周收到更多这样的内容。有问题或建议,欢迎通过电子邮件告诉我,也欢迎提出改进。


Edit page
Share this post:

Comments


Previous Post
My Senior Engineer Interview Experiences|我的高级软件工程师面试经历
Next Post
Prompt caching: 10x cheaper LLM tokens, but how?|提示词缓存:LLM 的输入 token 为什么能便宜十倍?