zh-cn: Sync with upstream to keep it up-to-date (#374)

pull/391/head
根号三 2020-03-10 09:34:18 +08:00 committed by GitHub
parent 8e9c89129b
commit 301b9d88e4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 1449 additions and 1457 deletions

View File

@ -1,6 +1,6 @@
> * 原文地址:[github.com/donnemartin/system-design-primer](https://github.com/donnemartin/system-design-primer) > * 原文地址:[github.com/donnemartin/system-design-primer](https://github.com/donnemartin/system-design-primer)
> * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner) > * 译文出自:[掘金翻译计划](https://github.com/xitu/gold-miner)
> * 译者:[XatMassacrE](https://github.com/XatMassacrE)、[L9m](https://github.com/L9m)、[Airmacho](https://github.com/Airmacho)、[xiaoyusilen](https://github.com/xiaoyusilen)、[jifaxu](https://github.com/jifaxu) > * 译者:[XatMassacrE](https://github.com/XatMassacrE)、[L9m](https://github.com/L9m)、[Airmacho](https://github.com/Airmacho)、[xiaoyusilen](https://github.com/xiaoyusilen)、[jifaxu](https://github.com/jifaxu)、[根号三](https://github.com/sqrthree)
> * 这个 [链接](https://github.com/xitu/system-design-primer/compare/master...donnemartin:master) 用来查看本翻译与英文版是否有差别(如果你没有看到 README.md 发生变化,那就意味着这份翻译文档是最新的)。 > * 这个 [链接](https://github.com/xitu/system-design-primer/compare/master...donnemartin:master) 用来查看本翻译与英文版是否有差别(如果你没有看到 README.md 发生变化,那就意味着这份翻译文档是最新的)。
*[English](README.md) ∙ [日本語](README-ja.md) ∙ [简体中文](README-zh-Hans.md) ∙ [繁體中文](README-zh-TW.md) | [العَرَبِيَّة‎](https://github.com/donnemartin/system-design-primer/issues/170) ∙ [বাংলা](https://github.com/donnemartin/system-design-primer/issues/220) ∙ [Português do Brasil](https://github.com/donnemartin/system-design-primer/issues/40) ∙ [Deutsch](https://github.com/donnemartin/system-design-primer/issues/186) ∙ [ελληνικά](https://github.com/donnemartin/system-design-primer/issues/130) ∙ [עברית](https://github.com/donnemartin/system-design-primer/issues/272) ∙ [Italiano](https://github.com/donnemartin/system-design-primer/issues/104) ∙ [韓國語](https://github.com/donnemartin/system-design-primer/issues/102) ∙ [فارسی](https://github.com/donnemartin/system-design-primer/issues/110) ∙ [Polski](https://github.com/donnemartin/system-design-primer/issues/68) ∙ [русский язык](https://github.com/donnemartin/system-design-primer/issues/87) ∙ [Español](https://github.com/donnemartin/system-design-primer/issues/136) ∙ [ภาษาไทย](https://github.com/donnemartin/system-design-primer/issues/187) ∙ [Türkçe](https://github.com/donnemartin/system-design-primer/issues/39) ∙ [tiếng Việt](https://github.com/donnemartin/system-design-primer/issues/127) ∙ [Français](https://github.com/donnemartin/system-design-primer/issues/250) | [Add Translation](https://github.com/donnemartin/system-design-primer/issues/28)* *[English](README.md) ∙ [日本語](README-ja.md) ∙ [简体中文](README-zh-Hans.md) ∙ [繁體中文](README-zh-TW.md) | [العَرَبِيَّة‎](https://github.com/donnemartin/system-design-primer/issues/170) ∙ [বাংলা](https://github.com/donnemartin/system-design-primer/issues/220) ∙ [Português do Brasil](https://github.com/donnemartin/system-design-primer/issues/40) ∙ [Deutsch](https://github.com/donnemartin/system-design-primer/issues/186) ∙ [ελληνικά](https://github.com/donnemartin/system-design-primer/issues/130) ∙ [עברית](https://github.com/donnemartin/system-design-primer/issues/272) ∙ [Italiano](https://github.com/donnemartin/system-design-primer/issues/104) ∙ [韓國語](https://github.com/donnemartin/system-design-primer/issues/102) ∙ [فارسی](https://github.com/donnemartin/system-design-primer/issues/110) ∙ [Polski](https://github.com/donnemartin/system-design-primer/issues/68) ∙ [русский язык](https://github.com/donnemartin/system-design-primer/issues/87) ∙ [Español](https://github.com/donnemartin/system-design-primer/issues/136) ∙ [ภาษาไทย](https://github.com/donnemartin/system-design-primer/issues/187) ∙ [Türkçe](https://github.com/donnemartin/system-design-primer/issues/39) ∙ [tiếng Việt](https://github.com/donnemartin/system-design-primer/issues/127) ∙ [Français](https://github.com/donnemartin/system-design-primer/issues/250) | [Add Translation](https://github.com/donnemartin/system-design-primer/issues/28)*
@ -12,14 +12,6 @@
<br/> <br/>
</p> </p>
## 翻译
有兴趣参与[翻译](https://github.com/donnemartin/system-design-primer/issues/28)? 以下是正在进行中的翻译:
* [巴西葡萄牙语](https://github.com/donnemartin/system-design-primer/issues/40)
* [简体中文](https://github.com/donnemartin/system-design-primer/issues/38)
* [土耳其语](https://github.com/donnemartin/system-design-primer/issues/39)
## 目的 ## 目的
> 学习如何设计大型系统。 > 学习如何设计大型系统。
@ -91,6 +83,7 @@
* 修复错误 * 修复错误
* 完善章节 * 完善章节
* 添加章节 * 添加章节
* [帮助翻译](https://github.com/donnemartin/system-design-primer/issues/28)
一些还需要完善的内容放在了[正在完善中](#正在完善中)。 一些还需要完善的内容放在了[正在完善中](#正在完善中)。

View File

@ -1,102 +1,102 @@
# Design Mint.com # 设计 Mint.com
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注意:这个文档中的链接会直接指向[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题索引)中的有关部分,以避免重复的内容。您可以参考链接的相关内容,来了解其总的要点、方案的权衡取舍以及可选的替代方案。**
## Step 1: Outline use cases and constraints ## 第一步:简述用例与约束条件
> Gather requirements and scope the problem. > 搜集需求与问题的范围。
> Ask questions to clarify use cases and constraints. > 提出问题来明确用例与约束条件。
> Discuss assumptions. > 讨论假设。
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 我们将在没有面试官明确说明问题的情况下,自己定义一些用例以及限制条件。
### Use cases ### 用例
#### We'll scope the problem to handle only the following use cases #### 我们将把问题限定在仅处理以下用例的范围中
* **User** connects to a financial account * **用户** 连接到一个财务账户
* **Service** extracts transactions from the account * **服务** 从账户中提取交易
* Updates daily * 每日更新
* Categorizes transactions * 分类交易
* Allows manual category override by the user * 允许用户手动分类
* No automatic re-categorization * 不自动重新分类
* Analyzes monthly spending, by category * 按类别分析每月支出
* **Service** recommends a budget * **服务** 推荐预算
* Allows users to manually set a budget * 允许用户手动设置预算
* Sends notifications when approaching or exceeding budget * 当接近或者超出预算时,发送通知
* **Service** has high availability * **服务** 具有高可用性
#### Out of scope #### 非用例范围
* **Service** performs additional logging and analytics * **服务** 执行附加的日志记录和分析
### Constraints and assumptions ### 限制条件与假设
#### State assumptions #### 提出假设
* Traffic is not evenly distributed * 网络流量非均匀分布
* Automatic daily update of accounts applies only to users active in the past 30 days * 自动账户日更新只适用于 30 天内活跃的用户
* Adding or removing financial accounts is relatively rare * 添加或者移除财务账户相对较少
* Budget notifications don't need to be instant * 预算通知不需要及时
* 10 million users * 1000 万用户
* 10 budget categories per user = 100 million budget items * 每个用户10个预算类别= 1亿个预算项
* Example categories: * 示例类别:
* Housing = $1,000 * Housing = $1,000
* Food = $200 * Food = $200
* Gas = $100 * Gas = $100
* Sellers are used to determine transaction category * 卖方确定交易类别
* 50,000 sellers * 50000 个卖方
* 30 million financial accounts * 3000 万财务账户
* 5 billion transactions per month * 每月 50 亿交易
* 500 million read requests per month * 每月 5 亿读请求
* 10:1 write to read ratio * 10:1 读写比
* Write-heavy, users make transactions daily, but few visit the site daily * Write-heavy,用户每天都进行交易,但是每天很少访问该网站
#### Calculate usage #### 计算用量
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** **如果你需要进行粗略的用量计算,请向你的面试官说明。**
* Size per transaction: * 每次交易的用量:
* `user_id` - 8 bytes * `user_id` - 8 字节
* `created_at` - 5 bytes * `created_at` - 5 字节
* `seller` - 32 bytes * `seller` - 32 字节
* `amount` - 5 bytes * `amount` - 5 字节
* Total: ~50 bytes * Total: ~50 字节
* 250 GB of new transaction content per month * 每月产生 250 GB 新的交易内容
* 50 bytes per transaction * 5 billion transactions per month * 每次交易 50 比特 * 50 亿交易每月
* 9 TB of new transaction content in 3 years * 3年内新的交易内容 9 TB
* Assume most are new transactions instead of updates to existing ones * Assume most are new transactions instead of updates to existing ones
* 2,000 transactions per second on average * 平均每秒产生 2000 次交易
* 200 read requests per second on average * 平均每秒产生 200 读请求
Handy conversion guide: 便利换算指南:
* 2.5 million seconds per month * 每个月有 250 万秒
* 1 request per second = 2.5 million requests per month * 每秒一个请求 = 每个月 250 万次请求
* 40 requests per second = 100 million requests per month * 每秒 40 个请求 = 每个月 1 亿次请求
* 400 requests per second = 1 billion requests per month * 每秒 400 个请求 = 每个月 10 亿次请求
## Step 2: Create a high level design ## 第二步:概要设计
> Outline a high level design with all important components. > 列出所有重要组件以规划概要设计。
![Imgur](http://i.imgur.com/E8klrBh.png) ![Imgur](http://i.imgur.com/E8klrBh.png)
## Step 3: Design core components ## 第三步:设计核心组件
> Dive into details for each core component. > 深入每个核心组件的细节。
### Use case: User connects to a financial account ### 用例:用户连接到一个财务账户
We could store info on the 10 million users in a [relational database](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms). We should discuss the [use cases and tradeoffs between choosing SQL or NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql). 我们可以将 1000 万用户的信息存储在一个[关系数据库](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms)中。我们应该讨论一下[选择SQL或NoSQL之间的用例和权衡](https://github.com/donnemartin/system-design-primer#sql-or-nosql)了。
* The **Client** sends a request to the **Web Server**, running as a [reverse proxy](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **客户端** 作为一个[反向代理](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server),发送请求到 **Web 服务器**
* The **Web Server** forwards the request to the **Accounts API** server * **Web 服务器** 转发请求到 **账户API** 服务器
* The **Accounts API** server updates the **SQL Database** `accounts` table with the newly entered account info * **账户API** 服务器将新输入的账户信息更新到 **SQL数据库** 的`accounts`表
**Clarify with your interviewer how much code you are expected to write**. **告知你的面试官你准备写多少代码**。
The `accounts` table could have the following structure: `accounts`表应该具有如下结构:
``` ```
id int NOT NULL AUTO_INCREMENT id int NOT NULL AUTO_INCREMENT
@ -110,9 +110,9 @@ PRIMARY KEY(id)
FOREIGN KEY(user_id) REFERENCES users(id) FOREIGN KEY(user_id) REFERENCES users(id)
``` ```
We'll create an [index](https://github.com/donnemartin/system-design-primer#use-good-indices) on `id`, `user_id `, and `created_at` to speed up lookups (log-time instead of scanning the entire table) and to keep the data in memory. Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> 我们将在`id``user_id`和`created_at`等字段上创建一个[索引](https://github.com/donnemartin/system-design-primer#use-good-indices)以加速查找(对数时间而不是扫描整个表)并保持数据在内存中。从内存中顺序读取 1 MB数据花费大约250毫秒而从SSD读取是其4倍从磁盘读取是其80倍。<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup>
We'll use a public [**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest): 我们将使用公开的[**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest):
``` ```
$ curl -X POST --data '{ "user_id": "foo", "account_url": "bar", \ $ curl -X POST --data '{ "user_id": "foo", "account_url": "bar", \
@ -120,35 +120,35 @@ $ curl -X POST --data '{ "user_id": "foo", "account_url": "bar", \
https://mint.com/api/v1/account https://mint.com/api/v1/account
``` ```
For internal communications, we could use [Remote Procedure Calls](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc). 对于内部通信,我们可以使用[远程过程调用](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc)。
Next, the service extracts transactions from the account. 接下来,服务从账户中提取交易。
### Use case: Service extracts transactions from the account ### 用例:服务从账户中提取交易
We'll want to extract information from an account in these cases: 如下几种情况下,我们会想要从账户中提取信息:
* The user first links the account * 用户首次链接账户
* The user manually refreshes the account * 用户手动更新账户
* Automatically each day for users who have been active in the past 30 days * 为过去 30 天内活跃的用户自动日更新
Data flow: 数据流:
* The **Client** sends a request to the **Web Server** * **客户端**向 **Web服务器** 发送请求
* The **Web Server** forwards the request to the **Accounts API** server * **Web服务器** 将请求转发到 **帐户API** 服务器
* The **Accounts API** server places a job on a **Queue** such as [Amazon SQS](https://aws.amazon.com/sqs/) or [RabbitMQ](https://www.rabbitmq.com/) * **帐户API** 服务器将job放在 **队列** 中,如 [Amazon SQS](https://aws.amazon.com/sqs/) 或者 [RabbitMQ](https://www.rabbitmq.com/)
* Extracting transactions could take awhile, we'd probably want to do this [asynchronously with a queue](https://github.com/donnemartin/system-design-primer#asynchronism), although this introduces additional complexity * 提取交易可能需要一段时间,我们可能希望[与队列异步](https://github.com/donnemartin/system-design-primer#asynchronism)地来做,虽然这会引入额外的复杂度。
* The **Transaction Extraction Service** does the following: * **交易提取服务** 执行如下操作:
* Pulls from the **Queue** and extracts transactions for the given account from the financial institution, storing the results as raw log files in the **Object Store** * 从 **Queue** 中拉取并从金融机构中提取给定用户的交易,将结果作为原始日志文件存储在 **对象存储区**。
* Uses the **Category Service** to categorize each transaction * 使用 **分类服务** 来分类每个交易
* Uses the **Budget Service** to calculate aggregate monthly spending by category * 使用 **预算服务** 来按类别计算每月总支出
* The **Budget Service** uses the **Notification Service** to let users know if they are nearing or have exceeded their budget * **预算服务** 使用 **通知服务** 让用户知道他们是否接近或者已经超出预算
* Updates the **SQL Database** `transactions` table with categorized transactions * 更新具有分类交易的 **SQL数据库** 的`transactions`表
* Updates the **SQL Database** `monthly_spending` table with aggregate monthly spending by category * 按类别更新 **SQL数据库** `monthly_spending`表的每月总支出
* Notifies the user the transactions have completed through the **Notification Service**: * 通过 **通知服务** 提醒用户交易完成
* Uses a **Queue** (not pictured) to asynchronously send out notifications * 使用一个 **队列** (没有画出来) 来异步发送通知
The `transactions` table could have the following structure: `transactions`表应该具有如下结构:
``` ```
id int NOT NULL AUTO_INCREMENT id int NOT NULL AUTO_INCREMENT
@ -160,9 +160,9 @@ PRIMARY KEY(id)
FOREIGN KEY(user_id) REFERENCES users(id) FOREIGN KEY(user_id) REFERENCES users(id)
``` ```
We'll create an [index](https://github.com/donnemartin/system-design-primer#use-good-indices) on `id`, `user_id `, and `created_at`. 我们将在 `id``user_id`,和 `created_at`字段上创建[索引](https://github.com/donnemartin/system-design-primer#use-good-indices)。
The `monthly_spending` table could have the following structure: `monthly_spending`表应该具有如下结构:
``` ```
id int NOT NULL AUTO_INCREMENT id int NOT NULL AUTO_INCREMENT
@ -174,13 +174,13 @@ PRIMARY KEY(id)
FOREIGN KEY(user_id) REFERENCES users(id) FOREIGN KEY(user_id) REFERENCES users(id)
``` ```
We'll create an [index](https://github.com/donnemartin/system-design-primer#use-good-indices) on `id` and `user_id `. 我们将在`id``user_id`字段上创建[索引](https://github.com/donnemartin/system-design-primer#use-good-indices)。
#### Category service #### 分类服务
For the **Category Service**, we can seed a seller-to-category dictionary with the most popular sellers. If we estimate 50,000 sellers and estimate each entry to take less than 255 bytes, the dictionary would only take about 12 MB of memory. 对于 **分类服务**,我们可以生成一个带有最受欢迎卖家的卖家-类别字典。如果我们估计 50000 个卖家,并估计每个条目占用不少于 255 个字节,该字典只需要大约 12 MB内存。
**Clarify with your interviewer how much code you are expected to write**. **告知你的面试官你准备写多少代码**。
```python ```python
class DefaultCategories(Enum): class DefaultCategories(Enum):
@ -197,7 +197,7 @@ seller_category_map['Target'] = DefaultCategories.SHOPPING
... ...
``` ```
For sellers not initially seeded in the map, we could use a crowdsourcing effort by evaluating the manual category overrides our users provide. We could use a heap to quickly lookup the top manual override per seller in O(1) time. 对于一开始没有在映射中的卖家,我们可以通过评估用户提供的手动类别来进行众包。在 O(1) 时间内,我们可以用堆来快速查找每个卖家的顶端的手动覆盖。
```python ```python
class Categorizer(object): class Categorizer(object):
@ -217,7 +217,7 @@ class Categorizer(object):
return None return None
``` ```
Transaction implementation: 交易实现:
```python ```python
class Transaction(object): class Transaction(object):
@ -228,9 +228,10 @@ class Transaction(object):
self.amount = amount self.amount = amount
``` ```
### Use case: Service recommends a budget ### 用例:服务推荐预算
To start, we could use a generic budget template that allocates category amounts based on income tiers. Using this approach, we would not have to store the 100 million budget items identified in the constraints, only those that the user overrides. If a user overrides a budget category, which we could store the override in the `TABLE budget_overrides`. 首先,我们可以使用根据收入等级分配每类别金额的通用预算模板。使用这种方法,我们不必存储在约束中标识的 1 亿个预算项目,只需存储用户覆盖的预算项目。如果用户覆盖预算类别,我们可以在
`TABLE budget_overrides`中存储此覆盖。
```python ```python
class Budget(object): class Budget(object):
@ -252,26 +253,26 @@ class Budget(object):
self.categories_to_budget_map[category] = amount self.categories_to_budget_map[category] = amount
``` ```
For the **Budget Service**, we can potentially run SQL queries on the `transactions` table to generate the `monthly_spending` aggregate table. The `monthly_spending` table would likely have much fewer rows than the total 5 billion transactions, since users typically have many transactions per month. 对于 **预算服务** 而言,我们可以在`transactions`表上运行SQL查询以生成`monthly_spending`聚合表。由于用户通常每个月有很多交易,所以`monthly_spending`表的行数可能会少于总共50亿次交易的行数。
As an alternative, we can run **MapReduce** jobs on the raw transaction files to: 作为替代,我们可以在原始交易文件上运行 **MapReduce** 作业来:
* Categorize each transaction * 分类每个交易
* Generate aggregate monthly spending by category * 按类别生成每月总支出
Running analyses on the transaction files could significantly reduce the load on the database. 对交易文件的运行分析可以显著减少数据库的负载。
We could call the **Budget Service** to re-run the analysis if the user updates a category. 如果用户更新类别,我们可以调用 **预算服务** 重新运行分析。
**Clarify with your interviewer how much code you are expected to write**. **告知你的面试官你准备写多少代码**.
Sample log file format, tab delimited: 日志文件格式样例以tab分割
``` ```
user_id timestamp seller amount user_id timestamp seller amount
``` ```
**MapReduce** implementation: **MapReduce** 实现:
```python ```python
class SpendingByCategory(MRJob): class SpendingByCategory(MRJob):
@ -282,26 +283,25 @@ class SpendingByCategory(MRJob):
... ...
def calc_current_year_month(self): def calc_current_year_month(self):
"""Return the current year and month.""" """返回当前年月"""
... ...
def extract_year_month(self, timestamp): def extract_year_month(self, timestamp):
"""Return the year and month portions of the timestamp.""" """返回时间戳的年,月部分"""
... ...
def handle_budget_notifications(self, key, total): def handle_budget_notifications(self, key, total):
"""Call notification API if nearing or exceeded budget.""" """如果接近或超出预算调用通知API"""
... ...
def mapper(self, _, line): def mapper(self, _, line):
"""Parse each log line, extract and transform relevant lines. """解析每个日志行,提取和转换相关行。
Argument line will be of the form: 参数行应为如下形式:
user_id timestamp seller amount user_id timestamp seller amount
Using the categorizer to convert seller to category, 使用分类器来将卖家转换成类别生成如下形式的key-value对
emit key value pairs of the form:
(user_id, 2016-01, shopping), 25 (user_id, 2016-01, shopping), 25
(user_id, 2016-01, shopping), 100 (user_id, 2016-01, shopping), 100
@ -314,7 +314,7 @@ class SpendingByCategory(MRJob):
yield (user_id, period, category), amount yield (user_id, period, category), amount
def reducer(self, key, value): def reducer(self, key, value):
"""Sum values for each key. """将每个key对应的值求和。
(user_id, 2016-01, shopping), 125 (user_id, 2016-01, shopping), 125
(user_id, 2016-01, gas), 50 (user_id, 2016-01, gas), 50
@ -323,119 +323,118 @@ class SpendingByCategory(MRJob):
yield key, sum(values) yield key, sum(values)
``` ```
## Step 4: Scale the design ## 第四步:设计扩展
> Identify and address bottlenecks, given the constraints. > 根据限制条件,找到并解决瓶颈。
![Imgur](http://i.imgur.com/V5q57vU.png) ![Imgur](http://i.imgur.com/V5q57vU.png)
**Important: Do not simply jump right into the final design from the initial design!** **重要提示:不要从最初设计直接跳到最终设计中!**
State you would 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat. See [Design a system that scales to millions of users on AWS](../scaling_aws/README.md) as a sample on how to iteratively scale the initial design. 现在你要 1) **基准测试、负载测试**。2) **分析、描述**性能瓶颈。3) 在解决瓶颈问题的同时评估替代方案、权衡利弊。4) 重复以上步骤。请阅读[「设计一个系统,并将其扩大到为数以百万计的 AWS 用户服务」](../scaling_aws/README.md) 来了解如何逐步扩大初始设计。
It's important to discuss what bottlenecks you might encounter with the initial design and how you might address each of them. For example, what issues are addressed by adding a **Load Balancer** with multiple **Web Servers**? **CDN**? **Master-Slave Replicas**? What are the alternatives and **Trade-Offs** for each? 讨论初始设计可能遇到的瓶颈及相关解决方案是很重要的。例如加上一个配置多台 **Web 服务器**的**负载均衡器**是否能够解决问题?**CDN**呢?**主从复制**呢?它们各自的替代方案和需要**权衡**的利弊又有什么呢?
We'll introduce some components to complete the design and to address scalability issues. Internal load balancers are not shown to reduce clutter. 我们将会介绍一些组件来完成设计,并解决架构扩张问题。内置的负载均衡器将不做讨论以节省篇幅。
*To avoid repeating discussions*, refer to the following [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) for main talking points, tradeoffs, and alternatives: **为了避免重复讨论**,请参考[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)相关部分来了解其要点、方案的权衡取舍以及可选的替代方案。
* [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system) * [DNS](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#域名系统)
* [CDN](https://github.com/donnemartin/system-design-primer#content-delivery-network) * [负载均衡器](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#负载均衡器)
* [Load balancer](https://github.com/donnemartin/system-design-primer#load-balancer) * [水平拓展](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#水平扩展)
* [Horizontal scaling](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * [反向代理web 服务器)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)
* [Web server (reverse proxy)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * [API 服务(应用层)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用层)
* [API server (application layer)](https://github.com/donnemartin/system-design-primer#application-layer) * [缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存)
* [Cache](https://github.com/donnemartin/system-design-primer#cache) * [关系型数据库管理系统 (RDBMS)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#关系型数据库管理系统rdbms)
* [Relational database management system (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) * [SQL 故障主从切换](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#故障切换)
* [SQL write master-slave failover](https://github.com/donnemartin/system-design-primer#fail-over) * [主从复制](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#主从复制)
* [Master-slave replication](https://github.com/donnemartin/system-design-primer#master-slave-replication) * [异步](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#异步)
* [Asynchronism](https://github.com/donnemartin/system-design-primer#asynchronism) * [一致性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#一致性模式)
* [Consistency patterns](https://github.com/donnemartin/system-design-primer#consistency-patterns) * [可用性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#可用性模式)
* [Availability patterns](https://github.com/donnemartin/system-design-primer#availability-patterns)
We'll add an additional use case: **User** accesses summaries and transactions. 我们将增加一个额外的用例:**用户** 访问摘要和交易数据。
User sessions, aggregate stats by category, and recent transactions could be placed in a **Memory Cache** such as Redis or Memcached. 用户会话,按类别统计的统计信息,以及最近的事务可以放在 **内存缓存**(如 Redis 或 Memcached )中。
* The **Client** sends a read request to the **Web Server** * **客户端** 发送读请求给 **Web 服务器**
* The **Web Server** forwards the request to the **Read API** server * **Web 服务器** 转发请求到 **读 API** 服务器
* Static content can be served from the **Object Store** such as S3, which is cached on the **CDN** * 静态内容可通过 **对象存储** 比如缓存在 **CDN** 上的 S3 来服务
* The **Read API** server does the following: * **读 API** 服务器做如下动作:
* Checks the **Memory Cache** for the content * 检查 **内存缓存** 的内容
* If the url is in the **Memory Cache**, returns the cached contents * 如果URL在 **内存缓存**中,返回缓存的内容
* Else * 否则
* If the url is in the **SQL Database**, fetches the contents * 如果URL在 **SQL 数据库**中,获取该内容
* Updates the **Memory Cache** with the contents * 以其内容更新 **内存缓存**
Refer to [When to update the cache](https://github.com/donnemartin/system-design-primer#when-to-update-the-cache) for tradeoffs and alternatives. The approach above describes [cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside). 参考 [何时更新缓存](https://github.com/donnemartin/system-design-primer#when-to-update-the-cache) 中权衡和替代的内容。以上方法描述了 [cache-aside缓存模式](https://github.com/donnemartin/system-design-primer#cache-aside).
Instead of keeping the `monthly_spending` aggregate table in the **SQL Database**, we could create a separate **Analytics Database** using a data warehousing solution such as Amazon Redshift or Google BigQuery. 我们可以使用诸如 Amazon Redshift 或者 Google BigQuery 等数据仓库解决方案,而不是将`monthly_spending`聚合表保留在 **SQL 数据库** 中。
We might only want to store a month of `transactions` data in the database, while storing the rest in a data warehouse or in an **Object Store**. An **Object Store** such as Amazon S3 can comfortably handle the constraint of 250 GB of new content per month. 我们可能只想在数据库中存储一个月的`交易`数据,而将其余数据存储在数据仓库或者 **对象存储区** 中。**对象存储区** 如Amazon S3) 能够舒服地解决每月 250 GB新内容的限制。
To address the 2,000 *average* read requests per second (higher at peak), traffic for popular content should be handled by the **Memory Cache** instead of the database. The **Memory Cache** is also useful for handling the unevenly distributed traffic and traffic spikes. The **SQL Read Replicas** should be able to handle the cache misses, as long as the replicas are not bogged down with replicating writes. 为了解决每秒 *平均* 2000 次读请求数(峰值时更高),受欢迎的内容的流量应由 **内存缓存** 而不是数据库来处理。 **内存缓存** 也可用于处理不均匀分布的流量和流量尖峰。 只要副本不陷入重复写入的困境,**SQL 读副本** 应该能够处理高速缓存未命中。
200 *average* transaction writes per second (higher at peak) might be tough for a single **SQL Write Master-Slave**. We might need to employ additional SQL scaling patterns: *平均* 200 次交易写入每秒(峰值时更高)对于单个 **SQL 写入主-从服务** 来说可能是棘手的。我们可能需要考虑其它的 SQL 性能拓展技术:
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [联合](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#联合)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分片](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#分片)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [非规范化](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#非规范化)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-调优)
We should also consider moving some data to a **NoSQL Database**. 我们也可以考虑将一些数据移至 **NoSQL 数据库**
## Additional talking points ## 其它要点
> Additional topics to dive into, depending on the problem scope and time remaining. > 是否深入这些额外的主题,取决于你的问题范围和剩下的时间。
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键-值存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#键-值存储)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档类型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#文档类型存储)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [列型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#列型存储)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#图数据库)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)
### Caching ### 缓存
* Where to cache * 在哪缓存
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching) * [客户端缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#客户端缓存)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching) * [CDN 缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#cdn-缓存)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching) * [Web 服务器缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#web-服务器缓存)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching) * [数据库缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库缓存)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching) * [应用缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用缓存)
* What to cache * 什么需要缓存
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level) * [数据库查询级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库查询级别的缓存)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level) * [对象级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#对象级别的缓存)
* When to update the cache * 何时更新缓存
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside) * [缓存模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存模式)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through) * [直写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#直写模式)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back) * [回写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#回写模式)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead) * [刷新](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#刷新)
### Asynchronism and microservices ### 异步与微服务
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) * [消息队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#消息队列)
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues) * [任务队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#任务队列)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure) * [背压](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#背压)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices) * [微服务](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#微服务)
### Communications ### 通信
* Discuss tradeoffs: * 可权衡选择的方案:
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest) * 与客户端的外部通信 - [使用 REST 作为 HTTP API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc) * 服务器内部通信 - [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery) * [服务发现](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#服务发现)
### Security ### 安全性
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security). 请参阅[「安全」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#安全)一章。
### Latency numbers ### 延迟数值
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 请参阅[「每个程序员都应该知道的延迟数」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数)。
### Ongoing ### 持续探讨
* Continue benchmarking and monitoring your system to address bottlenecks as they come up * 持续进行基准测试并监控你的系统,以解决他们提出的瓶颈问题。
* Scaling is an iterative process * 架构拓展是一个迭代的过程。

View File

@ -1,112 +1,113 @@
# Design Pastebin.com (or Bit.ly) # 设计 Pastebin.com或 Bit.ly
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注意:这个文档中的链接会直接指向[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)中的有关部分,以避免重复的内容。你可以参考链接的相关内容,来了解其总的要点、方案的权衡取舍以及可选的替代方案。**
**Design Bit.ly** - is a similar question, except pastebin requires storing the paste contents instead of the original unshortened url. 除了粘贴板需要存储的是完整的内容而不是短链接之外,**设计 Bit.ly**是与本文类似的一个问题。
## Step 1: Outline use cases and constraints ## 第一步:简述用例与约束条件
> Gather requirements and scope the problem. > 搜集需求与问题的范围。
> Ask questions to clarify use cases and constraints. > 提出问题来明确用例与约束条件。
> Discuss assumptions. > 讨论假设。
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 我们将在没有面试官明确说明问题的情况下,自己定义一些用例以及限制条件。
### Use cases ### 用例
#### We'll scope the problem to handle only the following use cases #### 我们将把问题限定在仅处理以下用例的范围中
* **User** enters a block of text and gets a randomly generated link
* Expiration
* Default setting does not expire
* Can optionally set a timed expiration
* **User** enters a paste's url and views the contents
* **User** is anonymous
* **Service** tracks analytics of pages
* Monthly visit stats
* **Service** deletes expired pastes
* **Service** has high availability
#### Out of scope * **用户**输入一些文本,然后得到一个随机生成的链接
* 过期时间
* 默认为永不过期
* 可选设置为一定时间过期
* **用户**输入粘贴板中的 url查看内容
* **用户**是匿名访问的
* **服务**需要能够对页面进行跟踪分析
* 月访问量统计
* **服务**将过期的内容删除
* **服务**有着高可用性
* **User** registers for an account #### 不在用例范围内的有
* **User** verifies email
* **User** logs into a registered account
* **User** edits the document
* **User** can set visibility
* **User** can set the shortlink
### Constraints and assumptions * **用户**注册了账号
* **用户**通过了邮箱验证
* **用户**登录已注册的账号
* **用户**编辑他们的文档
* **用户**能设置他们的内容是否可见
* **用户**是否能自行设置短链接
#### State assumptions ### 限制条件与假设
* Traffic is not evenly distributed #### 提出假设
* Following a short link should be fast
* Pastes are text only
* Page view analytics do not need to be realtime
* 10 million users
* 10 million paste writes per month
* 100 million paste reads per month
* 10:1 read to write ratio
#### Calculate usage * 网络流量不是均匀分布的
* 生成短链接的速度必须要快
* 只允许粘贴文本
* 不需要对页面预览做实时分析
* 1000 万用户
* 每个月 1000 万次粘贴
* 每个月 1 亿次读取请求
* 10:1 的读写比例
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** #### 计算用量
* Size per paste **如果你需要进行粗略的用量计算,请向你的面试官说明。**
* 1 KB content per paste
* `shortlink` - 7 bytes
* `expiration_length_in_minutes` - 4 bytes
* `created_at` - 5 bytes
* `paste_path` - 255 bytes
* total = ~1.27 KB
* 12.7 GB of new paste content per month
* 1.27 KB per paste * 10 million pastes per month
* ~450 GB of new paste content in 3 years
* 360 million shortlinks in 3 years
* Assume most are new pastes instead of updates to existing ones
* 4 paste writes per second on average
* 40 read requests per second on average
Handy conversion guide: * 每次粘贴的用量
* 1 KB 的内容
* `shortlink` - 7 字节
* `expiration_length_in_minutes` - 4 字节
* `created_at` - 5 字节
* `paste_path` - 255 字节
* 总计:大约 1.27 KB
* 每个月的粘贴造作将会产生 12.7 GB 的记录
* 每次粘贴 1.27 KB * 1000 万次粘贴
* 3年内大约产生了 450 GB 的新内容记录
* 3年内生成了 36000 万个短链接
* 假设大多数的粘贴操作都是新的粘贴而不是更新以前的粘贴内容
* 平均每秒 4 次读取粘贴
* 平均每秒 40 次读取粘贴请求
* 2.5 million seconds per month 便利换算指南:
* 1 request per second = 2.5 million requests per month
* 40 requests per second = 100 million requests per month
* 400 requests per second = 1 billion requests per month
## Step 2: Create a high level design * 每个月有 250 万秒
* 每秒一个请求 = 每个月 250 万次请求
* 每秒 40 个请求 = 每个月 1 亿次请求
* 每秒 400 个请求 = 每个月 10 亿次请求
> Outline a high level design with all important components. ## 第二步:概要设计
> 列出所有重要组件以规划概要设计。
![Imgur](http://i.imgur.com/BKsBnmG.png) ![Imgur](http://i.imgur.com/BKsBnmG.png)
## Step 3: Design core components ## 第三步:设计核心组件
> Dive into details for each core component. > 深入每个核心组件的细节。
### Use case: User enters a block of text and gets a randomly generated link ### 用例:用户输入一些文本,然后得到一个随机生成的链接
We could use a [relational database](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) as a large hash table, mapping the generated url to a file server and path containing the paste file. 我们将使用[关系型数据库](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#关系型数据库管理系统rdbms),将其作为一个超大哈希表,将生成的 url 和文件服务器上对应文件的路径一一对应。
Instead of managing a file server, we could use a managed **Object Store** such as Amazon S3 or a [NoSQL document store](https://github.com/donnemartin/system-design-primer#document-store). 我们可以使用诸如 Amazon S3 之类的**对象存储服务**或者[NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#nosql)来代替自建文件服务器。
An alternative to a relational database acting as a large hash table, we could use a [NoSQL key-value store](https://github.com/donnemartin/system-design-primer#key-value-store). We should discuss the [tradeoffs between choosing SQL or NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql). The following discussion uses the relational database approach. 除了使用关系型数据库来作为一个超大哈希表之外,我们也可以使用[NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#nosql)来代替它。[究竟是用 SQL 还是用 NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)。不过在下面的讨论中,我们默认选择了使用关系型数据库的方案。
* The **Client** sends a create paste request to the **Web Server**, running as a [reverse proxy](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **客户端**向向运行[反向代理](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)的 **Web 服务器**发送一个粘贴请求
* The **Web Server** forwards the request to the **Write API** server * **Web 服务器** 将请求转发给**Write API** 服务
* The **Write API** server does the following: * **Write API**服务将会:
* Generates a unique url * 生成一个独一无二的 url
* Checks if the url is unique by looking at the **SQL Database** for a duplicate * 通过在 **SQL 数据库**中查重来确认这个 url 是否的确独一无二
* If the url is not unique, it generates another url * 如果这个 url 已经存在了,重新生成一个 url
* If we supported a custom url, we could use the user-supplied (also check for a duplicate) * 如果支持自定义 url我们也可以使用用户提供的 url也需要进行查重
* Saves to the **SQL Database** `pastes` table * 将 url 存入 **SQL 数据库**的 `pastes` 表中
* Saves the paste data to the **Object Store** * 将粘贴的数据存入**对象存储**系统中
* Returns the url * 返回 url
**Clarify with your interviewer how much code you are expected to write**. **向你的面试官告知你准备写多少代码**。
The `pastes` table could have the following structure: `pastes` 表的数据结构如下:
``` ```
shortlink char(7) NOT NULL shortlink char(7) NOT NULL
@ -116,19 +117,19 @@ paste_path varchar(255) NOT NULL
PRIMARY KEY(shortlink) PRIMARY KEY(shortlink)
``` ```
We'll create an [index](https://github.com/donnemartin/system-design-primer#use-good-indices) on `shortlink ` and `created_at` to speed up lookups (log-time instead of scanning the entire table) and to keep the data in memory. Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> 我们会以`shortlink` 与 `created_at` 创建一个 [索引](https://github.com/donnemartin/system-design-primer#use-good-indices)以加快查询速度(只需要使用读取日志的时间,不再需要每次都扫描整个数据表)并让数据常驻内存。从内存读取 1 MB 连续数据大约要花 250 微秒,而从 SSD 读取同样大小的数据要花费 4 倍的时间,从机械硬盘读取需要花费 80 倍以上的时间。<sup><a href=https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数>1</a></sup>
To generate the unique url, we could: 为了生成独一无二的 url我们需要
* Take the [**MD5**](https://en.wikipedia.org/wiki/MD5) hash of the user's ip_address + timestamp * 对用户的 IP 地址 + 时间戳进行 [**MD5**](https://en.wikipedia.org/wiki/MD5) 哈希编码
* MD5 is a widely used hashing function that produces a 128-bit hash value * MD5 是一种非常常用的哈希化函数,它能生成 128 字节的哈希值
* MD5 is uniformly distributed * MD5 是均匀分布的
* Alternatively, we could also take the MD5 hash of randomly-generated data * 另外,我们可以使用 MD5 哈希算法来生成随机数据
* [**Base 62**](https://www.kerstner.at/2012/07/shortening-strings-using-base-62-encoding/) encode the MD5 hash * 对 MD5 哈希值进行 [**Base 62**](https://www.kerstner.at/2012/07/shortening-strings-using-base-62-encoding/) 编码
* Base 62 encodes to `[a-zA-Z0-9]` which works well for urls, eliminating the need for escaping special characters * Base 62 编码后的值由 `[a-zA-Z0-9]` 组成,它们可以直接作为 url 的字符,不需要再次转义
* There is only one hash result for the original input and Base 62 is deterministic (no randomness involved) * 在这儿仅仅只对原始输入进行过一次哈希处理Base 62 编码步骤是确定性的(不涉及随机性)
* Base 64 is another popular encoding but provides issues for urls because of the additional `+` and `/` characters * Base 64 是另一种很流行的编码形式,但是它生成的字符串作为 url 存在一些问题Base 64m字符串内包含 `+``/` 符号
* The following [Base 62 pseudocode](http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener) runs in O(k) time where k is the number of digits = 7: * 下面的 [Base 62 pseudocode](http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener) 算法时间复杂度为 O(k),本例中取 num =7即 k 值为 7
```python ```python
def base_encode(num, base=62): def base_encode(num, base=62):
@ -140,20 +141,19 @@ def base_encode(num, base=62):
digits = digits.reverse digits = digits.reverse
``` ```
* Take the first 7 characters of the output, which results in 62^7 possible values and should be sufficient to handle our constraint of 360 million shortlinks in 3 years: * 输出前 7 个字符,其结果将有 62^7 种可能的值,作为短链接来说足够了。因为我们限制了 3 年内最多产生 36000 万个短链接:
```python ```python
url = base_encode(md5(ip_address+timestamp))[:URL_LENGTH] url = base_encode(md5(ip_address+timestamp))[:URL_LENGTH]
``` ```
我们可以调用一个公共的 [REST API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
We'll use a public [**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest):
``` ```
$ curl -X POST --data '{ "expiration_length_in_minutes": "60", \ $ curl -X POST --data '{ "expiration_length_in_minutes": "60", \
"paste_contents": "Hello World!" }' https://pastebin.com/api/v1/paste "paste_contents": "Hello World!" }' https://pastebin.com/api/v1/paste
``` ```
Response: 返回:
``` ```
{ {
@ -161,16 +161,16 @@ Response:
} }
``` ```
For internal communications, we could use [Remote Procedure Calls](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc). 而对于服务器内部的通信,我们可以使用 [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)。
### Use case: User enters a paste's url and views the contents ### 用例:用户输入了一个之前粘贴得到的 url希望浏览其存储的内容
* The **Client** sends a get paste request to the **Web Server** * **客户端**向**Web 服务器**发起读取内容请求
* The **Web Server** forwards the request to the **Read API** server * **Web 服务器**将请求转发给**Read API**服务
* The **Read API** server does the following: * **Read API**服务将会:
* Checks the **SQL Database** for the generated url * 在**SQL 数据库**中检查生成的 url
* If the url is in the **SQL Database**, fetch the paste contents from the **Object Store** * 如果查询的 url 存在于 **SQL 数据库**中,从**对象存储**服务将对应的粘贴内容取出
* Else, return an error message for the user * 否则,给用户返回报错
REST API: REST API:
@ -178,7 +178,7 @@ REST API:
$ curl https://pastebin.com/api/v1/paste?shortlink=foobar $ curl https://pastebin.com/api/v1/paste?shortlink=foobar
``` ```
Response: 返回:
``` ```
{ {
@ -188,27 +188,27 @@ Response:
} }
``` ```
### Use case: Service tracks analytics of pages ### 用例:对页面进行跟踪分析
Since realtime analytics are not a requirement, we could simply **MapReduce** the **Web Server** logs to generate hit counts. 由于不需要进行实时分析,因此我们可以简单地对 **Web 服务**产生的日志用 **MapReduce** 来统计 hit 计数(命中数)。
**Clarify with your interviewer how much code you are expected to write**. **向你的面试官告知你准备写多少代码**。
```python ```python
class HitCounts(MRJob): class HitCounts(MRJob):
def extract_url(self, line): def extract_url(self, line):
"""Extract the generated url from the log line.""" """从 log 中取出生成的 url。"""
... ...
def extract_year_month(self, line): def extract_year_month(self, line):
"""Return the year and month portions of the timestamp.""" """返回时间戳中表示年份与月份的一部分"""
... ...
def mapper(self, _, line): def mapper(self, _, line):
"""Parse each log line, extract and transform relevant lines. """解析日志的每一行,提取并转换相关行,
Emit key value pairs of the form: 将键值对设定为如下形式:
(2016-01, url0), 1 (2016-01, url0), 1
(2016-01, url0), 1 (2016-01, url0), 1
@ -218,8 +218,8 @@ class HitCounts(MRJob):
period = self.extract_year_month(line) period = self.extract_year_month(line)
yield (period, url), 1 yield (period, url), 1
def reducer(self, key, values): def reducer(self, key, value):
"""Sum values for each key. """将所有的 key 加起来
(2016-01, url0), 2 (2016-01, url0), 2
(2016-01, url1), 1 (2016-01, url1), 1
@ -227,106 +227,105 @@ class HitCounts(MRJob):
yield key, sum(values) yield key, sum(values)
``` ```
### Use case: Service deletes expired pastes ### 用例:服务删除过期的粘贴内容
To delete expired pastes, we could just scan the **SQL Database** for all entries whose expiration timestamp are older than the current timestamp. All expired entries would then be deleted (or marked as expired) from the table. 我们可以通过扫描 **SQL 数据库**,查找出那些过期时间戳小于当前时间戳的条目,然后在表中删除(或者将其标记为过期)这些过期的粘贴内容。
## Step 4: Scale the design ## 第四步:架构扩展
> Identify and address bottlenecks, given the constraints. > 根据限制条件,找到并解决瓶颈。
![Imgur](http://i.imgur.com/4edXG0T.png) ![Imgur](http://i.imgur.com/4edXG0T.png)
**Important: Do not simply jump right into the final design from the initial design!** **重要提示:不要从最初设计直接跳到最终设计中!**
State you would do this iteratively: 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat. See [Design a system that scales to millions of users on AWS](../scaling_aws/README.md) as a sample on how to iteratively scale the initial design. 现在你要 1) **基准测试、负载测试**。2) **分析、描述**性能瓶颈。3) 在解决瓶颈问题的同时评估替代方案、权衡利弊。4) 重复以上步骤。请阅读[「设计一个系统,并将其扩大到为数以百万计的 AWS 用户服务」](../scaling_aws/README.md) 来了解如何逐步扩大初始设计。
It's important to discuss what bottlenecks you might encounter with the initial design and how you might address each of them. For example, what issues are addressed by adding a **Load Balancer** with multiple **Web Servers**? **CDN**? **Master-Slave Replicas**? What are the alternatives and **Trade-Offs** for each? 讨论初始设计可能遇到的瓶颈及相关解决方案是很重要的。例如加上一个配置多台 **Web 服务器**的**负载均衡器**是否能够解决问题?**CDN**呢?**主从复制**呢?它们各自的替代方案和需要**权衡**的利弊又有什么呢?
We'll introduce some components to complete the design and to address scalability issues. Internal load balancers are not shown to reduce clutter. 我们将会介绍一些组件来完成设计,并解决架构扩张问题。内置的负载均衡器将不做讨论以节省篇幅。
*To avoid repeating discussions*, refer to the following [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) for main talking points, tradeoffs, and alternatives: **为了避免重复讨论**,请参考[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)相关部分来了解其要点、方案的权衡取舍以及可选的替代方案。
* [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system) * [DNS](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#域名系统)
* [CDN](https://github.com/donnemartin/system-design-primer#content-delivery-network) * [负载均衡器](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#负载均衡器)
* [Load balancer](https://github.com/donnemartin/system-design-primer#load-balancer) * [水平拓展](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#水平扩展)
* [Horizontal scaling](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * [反向代理web 服务器)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)
* [Web server (reverse proxy)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * [API 服务(应用层)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用层)
* [API server (application layer)](https://github.com/donnemartin/system-design-primer#application-layer) * [缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存)
* [Cache](https://github.com/donnemartin/system-design-primer#cache) * [关系型数据库管理系统 (RDBMS)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#关系型数据库管理系统rdbms)
* [Relational database management system (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) * [SQL 故障主从切换](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#故障切换)
* [SQL write master-slave failover](https://github.com/donnemartin/system-design-primer#fail-over) * [主从复制](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#主从复制)
* [Master-slave replication](https://github.com/donnemartin/system-design-primer#master-slave-replication) * [一致性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#一致性模式)
* [Consistency patterns](https://github.com/donnemartin/system-design-primer#consistency-patterns) * [可用性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#可用性模式)
* [Availability patterns](https://github.com/donnemartin/system-design-primer#availability-patterns)
The **Analytics Database** could use a data warehousing solution such as Amazon Redshift or Google BigQuery. **分析数据库** 可以用现成的数据仓储系统,例如使用 Amazon Redshift 或者 Google BigQuery 的解决方案。
An **Object Store** such as Amazon S3 can comfortably handle the constraint of 12.7 GB of new content per month. Amazon S3 的**对象存储**系统可以很方便地设置每个月限制只允许新增 12.7 GB 的存储内容。
To address the 40 *average* read requests per second (higher at peak), traffic for popular content should be handled by the **Memory Cache** instead of the database. The **Memory Cache** is also useful for handling the unevenly distributed traffic and traffic spikes. The **SQL Read Replicas** should be able to handle the cache misses, as long as the replicas are not bogged down with replicating writes. 平均每秒 40 次的读取请求(峰值将会更高), 可以通过扩展 **内存缓存** 来处理热点内容的读取流量,这对于处理不均匀分布的流量和流量峰值也很有用。只要 SQL 副本不陷入复制-写入困境中,**SQL Read 副本** 基本能够处理缓存命中问题。
4 *average* paste writes per second (with higher at peak) should be do-able for a single **SQL Write Master-Slave**. Otherwise, we'll need to employ additional SQL scaling patterns: 平均每秒 4 次的粘贴写入操作(峰值将会更高)对于单个**SQL 写主-从** 模式来说是可行的。不过,我们也需要考虑其它的 SQL 性能拓展技术:
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [联合](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#联合)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分片](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#分片)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [非规范化](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#非规范化)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-调优)
We should also consider moving some data to a **NoSQL Database**. 我们也可以考虑将一些数据移至 **NoSQL 数据库**
## Additional talking points ## 其它要点
> Additional topics to dive into, depending on the problem scope and time remaining. > 是否深入这些额外的主题,取决于你的问题范围和剩下的时间。
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键-值存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#键-值存储)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档类型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#文档类型存储)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [列型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#列型存储)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#图数据库)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)
### Caching ### 缓存
* Where to cache * 在哪缓存
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching) * [客户端缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#客户端缓存)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching) * [CDN 缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#cdn-缓存)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching) * [Web 服务器缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#web-服务器缓存)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching) * [数据库缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库缓存)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching) * [应用缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用缓存)
* What to cache * 什么需要缓存
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level) * [数据库查询级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库查询级别的缓存)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level) * [对象级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#对象级别的缓存)
* When to update the cache * 何时更新缓存
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside) * [缓存模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存模式)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through) * [直写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#直写模式)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back) * [回写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#回写模式)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead) * [刷新](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#刷新)
### Asynchronism and microservices ### 异步与微服务
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) * [消息队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#消息队列)
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues) * [任务队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#任务队列)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure) * [背压](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#背压)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices) * [微服务](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#微服务)
### Communications ### 通信
* Discuss tradeoffs: * 可权衡选择的方案:
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest) * 与客户端的外部通信 - [使用 REST 作为 HTTP API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc) * 服务器内部通信 - [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery) * [服务发现](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#服务发现)
### Security ### 安全性
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security). 请参阅[「安全」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#安全)一章。
### Latency numbers ### 延迟数值
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 请参阅[「每个程序员都应该知道的延迟数」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数)。
### Ongoing ### 持续探讨
* Continue benchmarking and monitoring your system to address bottlenecks as they come up * 持续进行基准测试并监控你的系统,以解决他们提出的瓶颈问题。
* Scaling is an iterative process * 架构拓展是一个迭代的过程。

View File

@ -1,101 +1,101 @@
# Design a key-value cache to save the results of the most recent web server queries # 设计一个键-值缓存来存储最近 web 服务查询的结果
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注意:这个文档中的链接会直接指向[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)中的有关部分,以避免重复的内容。你可以参考链接的相关内容,来了解其总的要点、方案的权衡取舍以及可选的替代方案。**
## Step 1: Outline use cases and constraints ## 第一步:简述用例与约束条件
> Gather requirements and scope the problem. > 搜集需求与问题的范围。
> Ask questions to clarify use cases and constraints. > 提出问题来明确用例与约束条件。
> Discuss assumptions. > 讨论假设。
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 我们将在没有面试官明确说明问题的情况下,自己定义一些用例以及限制条件。
### Use cases ### 用例
#### We'll scope the problem to handle only the following use cases #### 我们将把问题限定在仅处理以下用例的范围中
* **User** sends a search request resulting in a cache hit * **用户**发送一个搜索请求,命中缓存
* **User** sends a search request resulting in a cache miss * **用户**发送一个搜索请求,未命中缓存
* **Service** has high availability * **服务**有着高可用性
### Constraints and assumptions ### 限制条件与假设
#### State assumptions #### 提出假设
* Traffic is not evenly distributed * 网络流量不是均匀分布的
* Popular queries should almost always be in the cache * 经常被查询的内容应该一直存于缓存中
* Need to determine how to expire/refresh * 需要确定如何规定缓存过期、缓存刷新规则
* Serving from cache requires fast lookups * 缓存提供的服务查询速度要快
* Low latency between machines * 机器间延迟较低
* Limited memory in cache * 缓存有内存限制
* Need to determine what to keep/remove * 需要决定缓存什么、移除什么
* Need to cache millions of queries * 需要缓存百万级的查询
* 10 million users * 1000 万用户
* 10 billion queries per month * 每个月 100 亿次查询
#### Calculate usage #### 计算用量
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** **如果你需要进行粗略的用量计算,请向你的面试官说明。**
* Cache stores ordered list of key: query, value: results * 缓存存储的是键值对有序表,键为 `query`(查询),值为 `results`(结果)。
* `query` - 50 bytes * `query` - 50 字节
* `title` - 20 bytes * `title` - 20 字节
* `snippet` - 200 bytes * `snippet` - 200 字节
* Total: 270 bytes * 总计270 字节
* 2.7 TB of cache data per month if all 10 billion queries are unique and all are stored * 假如 100 亿次查询都是不同的,且全部需要存储,那么每个月需要 2.7 TB 的缓存空间
* 270 bytes per search * 10 billion searches per month * 单次查询 270 字节 * 每月查询 100 亿次
* Assumptions state limited memory, need to determine how to expire contents * 假设内存大小有限制,需要决定如何制定缓存过期规则
* 4,000 requests per second * 每秒 4,000 次请求
Handy conversion guide: 便利换算指南:
* 2.5 million seconds per month * 每个月有 250 万秒
* 1 request per second = 2.5 million requests per month * 每秒一个请求 = 每个月 250 万次请求
* 40 requests per second = 100 million requests per month * 每秒 40 个请求 = 每个月 1 亿次请求
* 400 requests per second = 1 billion requests per month * 每秒 400 个请求 = 每个月 10 亿次请求
## Step 2: Create a high level design ## 第二步:概要设计
> Outline a high level design with all important components. > 列出所有重要组件以规划概要设计。
![Imgur](http://i.imgur.com/KqZ3dSx.png) ![Imgur](http://i.imgur.com/KqZ3dSx.png)
## Step 3: Design core components ## 第三步:设计核心组件
> Dive into details for each core component. > 深入每个核心组件的细节。
### Use case: User sends a request resulting in a cache hit ### 用例:用户发送了一次请求,命中了缓存
Popular queries can be served from a **Memory Cache** such as Redis or Memcached to reduce read latency and to avoid overloading the **Reverse Index Service** and **Document Service**. Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> 常用的查询可以由例如 Redis 或者 Memcached 之类的**内存缓存**提供支持,以减少数据读取延迟,并且避免**反向索引服务**以及**文档服务**的过载。从内存读取 1 MB 连续数据大约要花 250 微秒,而从 SSD 读取同样大小的数据要花费 4 倍的时间,从机械硬盘读取需要花费 80 倍以上的时间。<sup><a href=https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数>1</a></sup>
Since the cache has limited capacity, we'll use a least recently used (LRU) approach to expire older entries. 由于缓存容量有限,我们将使用 LRU近期最少使用算法来控制缓存的过期。
* The **Client** sends a request to the **Web Server**, running as a [reverse proxy](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **客户端**向运行[反向代理](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)的 **Web 服务器**发送一个请求
* The **Web Server** forwards the request to the **Query API** server * 这个 **Web 服务器**将请求转发给**查询 API** 服务
* The **Query API** server does the following: * **查询 API** 服务将会做这些事情:
* Parses the query * 分析查询
* Removes markup * 移除多余的内容
* Breaks up the text into terms * 将文本分割成词组
* Fixes typos * 修正拼写错误
* Normalizes capitalization * 规范化字母的大小写
* Converts the query to use boolean operations * 将查询转换为布尔运算
* Checks the **Memory Cache** for the content matching the query * 检测**内存缓存**是否有匹配查询的内容
* If there's a hit in the **Memory Cache**, the **Memory Cache** does the following: * 如果命中**内存缓存****内存缓存**将会做以下事情:
* Updates the cached entry's position to the front of the LRU list * 将缓存入口的位置指向 LRU 链表的头部
* Returns the cached contents * 返回缓存内容
* Else, the **Query API** does the following: * 否则,**查询 API** 将会做以下事情:
* Uses the **Reverse Index Service** to find documents matching the query * 使用**反向索引服务**来查找匹配查询的文档
* The **Reverse Index Service** ranks the matching results and returns the top ones * **反向索引服务**对匹配到的结果进行排名,然后返回最符合的结果
* Uses the **Document Service** to return titles and snippets * 使用**文档服务**返回文章标题与片段
* Updates the **Memory Cache** with the contents, placing the entry at the front of the LRU list * 更新**内存缓存**,存入内容,将**内存缓存**入口位置指向 LRU 链表的头部
#### Cache implementation #### 缓存的实现
The cache can use a doubly-linked list: new items will be added to the head while items to expire will be removed from the tail. We'll use a hash table for fast lookups to each linked list node. 缓存可以使用双向链表实现:新元素将会在头结点加入,过期的元素将会在尾节点被删除。我们使用哈希表以便能够快速查找每个链表节点。
**Clarify with your interviewer how much code you are expected to write**. **向你的面试官告知你准备写多少代码**。
**Query API Server** implementation: 实现**查询 API 服务**
```python ```python
class QueryApi(object): class QueryApi(object):
@ -105,8 +105,8 @@ class QueryApi(object):
self.reverse_index_service = reverse_index_service self.reverse_index_service = reverse_index_service
def parse_query(self, query): def parse_query(self, query):
"""Remove markup, break text into terms, deal with typos, """移除多余内容,将文本分割成词组,修复拼写错误,
normalize capitalization, convert to use boolean operations. 规范化字母大小写,转换布尔运算。
""" """
... ...
@ -119,7 +119,7 @@ class QueryApi(object):
return results return results
``` ```
**Node** implementation: 实现**节点**
```python ```python
class Node(object): class Node(object):
@ -129,7 +129,7 @@ class Node(object):
self.results = results self.results = results
``` ```
**LinkedList** implementation: 实现**链表**
```python ```python
class LinkedList(object): class LinkedList(object):
@ -148,7 +148,7 @@ class LinkedList(object):
... ...
``` ```
**Cache** implementation: 实现**缓存**
```python ```python
class Cache(object): class Cache(object):
@ -160,9 +160,9 @@ class Cache(object):
self.linked_list = LinkedList() self.linked_list = LinkedList()
def get(self, query) def get(self, query)
"""Get the stored query result from the cache. """从缓存取得存储的内容
Accessing a node updates its position to the front of the LRU list. 将入口节点位置更新为 LRU 链表的头部。
""" """
node = self.lookup[query] node = self.lookup[query]
if node is None: if node is None:
@ -171,136 +171,136 @@ class Cache(object):
return node.results return node.results
def set(self, results, query): def set(self, results, query):
"""Set the result for the given query key in the cache. """将所给查询键的结果存在缓存中。
When updating an entry, updates its position to the front of the LRU list. 当更新缓存记录的时候,将它的位置指向 LRU 链表的头部。
If the entry is new and the cache is at capacity, removes the oldest entry 如果这个记录是新的记录,并且缓存空间已满,应该在加入新记录前
before the new entry is added. 删除最老的记录。
""" """
node = self.lookup[query] node = self.lookup[query]
if node is not None: if node is not None:
# Key exists in cache, update the value # 键存在于缓存中,更新它对应的值
node.results = results node.results = results
self.linked_list.move_to_front(node) self.linked_list.move_to_front(node)
else: else:
# Key does not exist in cache # 键不存在于缓存中
if self.size == self.MAX_SIZE: if self.size == self.MAX_SIZE:
# Remove the oldest entry from the linked list and lookup # 在链表中查找并删除最老的记录
self.lookup.pop(self.linked_list.tail.query, None) self.lookup.pop(self.linked_list.tail.query, None)
self.linked_list.remove_from_tail() self.linked_list.remove_from_tail()
else: else:
self.size += 1 self.size += 1
# Add the new key and value # 添加新的键值对
new_node = Node(query, results) new_node = Node(query, results)
self.linked_list.append_to_front(new_node) self.linked_list.append_to_front(new_node)
self.lookup[query] = new_node self.lookup[query] = new_node
``` ```
#### When to update the cache #### 何时更新缓存
The cache should be updated when: 缓存将会在以下几种情况更新:
* The page contents change * 页面内容发生变化
* The page is removed or a new page is added * 页面被移除或者加入了新页面
* The page rank changes * 页面的权值发生变动
The most straightforward way to handle these cases is to simply set a max time that a cached entry can stay in the cache before it is updated, usually referred to as time to live (TTL). 解决这些问题的最直接的方法就是为缓存记录设置一个它在被更新前能留在缓存中的最长时间这个时间简称为存活时间TTL
Refer to [When to update the cache](https://github.com/donnemartin/system-design-primer#when-to-update-the-cache) for tradeoffs and alternatives. The approach above describes [cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside). 参考 [「何时更新缓存」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#何时更新缓存)来了解其权衡取舍及替代方案。以上方法在[缓存模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存模式)一章中详细地进行了描述。
## Step 4: Scale the design ## 第四步:架构扩展
> Identify and address bottlenecks, given the constraints. > 根据限制条件,找到并解决瓶颈。
![Imgur](http://i.imgur.com/4j99mhe.png) ![Imgur](http://i.imgur.com/4j99mhe.png)
**Important: Do not simply jump right into the final design from the initial design!** **重要提示:不要从最初设计直接跳到最终设计中!**
State you would 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat. See [Design a system that scales to millions of users on AWS](../scaling_aws/README.md) as a sample on how to iteratively scale the initial design. 现在你要 1) **基准测试、负载测试**。2) **分析、描述**性能瓶颈。3) 在解决瓶颈问题的同时评估替代方案、权衡利弊。4) 重复以上步骤。请阅读[「设计一个系统,并将其扩大到为数以百万计的 AWS 用户服务」](../scaling_aws/README.md) 来了解如何逐步扩大初始设计。
It's important to discuss what bottlenecks you might encounter with the initial design and how you might address each of them. For example, what issues are addressed by adding a **Load Balancer** with multiple **Web Servers**? **CDN**? **Master-Slave Replicas**? What are the alternatives and **Trade-Offs** for each? 讨论初始设计可能遇到的瓶颈及相关解决方案是很重要的。例如加上一个配置多台 **Web 服务器**的**负载均衡器**是否能够解决问题?**CDN**呢?**主从复制**呢?它们各自的替代方案和需要**权衡**的利弊又有什么呢?
We'll introduce some components to complete the design and to address scalability issues. Internal load balancers are not shown to reduce clutter. 我们将会介绍一些组件来完成设计,并解决架构扩张问题。内置的负载均衡器将不做讨论以节省篇幅。
*To avoid repeating discussions*, refer to the following [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) for main talking points, tradeoffs, and alternatives: **为了避免重复讨论**,请参考[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)相关部分来了解其要点、方案的权衡取舍以及可选的替代方案。
* [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system) * [DNS](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#域名系统)
* [Load balancer](https://github.com/donnemartin/system-design-primer#load-balancer) * [负载均衡器](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#负载均衡器)
* [Horizontal scaling](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * [水平拓展](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#水平扩展)
* [Web server (reverse proxy)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * [反向代理web 服务器)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)
* [API server (application layer)](https://github.com/donnemartin/system-design-primer#application-layer) * [API 服务(应用层)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用层)
* [Cache](https://github.com/donnemartin/system-design-primer#cache) * [缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存)
* [Consistency patterns](https://github.com/donnemartin/system-design-primer#consistency-patterns) * [一致性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#一致性模式)
* [Availability patterns](https://github.com/donnemartin/system-design-primer#availability-patterns) * [可用性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#可用性模式)
### Expanding the Memory Cache to many machines ### 将内存缓存扩大到多台机器
To handle the heavy request load and the large amount of memory needed, we'll scale horizontally. We have three main options on how to store the data on our **Memory Cache** cluster: 为了解决庞大的请求负载以及巨大的内存需求,我们将要对架构进行水平拓展。如何在我们的**内存缓存**集群中存储数据呢?我们有以下三个主要可选方案:
* **Each machine in the cache cluster has its own cache** - Simple, although it will likely result in a low cache hit rate. * **缓存集群中的每一台机器都有自己的缓存** - 简单,但是它会降低缓存命中率。
* **Each machine in the cache cluster has a copy of the cache** - Simple, although it is an inefficient use of memory. * **缓存集群中的每一台机器都有缓存的拷贝** - 简单,但是它的内存使用效率太低了。
* **The cache is [sharded](https://github.com/donnemartin/system-design-primer#sharding) across all machines in the cache cluster** - More complex, although it is likely the best option. We could use hashing to determine which machine could have the cached results of a query using `machine = hash(query)`. We'll likely want to use [consistent hashing](https://github.com/donnemartin/system-design-primer#under-development). * **对缓存进行[分片](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#分片),分别部署在缓存集群中的所有机器中** - 更加复杂,但是它是最佳的选择。我们可以使用哈希,用查询语句 `machine = hash(query)` 来确定哪台机器有需要缓存。当然我们也可以使用[一致性哈希](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#正在完善中)。
## Additional talking points ## 其它要点
> Additional topics to dive into, depending on the problem scope and time remaining. > 是否深入这些额外的主题,取决于你的问题范围和剩下的时间。
### SQL scaling patterns ### SQL 缩放模式
* [Read replicas](https://github.com/donnemartin/system-design-primer#master-slave-replication) * [读取复制](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#主从复制)
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [联合](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#联合)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分片](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#分片)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [非规范化](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#非规范化)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-调优)
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键-值存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#键-值存储)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档类型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#文档类型存储)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [列型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#列型存储)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#图数据库)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)
### Caching ### 缓存
* Where to cache * 在哪缓存
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching) * [客户端缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#客户端缓存)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching) * [CDN 缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#cdn-缓存)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching) * [Web 服务器缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#web-服务器缓存)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching) * [数据库缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库缓存)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching) * [应用缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用缓存)
* What to cache * 什么需要缓存
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level) * [数据库查询级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库查询级别的缓存)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level) * [对象级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#对象级别的缓存)
* When to update the cache * 何时更新缓存
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside) * [缓存模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存模式)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through) * [直写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#直写模式)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back) * [回写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#回写模式)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead) * [刷新](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#刷新)
### Asynchronism and microservices ### 异步与微服务
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) * [消息队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#消息队列)
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues) * [任务队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#任务队列)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure) * [背压](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#背压)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices) * [微服务](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#微服务)
### Communications ### 通信
* Discuss tradeoffs: * 可权衡选择的方案:
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest) * 与客户端的外部通信 - [使用 REST 作为 HTTP API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc) * 服务器内部通信 - [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery) * [服务发现](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#服务发现)
### Security ### 安全性
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security). 请参阅[「安全」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#安全)一章。
### Latency numbers ### 延迟数值
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 请参阅[「每个程序员都应该知道的延迟数」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数)。
### Ongoing ### 持续探讨
* Continue benchmarking and monitoring your system to address bottlenecks as they come up * 持续进行基准测试并监控你的系统,以解决他们提出的瓶颈问题。
* Scaling is an iterative process * 架构拓展是一个迭代的过程。

View File

@ -1,88 +1,88 @@
# Design Amazon's sales rank by category feature # 为 Amazon 设计分类售卖排行
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注意:这个文档中的链接会直接指向[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)中的有关部分,以避免重复的内容。你可以参考链接的相关内容,来了解其总的要点、方案的权衡取舍以及可选的替代方案。**
## Step 1: Outline use cases and constraints ## 第一步:简述用例与约束条件
> Gather requirements and scope the problem. > 搜集需求与问题的范围。
> Ask questions to clarify use cases and constraints. > 提出问题来明确用例与约束条件。
> Discuss assumptions. > 讨论假设。
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 我们将在没有面试官明确说明问题的情况下,自己定义一些用例以及限制条件。
### Use cases ### 用例
#### We'll scope the problem to handle only the following use case #### 我们将把问题限定在仅处理以下用例的范围中
* **Service** calculates the past week's most popular products by category * **服务**根据分类计算过去一周中最受欢迎的商品
* **User** views the past week's most popular products by category * **用户**通过分类浏览过去一周中最受欢迎的商品
* **Service** has high availability * **服务**有着高可用性
#### Out of scope #### 不在用例范围内的有
* The general e-commerce site * 一般的电商网站
* Design components only for calculating sales rank * 只为售卖排行榜设计组件
### Constraints and assumptions ### 限制条件与假设
#### State assumptions #### 提出假设
* Traffic is not evenly distributed * 网络流量不是均匀分布的
* Items can be in multiple categories * 一个商品可能存在于多个分类中
* Items cannot change categories * 商品不能够更改分类
* There are no subcategories ie `foo/bar/baz` * 不会存在如 `foo/bar/baz` 之类的子分类
* Results must be updated hourly * 每小时更新一次结果
* More popular products might need to be updated more frequently * 受欢迎的商品越多,就需要更频繁地更新
* 10 million products * 1000 万个商品
* 1000 categories * 1000 个分类
* 1 billion transactions per month * 每个月 10 亿次交易
* 100 billion read requests per month * 每个月 1000 亿次读取请求
* 100:1 read to write ratio * 100:1 的读写比例
#### Calculate usage #### 计算用量
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** **如果你需要进行粗略的用量计算,请向你的面试官说明。**
* Size per transaction: * 每笔交易的用量:
* `created_at` - 5 bytes * `created_at` - 5 字节
* `product_id` - 8 bytes * `product_id` - 8 字节
* `category_id` - 4 bytes * `category_id` - 4 字节
* `seller_id` - 8 bytes * `seller_id` - 8 字节
* `buyer_id` - 8 bytes * `buyer_id` - 8 字节
* `quantity` - 4 bytes * `quantity` - 4 字节
* `total_price` - 5 bytes * `total_price` - 5 字节
* Total: ~40 bytes * 总计:大约 40 字节
* 40 GB of new transaction content per month * 每个月的交易内容会产生 40 GB 的记录
* 40 bytes per transaction * 1 billion transactions per month * 每次交易 40 字节 * 每个月 10 亿次交易
* 1.44 TB of new transaction content in 3 years * 3年内产生了 1.44 TB 的新交易内容记录
* Assume most are new transactions instead of updates to existing ones * 假定大多数的交易都是新交易而不是更改以前进行完的交易
* 400 transactions per second on average * 平均每秒 400 次交易次数
* 40,000 read requests per second on average * 平均每秒 40,000 次读取请求
Handy conversion guide: 便利换算指南:
* 2.5 million seconds per month * 每个月有 250 万秒
* 1 request per second = 2.5 million requests per month * 每秒一个请求 = 每个月 250 万次请求
* 40 requests per second = 100 million requests per month * 每秒 40 个请求 = 每个月 1 亿次请求
* 400 requests per second = 1 billion requests per month * 每秒 400 个请求 = 每个月 10 亿次请求
## Step 2: Create a high level design ## 第二步:概要设计
> Outline a high level design with all important components. > 列出所有重要组件以规划概要设计。
![Imgur](http://i.imgur.com/vwMa1Qu.png) ![Imgur](http://i.imgur.com/vwMa1Qu.png)
## Step 3: Design core components ## 第三步:设计核心组件
> Dive into details for each core component. > 深入每个核心组件的细节。
### Use case: Service calculates the past week's most popular products by category ### 用例:服务需要根据分类计算上周最受欢迎的商品
We could store the raw **Sales API** server log files on a managed **Object Store** such as Amazon S3, rather than managing our own distributed file system. 我们可以在现成的**对象存储**系统(例如 Amazon S3 服务)中存储 **售卖 API** 服务产生的日志文本, 因此不需要我们自己搭建分布式文件系统了。
**Clarify with your interviewer how much code you are expected to write**. **向你的面试官告知你准备写多少代码**。
We'll assume this is a sample log entry, tab delimited: 假设下面是一个用 tab 分割的简易的日志记录:
``` ```
timestamp product_id category_id qty total_price seller_id buyer_id timestamp product_id category_id qty total_price seller_id buyer_id
@ -95,24 +95,25 @@ t5 product4 category1 1 5.00 5 6
... ...
``` ```
The **Sales Rank Service** could use **MapReduce**, using the **Sales API** server log files as input and writing the results to an aggregate table `sales_rank` in a **SQL Database**. We should discuss the [use cases and tradeoffs between choosing SQL or NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql). **售卖排行服务** 需要用到 **MapReduce**,并使用 **售卖 API** 服务进行日志记录,同时将结果写入 **SQL 数据库**中的总表 `sales_rank` 中。我们也可以讨论一下[究竟是用 SQL 还是用 NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)。
We'll use a multi-step **MapReduce**: 我们需要通过以下步骤使用 **MapReduce**
* **Step 1** - Transform the data to `(category, product_id), sum(quantity)` * **第 1 步** - 将数据转换为 `(category, product_id), sum(quantity)` 的形式
* **Step 2** - Perform a distributed sort * **第 2 步** - 执行分布式排序
```python ```python
class SalesRanker(MRJob): class SalesRanker(MRJob):
def within_past_week(self, timestamp): def within_past_week(self, timestamp):
"""Return True if timestamp is within past week, False otherwise.""" """如果时间戳属于过去的一周则返回 True
否则返回 False。"""
... ...
def mapper(self, _ line): def mapper(self, _ line):
"""Parse each log line, extract and transform relevant lines. """解析日志的每一行,提取并转换相关行,
Emit key value pairs of the form: 将键值对设定为如下形式:
(category1, product1), 2 (category1, product1), 2
(category2, product1), 2 (category2, product1), 2
@ -127,7 +128,7 @@ class SalesRanker(MRJob):
yield (category_id, product_id), quantity yield (category_id, product_id), quantity
def reducer(self, key, value): def reducer(self, key, value):
"""Sum values for each key. """将每个 key 的值加起来。
(category1, product1), 2 (category1, product1), 2
(category2, product1), 3 (category2, product1), 3
@ -138,9 +139,9 @@ class SalesRanker(MRJob):
yield key, sum(values) yield key, sum(values)
def mapper_sort(self, key, value): def mapper_sort(self, key, value):
"""Construct key to ensure proper sorting. """构造 key 以确保正确的排序。
Transform key and value to the form: 将键值对转换成如下形式:
(category1, 2), product1 (category1, 2), product1
(category2, 3), product1 (category2, 3), product1
@ -148,8 +149,8 @@ class SalesRanker(MRJob):
(category2, 7), product3 (category2, 7), product3
(category1, 1), product4 (category1, 1), product4
The shuffle/sort step of MapReduce will then do a MapReduce 的随机排序步骤会将键
distributed sort on the keys, resulting in: 值的排序打乱,变成下面这样:
(category1, 1), product4 (category1, 1), product4
(category1, 2), product1 (category1, 2), product1
@ -165,7 +166,7 @@ class SalesRanker(MRJob):
yield key, value yield key, value
def steps(self): def steps(self):
"""Run the map and reduce steps.""" """ 此处为 map reduce 步骤"""
return [ return [
self.mr(mapper=self.mapper, self.mr(mapper=self.mapper,
reducer=self.reducer), reducer=self.reducer),
@ -174,7 +175,7 @@ class SalesRanker(MRJob):
] ]
``` ```
The result would be the following sorted list, which we could insert into the `sales_rank` table: 得到的结果将会是如下的排序列,我们将其插入 `sales_rank` 表中:
``` ```
(category1, 1), product4 (category1, 1), product4
@ -184,7 +185,7 @@ The result would be the following sorted list, which we could insert into the `s
(category2, 7), product3 (category2, 7), product3
``` ```
The `sales_rank` table could have the following structure: `sales_rank` 表的数据结构如下:
``` ```
id int NOT NULL AUTO_INCREMENT id int NOT NULL AUTO_INCREMENT
@ -196,21 +197,21 @@ FOREIGN KEY(category_id) REFERENCES Categories(id)
FOREIGN KEY(product_id) REFERENCES Products(id) FOREIGN KEY(product_id) REFERENCES Products(id)
``` ```
We'll create an [index](https://github.com/donnemartin/system-design-primer#use-good-indices) on `id `, `category_id`, and `product_id` to speed up lookups (log-time instead of scanning the entire table) and to keep the data in memory. Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> 我们会以 `id`、`category_id` 与 `product_id` 创建一个 [索引](https://github.com/donnemartin/system-design-primer#use-good-indices)以加快查询速度(只需要使用读取日志的时间,不再需要每次都扫描整个数据表)并让数据常驻内存。从内存读取 1 MB 连续数据大约要花 250 微秒,而从 SSD 读取同样大小的数据要花费 4 倍的时间,从机械硬盘读取需要花费 80 倍以上的时间。<sup><a href=https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数>1</a></sup>
### Use case: User views the past week's most popular products by category ### 用例:用户需要根据分类浏览上周中最受欢迎的商品
* The **Client** sends a request to the **Web Server**, running as a [reverse proxy](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **客户端**向运行[反向代理](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)的 **Web 服务器**发送一个请求
* The **Web Server** forwards the request to the **Read API** server * 这个 **Web 服务器**将请求转发给**查询 API** 服务
* The **Read API** server reads from the **SQL Database** `sales_rank` table * The **查询 API** 服务将从 **SQL 数据库**`sales_rank` 表中读取数据
We'll use a public [**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest): 我们可以调用一个公共的 [REST API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
``` ```
$ curl https://amazon.com/api/v1/popular?category_id=1234 $ curl https://amazon.com/api/v1/popular?category_id=1234
``` ```
Response: 返回:
``` ```
{ {
@ -233,106 +234,105 @@ Response:
}, },
``` ```
For internal communications, we could use [Remote Procedure Calls](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc). 而对于服务器内部的通信,我们可以使用 [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)。
## Step 4: Scale the design ## 第四步:架构扩展
> Identify and address bottlenecks, given the constraints. > 根据限制条件,找到并解决瓶颈。
![Imgur](http://i.imgur.com/MzExP06.png) ![Imgur](http://i.imgur.com/MzExP06.png)
**Important: Do not simply jump right into the final design from the initial design!** **重要提示:不要从最初设计直接跳到最终设计中!**
State you would 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat. See [Design a system that scales to millions of users on AWS](../scaling_aws/README.md) as a sample on how to iteratively scale the initial design. 现在你要 1) **基准测试、负载测试**。2) **分析、描述**性能瓶颈。3) 在解决瓶颈问题的同时评估替代方案、权衡利弊。4) 重复以上步骤。请阅读[「设计一个系统,并将其扩大到为数以百万计的 AWS 用户服务」](../scaling_aws/README.md) 来了解如何逐步扩大初始设计。
It's important to discuss what bottlenecks you might encounter with the initial design and how you might address each of them. For example, what issues are addressed by adding a **Load Balancer** with multiple **Web Servers**? **CDN**? **Master-Slave Replicas**? What are the alternatives and **Trade-Offs** for each? 讨论初始设计可能遇到的瓶颈及相关解决方案是很重要的。例如加上一个配置多台 **Web 服务器**的**负载均衡器**是否能够解决问题?**CDN**呢?**主从复制**呢?它们各自的替代方案和需要**权衡**的利弊又有什么呢?
We'll introduce some components to complete the design and to address scalability issues. Internal load balancers are not shown to reduce clutter. 我们将会介绍一些组件来完成设计,并解决架构扩张问题。内置的负载均衡器将不做讨论以节省篇幅。
*To avoid repeating discussions*, refer to the following [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) for main talking points, tradeoffs, and alternatives: **为了避免重复讨论**,请参考[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)相关部分来了解其要点、方案的权衡取舍以及可选的替代方案。
* [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system) * [DNS](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#域名系统)
* [CDN](https://github.com/donnemartin/system-design-primer#content-delivery-network) * [负载均衡器](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#负载均衡器)
* [Load balancer](https://github.com/donnemartin/system-design-primer#load-balancer) * [水平拓展](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#水平扩展)
* [Horizontal scaling](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * [反向代理web 服务器)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)
* [Web server (reverse proxy)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * [API 服务(应用层)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用层)
* [API server (application layer)](https://github.com/donnemartin/system-design-primer#application-layer) * [缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存)
* [Cache](https://github.com/donnemartin/system-design-primer#cache) * [关系型数据库管理系统 (RDBMS)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#关系型数据库管理系统rdbms)
* [Relational database management system (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) * [SQL 故障主从切换](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#故障切换)
* [SQL write master-slave failover](https://github.com/donnemartin/system-design-primer#fail-over) * [主从复制](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#主从复制)
* [Master-slave replication](https://github.com/donnemartin/system-design-primer#master-slave-replication) * [一致性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#一致性模式)
* [Consistency patterns](https://github.com/donnemartin/system-design-primer#consistency-patterns) * [可用性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#可用性模式)
* [Availability patterns](https://github.com/donnemartin/system-design-primer#availability-patterns)
The **Analytics Database** could use a data warehousing solution such as Amazon Redshift or Google BigQuery. **分析数据库** 可以用现成的数据仓储系统,例如使用 Amazon Redshift 或者 Google BigQuery 的解决方案。
We might only want to store a limited time period of data in the database, while storing the rest in a data warehouse or in an **Object Store**. An **Object Store** such as Amazon S3 can comfortably handle the constraint of 40 GB of new content per month. 当使用数据仓储技术或者**对象存储**系统时我们只想在数据库中存储有限时间段的数据。Amazon S3 的**对象存储**系统可以很方便地设置每个月限制只允许新增 40 GB 的存储内容。
To address the 40,000 *average* read requests per second (higher at peak), traffic for popular content (and their sales rank) should be handled by the **Memory Cache** instead of the database. The **Memory Cache** is also useful for handling the unevenly distributed traffic and traffic spikes. With the large volume of reads, the **SQL Read Replicas** might not be able to handle the cache misses. We'll probably need to employ additional SQL scaling patterns. 平均每秒 40,000 次的读取请求(峰值将会更高), 可以通过扩展 **内存缓存** 来处理热点内容的读取流量,这对于处理不均匀分布的流量和流量峰值也很有用。由于读取量非常大,**SQL Read 副本** 可能会遇到处理缓存未命中的问题,我们可能需要使用额外的 SQL 扩展模式。
400 *average* writes per second (higher at peak) might be tough for a single **SQL Write Master-Slave**, also pointing to a need for additional scaling techniques. 平均每秒 400 次写操作(峰值将会更高)可能对于单个 **SQL 写主-从** 模式来说比较很困难,因此同时还需要更多的扩展技术
SQL scaling patterns include: SQL 缩放模式包括:
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [联合](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#联合)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分片](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#分片)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [非规范化](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#非规范化)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-调优)
We should also consider moving some data to a **NoSQL Database**. 我们也可以考虑将一些数据移至 **NoSQL 数据库**
## Additional talking points ## 其它要点
> Additional topics to dive into, depending on the problem scope and time remaining. > 是否深入这些额外的主题,取决于你的问题范围和剩下的时间。
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键-值存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#键-值存储)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档类型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#文档类型存储)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [列型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#列型存储)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#图数据库)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)
### Caching ### 缓存
* Where to cache * 在哪缓存
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching) * [客户端缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#客户端缓存)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching) * [CDN 缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#cdn-缓存)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching) * [Web 服务器缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#web-服务器缓存)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching) * [数据库缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库缓存)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching) * [应用缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用缓存)
* What to cache * 什么需要缓存
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level) * [数据库查询级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库查询级别的缓存)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level) * [对象级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#对象级别的缓存)
* When to update the cache * 何时更新缓存
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside) * [缓存模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存模式)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through) * [直写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#直写模式)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back) * [回写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#回写模式)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead) * [刷新](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#刷新)
### Asynchronism and microservices ### 异步与微服务
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) * [消息队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#消息队列)
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues) * [任务队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#任务队列)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure) * [背压](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#背压)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices) * [微服务](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#微服务)
### Communications ### 通信
* Discuss tradeoffs: * 可权衡选择的方案:
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest) * 与客户端的外部通信 - [使用 REST 作为 HTTP API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc) * 服务器内部通信 - [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery) * [服务发现](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#服务发现)
### Security ### 安全性
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security). 请参阅[「安全」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#安全)一章。
### Latency numbers ### 延迟数值
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 请参阅[「每个程序员都应该知道的延迟数」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数)。
### Ongoing ### 持续探讨
* Continue benchmarking and monitoring your system to address bottlenecks as they come up * 持续进行基准测试并监控你的系统,以解决他们提出的瓶颈问题。
* Scaling is an iterative process * 架构拓展是一个迭代的过程。

View File

@ -1,403 +1,403 @@
# Design a system that scales to millions of users on AWS # 在 AWS 上设计支持百万级到千万级用户的系统
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注释:为了避免重复,这篇文章的链接直接关联到 [系统设计主题](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) 的相关章节。为一讨论要点、折中方案和可选方案做参考。**
## Step 1: Outline use cases and constraints ## 第 1 步:用例和约束概要
> Gather requirements and scope the problem. > 收集需求并调查问题。
> Ask questions to clarify use cases and constraints. > 通过提问清晰用例和约束。
> Discuss assumptions. > 讨论假设。
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 如果没有面试官提出明确的问题,我们将自己定义一些用例和约束条件。
### Use cases ### 用例
Solving this problem takes an iterative approach of: 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat, which is good pattern for evolving basic designs to scalable designs. 解决这个问题是一个循序渐进的过程1) **基准/负载 测试** 2) 瓶颈 **概述** 3) 当评估可选和折中方案时定位瓶颈4) 重复,这是向可扩展的设计发展基础设计的好模式。
Unless you have a background in AWS or are applying for a position that requires AWS knowledge, AWS-specific details are not a requirement. However, **much of the principles discussed in this exercise can apply more generally outside of the AWS ecosystem.** 除非你有 AWS 的背景或者正在申请需要 AWS 知识的相关职位,否则不要求了解 AWS 的相关细节。并且这个练习中讨论的许多原则可以更广泛地应用于AWS生态系统之外。
#### We'll scope the problem to handle only the following use cases #### 我们就处理以下用例讨论这一问题
* **User** makes a read or write request * **用户** 进行读或写请求
* **Service** does processing, stores user data, then returns the results * **服务** 进行处理,存储用户数据,然后返回结果
* **Service** needs to evolve from serving a small amount of users to millions of users * **服务** 需要从支持小规模用户开始到百万用户
* Discuss general scaling patterns as we evolve an architecture to handle a large number of users and requests * 在我们演化架构来处理大量的用户和请求时,讨论一般的扩展模式
* **Service** has high availability * **服务** 高可用
### Constraints and assumptions ### 约束和假设
#### State assumptions #### 状态假设
* Traffic is not evenly distributed * 流量不均匀分布
* Need for relational data * 需要关系数据
* Scale from 1 user to tens of millions of users * 从一个用户扩展到千万用户
* Denote increase of users as: * 表示用户量的增长
* Users+ * 用户量+
* Users++ * 用户量++
* Users+++ * 用户量+++
* ... * ...
* 10 million users * 1000 万用户
* 1 billion writes per month * 每月 10 亿次写入
* 100 billion reads per month * 每月 1000 亿次读出
* 100:1 read to write ratio * 100:1 读写比率
* 1 KB content per write * 每次写入 1 KB 内容
#### Calculate usage #### 计算使用
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** **向你的面试官厘清你是否应该做粗略的使用计算**
* 1 TB of new content per month * 1 TB 新内容 / 月
* 1 KB per write * 1 billion writes per month * 1 KB 每次写入 * 10 亿 写入 / 月
* 36 TB of new content in 3 years * 36 TB 新内容 / 3 年
* Assume most writes are from new content instead of updates to existing ones * 假设大多数写入都是新内容而不是更新已有内容
* 400 writes per second on average * 平均每秒 400 次写入
* 40,000 reads per second on average * 平均每秒 40,000 次读取
Handy conversion guide: 便捷的转换指南:
* 2.5 million seconds per month * 250 万秒 / 月
* 1 request per second = 2.5 million requests per month * 1 次请求 / 秒 = 250 万次请求 / 月
* 40 requests per second = 100 million requests per month * 40 次请求 / 秒 = 1 亿次请求 / 月
* 400 requests per second = 1 billion requests per month * 400 次请求 / 秒 = 10 亿请求 / 月
## Step 2: Create a high level design ## 第 2 步:创建高级设计方案
> Outline a high level design with all important components. > 用所有重要组件概述高水平设计
![Imgur](http://i.imgur.com/B8LDKD7.png) ![Imgur](http://i.imgur.com/B8LDKD7.png)
## Step 3: Design core components ## 第 3 步:设计核心组件
> Dive into details for each core component. > 深入每个核心组件的细节。
### Use case: User makes a read or write request ### 用例:用户进行读写请求
#### Goals #### 目标
* With only 1-2 users, you only need a basic setup * 只有 1-2 个用户时,你只需要基础配置
* Single box for simplicity * 为简单起见,只需要一台服务器
* Vertical scaling when needed * 必要时进行纵向扩展
* Monitor to determine bottlenecks * 监控以确定瓶颈
#### Start with a single box #### 以单台服务器开始
* **Web server** on EC2 * **Web 服务器** 在 EC2 上
* Storage for user data * 存储用户数据
* [**MySQL Database**](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) * [**MySQL 数据库**](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms)
Use **Vertical Scaling**: 运用 **纵向扩展**
* Simply choose a bigger box * 选择一台更大容量的服务器
* Keep an eye on metrics to determine how to scale up * 密切关注指标,确定如何扩大规模
* Use basic monitoring to determine bottlenecks: CPU, memory, IO, network, etc * 使用基本监控来确定瓶颈:CPU、内存、IO、网络等
* CloudWatch, top, nagios, statsd, graphite, etc * CloudWatch, top, nagios, statsd, graphite
* Scaling vertically can get very expensive * 纵向扩展的代价将变得更昂贵
* No redundancy/failover * 无冗余/容错
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* The alternative to **Vertical Scaling** is [**Horizontal scaling**](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * **纵向扩展** 的可选方案是 [**横向扩展**](https://github.com/donnemartin/system-design-primer#horizontal-scaling)
#### Start with SQL, consider NoSQL #### 自 SQL 开始,但认真考虑 NoSQL
The constraints assume there is a need for relational data. We can start off using a **MySQL Database** on the single box. 约束条件假设需要关系型数据。我们可以开始时在单台服务器上使用 **MySQL 数据库**
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the [Relational database management system (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) section * 查阅 [关系型数据库管理系统 (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) 章节
* Discuss reasons to use [SQL or NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * 讨论使用 [SQL 或 NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) 的原因
#### Assign a public static IP #### 分配公共静态 IP
* Elastic IPs provide a public endpoint whose IP doesn't change on reboot * 弹性 IP 提供了一个公共端点,不会在重启时改变 IP。
* Helps with failover, just point the domain to a new IP * 故障转移时只需要把域名指向新 IP。
#### Use a DNS #### 使用 DNS 服务
Add a **DNS** such as Route 53 to map the domain to the instance's public IP. 添加 **DNS** 服务,比如 Route 53[Amazon Route 53](https://aws.amazon.com/cn/route53/) - 译者注),将域映射到实例的公共 IP 中。
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the [Domain name system](https://github.com/donnemartin/system-design-primer#domain-name-system) section * 查阅 [域名系统](https://github.com/donnemartin/system-design-primer#domain-name-system) 章节
#### Secure the web server #### 安全的 Web 服务器
* Open up only necessary ports * 只开放必要的端口
* Allow the web server to respond to incoming requests from: * 允许 Web 服务器响应来自以下端口的请求
* 80 for HTTP * HTTP 80
* 443 for HTTPS * HTTPS 443
* 22 for SSH to only whitelisted IPs * SSH IP 白名单 22
* Prevent the web server from initiating outbound connections * 防止 Web 服务器启动外链
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the [Security](https://github.com/donnemartin/system-design-primer#security) section * 查阅 [安全](https://github.com/donnemartin/system-design-primer#security) 章节
## Step 4: Scale the design ## 第 4 步:扩展设计
> Identify and address bottlenecks, given the constraints. > 在给定约束条件下,定义和确认瓶颈。
### Users+ ### 用户+
![Imgur](http://i.imgur.com/rrfjMXB.png) ![Imgur](http://i.imgur.com/rrfjMXB.png)
#### Assumptions #### 假设
Our user count is starting to pick up and the load is increasing on our single box. Our **Benchmarks/Load Tests** and **Profiling** are pointing to the **MySQL Database** taking up more and more memory and CPU resources, while the user content is filling up disk space. 我们的用户数量开始上升,并且单台服务器的负载上升。**基准/负载测试** 和 **分析** 指出 **MySQL 数据库** 占用越来越多的内存和 CPU 资源,同时用户数据将填满硬盘空间。
We've been able to address these issues with **Vertical Scaling** so far. Unfortunately, this has become quite expensive and it doesn't allow for independent scaling of the **MySQL Database** and **Web Server**. 目前,我们尚能在纵向扩展时解决这些问题。不幸的是,解决这些问题的代价变得相当昂贵,并且原来的系统并不能允许在 **MySQL 数据库****Web 服务器** 的基础上进行独立扩展。
#### Goals #### 目标
* Lighten load on the single box and allow for independent scaling * 减轻单台服务器负载并且允许独立扩展
* Store static content separately in an **Object Store** * 在 **对象存储** 中单独存储静态内容
* Move the **MySQL Database** to a separate box * 将 **MySQL 数据库** 迁移到单独的服务器上
* Disadvantages * 缺点
* These changes would increase complexity and would require changes to the **Web Server** to point to the **Object Store** and the **MySQL Database** * 这些变化会增加复杂性,并要求对 **Web服务器** 进行更改,以指向 **对象存储** 和 **MySQL 数据库**
* Additional security measures must be taken to secure the new components * 必须采取额外的安全措施来确保新组件的安全
* AWS costs could also increase, but should be weighed with the costs of managing similar systems on your own * AWS 的成本也会增加,但应该与自身管理类似系统的成本做比较
#### Store static content separately #### 独立保存静态内容
* Consider using a managed **Object Store** like S3 to store static content * 考虑使用像 S3 这样可管理的 **对象存储** 服务来存储静态内容
* Highly scalable and reliable * 高扩展性和可靠性
* Server side encryption * 服务器端加密
* Move static content to S3 * 迁移静态内容到 S3
* User files * 用户文件
* JS * JS
* CSS * CSS
* Images * 图片
* Videos * 视频
#### Move the MySQL database to a separate box #### 迁移 MySQL 数据库到独立机器上
* Consider using a service like RDS to manage the **MySQL Database** * 考虑使用类似 RDS 的服务来管理 **MySQL 数据库**
* Simple to administer, scale * 简单的管理,扩展
* Multiple availability zones * 多个可用区域
* Encryption at rest * 空闲时加密
#### Secure the system #### 系统安全
* Encrypt data in transit and at rest * 在传输和空闲时对数据进行加密
* Use a Virtual Private Cloud * 使用虚拟私有云
* Create a public subnet for the single **Web Server** so it can send and receive traffic from the internet * 为单个 **Web 服务器** 创建一个公共子网,这样就可以发送和接收来自 internet 的流量
* Create a private subnet for everything else, preventing outside access * 为其他内容创建一个私有子网,禁止外部访问
* Only open ports from whitelisted IPs for each component * 在每个组件上只为白名单 IP 打开端口
* These same patterns should be implemented for new components in the remainder of the exercise * 这些相同的模式应当在新的组件的实现中实践
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the [Security](https://github.com/donnemartin/system-design-primer#security) section * 查阅 [安全](https://github.com/donnemartin/system-design-primer#security) 章节
### Users++ ### 用户+++
![Imgur](http://i.imgur.com/raoFTXM.png) ![Imgur](http://i.imgur.com/raoFTXM.png)
#### Assumptions #### 假设
Our **Benchmarks/Load Tests** and **Profiling** show that our single **Web Server** bottlenecks during peak hours, resulting in slow responses and in some cases, downtime. As the service matures, we'd also like to move towards higher availability and redundancy. 我们的 **基准/负载测试** 和 **性能测试** 显示,在高峰时段,我们的单一 **Web服务器** 存在瓶颈,导致响应缓慢,在某些情况下还会宕机。随着服务的成熟,我们也希望朝着更高的可用性和冗余发展。
#### Goals #### 目标
* The following goals attempt to address the scaling issues with the **Web Server** * 下面的目标试图用 **Web服务器** 解决扩展问题
* Based on the **Benchmarks/Load Tests** and **Profiling**, you might only need to implement one or two of these techniques * 基于 **基准/负载测试** 和 **分析**,你可能只需要实现其中的一两个技术
* Use [**Horizontal Scaling**](https://github.com/donnemartin/system-design-primer#horizontal-scaling) to handle increasing loads and to address single points of failure * 使用 [**横向扩展**](https://github.com/donnemartin/system-design-primer#horizontal-scaling) 来处理增加的负载和单点故障
* Add a [**Load Balancer**](https://github.com/donnemartin/system-design-primer#load-balancer) such as Amazon's ELB or HAProxy * 添加 [**负载均衡器**](https://github.com/donnemartin/system-design-primer#load-balancer) 例如 Amazon 的 ELB 或 HAProxy
* ELB is highly available * ELB 是高可用的
* If you are configuring your own **Load Balancer**, setting up multiple servers in [active-active](https://github.com/donnemartin/system-design-primer#active-active) or [active-passive](https://github.com/donnemartin/system-design-primer#active-passive) in multiple availability zones will improve availability * 如果你正在配置自己的 **负载均衡器**, 在多个可用区域中设置多台服务器用于 [双活](https://github.com/donnemartin/system-design-primer#active-active) 或 [主被](https://github.com/donnemartin/system-design-primer#active-passive) 将提高可用性
* Terminate SSL on the **Load Balancer** to reduce computational load on backend servers and to simplify certificate administration * 终止在 **负载平衡器** 上的SSL以减少后端服务器上的计算负载并简化证书管理
* Use multiple **Web Servers** spread out over multiple availability zones * 在多个可用区域中使用多台 **Web服务器**
* Use multiple **MySQL** instances in [**Master-Slave Failover**](https://github.com/donnemartin/system-design-primer#master-slave-replication) mode across multiple availability zones to improve redundancy * 在多个可用区域的 [**主-从 故障转移**](https://github.com/donnemartin/system-design-primer#master-slave-replication) 模式中使用多个 **MySQL** 实例来改进冗余
* Separate out the **Web Servers** from the [**Application Servers**](https://github.com/donnemartin/system-design-primer#application-layer) * 分离 **Web 服务器** 和 [**应用服务器**](https://github.com/donnemartin/system-design-primer#application-layer)
* Scale and configure both layers independently * 独立扩展和配置每一层
* **Web Servers** can run as a [**Reverse Proxy**](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **Web 服务器** 可以作为 [**反向代理**](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server)
* For example, you can add **Application Servers** handling **Read APIs** while others handle **Write APIs** * 例如, 你可以添加 **应用服务器** 处理 **读 API** 而另外一些处理 **写 API**
* Move static (and some dynamic) content to a [**Content Delivery Network (CDN)**](https://github.com/donnemartin/system-design-primer#content-delivery-network) such as CloudFront to reduce load and latency * 将静态(和一些动态)内容转移到 [**内容分发网络 (CDN)**](https://github.com/donnemartin/system-design-primer#content-delivery-network) 例如 CloudFront 以减少负载和延迟
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the linked content above for details * 查阅以上链接获得更多细节
### Users+++ ### 用户+++
![Imgur](http://i.imgur.com/OZCxJr0.png) ![Imgur](http://i.imgur.com/OZCxJr0.png)
**Note:** **Internal Load Balancers** not shown to reduce clutter **注意:** **内部负载均衡** 不显示以减少混乱
#### Assumptions #### 假设
Our **Benchmarks/Load Tests** and **Profiling** show that we are read-heavy (100:1 with writes) and our database is suffering from poor performance from the high read requests. 我们的 **性能/负载测试** 和 **性能测试** 显示我们读操作频繁100:1 的读写比率),并且数据库在高读请求时表现很糟糕。
#### Goals #### 目标
* The following goals attempt to address the scaling issues with the **MySQL Database** * 下面的目标试图解决 **MySQL数据库** 的伸缩性问题
* Based on the **Benchmarks/Load Tests** and **Profiling**, you might only need to implement one or two of these techniques * * 基于 **基准/负载测试** 和 **分析**,你可能只需要实现其中的一两个技术
* Move the following data to a [**Memory Cache**](https://github.com/donnemartin/system-design-primer#cache) such as Elasticache to reduce load and latency: * 将下列数据移动到一个 [**内存缓存**](https://github.com/donnemartin/system-design-primer#cache),例如弹性缓存,以减少负载和延迟:
* Frequently accessed content from **MySQL** * **MySQL** 中频繁访问的内容
* First, try to configure the **MySQL Database** cache to see if that is sufficient to relieve the bottleneck before implementing a **Memory Cache** * 首先, 尝试配置 **MySQL 数据库** 缓存以查看是否足以在实现 **内存缓存** 之前缓解瓶颈
* Session data from the **Web Servers** * 来自 **Web 服务器** 的会话数据
* The **Web Servers** become stateless, allowing for **Autoscaling** * **Web 服务器** 变成无状态的, 允许 **自动伸缩**
* Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> * 从内存中读取 1 MB 内存需要大约 250 微秒而从SSD中读取时间要长 4 倍,从磁盘读取的时间要长 80 倍。<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup>
* Add [**MySQL Read Replicas**](https://github.com/donnemartin/system-design-primer#master-slave-replication) to reduce load on the write master * 添加 [**MySQL 读取副本**](https://github.com/donnemartin/system-design-primer#master-slave-replication) 来减少写主线程的负载
* Add more **Web Servers** and **Application Servers** to improve responsiveness * 添加更多 **Web 服务器** and **应用服务器** 来提高响应
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the linked content above for details * 查阅以上链接获得更多细节
#### Add MySQL read replicas #### 添加 MySQL 读取副本
* In addition to adding and scaling a **Memory Cache**, **MySQL Read Replicas** can also help relieve load on the **MySQL Write Master** * 除了添加和扩展 **内存缓存****MySQL 读副本服务器** 也能够帮助缓解在 **MySQL 写主服务器** 的负载。
* Add logic to **Web Server** to separate out writes and reads * 添加逻辑到 **Web 服务器** 来区分读和写操作
* Add **Load Balancers** in front of **MySQL Read Replicas** (not pictured to reduce clutter) * **MySQL 读副本服务器** 之上添加 **负载均衡器** (不是为了减少混乱)
* Most services are read-heavy vs write-heavy * 大多数服务都是读取负载大于写入负载
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the [Relational database management system (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) section * 查阅 [关系型数据库管理系统 (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) 章节
### Users++++ ### 用户++++
![Imgur](http://i.imgur.com/3X8nmdL.png) ![Imgur](http://i.imgur.com/3X8nmdL.png)
#### Assumptions #### 假设
Our **Benchmarks/Load Tests** and **Profiling** show that our traffic spikes during regular business hours in the U.S. and drop significantly when users leave the office. We think we can cut costs by automatically spinning up and down servers based on actual load. We're a small shop so we'd like to automate as much of the DevOps as possible for **Autoscaling** and for the general operations. **基准/负载测试** 和 **分析** 显示,在美国,正常工作时间存在流量峰值,当用户离开办公室时,流量骤降。我们认为,可以通过真实负载自动转换服务器数量来降低成本。我们是一家小商店,所以我们希望 DevOps 尽量自动化地进行 **自动伸缩** 和通用操作。
#### Goals #### 目标
* Add **Autoscaling** to provision capacity as needed * 根据需要添加 **自动扩展**
* Keep up with traffic spikes * 跟踪流量高峰
* Reduce costs by powering down unused instances * 通过关闭未使用的实例来降低成本
* Automate DevOps * 自动化 DevOps
* Chef, Puppet, Ansible, etc * Chef, Puppet, Ansible 工具等
* Continue monitoring metrics to address bottlenecks * 继续监控指标以解决瓶颈
* **Host level** - Review a single EC2 instance * **主机水平** - 检查一个 EC2 实例
* **Aggregate level** - Review load balancer stats * **总水平** - 检查负载均衡器统计数据
* **Log analysis** - CloudWatch, CloudTrail, Loggly, Splunk, Sumo * **日志分析** - CloudWatch, CloudTrail, Loggly, Splunk, Sumo
* **External site performance** - Pingdom or New Relic * **外部站点的性能** - Pingdom or New Relic
* **Handle notifications and incidents** - PagerDuty * **处理通知和事件** - PagerDuty
* **Error Reporting** - Sentry * **错误报告** - Sentry
#### Add autoscaling #### 添加自动扩展
* Consider a managed service such as AWS **Autoscaling** * 考虑使用一个托管服务比如AWS **自动扩展**
* Create one group for each **Web Server** and one for each **Application Server** type, place each group in multiple availability zones * 为每个 **Web 服务器** 创建一个组,并为每个 **应用服务器** 类型创建一个组,将每个组放置在多个可用区域中
* Set a min and max number of instances * 设置最小和最大实例数
* Trigger to scale up and down through CloudWatch * 通过 CloudWatch 来扩展或收缩
* Simple time of day metric for predictable loads or * 可预测负载的简单时间度量
* Metrics over a time period: * 一段时间内的指标:
* CPU load * CPU 负载
* Latency * 延迟
* Network traffic * 网络流量
* Custom metric * 自定义指标
* Disadvantages * 缺点
* Autoscaling can introduce complexity * 自动扩展会引入复杂性
* It could take some time before a system appropriately scales up to meet increased demand, or to scale down when demand drops * 可能需要一段时间才能适当扩大规模,以满足增加的需求,或者在需求下降时缩减规模
### Users+++++ ### 用户+++++
![Imgur](http://i.imgur.com/jj3A5N8.png) ![Imgur](http://i.imgur.com/jj3A5N8.png)
**Note:** **Autoscaling** groups not shown to reduce clutter **注释:** **自动伸缩** 组不显示以减少混乱
#### Assumptions #### 假设
As the service continues to grow towards the figures outlined in the constraints, we iteratively run **Benchmarks/Load Tests** and **Profiling** to uncover and address new bottlenecks. 当服务继续向着限制条件概述的方向发展,我们反复地运行 **基准/负载测试** 和 **分析** 来进一步发现和定位新的瓶颈。
#### Goals #### 目标
We'll continue to address scaling issues due to the problem's constraints: 由于问题的约束,我们将继续提出扩展性的问题:
* If our **MySQL Database** starts to grow too large, we might consider only storing a limited time period of data in the database, while storing the rest in a data warehouse such as Redshift * 如果我们的 **MySQL 数据库** 开始变得过于庞大, 我们可能只考虑把数据在数据库中存储一段有限的时间, 同时在例如 Redshift 这样的数据仓库中存储其余的数据
* A data warehouse such as Redshift can comfortably handle the constraint of 1 TB of new content per month * 像 Redshift 这样的数据仓库能够轻松处理每月 1TB 的新内容
* With 40,000 average read requests per second, read traffic for popular content can be addressed by scaling the **Memory Cache**, which is also useful for handling the unevenly distributed traffic and traffic spikes * 平均每秒 40,000 次的读取请求, 可以通过扩展 **内存缓存** 来处理热点内容的读取流量,这对于处理不均匀分布的流量和流量峰值也很有用
* The **SQL Read Replicas** might have trouble handling the cache misses, we'll probably need to employ additional SQL scaling patterns * **SQL读取副本** 可能会遇到处理缓存未命中的问题, 我们可能需要使用额外的 SQL 扩展模式
* 400 average writes per second (with presumably significantly higher peaks) might be tough for a single **SQL Write Master-Slave**, also pointing to a need for additional scaling techniques * 对于单个 **SQL 写主-从** 模式来说,平均每秒 400 次写操作(明显更高)可能会很困难,同时还需要更多的扩展技术
SQL scaling patterns include: SQL 扩展模型包括:
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [集合](https://github.com/donnemartin/system-design-primer#federation)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分片](https://github.com/donnemartin/system-design-primer#sharding)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [反范式](https://github.com/donnemartin/system-design-primer#denormalization)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer#sql-tuning)
To further address the high read and write requests, we should also consider moving appropriate data to a [**NoSQL Database**](https://github.com/donnemartin/system-design-primer#nosql) such as DynamoDB. 为了进一步处理高读和写请求,我们还应该考虑将适当的数据移动到一个 [**NoSQL数据库**](https://github.com/donnemartin/system-design-primer#nosql) ,例如 DynamoDB。
We can further separate out our [**Application Servers**](https://github.com/donnemartin/system-design-primer#application-layer) to allow for independent scaling. Batch processes or computations that do not need to be done in real-time can be done [**Asynchronously**](https://github.com/donnemartin/system-design-primer#asynchronism) with **Queues** and **Workers**: 我们可以进一步分离我们的 [**应用服务器**](https://github.com/donnemartin/system-design-primer#application-layer) 以允许独立扩展。不需要实时完成的批处理任务和计算可以通过 Queues 和 Workers 异步完成:
* For example, in a photo service, the photo upload and the thumbnail creation can be separated: * 以照片服务为例,照片上传和缩略图的创建可以分开进行
* **Client** uploads photo * **客户端** 上传图片
* **Application Server** puts a job in a **Queue** such as SQS * **应用服务器** 推送一个任务到 **队列** 例如 SQS
* The **Worker Service** on EC2 or Lambda pulls work off the **Queue** then: * EC2 上的 **Worker 服务** 或者 Lambda 从 **队列** 拉取 work然后
* Creates a thumbnail * 创建缩略图
* Updates a **Database** * 更新 **数据库**
* Stores the thumbnail in the **Object Store** * 在 **对象存储** 中存储缩略图
*Trade-offs, alternatives, and additional details:* **折中方案, 可选方案, 和其他细节:**
* See the linked content above for details * 查阅以上链接获得更多细节
## Additional talking points ## 额外的话题
> Additional topics to dive into, depending on the problem scope and time remaining. > 根据问题的范围和剩余时间,还需要深入讨论其他问题。
### SQL scaling patterns ### SQL 扩展模式
* [Read replicas](https://github.com/donnemartin/system-design-primer#master-slave-replication) * [读取副本](https://github.com/donnemartin/system-design-primer#master-slave-replication)
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [集合](https://github.com/donnemartin/system-design-primer#federation)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分区](https://github.com/donnemartin/system-design-primer#sharding)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [反规范化](https://github.com/donnemartin/system-design-primer#denormalization)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer#sql-tuning)
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键值存储](https://github.com/donnemartin/system-design-primer#key-value-store)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档存储](https://github.com/donnemartin/system-design-primer#document-store)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [宽表存储](https://github.com/donnemartin/system-design-primer#wide-column-store)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer#graph-database)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql)
### Caching ### 缓存
* Where to cache * 缓存到哪里
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching) * [客户端缓存](https://github.com/donnemartin/system-design-primer#client-caching)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching) * [CDN 缓存](https://github.com/donnemartin/system-design-primer#cdn-caching)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching) * [Web 服务缓存](https://github.com/donnemartin/system-design-primer#web-server-caching)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching) * [数据库缓存](https://github.com/donnemartin/system-design-primer#database-caching)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching) * [应用缓存](https://github.com/donnemartin/system-design-primer#application-caching)
* What to cache * 缓存什么
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level) * [数据库请求层缓存](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level) * [对象层缓存](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level)
* When to update the cache * 何时更新缓存
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside) * [预留缓存](https://github.com/donnemartin/system-design-primer#cache-aside)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through) * [完全写入](https://github.com/donnemartin/system-design-primer#write-through)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back) * [延迟写 (写回)](https://github.com/donnemartin/system-design-primer#write-behind-write-back)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead) * [事先更新](https://github.com/donnemartin/system-design-primer#refresh-ahead)
### Asynchronism and microservices ### 异步性和微服务
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) * [消息队列](https://github.com/donnemartin/system-design-primer#message-queues)
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues) * [任务队列](https://github.com/donnemartin/system-design-primer#task-queues)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure) * [回退压力](https://github.com/donnemartin/system-design-primer#back-pressure)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices) * [微服务](https://github.com/donnemartin/system-design-primer#microservices)
### Communications ### 沟通
* Discuss tradeoffs: * 关于折中方案的讨论:
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest) * 客户端的外部通讯 - [遵循 REST 的 HTTP APIs](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc) * 内部通讯 - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery) * [服务探索](https://github.com/donnemartin/system-design-primer#service-discovery)
### Security ### 安全性
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security). 参考 [安全章节](https://github.com/donnemartin/system-design-primer#security)
### Latency numbers ### 延迟数字指标
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 查阅 [每个程序员必懂的延迟数字](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know)
### Ongoing ### 正在进行
* Continue benchmarking and monitoring your system to address bottlenecks as they come up * 继续基准测试并监控你的系统以解决出现的瓶颈问题
* Scaling is an iterative process * 扩展是一个迭代的过程

View File

@ -1,66 +1,66 @@
# Design the data structures for a social network # 为社交网络设计数据结构
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注释:为了避免重复,这篇文章的链接直接关联到 [系统设计主题](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) 的相关章节。为一讨论要点、折中方案和可选方案做参考。**
## Step 1: Outline use cases and constraints ## 第 1 步:用例和约束概要
> Gather requirements and scope the problem. > 收集需求并调查问题。
> Ask questions to clarify use cases and constraints. > 通过提问清晰用例和约束。
> Discuss assumptions. > 讨论假设。
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 如果没有面试官提出明确的问题,我们将自己定义一些用例和约束条件。
### Use cases ### 用例
#### We'll scope the problem to handle only the following use cases #### 我们就处理以下用例审视这一问题
* **User** searches for someone and sees the shortest path to the searched person * **用户** 寻找某人并显示与被寻人之间的最短路径
* **Service** has high availability * **服务** 高可用
### Constraints and assumptions ### 约束和假设
#### State assumptions #### 状态假设
* Traffic is not evenly distributed * 流量分布不均
* Some searches are more popular than others, while others are only executed once * 某些搜索比别的更热门,同时某些搜索仅执行一次
* Graph data won't fit on a single machine * 图数据不适用单一机器
* Graph edges are unweighted * 图的边没有权重
* 100 million users * 1 千万用户
* 50 friends per user average * 每个用户平均有 50 个朋友
* 1 billion friend searches per month * 每月 10 亿次朋友搜索
Exercise the use of more traditional systems - don't use graph-specific solutions such as [GraphQL](http://graphql.org/) or a graph database like [Neo4j](https://neo4j.com/) 训练使用更传统的系统 - 别用图特有的解决方案例如 [GraphQL](http://graphql.org/) 或图数据库如 [Neo4j](https://neo4j.com/)。
#### Calculate usage #### 计算使用
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** **向你的面试官厘清你是否应该做粗略的使用计算**
* 5 billion friend relationships * 50 亿朋友关系
* 100 million users * 50 friends per user average * 1 亿用户 * 平均每人 50 个朋友
* 400 search requests per second * 每秒 400 次搜索请求
Handy conversion guide: 便捷的转换指南:
* 2.5 million seconds per month * 每月 250 万秒
* 1 request per second = 2.5 million requests per month * 每秒 1 个请求 = 每月 250 万次请求
* 40 requests per second = 100 million requests per month * 每秒 40 个请求 = 每月 1 亿次请求
* 400 requests per second = 1 billion requests per month * 每秒 400 个请求 = 每月 10 亿次请求
## Step 2: Create a high level design ## 第 2 步:创建高级设计方案
> Outline a high level design with all important components. > 用所有重要组件概述高水平设计
![Imgur](http://i.imgur.com/wxXyq2J.png) ![Imgur](http://i.imgur.com/wxXyq2J.png)
## Step 3: Design core components ## 第 3 步:设计核心组件
> Dive into details for each core component. > 深入每个核心组件的细节。
### Use case: User searches for someone and sees the shortest path to the searched person ### 用例: 用户搜索某人并查看到被搜人的最短路径
**Clarify with your interviewer how much code you are expected to write**. **和你的面试官说清你期望的代码量**
Without the constraint of millions of users (vertices) and billions of friend relationships (edges), we could solve this unweighted shortest path task with a general BFS approach: 没有百万用户(点)的和十亿朋友关系(边)的限制,我们能够用一般 BFS 方法解决无权重最短路径任务:
```python ```python
class Graph(Graph): class Graph(Graph):
@ -99,23 +99,22 @@ class Graph(Graph):
return None return None
``` ```
We won't be able to fit all users on the same machine, we'll need to [shard](https://github.com/donnemartin/system-design-primer#sharding) users across **Person Servers** and access them with a **Lookup Service**. 我们不能在同一台机器上满足所有用户,我们需要通过 **人员服务器** [拆分](https://github.com/donnemartin/system-design-primer#sharding) 用户并且通过 **查询服务** 访问。
* The **Client** sends a request to the **Web Server**, running as a [reverse proxy](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **客户端** 向 **服务器** 发送请求,**服务器** 作为 [反向代理](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server)
* The **Web Server** forwards the request to the **Search API** server * **搜索 API** 服务器向 **用户图服务** 转发请求
* The **Search API** server forwards the request to the **User Graph Service** * **用户图服务** 有以下功能:
* The **User Graph Service** does the following: * 使用 **查询服务** 找到当前用户信息存储的 **人员服务器**
* Uses the **Lookup Service** to find the **Person Server** where the current user's info is stored * 找到适当的 **人员服务器** 检索当前用户的 `friend_ids` 列表
* Finds the appropriate **Person Server** to retrieve the current user's list of `friend_ids` * 把当前用户作为 `source` 运行 BFS 搜索算法同时 当前用户的 `friend_ids` 作为每个 `adjacent_node` 的 ids
* Runs a BFS search using the current user as the `source` and the current user's `friend_ids` as the ids for each `adjacent_node` * 给定 id 获取 `adjacent_node`:
* To get the `adjacent_node` from a given id: * **用户图服务** 将 **再次** 和 **查询服务** 通讯,最后判断出和给定 id 相匹配的存储 `adjacent_node`**人员服务器**(有待优化)
* The **User Graph Service** will *again* need to communicate with the **Lookup Service** to determine which **Person Server** stores the`adjacent_node` matching the given id (potential for optimization)
**Clarify with your interviewer how much code you should be writing**. **和你的面试官说清你应该写的代码量**
**Note**: Error handling is excluded below for simplicity. Ask if you should code proper error handing. **注释**:简易版错误处理执行如下。询问你是否需要编写适当的错误处理方法。
**Lookup Service** implementation: **查询服务** 实现:
```python ```python
class LookupService(object): class LookupService(object):
@ -130,7 +129,7 @@ class LookupService(object):
return self.lookup[person_id] return self.lookup[person_id]
``` ```
**Person Server** implementation: **人员服务器** 实现:
```python ```python
class PersonServer(object): class PersonServer(object):
@ -149,7 +148,7 @@ class PersonServer(object):
return results return results
``` ```
**Person** implementation: **用户** 实现:
```python ```python
class Person(object): class Person(object):
@ -160,7 +159,7 @@ class Person(object):
self.friend_ids = friend_ids self.friend_ids = friend_ids
``` ```
**User Graph Service** implementation: **用户图服务** 实现:
```python ```python
class UserGraphService(object): class UserGraphService(object):
@ -218,13 +217,13 @@ class UserGraphService(object):
return None return None
``` ```
We'll use a public [**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest): 我们用的是公共的 [**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest)
``` ```
$ curl https://social.com/api/v1/friend_search?person_id=1234 $ curl https://social.com/api/v1/friend_search?person_id=1234
``` ```
Response: 响应:
``` ```
{ {
@ -244,106 +243,106 @@ Response:
}, },
``` ```
For internal communications, we could use [Remote Procedure Calls](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc). 内部通信使用 [远端过程调用](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc)。
## Step 4: Scale the design ## 第 4 步:扩展设计
> Identify and address bottlenecks, given the constraints. > 在给定约束条件下,定义和确认瓶颈。
![Imgur](http://i.imgur.com/cdCv5g7.png) ![Imgur](http://i.imgur.com/cdCv5g7.png)
**Important: Do not simply jump right into the final design from the initial design!** **重要:别简化从最初设计到最终设计的过程!**
State you would 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat. See [Design a system that scales to millions of users on AWS](../scaling_aws/README.md) as a sample on how to iteratively scale the initial design. 你将要做的是1) **基准/负载 测试** 2) 瓶颈 **概述** 3) 当评估可选和折中方案时定位瓶颈4) 重复。以 [在 AWS 上设计支持百万级到千万级用户的系统](../scaling_aws/README.md) 为参考迭代地扩展最初设计。
It's important to discuss what bottlenecks you might encounter with the initial design and how you might address each of them. For example, what issues are addressed by adding a **Load Balancer** with multiple **Web Servers**? **CDN**? **Master-Slave Replicas**? What are the alternatives and **Trade-Offs** for each? 讨论最初设计可能遇到的瓶颈和处理方法十分重要。例如,什么问题可以通过添加多台 **Web 服务器** 作为 **负载均衡** 解决?**CDN****主从副本**?每个问题都有哪些替代和 **折中** 方案?
We'll introduce some components to complete the design and to address scalability issues. Internal load balancers are not shown to reduce clutter. 我们即将介绍一些组件来完成设计和解决扩展性问题。内部负载均衡不显示以减少混乱。
*To avoid repeating discussions*, refer to the following [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) for main talking points, tradeoffs, and alternatives: **避免重复讨论**,以下网址链接到 [系统设计主题](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) 相关的主流方案、折中方案和替代方案。
* [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system) * [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system)
* [Load balancer](https://github.com/donnemartin/system-design-primer#load-balancer) * [负载均衡](https://github.com/donnemartin/system-design-primer#load-balancer)
* [Horizontal scaling](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * [横向扩展](https://github.com/donnemartin/system-design-primer#horizontal-scaling)
* [Web server (reverse proxy)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * [Web 服务器(反向代理)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server)
* [API server (application layer)](https://github.com/donnemartin/system-design-primer#application-layer) * [API 服务器(应用层)](https://github.com/donnemartin/system-design-primer#application-layer)
* [Cache](https://github.com/donnemartin/system-design-primer#cache) * [缓存](https://github.com/donnemartin/system-design-primer#cache)
* [Consistency patterns](https://github.com/donnemartin/system-design-primer#consistency-patterns) * [一致性模式](https://github.com/donnemartin/system-design-primer#consistency-patterns)
* [Availability patterns](https://github.com/donnemartin/system-design-primer#availability-patterns) * [可用性模式](https://github.com/donnemartin/system-design-primer#availability-patterns)
To address the constraint of 400 *average* read requests per second (higher at peak), person data can be served from a **Memory Cache** such as Redis or Memcached to reduce response times and to reduce traffic to downstream services. This could be especially useful for people who do multiple searches in succession and for people who are well-connected. Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> 解决 **平均** 每秒 400 次请求的限制(峰值),人员数据可以存在例如 Redis 或 Memcached 这样的 **内存** 中以减少响应次数和下游流量通信服务。这尤其在用户执行多次连续查询和查询哪些广泛连接的人时十分有用。从内存中读取 1MB 数据大约要 250 微秒,从 SSD 中读取同样大小的数据时间要长 4 倍,从硬盘要长 80 倍。<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup>
Below are further optimizations: 以下是进一步优化方案:
* Store complete or partial BFS traversals to speed up subsequent lookups in the **Memory Cache** * **内存** 中存储完整的或部分的BFS遍历加快后续查找
* Batch compute offline then store complete or partial BFS traversals to speed up subsequent lookups in a **NoSQL Database** * **NoSQL 数据库** 中批量离线计算并存储完整的或部分的BFS遍历加快后续查找
* Reduce machine jumps by batching together friend lookups hosted on the same **Person Server** * 在同一台 **人员服务器** 上托管批处理同一批朋友查找减少机器跳转
* [Shard](https://github.com/donnemartin/system-design-primer#sharding) **Person Servers** by location to further improve this, as friends generally live closer to each other * 通过地理位置 [拆分](https://github.com/donnemartin/system-design-primer#sharding) **人员服务器** 来进一步优化,因为朋友通常住得都比较近
* Do two BFS searches at the same time, one starting from the source, and one from the destination, then merge the two paths * 同时进行两个 BFS 查找,一个从 source 开始,一个从 destination 开始,然后合并两个路径
* Start the BFS search from people with large numbers of friends, as they are more likely to reduce the number of [degrees of separation](https://en.wikipedia.org/wiki/Six_degrees_of_separation) between the current user and the search target * 从有庞大朋友圈的人开始找起,这样更有可能减小当前用户和搜索目标之间的 [离散度数](https://en.wikipedia.org/wiki/Six_degrees_of_separation)
* Set a limit based on time or number of hops before asking the user if they want to continue searching, as searching could take a considerable amount of time in some cases * 在询问用户是否继续查询之前设置基于时间或跳跃数阈值,当在某些案例中搜索耗费时间过长时。
* Use a **Graph Database** such as [Neo4j](https://neo4j.com/) or a graph-specific query language such as [GraphQL](http://graphql.org/) (if there were no constraint preventing the use of **Graph Databases**) * 使用类似 [Neo4j](https://neo4j.com/) 的 **图数据库** 或图特定查询语法,例如 [GraphQL](http://graphql.org/)(如果没有禁止使用 **图数据库** 的限制的话)
## Additional talking points ## 额外的话题
> Additional topics to dive into, depending on the problem scope and time remaining. > 根据问题的范围和剩余时间,还需要深入讨论其他问题。
### SQL scaling patterns ### SQL 扩展模式
* [Read replicas](https://github.com/donnemartin/system-design-primer#master-slave-replication) * [读取副本](https://github.com/donnemartin/system-design-primer#master-slave-replication)
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [集合](https://github.com/donnemartin/system-design-primer#federation)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分区](https://github.com/donnemartin/system-design-primer#sharding)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [反规范化](https://github.com/donnemartin/system-design-primer#denormalization)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer#sql-tuning)
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键值存储](https://github.com/donnemartin/system-design-primer#key-value-store)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档存储](https://github.com/donnemartin/system-design-primer#document-store)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [宽表存储](https://github.com/donnemartin/system-design-primer#wide-column-store)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer#graph-database)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql)
### Caching ### 缓存
* Where to cache * 缓存到哪里
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching) * [客户端缓存](https://github.com/donnemartin/system-design-primer#client-caching)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching) * [CDN 缓存](https://github.com/donnemartin/system-design-primer#cdn-caching)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching) * [Web 服务缓存](https://github.com/donnemartin/system-design-primer#web-server-caching)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching) * [数据库缓存](https://github.com/donnemartin/system-design-primer#database-caching)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching) * [应用缓存](https://github.com/donnemartin/system-design-primer#application-caching)
* What to cache * 缓存什么
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level) * [数据库请求层缓存](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level) * [对象层缓存](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level)
* When to update the cache * 何时更新缓存
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside) * [预留缓存](https://github.com/donnemartin/system-design-primer#cache-aside)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through) * [完全写入](https://github.com/donnemartin/system-design-primer#write-through)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back) * [延迟写 (写回)](https://github.com/donnemartin/system-design-primer#write-behind-write-back)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead) * [事先更新](https://github.com/donnemartin/system-design-primer#refresh-ahead)
### Asynchronism and microservices ### 异步性和微服务
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) * [消息队列](https://github.com/donnemartin/system-design-primer#message-queues)
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues) * [任务队列](https://github.com/donnemartin/system-design-primer#task-queues)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure) * [回退压力](https://github.com/donnemartin/system-design-primer#back-pressure)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices) * [微服务](https://github.com/donnemartin/system-design-primer#microservices)
### Communications ### 沟通
* Discuss tradeoffs: * 关于折中方案的讨论:
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest) * 客户端的外部通讯 - [遵循 REST 的 HTTP APIs](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc) * 内部通讯 - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery) * [服务探索](https://github.com/donnemartin/system-design-primer#service-discovery)
### Security ### 安全性
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security). 参考 [安全章节](https://github.com/donnemartin/system-design-primer#security)
### Latency numbers ### 延迟数字指标
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 查阅 [每个程序员必懂的延迟数字](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know)
### Ongoing ### 正在进行
* Continue benchmarking and monitoring your system to address bottlenecks as they come up * 继续基准测试并监控你的系统以解决出现的瓶颈问题
* Scaling is an iterative process * 扩展是一个迭代的过程

View File

@ -1,126 +1,126 @@
# Design the Twitter timeline and search # 设计推特时间轴与搜索功能
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注意:这个文档中的链接会直接指向[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)中的有关部分,以避免重复的内容。你可以参考链接的相关内容,来了解其总的要点、方案的权衡取舍以及可选的替代方案。**
**Design the Facebook feed** and **Design Facebook search** are similar questions. **设计 Facebook 的 feed** 与**设计 Facebook 搜索**与此为同一类型问题。
## Step 1: Outline use cases and constraints ## 第一步:简述用例与约束条件
> Gather requirements and scope the problem. > 搜集需求与问题的范围。
> Ask questions to clarify use cases and constraints. > 提出问题来明确用例与约束条件。
> Discuss assumptions. > 讨论假设。
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 我们将在没有面试官明确说明问题的情况下,自己定义一些用例以及限制条件。
### Use cases ### 用例
#### We'll scope the problem to handle only the following use cases #### 我们将把问题限定在仅处理以下用例的范围中
* **User** posts a tweet * **用户**发布了一篇推特
* **Service** pushes tweets to followers, sending push notifications and emails * **服务**将推特推送给关注者,给他们发送消息通知与邮件
* **User** views the user timeline (activity from the user) * **用户**浏览用户时间轴(用户最近的活动)
* **User** views the home timeline (activity from people the user is following) * **用户**浏览主页时间轴(用户关注的人最近的活动)
* **User** searches keywords * **用户**搜索关键词
* **Service** has high availability * **服务**需要有高可用性
#### Out of scope #### 不在用例范围内的有
* **Service** pushes tweets to the Twitter Firehose and other streams * **服务**向 Firehose 与其它流数据接口推送推特
* **Service** strips out tweets based on user's visibility settings * **服务**根据用户的”是否可见“选项排除推特
* Hide @reply if the user is not also following the person being replied to * 隐藏未关注者的 @回复
* Respect 'hide retweets' setting * 关心”隐藏转发“设置
* Analytics * 数据分析
### Constraints and assumptions ### 限制条件与假设
#### State assumptions #### 提出假设
General 普遍情况
* Traffic is not evenly distributed * 网络流量不是均匀分布的
* Posting a tweet should be fast * 发布推特的速度需要足够快速
* Fanning out a tweet to all of your followers should be fast, unless you have millions of followers * 除非有上百万的关注者,否则将推特推送给粉丝的速度要足够快
* 100 million active users * 1 亿个活跃用户
* 500 million tweets per day or 15 billion tweets per month * 每天新发布 5 亿条推特,每月新发布 150 亿条推特
* Each tweet averages a fanout of 10 deliveries * 平均每条推特需要推送给 5 个人
* 5 billion total tweets delivered on fanout per day * 每天需要进行 50 亿次推送
* 150 billion tweets delivered on fanout per month * 每月需要进行 1500 亿次推送
* 250 billion read requests per month * 每月需要处理 2500 亿次读取请求
* 10 billion searches per month * 每月需要处理 100 亿次搜索
Timeline 时间轴功能
* Viewing the timeline should be fast * 浏览时间轴需要足够快
* Twitter is more read heavy than write heavy * 推特的读取负载要大于写入负载
* Optimize for fast reads of tweets * 需要为推特的快速读取进行优化
* Ingesting tweets is write heavy * 存入推特是高写入负载功能
Search 搜索功能
* Searching should be fast * 搜索速度需要足够快
* Search is read-heavy * 搜索是高负载读取功能
#### Calculate usage #### 计算用量
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** **如果你需要进行粗略的用量计算,请向你的面试官说明。**
* Size per tweet: * 每条推特的大小:
* `tweet_id` - 8 bytes * `tweet_id` - 8 字节
* `user_id` - 32 bytes * `user_id` - 32 字节
* `text` - 140 bytes * `text` - 140 字节
* `media` - 10 KB average * `media` - 平均 10 KB
* Total: ~10 KB * 总计: 大约 10 KB
* 150 TB of new tweet content per month * 每月产生新推特的内容为 150 TB
* 10 KB per tweet * 500 million tweets per day * 30 days per month * 每条推特 10 KB * 每天 5 亿条推特 * 每月 30 天
* 5.4 PB of new tweet content in 3 years * 3 年产生新推特的内容为 5.4 PB
* 100 thousand read requests per second * 每秒需要处理 10 万次读取请求
* 250 billion read requests per month * (400 requests per second / 1 billion requests per month) * 每个月需要处理 2500 亿次请求 * (每秒 400 次请求 / 每月 10 亿次请求)
* 6,000 tweets per second * 每秒发布 6000 条推特
* 15 billion tweets per month * (400 requests per second / 1 billion requests per month) * 每月发布 150 亿条推特 * (每秒 400 次请求 / 每月 10 次请求)
* 60 thousand tweets delivered on fanout per second * 每秒推送 6 万条推特
* 150 billion tweets delivered on fanout per month * (400 requests per second / 1 billion requests per month) * 每月推送 1500 亿条推特 * (每秒 400 次请求 / 每月 10 亿次请求)
* 4,000 search requests per second * 每秒 4000 次搜索请求
Handy conversion guide: 便利换算指南:
* 2.5 million seconds per month * 每个月有 250 万秒
* 1 request per second = 2.5 million requests per month * 每秒一个请求 = 每个月 250 万次请求
* 40 requests per second = 100 million requests per month * 每秒 40 个请求 = 每个月 1 亿次请求
* 400 requests per second = 1 billion requests per month * 每秒 400 个请求 = 每个月 10 亿次请求
## Step 2: Create a high level design ## 第二步:概要设计
> Outline a high level design with all important components. > 列出所有重要组件以规划概要设计。
![Imgur](http://i.imgur.com/48tEA2j.png) ![Imgur](http://i.imgur.com/48tEA2j.png)
## Step 3: Design core components ## 第三步:设计核心组件
> Dive into details for each core component. > 深入每个核心组件的细节。
### Use case: User posts a tweet ### 用例:用户发表了一篇推特
We could store the user's own tweets to populate the user timeline (activity from the user) in a [relational database](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms). We should discuss the [use cases and tradeoffs between choosing SQL or NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql). 我们可以将用户自己发表的推特存储在[关系数据库](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms)中。我们也可以讨论一下[究竟是用 SQL 还是用 NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)。
Delivering tweets and building the home timeline (activity from people the user is following) is trickier. Fanning out tweets to all followers (60 thousand tweets delivered on fanout per second) will overload a traditional [relational database](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms). We'll probably want to choose a data store with fast writes such as a **NoSQL database** or **Memory Cache**. Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> 构建用户主页时间轴(查看关注用户的活动)以及推送推特是件麻烦事。将特推传播给所有关注者(每秒约递送 6 万条推特)这一操作有可能会使传统的[关系数据库](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms)超负载。因此,我们可以使用 **NoSQL 数据库**或**内存数据库**之类的更快的数据存储方式。从内存读取 1 MB 连续数据大约要花 250 微秒,而从 SSD 读取同样大小的数据要花费 4 倍的时间,从机械硬盘读取需要花费 80 倍以上的时间。<sup><a href=https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数>1</a></sup>
We could store media such as photos or videos on an **Object Store**. 我们可以将照片、视频之类的媒体存储于**对象存储**中。
* The **Client** posts a tweet to the **Web Server**, running as a [reverse proxy](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **客户端**向应用[反向代理](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server)的**Web 服务器**发送一条推特
* The **Web Server** forwards the request to the **Write API** server * **Web 服务器**将请求转发给**写 API**服务器
* The **Write API** stores the tweet in the user's timeline on a **SQL database** * **写 API**服务器将推特使用 **SQL 数据库**存储于用户时间轴中
* The **Write API** contacts the **Fan Out Service**, which does the following: * **写 API**调用**消息输出服务**,进行以下操作:
* Queries the **User Graph Service** to find the user's followers stored in the **Memory Cache** * 查询**用户 图 服务**找到存储于**内存缓存**中的此用户的粉丝
* Stores the tweet in the *home timeline of the user's followers* in a **Memory Cache** * 将推特存储于**内存缓存**中的**此用户的粉丝的主页时间轴**中
* O(n) operation: 1,000 followers = 1,000 lookups and inserts * O(n) 复杂度操作: 1000 名粉丝 = 1000 次查找与插入
* Stores the tweet in the **Search Index Service** to enable fast searching * 将特推存储在**搜索索引服务**中,以加快搜索
* Stores media in the **Object Store** * 将媒体存储于**对象存储**中
* Uses the **Notification Service** to send out push notifications to followers: * 使用**通知服务**向粉丝发送推送:
* Uses a **Queue** (not pictured) to asynchronously send out notifications * 使用**队列**异步推送通知
**Clarify with your interviewer how much code you are expected to write**. **向你的面试官告知你准备写多少代码**。
If our **Memory Cache** is Redis, we could use a native Redis list with the following structure: 如果我们用 Redis 作为**内存缓存**,那可以用 Redis 原生的 list 作为其数据结构。结构如下:
``` ```
tweet n+2 tweet n+1 tweet n tweet n+2 tweet n+1 tweet n
@ -128,9 +128,9 @@ If our **Memory Cache** is Redis, we could use a native Redis list with the foll
| tweet_id user_id meta | tweet_id user_id meta | tweet_id user_id meta | | tweet_id user_id meta | tweet_id user_id meta | tweet_id user_id meta |
``` ```
The new tweet would be placed in the **Memory Cache**, which populates user's home timeline (activity from people the user is following). 新发布的推特将被存储在对应用户(关注且活跃的用户)的主页时间轴的**内存缓存**中。
We'll use a public [**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest): 我们可以调用一个公共的 [REST API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
``` ```
$ curl -X POST --data '{ "user_id": "123", "auth_token": "ABC123", \ $ curl -X POST --data '{ "user_id": "123", "auth_token": "ABC123", \
@ -138,7 +138,7 @@ $ curl -X POST --data '{ "user_id": "123", "auth_token": "ABC123", \
https://twitter.com/api/v1/tweet https://twitter.com/api/v1/tweet
``` ```
Response: 返回:
``` ```
{ {
@ -150,24 +150,24 @@ Response:
} }
``` ```
For internal communications, we could use [Remote Procedure Calls](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc). 而对于服务器内部的通信,我们可以使用 [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)。
### Use case: User views the home timeline ### 用例:用户浏览主页时间轴
* The **Client** posts a home timeline request to the **Web Server** * **客户端**向 **Web 服务器**发起一次读取主页时间轴的请求
* The **Web Server** forwards the request to the **Read API** server * **Web 服务器**将请求转发给**读取 API**服务器
* The **Read API** server contacts the **Timeline Service**, which does the following: * **读取 API**服务器调用**时间轴服务**进行以下操作:
* Gets the timeline data stored in the **Memory Cache**, containing tweet ids and user ids - O(1) * 从**内存缓存**读取时间轴数据,其中包括推特 id 与用户 id - O(1)
* Queries the **Tweet Info Service** with a [multiget](http://redis.io/commands/mget) to obtain additional info about the tweet ids - O(n) * 通过 [multiget](http://redis.io/commands/mget) 向**推特信息服务**进行查询,以获取相关 id 推特的额外信息 - O(n)
* Queries the **User Info Service** with a multiget to obtain additional info about the user ids - O(n) * 通过 muiltiget 向**用户信息服务**进行查询,以获取相关 id 用户的额外信息 - O(n)
REST API: REST API
``` ```
$ curl https://twitter.com/api/v1/home_timeline?user_id=123 $ curl https://twitter.com/api/v1/home_timeline?user_id=123
``` ```
Response: 返回:
``` ```
{ {
@ -187,146 +187,145 @@ Response:
}, },
``` ```
### Use case: User views the user timeline ### 用例:用户浏览用户时间轴
* The **Client** posts a user timeline request to the **Web Server** * **客户端**向**Web 服务器**发起获得用户时间线的请求
* The **Web Server** forwards the request to the **Read API** server * **Web 服务器**将请求转发给**读取 API**服务器
* The **Read API** retrieves the user timeline from the **SQL Database** * **读取 API**从 **SQL 数据库**中取出用户的时间轴
The REST API would be similar to the home timeline, except all tweets would come from the user as opposed to the people the user is following. REST API 与前面的主页时间轴类似,区别只在于取出的推特是由用户自己发送而不是关注人发送。
### Use case: User searches keywords ### 用例:用户搜索关键词
* The **Client** sends a search request to the **Web Server** * **客户端**将搜索请求发给**Web 服务器**
* The **Web Server** forwards the request to the **Search API** server * **Web 服务器**将请求转发给**搜索 API**服务器
* The **Search API** contacts the **Search Service**, which does the following: * **搜索 API**调用**搜索服务**进行以下操作:
* Parses/tokenizes the input query, determining what needs to be searched * 对输入进行转换与分词,弄明白需要搜索什么东西
* Removes markup * 移除标点等额外内容
* Breaks up the text into terms * 将文本打散为词组
* Fixes typos * 修正拼写错误
* Normalizes capitalization * 规范字母大小写
* Converts the query to use boolean operations * 将查询转换为布尔操作
* Queries the **Search Cluster** (ie [Lucene](https://lucene.apache.org/)) for the results: * 查询**搜索集群**(例如[Lucene](https://lucene.apache.org/))检索结果:
* [Scatter gathers](https://github.com/donnemartin/system-design-primer#under-development) each server in the cluster to determine if there are any results for the query * 对集群内的所有服务器进行查询,将有结果的查询进行[发散聚合Scatter gathers](https://github.com/donnemartin/system-design-primer#under-development)
* Merges, ranks, sorts, and returns the results * 合并取到的条目,进行评分与排序,最终返回结果
REST API: REST API
``` ```
$ curl https://twitter.com/api/v1/search?query=hello+world $ curl https://twitter.com/api/v1/search?query=hello+world
``` ```
The response would be similar to that of the home timeline, except for tweets matching the given query. 返回结果与前面的主页时间轴类似,只不过返回的是符合查询条件的推特。
## Step 4: Scale the design ## 第四步:架构扩展
> Identify and address bottlenecks, given the constraints. > 根据限制条件,找到并解决瓶颈。
![Imgur](http://i.imgur.com/jrUBAF7.png) ![Imgur](http://i.imgur.com/MzExP06.png)
**Important: Do not simply jump right into the final design from the initial design!** **重要提示:不要从最初设计直接跳到最终设计中!**
State you would 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat. See [Design a system that scales to millions of users on AWS](../scaling_aws/README.md) as a sample on how to iteratively scale the initial design. 现在你要 1) **基准测试、负载测试**。2) **分析、描述**性能瓶颈。3) 在解决瓶颈问题的同时评估替代方案、权衡利弊。4) 重复以上步骤。请阅读[「设计一个系统,并将其扩大到为数以百万计的 AWS 用户服务」](../scaling_aws/README.md) 来了解如何逐步扩大初始设计。
It's important to discuss what bottlenecks you might encounter with the initial design and how you might address each of them. For example, what issues are addressed by adding a **Load Balancer** with multiple **Web Servers**? **CDN**? **Master-Slave Replicas**? What are the alternatives and **Trade-Offs** for each? 讨论初始设计可能遇到的瓶颈及相关解决方案是很重要的。例如加上一个配置多台 **Web 服务器**的**负载均衡器**是否能够解决问题?**CDN**呢?**主从复制**呢?它们各自的替代方案和需要**权衡**的利弊又有什么呢?
We'll introduce some components to complete the design and to address scalability issues. Internal load balancers are not shown to reduce clutter. 我们将会介绍一些组件来完成设计,并解决架构扩张问题。内置的负载均衡器将不做讨论以节省篇幅。
*To avoid repeating discussions*, refer to the following [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) for main talking points, tradeoffs, and alternatives: **为了避免重复讨论**,请参考[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)相关部分来了解其要点、方案的权衡取舍以及可选的替代方案。
* [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system) * [DNS](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#域名系统)
* [CDN](https://github.com/donnemartin/system-design-primer#content-delivery-network) * [负载均衡器](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#负载均衡器)
* [Load balancer](https://github.com/donnemartin/system-design-primer#load-balancer) * [水平拓展](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#水平扩展)
* [Horizontal scaling](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * [反向代理web 服务器)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)
* [Web server (reverse proxy)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * [API 服务(应用层)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用层)
* [API server (application layer)](https://github.com/donnemartin/system-design-primer#application-layer) * [缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存)
* [Cache](https://github.com/donnemartin/system-design-primer#cache) * [关系型数据库管理系统 (RDBMS)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#关系型数据库管理系统rdbms)
* [Relational database management system (RDBMS)](https://github.com/donnemartin/system-design-primer#relational-database-management-system-rdbms) * [SQL 故障主从切换](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#故障切换)
* [SQL write master-slave failover](https://github.com/donnemartin/system-design-primer#fail-over) * [主从复制](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#主从复制)
* [Master-slave replication](https://github.com/donnemartin/system-design-primer#master-slave-replication) * [一致性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#一致性模式)
* [Consistency patterns](https://github.com/donnemartin/system-design-primer#consistency-patterns) * [可用性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#可用性模式)
* [Availability patterns](https://github.com/donnemartin/system-design-primer#availability-patterns)
The **Fanout Service** is a potential bottleneck. Twitter users with millions of followers could take several minutes to have their tweets go through the fanout process. This could lead to race conditions with @replies to the tweet, which we could mitigate by re-ordering the tweets at serve time. **消息输出服务**有可能成为性能瓶颈。那些有着百万数量关注着的用户可能发一条推特就需要好几分钟才能完成消息输出进程。这有可能使 @回复 这种推特时出现竞争条件,因此需要根据服务时间对此推特进行重排序来降低影响。
We could also avoid fanning out tweets from highly-followed users. Instead, we could search to find tweets for highly-followed users, merge the search results with the user's home timeline results, then re-order the tweets at serve time. 我们还可以避免从高关注量的用户输出推特。相反,我们可以通过搜索来找到高关注量用户的推特,并将搜索结果与用户的主页时间轴合并,再根据时间对其进行排序。
Additional optimizations include: 此外,还可以通过以下内容进行优化:
* Keep only several hundred tweets for each home timeline in the **Memory Cache** * 仅为每个主页时间轴在**内存缓存**中存储数百条推特
* Keep only active users' home timeline info in the **Memory Cache** * 仅在**内存缓存**中存储活动用户的主页时间轴
* If a user was not previously active in the past 30 days, we could rebuild the timeline from the **SQL Database** * 如果某个用户在过去 30 天都没有产生活动,那我们可以使用 **SQL 数据库**重新构建他的时间轴
* Query the **User Graph Service** to determine who the user is following * 使用**用户 图 服务**来查询并确定用户关注的人
* Get the tweets from the **SQL Database** and add them to the **Memory Cache** * 从 **SQL 数据库**中取出推特,并将它们存入**内存缓存**
* Store only a month of tweets in the **Tweet Info Service** * 仅在**推特信息服务**中存储一个月的推特
* Store only active users in the **User Info Service** * 仅在**用户信息服务**中存储活动用户的信息
* The **Search Cluster** would likely need to keep the tweets in memory to keep latency low * **搜索集群**需要将推特保留在内存中,以降低延迟
We'll also want to address the bottleneck with the **SQL Database**. 我们还可以考虑优化 **SQL 数据库** 来解决一些瓶颈问题。
Although the **Memory Cache** should reduce the load on the database, it is unlikely the **SQL Read Replicas** alone would be enough to handle the cache misses. We'll probably need to employ additional SQL scaling patterns. **内存缓存**能减小一些数据库的负载,靠 **SQL Read 副本**已经足够处理缓存未命中情况。我们还可以考虑使用一些额外的 SQL 性能拓展技术。
The high volume of writes would overwhelm a single **SQL Write Master-Slave**, also pointing to a need for additional scaling techniques. 高容量的写入将淹没单个的 **SQL 写主从**模式,因此需要更多的拓展技术。
* [Federation](https://github.com/donnemartin/system-design-primer#federation) * [联合](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#联合)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [分片](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#分片)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [非规范化](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#非规范化)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [SQL 调优](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-调优)
We should also consider moving some data to a **NoSQL Database**. 我们也可以考虑将一些数据移至 **NoSQL 数据库**
## Additional talking points ## 其它要点
> Additional topics to dive into, depending on the problem scope and time remaining. > 是否深入这些额外的主题,取决于你的问题范围和剩下的时间。
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键-值存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#键-值存储)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档类型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#文档类型存储)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [列型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#列型存储)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#图数据库)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)
### Caching ### 缓存
* Where to cache * 在哪缓存
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching) * [客户端缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#客户端缓存)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching) * [CDN 缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#cdn-缓存)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching) * [Web 服务器缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#web-服务器缓存)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching) * [数据库缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库缓存)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching) * [应用缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用缓存)
* What to cache * 什么需要缓存
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level) * [数据库查询级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库查询级别的缓存)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level) * [对象级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#对象级别的缓存)
* When to update the cache * 何时更新缓存
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside) * [缓存模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存模式)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through) * [直写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#直写模式)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back) * [回写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#回写模式)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead) * [刷新](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#刷新)
### Asynchronism and microservices ### 异步与微服务
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) * [消息队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#消息队列)
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues) * [任务队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#任务队列)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure) * [背压](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#背压)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices) * [微服务](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#微服务)
### Communications ### 通信
* Discuss tradeoffs: * 可权衡选择的方案:
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest) * 与客户端的外部通信 - [使用 REST 作为 HTTP API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc) * 服务器内部通信 - [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery) * [服务发现](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#服务发现)
### Security ### 安全性
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security). 请参阅[「安全」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#安全)一章。
### Latency numbers ### 延迟数值
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 请参阅[「每个程序员都应该知道的延迟数」](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数)。
### Ongoing ### 持续探讨
* Continue benchmarking and monitoring your system to address bottlenecks as they come up * 持续进行基准测试并监控你的系统,以解决他们提出的瓶颈问题。
* Scaling is an iterative process * 架构拓展是一个迭代的过程。

View File

@ -1,104 +1,102 @@
# Design a web crawler # 设计一个网页爬虫
*Note: This document links directly to relevant areas found in the [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) to avoid duplication. Refer to the linked content for general talking points, tradeoffs, and alternatives.* **注意:这个文档中的链接会直接指向[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)中的有关部分,以避免重复的内容。你可以参考链接的相关内容,来了解其总的要点、方案的权衡取舍以及可选的替代方案。**
## Step 1: Outline use cases and constraints ## 第一步:简述用例与约束条件
> Gather requirements and scope the problem. > 把所有需要的东西聚集在一起,审视问题。不停的提问,以至于我们可以明确使用场景和约束。讨论假设。
> Ask questions to clarify use cases and constraints.
> Discuss assumptions.
Without an interviewer to address clarifying questions, we'll define some use cases and constraints. 我们将在没有面试官明确说明问题的情况下,自己定义一些用例以及限制条件。
### Use cases ### 用例
#### We'll scope the problem to handle only the following use cases #### 我们把问题限定在仅处理以下用例的范围中
* **Service** crawls a list of urls: * **服务** 抓取一系列链接:
* Generates reverse index of words to pages containing the search terms * 生成包含搜索词的网页倒排索引
* Generates titles and snippets for pages * 生成页面的标题和摘要信息
* Title and snippets are static, they do not change based on search query * 页面标题和摘要都是静态的,它们不会根据搜索词改变
* **User** inputs a search term and sees a list of relevant pages with titles and snippets the crawler generated * **用户** 输入搜索词后,可以看到相关的搜索结果列表,列表每一项都包含由网页爬虫生成的页面标题及摘要
* Only sketch high level components and interactions for this use case, no need to go into depth * 只给该用例绘制出概要组件和交互说明,无需讨论细节
* **Service** has high availability * **服务** 具有高可用性
#### Out of scope #### 无需考虑
* Search analytics * 搜索分析
* Personalized search results * 个性化搜索结果
* Page rank * 页面排名
### Constraints and assumptions ### 限制条件与假设
#### State assumptions #### 提出假设
* Traffic is not evenly distributed * 搜索流量分布不均
* Some searches are very popular, while others are only executed once * 有些搜索词非常热门,有些则非常冷门
* Support only anonymous users * 只支持匿名用户
* Generating search results should be fast * 用户很快就能看到搜索结果
* The web crawler should not get stuck in an infinite loop * 网页爬虫不应该陷入死循环
* We get stuck in an infinite loop if the graph contains a cycle * 当爬虫路径包含环的时候,将会陷入死循环
* 1 billion links to crawl * 抓取 10 亿个链接
* Pages need to be crawled regularly to ensure freshness * 要定期重新抓取页面以确保新鲜度
* Average refresh rate of about once per week, more frequent for popular sites * 平均每周重新抓取一次,网站越热门,那么重新抓取的频率越高
* 4 billion links crawled each month * 每月抓取 40 亿个链接
* Average stored size per web page: 500 KB * 每个页面的平均存储大小:500 KB
* For simplicity, count changes the same as new pages * 简单起见,重新抓取的页面算作新页面
* 100 billion searches per month * 每月搜索量 1000 亿次
Exercise the use of more traditional systems - don't use existing systems such as [solr](http://lucene.apache.org/solr/) or [nutch](http://nutch.apache.org/). 用更传统的系统来练习 —— 不要使用 [solr](http://lucene.apache.org/solr/) 、[nutch](http://nutch.apache.org/) 之类的现成系统。
#### Calculate usage #### 计算用量
**Clarify with your interviewer if you should run back-of-the-envelope usage calculations.** **如果你需要进行粗略的用量计算,请向你的面试官说明。**
* 2 PB of stored page content per month * 每月存储 2 PB 页面
* 500 KB per page * 4 billion links crawled per month * 每月抓取 40 亿个页面,每个页面 500 KB
* 72 PB of stored page content in 3 years * 三年存储 72 PB 页面
* 1,600 write requests per second * 每秒 1600 次写请求
* 40,000 search requests per second * 每秒 40000 次搜索请求
Handy conversion guide: 简便换算指南:
* 2.5 million seconds per month * 一个月有 250 万秒
* 1 request per second = 2.5 million requests per month * 每秒 1 个请求,即每月 250 万个请求
* 40 requests per second = 100 million requests per month * 每秒 40 个请求,即每月 1 亿个请求
* 400 requests per second = 1 billion requests per month * 每秒 400 个请求,即每月 10 亿个请求
## Step 2: Create a high level design ## 第二步: 概要设计
> Outline a high level design with all important components. > 列出所有重要组件以规划概要设计。
![Imgur](http://i.imgur.com/xjdAAUv.png) ![Imgur](http://i.imgur.com/xjdAAUv.png)
## Step 3: Design core components ## 第三步:设计核心组件
> Dive into details for each core component. > 对每一个核心组件进行详细深入的分析。
### Use case: Service crawls a list of urls ### 用例:爬虫服务抓取一系列网页
We'll assume we have an initial list of `links_to_crawl` ranked initially based on overall site popularity. If this is not a reasonable assumption, we can seed the crawler with popular sites that link to outside content such as [Yahoo](https://www.yahoo.com/), [DMOZ](http://www.dmoz.org/), etc 假设我们有一个初始列表 `links_to_crawl`(待抓取链接),它最初基于网站整体的知名度来排序。当然如果这个假设不合理,我们可以使用 [Yahoo](https://www.yahoo.com/)、[DMOZ](http://www.dmoz.org/) 等知名门户网站作为种子链接来进行扩散 。
We'll use a table `crawled_links` to store processed links and their page signatures. 我们将用表 `crawled_links` (已抓取链接 )来记录已经处理过的链接以及相应的页面签名。
We could store `links_to_crawl` and `crawled_links` in a key-value **NoSQL Database**. For the ranked links in `links_to_crawl`, we could use [Redis](https://redis.io/) with sorted sets to maintain a ranking of page links. We should discuss the [use cases and tradeoffs between choosing SQL or NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql). 我们可以将 `links_to_crawl``crawled_links` 记录在键-值型 **NoSQL 数据库**中。对于 `crawled_links` 中已排序的链接,我们可以使用 [Redis](https://redis.io/) 的有序集合来维护网页链接的排名。我们应当在 [选择 SQL 还是 NoSQL 的问题上,讨论有关使用场景以及利弊 ](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)。
* The **Crawler Service** processes each page link by doing the following in a loop: * **爬虫服务**按照以下流程循环处理每一个页面链接:
* Takes the top ranked page link to crawl * 选取排名最靠前的待抓取链接
* Checks `crawled_links` in the **NoSQL Database** for an entry with a similar page signature * 在 **NoSQL 数据库**的 `crawled_links` 中,检查待抓取页面的签名是否与某个已抓取页面的签名相似
* If we have a similar page, reduces the priority of the page link * 若存在,则降低该页面链接的优先级
* This prevents us from getting into a cycle * 这样做可以避免陷入死循环
* Continue * 继续(进入下一次循环)
* Else, crawls the link * 若不存在,则抓取该链接
* Adds a job to the **Reverse Index Service** queue to generate a [reverse index](https://en.wikipedia.org/wiki/Search_engine_indexing) * 在**倒排索引服务**任务队列中,新增一个生成[倒排索引](https://en.wikipedia.org/wiki/Search_engine_indexing)任务。
* Adds a job to the **Document Service** queue to generate a static title and snippet * 在**文档服务**任务队列中,新增一个生成静态标题和摘要的任务。
* Generates the page signature * 生成页面签名
* Removes the link from `links_to_crawl` in the **NoSQL Database** * 在 **NoSQL 数据库**的 `links_to_crawl` 中删除该链接
* Inserts the page link and signature to `crawled_links` in the **NoSQL Database** * 在 **NoSQL 数据库**的 `crawled_links` 中插入该链接以及页面签名
**Clarify with your interviewer how much code you are expected to write**. **向面试官了解你需要写多少代码**。
`PagesDataStore` is an abstraction within the **Crawler Service** that uses the **NoSQL Database**: `PagesDataStore` 是**爬虫服务**中的一个抽象类,它使用 **NoSQL 数据库**进行存储。
```python ```python
class PagesDataStore(object): class PagesDataStore(object):
@ -108,31 +106,31 @@ class PagesDataStore(object):
... ...
def add_link_to_crawl(self, url): def add_link_to_crawl(self, url):
"""Add the given link to `links_to_crawl`.""" """将指定链接加入 `links_to_crawl`"""
... ...
def remove_link_to_crawl(self, url): def remove_link_to_crawl(self, url):
"""Remove the given link from `links_to_crawl`.""" """`links_to_crawl` 中删除指定链接。"""
... ...
def reduce_priority_link_to_crawl(self, url) def reduce_priority_link_to_crawl(self, url)
"""Reduce the priority of a link in `links_to_crawl` to avoid cycles.""" """`links_to_crawl` 中降低一个链接的优先级以避免死循环。"""
... ...
def extract_max_priority_page(self): def extract_max_priority_page(self):
"""Return the highest priority link in `links_to_crawl`.""" """返回 `links_to_crawl` 中优先级最高的链接。"""
... ...
def insert_crawled_link(self, url, signature): def insert_crawled_link(self, url, signature):
"""Add the given link to `crawled_links`.""" """将指定链接加入 `crawled_links`"""
... ...
def crawled_similar(self, signature): def crawled_similar(self, signature):
"""Determine if we've already crawled a page matching the given signature""" """判断待抓取页面的签名是否与某个已抓取页面的签名相似。"""
... ...
``` ```
`Page` is an abstraction within the **Crawler Service** that encapsulates a page, its contents, child urls, and signature: `Page` 是**爬虫服务**的一个抽象类,它封装了网页对象,由页面链接、页面内容、子链接和页面签名构成。
```python ```python
class Page(object): class Page(object):
@ -144,7 +142,7 @@ class Page(object):
self.signature = signature self.signature = signature
``` ```
`Crawler` is the main class within **Crawler Service**, composed of `Page` and `PagesDataStore`. `Crawler` 是**爬虫服务**的主类,由`Page` 和 `PagesDataStore` 组成。
```python ```python
class Crawler(object): class Crawler(object):
@ -155,7 +153,7 @@ class Crawler(object):
self.doc_index_queue = doc_index_queue self.doc_index_queue = doc_index_queue
def create_signature(self, page): def create_signature(self, page):
"""Create signature based on url and contents.""" """基于页面链接与内容生成签名。"""
... ...
def crawl_page(self, page): def crawl_page(self, page):
@ -176,16 +174,16 @@ class Crawler(object):
self.crawl_page(page) self.crawl_page(page)
``` ```
### Handling duplicates ### 处理重复内容
We need to be careful the web crawler doesn't get stuck in an infinite loop, which happens when the graph contains a cycle. 我们要谨防网页爬虫陷入死循环,这通常会发生在爬虫路径中存在环的情况。
**Clarify with your interviewer how much code you are expected to write**. **向面试官了解你需要写多少代码**.
We'll want to remove duplicate urls: 删除重复链接:
* For smaller lists we could use something like `sort | unique` * 假设数据量较小,我们可以用类似于 `sort | unique` 的方法。(译注: 先排序,后去重)
* With 1 billion links to crawl, we could use **MapReduce** to output only entries that have a frequency of 1 * 假设有 10 亿条数据,我们应该使用 **MapReduce** 来输出只出现 1 次的记录。
```python ```python
class RemoveDuplicateUrls(MRJob): class RemoveDuplicateUrls(MRJob):
@ -199,38 +197,38 @@ class RemoveDuplicateUrls(MRJob):
yield key, total yield key, total
``` ```
Detecting duplicate content is more complex. We could generate a signature based on the contents of the page and compare those two signatures for similarity. Some potential algorithms are [Jaccard index](https://en.wikipedia.org/wiki/Jaccard_index) and [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity). 比起处理重复内容,检测重复内容更为复杂。我们可以基于网页内容生成签名,然后对比两者签名的相似度。可能会用到的算法有 [Jaccard index](https://en.wikipedia.org/wiki/Jaccard_index) 以及 [cosine similarity](https://en.wikipedia.org/wiki/Cosine_similarity)。
### Determining when to update the crawl results ### 抓取结果更新策略
Pages need to be crawled regularly to ensure freshness. Crawl results could have a `timestamp` field that indicates the last time a page was crawled. After a default time period, say one week, all pages should be refreshed. Frequently updated or more popular sites could be refreshed in shorter intervals. 要定期重新抓取页面以确保新鲜度。抓取结果应该有个 `timestamp` 字段记录上一次页面抓取时间。每隔一段时间,比如说 1 周,所有页面都需要更新一次。对于热门网站或是内容频繁更新的网站,爬虫抓取间隔可以缩短。
Although we won't dive into details on analytics, we could do some data mining to determine the mean time before a particular page is updated, and use that statistic to determine how often to re-crawl the page. 尽管我们不会深入网页数据分析的细节,我们仍然要做一些数据挖掘工作来确定一个页面的平均更新时间,并且根据相关的统计数据来决定爬虫的重新抓取频率。
We might also choose to support a `Robots.txt` file that gives webmasters control of crawl frequency. 当然我们也应该根据站长提供的 `Robots.txt` 来控制爬虫的抓取频率。
### Use case: User inputs a search term and sees a list of relevant pages with titles and snippets ### 用例:用户输入搜索词后,可以看到相关的搜索结果列表,列表每一项都包含由网页爬虫生成的页面标题及摘要
* The **Client** sends a request to the **Web Server**, running as a [reverse proxy](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * **客户端**向运行[反向代理](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)的 **Web 服务器**发送一个请求
* The **Web Server** forwards the request to the **Query API** server * **Web 服务器** 发送请求到 **Query API** 服务器
* The **Query API** server does the following: * **查询 API** 服务将会做这些事情:
* Parses the query * 解析查询参数
* Removes markup * 删除 HTML 标记
* Breaks up the text into terms * 将文本分割成词组 (译注: 分词处理)
* Fixes typos * 修正错别字
* Normalizes capitalization * 规范化大小写
* Converts the query to use boolean operations * 将搜索词转换为布尔运算
* Uses the **Reverse Index Service** to find documents matching the query * 使用**倒排索引服务**来查找匹配查询的文档
* The **Reverse Index Service** ranks the matching results and returns the top ones * **倒排索引服务**对匹配到的结果进行排名,然后返回最符合的结果
* Uses the **Document Service** to return titles and snippets * 使用**文档服务**返回文章标题与摘要
We'll use a public [**REST API**](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest): 我们使用 [**REST API**](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest) 与客户端通信:
``` ```
$ curl https://search.com/api/v1/search?query=hello+world $ curl https://search.com/api/v1/search?query=hello+world
``` ```
Response: 响应内容:
``` ```
{ {
@ -250,104 +248,109 @@ Response:
}, },
``` ```
For internal communications, we could use [Remote Procedure Calls](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc). 对于服务器内部通信,我们可以使用 [远程过程调用协议RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)
## Step 4: Scale the design
> Identify and address bottlenecks, given the constraints. ## 第四步:架构扩展
> 根据限制条件,找到并解决瓶颈。
![Imgur](http://i.imgur.com/bWxPtQA.png) ![Imgur](http://i.imgur.com/bWxPtQA.png)
**Important: Do not simply jump right into the final design from the initial design!** **重要提示:不要直接从最初设计跳到最终设计!**
State you would 1) **Benchmark/Load Test**, 2) **Profile** for bottlenecks 3) address bottlenecks while evaluating alternatives and trade-offs, and 4) repeat. See [Design a system that scales to millions of users on AWS](../scaling_aws/README.md) as a sample on how to iteratively scale the initial design. 现在你要 1) **基准测试、负载测试**。2) **分析、描述**性能瓶颈。3) 在解决瓶颈问题的同时评估替代方案、权衡利弊。4) 重复以上步骤。请阅读[设计一个系统,并将其扩大到为数以百万计的 AWS 用户服务](../scaling_aws/README.md) 来了解如何逐步扩大初始设计。
It's important to discuss what bottlenecks you might encounter with the initial design and how you might address each of them. For example, what issues are addressed by adding a **Load Balancer** with multiple **Web Servers**? **CDN**? **Master-Slave Replicas**? What are the alternatives and **Trade-Offs** for each? 讨论初始设计可能遇到的瓶颈及相关解决方案是很重要的。例如加上一套配备多台 **Web 服务器**的**负载均衡器**是否能够解决问题?**CDN**呢?**主从复制**呢?它们各自的替代方案和需要**权衡**的利弊又有哪些呢?
We'll introduce some components to complete the design and to address scalability issues. Internal load balancers are not shown to reduce clutter. 我们将会介绍一些组件来完成设计,并解决架构规模扩张问题。内置的负载均衡器将不做讨论以节省篇幅。
*To avoid repeating discussions*, refer to the following [system design topics](https://github.com/donnemartin/system-design-primer#index-of-system-design-topics) for main talking points, tradeoffs, and alternatives: **为了避免重复讨论**,请参考[系统设计主题索引](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#系统设计主题的索引)相关部分来了解其要点、方案的权衡取舍以及替代方案。
* [DNS](https://github.com/donnemartin/system-design-primer#domain-name-system) * [DNS](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#域名系统)
* [Load balancer](https://github.com/donnemartin/system-design-primer#load-balancer) * [负载均衡器](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#负载均衡器)
* [Horizontal scaling](https://github.com/donnemartin/system-design-primer#horizontal-scaling) * [水平扩展](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#水平扩展)
* [Web server (reverse proxy)](https://github.com/donnemartin/system-design-primer#reverse-proxy-web-server) * [Web 服务器(反向代理)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#反向代理web-服务器)
* [API server (application layer)](https://github.com/donnemartin/system-design-primer#application-layer) * [API 服务器(应用层)](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用层)
* [Cache](https://github.com/donnemartin/system-design-primer#cache) * [缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存)
* [NoSQL](https://github.com/donnemartin/system-design-primer#nosql) * [NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#nosql)
* [Consistency patterns](https://github.com/donnemartin/system-design-primer#consistency-patterns) * [一致性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#一致性模式)
* [Availability patterns](https://github.com/donnemartin/system-design-primer#availability-patterns) * [可用性模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#可用性模式)
Some searches are very popular, while others are only executed once. Popular queries can be served from a **Memory Cache** such as Redis or Memcached to reduce response times and to avoid overloading the **Reverse Index Service** and **Document Service**. The **Memory Cache** is also useful for handling the unevenly distributed traffic and traffic spikes. Reading 1 MB sequentially from memory takes about 250 microseconds, while reading from SSD takes 4x and from disk takes 80x longer.<sup><a href=https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know>1</a></sup> 有些搜索词非常热门,有些则非常冷门。热门的搜索词可以通过诸如 Redis 或者 Memcached 之类的**内存缓存**来缩短响应时间,避免**倒排索引服务**以及**文档服务**过载。**内存缓存**同样适用于流量分布不均匀以及流量短时高峰问题。从内存中读取 1 MB 连续数据大约需要 250 微秒,而从 SSD 读取同样大小的数据要花费 4 倍的时间,从机械硬盘读取需要花费 80 倍以上的时间。<sup><a href="https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数">1</a></sup>
Below are a few other optimizations to the **Crawling Service**:
* To handle the data size and request load, the **Reverse Index Service** and **Document Service** will likely need to make heavy use sharding and replication. 以下是优化**爬虫服务**的其他建议:
* DNS lookup can be a bottleneck, the **Crawler Service** can keep its own DNS lookup that is refreshed periodically
* The **Crawler Service** can improve performance and reduce memory usage by keeping many open connections at a time, referred to as [connection pooling](https://en.wikipedia.org/wiki/Connection_pool)
* Switching to [UDP](https://github.com/donnemartin/system-design-primer#user-datagram-protocol-udp) could also boost performance
* Web crawling is bandwidth intensive, ensure there is enough bandwidth to sustain high throughput
## Additional talking points * 为了处理数据大小问题以及网络请求负载,**倒排索引服务**和**文档服务**可能需要大量应用数据分片和数据复制。
* DNS 查询可能会成为瓶颈,**爬虫服务**最好专门维护一套定期更新的 DNS 查询服务。
* 借助于[连接池](https://en.wikipedia.org/wiki/Connection_pool),即同时维持多个开放网络连接,可以提升**爬虫服务**的性能并减少内存使用量。
* 改用 [UDP](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#用户数据报协议udp) 协议同样可以提升性能
* 网络爬虫受带宽影响较大,请确保带宽足够维持高吞吐量。
> Additional topics to dive into, depending on the problem scope and time remaining. ## 其它要点
### SQL scaling patterns > 是否深入这些额外的主题,取决于你的问题范围和剩下的时间。
* [Read replicas](https://github.com/donnemartin/system-design-primer#master-slave-replication) ### SQL 扩展模式
* [Federation](https://github.com/donnemartin/system-design-primer#federation)
* [Sharding](https://github.com/donnemartin/system-design-primer#sharding) * [读取复制](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#主从复制)
* [Denormalization](https://github.com/donnemartin/system-design-primer#denormalization) * [联合](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#联合)
* [SQL Tuning](https://github.com/donnemartin/system-design-primer#sql-tuning) * [分片](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#分片)
* [非规范化](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#非规范化)
* [SQL 调优](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-调优)
#### NoSQL #### NoSQL
* [Key-value store](https://github.com/donnemartin/system-design-primer#key-value-store) * [键-值存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#键-值存储)
* [Document store](https://github.com/donnemartin/system-design-primer#document-store) * [文档类型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#文档类型存储)
* [Wide column store](https://github.com/donnemartin/system-design-primer#wide-column-store) * [列型存储](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#列型存储)
* [Graph database](https://github.com/donnemartin/system-design-primer#graph-database) * [图数据库](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#图数据库)
* [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer#sql-or-nosql) * [SQL vs NoSQL](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#sql-还是-nosql)
### Caching
* Where to cache ### 缓存
* [Client caching](https://github.com/donnemartin/system-design-primer#client-caching)
* [CDN caching](https://github.com/donnemartin/system-design-primer#cdn-caching)
* [Web server caching](https://github.com/donnemartin/system-design-primer#web-server-caching)
* [Database caching](https://github.com/donnemartin/system-design-primer#database-caching)
* [Application caching](https://github.com/donnemartin/system-design-primer#application-caching)
* What to cache
* [Caching at the database query level](https://github.com/donnemartin/system-design-primer#caching-at-the-database-query-level)
* [Caching at the object level](https://github.com/donnemartin/system-design-primer#caching-at-the-object-level)
* When to update the cache
* [Cache-aside](https://github.com/donnemartin/system-design-primer#cache-aside)
* [Write-through](https://github.com/donnemartin/system-design-primer#write-through)
* [Write-behind (write-back)](https://github.com/donnemartin/system-design-primer#write-behind-write-back)
* [Refresh ahead](https://github.com/donnemartin/system-design-primer#refresh-ahead)
### Asynchronism and microservices * 在哪缓存
* [客户端缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#客户端缓存)
* [CDN 缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#cdn-缓存)
* [Web 服务器缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#web-服务器缓存)
* [数据库缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库缓存)
* [应用缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#应用缓存)
* 什么需要缓存
* [数据库查询级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#数据库查询级别的缓存)
* [对象级别的缓存](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#对象级别的缓存)
* 何时更新缓存
* [缓存模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#缓存模式)
* [直写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#直写模式)
* [回写模式](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#回写模式)
* [刷新](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#刷新)
* [Message queues](https://github.com/donnemartin/system-design-primer#message-queues) ### 异步与微服务
* [Task queues](https://github.com/donnemartin/system-design-primer#task-queues)
* [Back pressure](https://github.com/donnemartin/system-design-primer#back-pressure)
* [Microservices](https://github.com/donnemartin/system-design-primer#microservices)
### Communications * [消息队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#消息队列)
* [任务队列](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#任务队列)
* [背压](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#背压)
* [微服务](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#微服务)
* Discuss tradeoffs: ### 通信
* External communication with clients - [HTTP APIs following REST](https://github.com/donnemartin/system-design-primer#representational-state-transfer-rest)
* Internal communications - [RPC](https://github.com/donnemartin/system-design-primer#remote-procedure-call-rpc)
* [Service discovery](https://github.com/donnemartin/system-design-primer#service-discovery)
### Security * 可权衡选择的方案:
* 与客户端的外部通信 - [使用 REST 作为 HTTP API](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#表述性状态转移rest)
* 内部通信 - [RPC](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#远程过程调用协议rpc)
* [服务发现](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#服务发现)
Refer to the [security section](https://github.com/donnemartin/system-design-primer#security).
### Latency numbers ### 安全性
See [Latency numbers every programmer should know](https://github.com/donnemartin/system-design-primer#latency-numbers-every-programmer-should-know). 请参阅[安全](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#安全)。
### Ongoing
* Continue benchmarking and monitoring your system to address bottlenecks as they come up ### 延迟数值
* Scaling is an iterative process
请参阅[每个程序员都应该知道的延迟数](https://github.com/donnemartin/system-design-primer/blob/master/README-zh-Hans.md#每个程序员都应该知道的延迟数)。
### 持续探讨
* 持续进行基准测试并监控你的系统,以解决他们提出的瓶颈问题。
* 架构扩展是一个迭代的过程。