Merge branch 'upstream' into save

pull/60/head
xujifa 2017-04-11 21:57:13 +08:00
commit 952aad566f
1 changed files with 571 additions and 572 deletions

1141
README-zh-Hant.md Normal file → Executable file
View File

@ -4,603 +4,604 @@
> * 校对者: > * 校对者:
> * 这个 [链接](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 发生变化,那就意味着这份翻译文档是最新的)。
# The System Design Primer # 系统设计入门
<p align="center"> <p align="center">
<img src="http://i.imgur.com/jj3A5N8.png"> <img src="http://i.imgur.com/jj3A5N8.png">
<br/> <br/>
</p> </p>
## Motivation ## 目的
> Learn how to design large scale systems. > 学习如何设计大型系统。
> >
> Prep for the system design interview. > 为系统设计面试做准备。
### Learn how to design large scale systems ### 学习如何设计大型系统
Learning how to design scalable systems will help you become a better engineer. 学习如何设计大型系统将会帮助你成为一个更好的工程师。
System design is a broad topic. There is a **vast amount of resources scattered throughout the web** on system design principles. 系统设计是一个很宽泛的话题。在互联网上,**关于系统设计原则的资源也是多如牛毛。**
This repo is an **organized collection** of resources to help you learn how to build systems at scale. 这个仓库就是这些资源的**有组织的集合**,它可以帮助你学习如何构建可扩展的系统。
### Learn from the open source community ### 从开源社区学习
This is an early draft of a continually updated, open source project. 这是一个不断更新的开源项目的初期的版本。
[Contributions](#contributing) are welcome! 欢迎 [贡献](#contributing)
### Prep for the system design interview ### 为系统设计面试做准备
In addition to coding interviews, system design is a **required component** of the **technical interview process** at many tech companies. 在很多科技公司中,除了代码面试,系统设计也是**技术面试过程**中的一个**必要环节**。
**Practice common system design interview questions** and **compare** your results with **sample solutions**: discussions, code, and diagrams. **练习普通的系统设计面试题**并且把你的结果和**例子的解答**进行**对照**:讨论,代码和图表。
Additional topics for interview prep: 面试准备的其他主题:
* [Study guide](#study-guide) * [学习指引](#study-guide)
* [How to approach a system design interview question](#how-to-approach-a-system-design-interview-question) * [如何回答一个系统设计面试题](#how-to-approach-a-system-design-interview-question)
* [System design interview questions, **with solutions**](#system-design-interview-questions-with-solutions) * [系统设计面试题, **含解答**](#system-design-interview-questions-with-solutions)
* [Object-oriented design interview questions, **with solutions**](#object-oriented-design-interview-questions-with-solutions) * [面向对象设计面试题, **含解答**](#object-oriented-design-interview-questions-with-solutions)
* [Additional system design interview questions](#additional-system-design-interview-questions) * [其他系统设计面试题](#additional-system-design-interview-questions)
## Anki flashcards ## 抽认卡
<p align="center"> <p align="center">
<img src="http://i.imgur.com/zdCAkB3.png"> <img src="http://i.imgur.com/zdCAkB3.png">
<br/> <br/>
</p> </p>
The provided [Anki flashcard decks](https://apps.ankiweb.net/) use spaced repetition to help you retain key system design concepts. 这里提供的 [抽认卡堆](https://apps.ankiweb.net/) 使用间隔重复的方法帮助你记住系统设计的概念。
* [System design deck](resources/flash_cards/System%20Design.apkg) * [系统设计卡堆](resources/flash_cards/System%20Design.apkg)
* [System design exercises deck](resources/flash_cards/System%20Design%20Exercises.apkg) * [系统设计练习卡堆](resources/flash_cards/System%20Design%20Exercises.apkg)
* [Object oriented design exercises deck](resources/flash_cards/OO%20Design.apkg) * [面向对象设计练习卡堆](resources/flash_cards/OO%20Design.apkg)
Great for use while on-the-go. 用起来非常棒。
## Contributing ## 贡献
> Learn from the community. > 向社区学习。
Feel free to submit pull requests to help: 欢迎提交 PR 提供帮助:
* Fix errors * 修复错误
* Improve sections * 完善章节
* Add new sections * 添加章节
Content that needs some polishing is placed [under development](#under-development). 一些还需要完善的内容放在了[开发中](#under-development)。
Review the [Contributing Guidelines](CONTRIBUTING.md). 查看 [贡献指导](CONTRIBUTING.md)。
### Translations ### 翻译
Interested in **translating**? Please see the following [ticket](https://github.com/donnemartin/system-design-primer/issues/28). 对**翻译**感兴趣?请查看这个 [链接](https://github.com/donnemartin/system-design-primer/issues/28)。
## Index of system design topics ## 系统设计主题的索引
> Summaries of various system design topics, including pros and cons. **Everything is a trade-off**. > 各种系统设计主题的摘要,包括优点和缺点。**每一个主题都面临着取舍和权衡**。
> >
> Each section contains links to more in-depth resources. > 每个章节都包含更深层次的资源的链接。
<p align="center"> <p align="center">
<img src="http://i.imgur.com/jrUBAF7.png"> <img src="http://i.imgur.com/jrUBAF7.png">
<br/> <br/>
</p> </p>
* [System design topics: start here](#system-design-topics-start-here) * [系统设计主题:从这里开始](#system-design-topics-start-here)
* [Step 1: Review the scalability video lecture](#step-1-review-the-scalability-video-lecture) * [第一步:回顾可扩展性的视频讲座](#step-1-review-the-scalability-video-lecture)
* [Step 2: Review the scalability article](#step-2-review-the-scalability-article) * [第二步: 回顾可扩展性的文章](#step-2-review-the-scalability-article)
* [Next steps](#next-steps) * [接下来的步骤](#next-steps)
* [Performance vs scalability](#performance-vs-scalability) * [性能与拓展性](#performance-vs-scalability)
* [Latency vs throughput](#latency-vs-throughput) * [延迟与吞吐量](#latency-vs-throughput)
* [Availability vs consistency](#availability-vs-consistency) * [可用性与一致性](#availability-vs-consistency)
* [CAP theorem](#cap-theorem) * [CAP 理论](#cap-theorem)
* [CP - consistency and partition tolerance](#cp---consistency-and-partition-tolerance) * [CP - 一致性和分区容错性](#cp---consistency-and-partition-tolerance)
* [AP - availability and partition tolerance](#ap---availability-and-partition-tolerance) * [AP - 可用性和分区容错性](#ap---availability-and-partition-tolerance)
* [Consistency patterns](#consistency-patterns) * [一致模式](#consistency-patterns)
* [Weak consistency](#weak-consistency) * [弱一致性](#weak-consistency)
* [Eventual consistency](#eventual-consistency) * [最终一致性](#eventual-consistency)
* [Strong consistency](#strong-consistency) * [强一致性](#strong-consistency)
* [Availability patterns](#availability-patterns) * [可用模式](#availability-patterns)
* [Fail-over](#fail-over) * [故障转移](#fail-over)
* [Replication](#replication) * [复制](#replication)
* [Domain name system](#domain-name-system) * [域名系统](#domain-name-system)
* [Content delivery network](#content-delivery-network) * [CDN](#content-delivery-network)
* [Push CDNs](#push-cdns) * [CDN 推送](#push-cdns)
* [Pull CDNs](#pull-cdns) * [CDN 拉取](#pull-cdns)
* [Load balancer](#load-balancer) * [负载均衡器](#load-balancer)
* [Active-passive](#active-passive) * [工作到备用切换(active-passive)](#active-passive)
* [Active-active](#active-active) * [双工作切换(active-active)](#active-active)
* [Layer 4 load balancing](#layer-4-load-balancing) * [4 层负载均衡](#layer-4-load-balancing)
* [Layer 7 load balancing](#layer-7-load-balancing) * [7 层负载均衡](#layer-7-load-balancing)
* [Horizontal scaling](#horizontal-scaling) * [水平拓展](#horizontal-scaling)
* [Reverse proxy (web server)](#reverse-proxy-web-server) * [反向代理web 服务)](#reverse-proxy-web-server)
* [Load balancer vs reverse proxy](#load-balancer-vs-reverse-proxy) * [负载均衡 vs 反向代理](#load-balancer-vs-reverse-proxy)
* [Application layer](#application-layer) * [应用层](#application-layer)
* [Microservices](#microservices) * [微服务](#microservices)
* [Service discovery](#service-discovery) * [服务发现](#service-discovery)
* [Database](#database) * [数据库](#database)
* [Relational database management system (RDBMS)](#relational-database-management-system-rdbms) * [关系型数据库管理系统 (RDBMS)](#relational-database-management-system-rdbms)
* [Master-slave replication](#master-slave-replication) * [Master-slave 复制集](#master-slave-replication)
* [Master-master replication](#master-master-replication) * [Master-master 复制集](#master-master-replication)
* [Federation](#federation) * [联合](#federation)
* [Sharding](#sharding) * [分片](#sharding)
* [Denormalization](#denormalization) * [反规则化](#denormalization)
* [SQL tuning](#sql-tuning) * [SQL 笔试题](#sql-tuning)
* [NoSQL](#nosql) * [NoSQL](#nosql)
* [Key-value store](#key-value-store) * [Key-value 存储](#key-value-store)
* [Document store](#document-store) * [文档存储](#document-store)
* [Wide column store](#wide-column-store) * [宽列存储](#wide-column-store)
* [Graph Database](#graph-database) * [图数据库](#graph-database)
* [SQL or NoSQL](#sql-or-nosql) * [SQL 还是 NoSQL](#sql-or-nosql)
* [Cache](#cache) * [缓存](#cache)
* [Client caching](#client-caching) * [客户端缓存](#client-caching)
* [CDN caching](#cdn-caching) * [CDN 缓存](#cdn-caching)
* [Web server caching](#web-server-caching) * [Web 服务器缓存](#web-server-caching)
* [Database caching](#database-caching) * [数据库缓存](#database-caching)
* [Application caching](#application-caching) * [应用缓存](#application-caching)
* [Caching at the database query level](#caching-at-the-database-query-level) * [数据库查询级别的缓存](#caching-at-the-database-query-level)
* [Caching at the object level](#caching-at-the-object-level) * [对象级别的缓存](#caching-at-the-object-level)
* [When to update the cache](#when-to-update-the-cache) * [何时更新缓存](#when-to-update-the-cache)
* [Cache-aside](#cache-aside) * [缓存模式](#cache-aside)
* [Write-through](#write-through) * [直写模式](#write-through)
* [Write-behind (write-back)](#write-behind-write-back) * [回写模式](#write-behind-write-back)
* [Refresh-ahead](#refresh-ahead) * [刷新](#refresh-ahead)
* [Asynchronism](#asynchronism) * [异步](#asynchronism)
* [Message queues](#message-queues) * [消息队列](#message-queues)
* [Task queues](#task-queues) * [任务队列](#task-queues)
* [Back pressure](#back-pressure) * [背压机制](#back-pressure)
* [Communication](#communication) * [通讯](#communication)
* [Transmission control protocol (TCP)](#transmission-control-protocol-tcp) * [传输控制协议 (TCP)](#transmission-control-protocol-tcp)
* [User datagram protocol (UDP)](#user-datagram-protocol-udp) * [用户数据报协议 (UDP)](#user-datagram-protocol-udp)
* [Remote procedure call (RPC)](#remote-procedure-call-rpc) * [远程控制调用 (RPC)](#remote-procedure-call-rpc)
* [Representational state transfer (REST)](#representational-state-transfer-rest) * [表述性状态转移 (REST)](#representational-state-transfer-rest)
* [Security](#security) * [网络安全](#security)
* [Appendix](#appendix) * [附录](#appendix)
* [Powers of two table](#powers-of-two-table) * [两张表的威力](#powers-of-two-table)
* [Latency numbers every programmer should know](#latency-numbers-every-programmer-should-know) * [每一位程序员应该知道的数字误差](#latency-numbers-every-programmer-should-know)
* [Additional system design interview questions](#additional-system-design-interview-questions) * [其他系统设计面试题](#additional-system-design-interview-questions)
* [Real world architectures](#real-world-architectures) * [真实架构](#real-world-architectures)
* [Company architectures](#company-architectures) * [公司架构](#company-architectures)
* [Company engineering blogs](#company-engineering-blogs) * [公司工程博客](#company-engineering-blogs)
* [Under development](#under-development) * [开发中](#under-development)
* [Credits](#credits) * [致谢](#credits)
* [Contact info](#contact-info) * [联系方式](#contact-info)
* [License](#license) * [许可](#license)
## Study guide ## 学习指引
> Suggested topics to review based on your interview timeline (short, medium, long). > 基于你面试的时间线(短,中,长)去复习那些推荐的主题。
![Imgur](http://i.imgur.com/OfVllex.png) ![Imgur](http://i.imgur.com/OfVllex.png)
**Q: For interviews, do I need to know everything here?** **问:对于面试来说,我需要知道这里的所有知识点吗?**
**A: No, you don't need to know everything here to prepare for the interview**. **答:不,如果只是为了准备面试的话,你并不需要知道所有的知识点。**
What you are asked in an interview depends on variables such as: 在一场面试中你会被问到什么取决于下面这些因素:
* How much experience you have * 你的经验
* What your technical background is * 你的技术背景
* What positions you are interviewing for * 你面试的职位
* Which companies you are interviewing with * 你面试的公司
* Luck * 运气
More experienced candidates are generally expected to know more about system design. Architects or team leads might be expected to know more than individual contributors. Top tech companies are likely to have one or more design interview rounds. 那些有经验的候选人通常会被期望了解更多的系统设计的知识。架构师或者团队负责人则会被期望了解更多除了个人贡献之外的知识。顶级的科技公司通常也会有一次或者更多的系统设计面试。
Start broad and go deeper in a few areas. It helps to know a little about various key system design topics. Adjust the following guide based on your timeline, experience, what positions you are interviewing for, and which companies you are interviewing with. 面试会很宽泛的展开并在几个领域深入。这回帮助你了解一些关于系统设计的不同的主题。基于你的时间线,经验,面试的职位和面试的公司对下面的指导做出适当的调整。
* **Short timeline** - Aim for **breadth** with system design topics. Practice by solving **some** interview questions. * **短期** - 以系统设计主题的**广度**为目标。通过解决**一些**面试题来练习。
* **Medium timeline** - Aim for **breadth** and **some depth** with system design topics. Practice by solving **many** interview questions. * **中期** - 以系统设计主题的**广度**和**初级深度**为目标。通过解决**很多**面试题来练习。
* **Long timeline** - Aim for **breadth** and **more depth** with system design topics. Practice by solving **most** interview questions. * **长期** - 以系统设计主题的**广度**和**高级深度**为目标。通过解决**大部分**面试题来联系。
| | Short | Medium | Long | | | 短期 | 中期 | 长期 |
| ---------------------------------------- | ----- | ------ | ---- | | ---------------------------------------- | ---- | ---- | ---- |
| Read through the [System design topics](#index-of-system-design-topics) to get a broad understanding of how systems work | :+1: | :+1: | :+1: | | 阅读 [系统设计主题](#index-of-system-design-topics) 以获得一个关于系统如何工作的宽泛的认识 | :+1: | :+1: | :+1: |
| Read through a few articles in the [Company engineering blogs](#company-engineering-blogs) for the companies you are interviewing with | :+1: | :+1: | :+1: | | 阅读一些你要面试的 [公司工程博客](#company-engineering-blogs) 的文章 | :+1: | :+1: | :+1: |
| Read through a few [Real world architectures](#real-world-architectures) | :+1: | :+1: | :+1: | | 阅读 [真实世界的架构](#real-world-architectures) | :+1: | :+1: | :+1: |
| Review [How to approach a system design interview question](#how-to-approach-a-system-design-interview-question) | :+1: | :+1: | :+1: | | 复习 [如何处理一个系统设计面试题](#how-to-approach-a-system-design-interview-question) | :+1: | :+1: | :+1: |
| Work through [System design interview questions with solutions](#system-design-interview-questions-with-solutions) | Some | Many | Most | | 完成 [系统设计面试题和解答](#system-design-interview-questions-with-solutions) | 一些 | 很多 | 大部分 |
| Work through [Object-oriented design interview questions with solutions](#object-oriented-design-interview-questions-with-solutions) | Some | Many | Most | | 完成 [面向对象设计面试题和解答](#object-oriented-design-interview-questions-with-solutions) | 一些 | 很多 | 大部分 |
| Review [Additional system design interview questions](#additional-system-design-interview-questions) | Some | Many | Most | | 复习 [其他系统设计面试题和解答](#additional-system-design-interview-questions) | 一些 | 很多 | 大部分 |
## 如何处理一个系统设计面试题
## How to approach a system design interview question > 如何处理一个系统设计面试题。
> How to tackle a system design interview question. 系统设计面试是一个**开放式的对话**。他们期望你去主导这个对话。
The system design interview is an **open-ended conversation**. You are expected to lead it. 你可以使用下面的步骤来指引讨论。为了巩固这个过程,请使用下面的步骤完成 [系统设计面试题和解答](#system-design-interview-questions-with-solutions) 这个章节。
You can use the following steps to guide the discussion. To help solidify this process, work through the [System design interview questions with solutions](#system-design-interview-questions-with-solutions) section using the following steps. ### 第一步:描述使用场景,约束和假设
### Step 1: Outline use cases, constraints, and assumptions 把所有需要的东西聚集在一起,审视问题。不停的提问,以至于我们可以明确使用场景和约束。讨论假设。
Gather requirements and scope the problem. Ask questions to clarify use cases and constraints. Discuss assumptions. * 谁会使用它?
* 他们会怎样使用它?
* 有多少用户?
* 系统的作用是什么?
* 系统的输入输出分别是什么?
* 我们希望处理多少数据?
* 我们希望每秒钟处理多少请求?
* 我们希望的读写比率?
* Who is going to use it? ### 第二步:创造一个高级的设计
* How are they going to use it?
* How many users are there?
* What does the system do?
* What are the inputs and outputs of the system?
* How much data do we expect to handle?
* How many requests per second do we expect?
* What is the expected read to write ratio?
### Step 2: Create a high level design 使用所有重要的组件来描绘出一个高级的设计。
Outline a high level design with all important components. * 画出主要的组件和连接
* 证明你的想法
* Sketch the main components and connections ### 第三步:设计核心组件
* Justify your ideas
### Step 3: Design core components 对每一个核心组件进行详细深入的分析。举例来说,如果你被问到 [设计一个 url 缩写服务](solutions/system_design/pastebin/README.md),开始讨论:
Dive into details for each core component. For example, if you were asked to [design a url shortening service](solutions/system_design/pastebin/README.md), discuss: * 生成并储存一个完整 url 的 hash
* [MD5](solutions/system_design/pastebin/README.md) 和 [Base62](solutions/system_design/pastebin/README.md)
* Hash 碰撞
* SQL 还是 NoSQL
* 数据库模型
* 将一个 hashed url 翻译成完整的 url
* 数据库查找
* API 和面向对象设计
* Generating and storing a hash of the full url ### 第四步:度量设计
* [MD5](solutions/system_design/pastebin/README.md) and [Base62](solutions/system_design/pastebin/README.md)
* Hash collisions
* SQL or NoSQL
* Database schema
* Translating a hashed url to the full url
* Database lookup
* API and object-oriented design
### Step 4: Scale the design 确认和处理瓶颈以及一些限制。举例来说就是你需要下面的这些来完成拓展性的议题吗?
Identify and address bottlenecks, given the constraints. For example, do you need the following to address scalability issues? * 负载均衡
* 水平拓展
* 缓存
* 数据库分片
* Load balancer 论述可能的解决办法和代价。每件事情需要取舍。可以使用 [可拓展系统的设计原则](#index-of-system-design-topics) 来处理瓶颈。
* Horizontal scaling
* Caching
* Database sharding
Discuss potential solutions and trade-offs. Everything is a trade-off. Address bottlenecks using [principles of scalable system design](#index-of-system-design-topics). ### 信封背面的计算
### Back-of-the-envelope calculations 你或许会被要求通过手算进行一些估算。涉及到的 [附录](#appendix) 涉及到的是下面的这些资源:
You might be asked to do some estimates by hand. Refer to the [Appendix](#appendix) for the following resources: * [使用信封的背面做计算](http://highscalability.com/blog/2011/1/26/google-pro-tip-use-back-of-the-envelope-calculations-to-choo.html)
* [两张表的威力](#powers-of-two-table)
* [每一位程序员都应该知道的数字误差](#latency-numbers-every-programmer-should-know)
* [Use back of the envelope calculations](http://highscalability.com/blog/2011/1/26/google-pro-tip-use-back-of-the-envelope-calculations-to-choo.html) ### 相关资源和延伸阅读
* [Powers of two table](#powers-of-two-table)
* [Latency numbers every programmer should know](#latency-numbers-every-programmer-should-know)
### Source(s) and further reading 查看下面的链接以获得我们期望的更好的想法:
Check out the following links to get a better idea of what to expect: * [怎样通过一个系统设计面试](https://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/)
* [系统设计面试](http://www.hiredintech.com/system-design)
* [系统架构与设计面试简介](https://www.youtube.com/watch?v=ZgdS0EUmn70)
* [How to ace a systems design interview](https://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/) ## 系统设计面试题和解答
* [The system design interview](http://www.hiredintech.com/system-design)
* [Intro to Architecture and Systems Design Interviews](https://www.youtube.com/watch?v=ZgdS0EUmn70)
## System design interview questions with solutions > 普通的系统设计面试题和相关事例的论述,代码和图表。
> Common system design interview questions with sample discussions, code, and diagrams.
> >
> Solutions linked to content in the `solutions/` folder. > 与内容有关的解答在 `solutions/` 文件夹中。
| 问题 | |
| Question | |
| ---------------------------------------- | ---------------------------------------- | | ---------------------------------------- | ---------------------------------------- |
| Design Pastebin.com (or Bit.ly) | [Solution](solutions/system_design/pastebin/README.md) | | 设计 Pastebin.com (或者 Bit.ly) | [解答](solutions/system_design/pastebin/README.md) |
| Design the Twitter timeline (or Facebook feed)<br/>Design Twitter search (or Facebook search) | [Solution](solutions/system_design/twitter/README.md) | | 设计 Twitter 时间线和搜索 (或者 Facebook feed 和搜索) | [解答](solutions/system_design/twitter/README.md) |
| Design a web crawler | [Solution](solutions/system_design/web_crawler/README.md) | | 设计一个网页爬虫 | [解答](solutions/system_design/web_crawler/README.md) |
| Design Mint.com | [Solution](solutions/system_design/mint/README.md) | | 设计 Mint.com | [解答](solutions/system_design/mint/README.md) |
| Design the data structures for a social network | [Solution](solutions/system_design/social_graph/README.md) | | 为一个社交网络设计数据结构 | [解答](solutions/system_design/social_graph/README.md) |
| Design a key-value store for a search engine | [Solution](solutions/system_design/query_cache/README.md) | | 为搜索引擎设计一个 key-value 储存 | [解答](solutions/system_design/query_cache/README.md) |
| Design Amazon's sales ranking by category feature | [Solution](solutions/system_design/sales_rank/README.md) | | 通过分类特性设计 Amazon 的销售排名 | [解答](solutions/system_design/sales_rank/README.md) |
| Design a system that scales to millions of users on AWS | [Solution](solutions/system_design/scaling_aws/README.md) | | 在 AWS 上设计一个百万用户级别的系统 | [解答](solutions/system_design/scaling_aws/README.md) |
| Add a system design question | [Contribute](#contributing) | | 添加一个系统设计问题 | [贡献](#contributing) |
### Design Pastebin.com (or Bit.ly) ### 设计 Pastebin.com (或者 Bit.ly)
[View exercise and solution](solutions/system_design/pastebin/README.md) [查看练习和解答](solutions/system_design/pastebin/README.md)
![Imgur](http://i.imgur.com/4edXG0T.png) ![Imgur](http://i.imgur.com/4edXG0T.png)
### Design the Twitter timeline and search (or Facebook feed and search) ### 设计 Twitter 时间线和搜索 (或者 Facebook feed 和搜索)
[View exercise and solution](solutions/system_design/twitter/README.md) [查看练习和解答](solutions/system_design/twitter/README.md)
![Imgur](http://i.imgur.com/jrUBAF7.png) ![Imgur](http://i.imgur.com/jrUBAF7.png)
### Design a web crawler ### 设计一个网页爬虫
[View exercise and solution](solutions/system_design/web_crawler/README.md) [查看练习和解答](solutions/system_design/web_crawler/README.md)
![Imgur](http://i.imgur.com/bWxPtQA.png) ![Imgur](http://i.imgur.com/bWxPtQA.png)
### Design Mint.com ### 设计 Mint.com
[View exercise and solution](solutions/system_design/mint/README.md) [查看练习和解答](solutions/system_design/mint/README.md)
![Imgur](http://i.imgur.com/V5q57vU.png) ![Imgur](http://i.imgur.com/V5q57vU.png)
### Design the data structures for a social network ### 为一个社交网络设计数据结构
[View exercise and solution](solutions/system_design/social_graph/README.md) [查看练习和解答](solutions/system_design/social_graph/README.md)
![Imgur](http://i.imgur.com/cdCv5g7.png) ![Imgur](http://i.imgur.com/cdCv5g7.png)
### Design a key-value store for a search engine ### 为搜索引擎设计一个 key-value 储存
[View exercise and solution](solutions/system_design/query_cache/README.md) [查看练习和解答](solutions/system_design/query_cache/README.md)
![Imgur](http://i.imgur.com/4j99mhe.png) ![Imgur](http://i.imgur.com/4j99mhe.png)
### Design Amazon's sales ranking by category feature ### 通过分类特性设计 Amazon 的销售排名
[View exercise and solution](solutions/system_design/sales_rank/README.md) [查看练习和解答](solutions/system_design/sales_rank/README.md)
![Imgur](http://i.imgur.com/MzExP06.png) ![Imgur](http://i.imgur.com/MzExP06.png)
### Design a system that scales to millions of users on AWS ### 在 AWS 上设计一个百万用户级别的系统
[View exercise and solution](solutions/system_design/scaling_aws/README.md) [查看练习和解答](solutions/system_design/scaling_aws/README.md)
![Imgur](http://i.imgur.com/jj3A5N8.png) ![Imgur](http://i.imgur.com/jj3A5N8.png)
## Object-oriented design interview questions with solutions ## 面向对象设计面试问题及解答
> Common object-oriented design interview questions with sample discussions, code, and diagrams. > 常见面向对象设计面试问题及实例讨论,代码和图表演示。
> >
> Solutions linked to content in the `solutions/` folder. > 与内容相关的解决方案在 `solutions/` 文件夹中。
>**Note: This section is under development** >**注:此节还在完善中**
| Question | | | 问题 | |
| -------------------------------------- | ---------------------------------------- | |---|---|
| Design a hash map | [Solution](solutions/object_oriented_design/hash_table/hash_map.ipynb) | | 设计 hash map | [解决方案](solutions/object_oriented_design/hash_table/hash_map.ipynb) |
| Design a least recently used cache | [Solution](solutions/object_oriented_design/lru_cache/lru_cache.ipynb) | | 设计 LRU 缓存 | [解决方案](solutions/object_oriented_design/lru_cache/lru_cache.ipynb) |
| Design a call center | [Solution](solutions/object_oriented_design/call_center/call_center.ipynb) | | 设计一个呼叫中心 | [解决方案](solutions/object_oriented_design/call_center/call_center.ipynb) |
| Design a deck of cards | [Solution](solutions/object_oriented_design/deck_of_cards/deck_of_cards.ipynb) | | 设计一副牌 | [解决方案](solutions/object_oriented_design/deck_of_cards/deck_of_cards.ipynb) |
| Design a parking lot | [Solution](solutions/object_oriented_design/parking_lot/parking_lot.ipynb) | | 设计一个停车场 | [解决方案](solutions/object_oriented_design/parking_lot/parking_lot.ipynb) |
| Design a chat server | [Solution](solutions/object_oriented_design/online_chat/online_chat.ipynb) | | 设计一个聊天服务 | [解决方案](solutions/object_oriented_design/online_chat/online_chat.ipynb) |
| Design a circular array | [Contribute](#contributing) | | 设计一个环形数组 | [待解决](#contributing) |
| Add an object-oriented design question | [Contribute](#contributing) | | 添加一个面向对象设计问题 | [待解决](#contributing) |
## System design topics: start here ## 系统设计主题:从这里开始
New to system design? 不熟悉系统设计?
First, you'll need a basic understanding of common principles, learning about what they are, how they are used, and their pros and cons. 首先,你需要对一般性原则有一个基本的认识,知道它们是什么,怎样使用以及利弊。
### Step 1: Review the scalability video lecture ### 第一步回顾可扩展性scalability的视频讲座
[Scalability Lecture at Harvard](https://www.youtube.com/watch?v=-W9F__D3oY4) [哈佛大学可扩展性讲座](https://www.youtube.com/watch?v=-W9F__D3oY4)
* Topics covered: * 主题涵盖
* Vertical scaling * 垂直扩展(Vertical scaling
* Horizontal scaling * 水平扩展(Horizontal scaling
* Caching * 缓存
* Load balancing * 负载均衡
* Database replication * 数据库复制
* Database partitioning * 数据库分区
### Step 2: Review the scalability article ### 第二步:回顾可扩展性文章
[Scalability](http://www.lecloud.net/tagged/scalability) [可扩展性](http://www.lecloud.net/tagged/scalability)
* Topics covered: * 主题涵盖:
* [Clones](http://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones) * [Clones](http://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones)
* [Databases](http://www.lecloud.net/post/7994751381/scalability-for-dummies-part-2-database) * [数据库](http://www.lecloud.net/post/7994751381/scalability-for-dummies-part-2-database)
* [Caches](http://www.lecloud.net/post/9246290032/scalability-for-dummies-part-3-cache) * [缓存](http://www.lecloud.net/post/9246290032/scalability-for-dummies-part-3-cache)
* [Asynchronism](http://www.lecloud.net/post/9699762917/scalability-for-dummies-part-4-asynchronism) * [异步](http://www.lecloud.net/post/9699762917/scalability-for-dummies-part-4-asynchronism)
### Next steps ### 接下来的步骤
Next, we'll look at high-level trade-offs: 接下来,我们将看看高阶的权衡和取舍:
* **Performance** vs **scalability** * **性能**与**可扩展性**
* **Latency** vs **throughput** * **延迟**与**吞吐量**
* **Availability** vs **consistency** * **可用性**与**一致性**
Keep in mind that **everything is a trade-off**. 记住**每个方面都面临取舍和权衡**。
Then we'll dive into more specific topics such as DNS, CDNs, and load balancers. 然后,我们将深入更具体的主题,如 DNSCDN 和负载均衡器。
## Performance vs scalability ## 性能与可扩展性
A service is **scalable** if it results in increased **performance** in a manner proportional to resources added. Generally, increasing performance means serving more units of work, but it can also be to handle larger units of work, such as when datasets grow.<sup><a href=http://www.allthingsdistributed.com/2006/03/a_word_on_scalability.html>1</a></sup> 如果服务**性能**的增长与资源的增加是成比例的,服务就是可扩展的。通常,提高性能意味着服务于更多的工作单元,另一方面,当数据集增长时,同样也可以处理更大的工作单位。<sup><a href=http://www.allthingsdistributed.com/2006/03/a_word_on_scalability.html>1</a></sup>
Another way to look at performance vs scalability: 另一个角度来看待性能与可扩展性:
* If you have a **performance** problem, your system is slow for a single user. * 如果你的系统有**性能**问题,对于单个用户来说是缓慢的。
* If you have a **scalability** problem, your system is fast for a single user but slow under heavy load. * 如果你的系统有**可扩展性**问题,单个用户较快但在高负载下会变慢。
### Source(s) and further reading ### 来源及延伸阅读
* [A word on scalability](http://www.allthingsdistributed.com/2006/03/a_word_on_scalability.html) * [简单谈谈可扩展性](http://www.allthingsdistributed.com/2006/03/a_word_on_scalability.html)
* [Scalability, availability, stability, patterns](http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) * [可扩展性,可用性,稳定性和模式](http://www.slideshare.net/jboner/scalability-availability-stability-patterns/)
## Latency vs throughput ## 延迟与吞吐量
**Latency** is the time to perform some action or to produce some result. **延迟**是执行操作或运算结果所花费的时间。
**Throughput** is the number of such actions or results per unit of time. **吞吐量**是单位时间内(执行)此类操作或运算的数量。
Generally, you should aim for **maximal throughput** with **acceptable latency**. 通常,你应该以**可接受级延迟**下**最大化吞吐量**为目标。
### Source(s) and further reading ### 来源及延伸阅读
* [Understanding latency vs throughput](https://community.cadence.com/cadence_blogs_8/b/sd/archive/2010/09/13/understanding-latency-vs-throughput) * [理解延迟与吞吐量](https://community.cadence.com/cadence_blogs_8/b/sd/archive/2010/09/13/understanding-latency-vs-throughput)
## Availability vs consistency ## 可用性与一致性
### CAP theorem ### CAP 理论
<p align="center"> <p align="center">
<img src="http://i.imgur.com/bgLMI2u.png"> <img src="http://i.imgur.com/bgLMI2u.png">
<br/> <br/>
<i><a href=http://robertgreiner.com/2014/08/cap-theorem-revisited>Source: CAP theorem revisited</a></i> <i><a href=http://robertgreiner.com/2014/08/cap-theorem-revisited>来源:再看 CAP 理论</a></i>
</p> </p>
In a distributed computer system, you can only support two of the following guarantees: 在一个分布式计算系统中,只能同时满足下列的两点:
* **Consistency** - Every read receives the most recent write or an error * **一致性** ─ 每次访问都能获得最新数据但可能会收到错误响应
* **Availability** - Every request receives a response, without guarantee that it contains the most recent version of the information * **可用性** ─ 每次访问都能收到非错响应,但不保证获取到最新数据
* **Partition Tolerance** - The system continues to operate despite arbitrary partitioning due to network failures * **分区容错性** ─ 在任意分区网络故障的情况下系统仍能继续运行
*Networks aren't reliable, so you'll need to support partition tolerance. You'll need to make a software tradeoff between consistency and availability.* *网络并不可靠,所以你应要支持分区容错性,并需要在软件可用性和一致性间做出取舍。*
#### CP - consistency and partition tolerance #### CP ─ 一致性和分区容错性
Waiting for a response from the partitioned node might result in a timeout error. CP is a good choice if your business needs require atomic reads and writes. 等待分区节点的响应可能会导致延时错误。如果你的业务需求需要原子读写CP 是一个不错的选择。
#### AP - availability and partition tolerance #### AP ─ 可用性与分区容错性
Responses return the most recent version of the data, which might not be the latest. Writes might take some time to propagate when the partition is resolved. 响应返回的最近版本数据可能并不是最新的。当分区解析完后,写入(操作)可能需要一些时间来传播。
AP is a good choice if the business needs allow for [eventual consistency](#eventual-consistency) or when the system needs to continue working despite external errors. 如果业务需求允许[最终一致性](#eventual-consistency)或当有外部故障时要求系统继续运行AP 是一个不错的选择。
### Source(s) and further reading ### 来源及延伸阅读
* [CAP theorem revisited](http://robertgreiner.com/2014/08/cap-theorem-revisited/) * [再看 CAP 理论](http://robertgreiner.com/2014/08/cap-theorem-revisited/)
* [A plain english introduction to CAP theorem](http://ksat.me/a-plain-english-introduction-to-cap-theorem/) * [通俗易懂地介绍 CAP 理论](http://ksat.me/a-plain-english-introduction-to-cap-theorem/)
* [CAP FAQ](https://github.com/henryr/cap-faq) * [CAP FAQ](https://github.com/henryr/cap-faq)
## Consistency patterns ## 一致性模式
With multiple copies of the same data, we are faced with options on how to synchronize them so clients have a consistent view of the data. Recall the definition of consistency from the [CAP theorem](#cap-theorem) - Every read receives the most recent write or an error. 有同一份数据的多份副本,我们面临着怎样同步它们的选择,以便让客户端有一致的显示数据。回想 [CAP 定理](#cap-theorem)中的一致性定义 ─ 每次访问都能获得最新数据但可能会收到错误响应
### Weak consistency
After a write, reads may or may not see it. A best effort approach is taken. ### 弱一致性
This approach is seen in systems such as memcached. Weak consistency works well in real time use cases such as VoIP, video chat, and realtime multiplayer games. For example, if you are on a phone call and lose reception for a few seconds, when you regain connection you do not hear what was spoken during connection loss. 在写入之后,访问可能看到,也可能看不到(写入数据)。尽力优化之让其能访问最新数据。
### Eventual consistency 这种方式可以 memcached 等系统中看到。弱一致性在 VoIP视频聊天和实时多人游戏等真实用例中表现不错。打个比方如果你在通话中丢失信号几秒钟时间当重新连接时你是听不到这几秒钟所说的话的。
After a write, reads will eventually see it (typically within milliseconds). Data is replicated asynchronously. ### 最终一致性
This approach is seen in systems such as DNS and email. Eventual consistency works well in highly available systems. 在写入后,访问最终能看到写入数据(通常在数毫秒内)。数据被异步复制。
### Strong consistency DNS 和 email 等系统使用的是此种方式。最终一致性在高可用性系统中效果不错。
After a write, reads will see it. Data is replicated synchronously. ### 强一致性
This approach is seen in file systems and RDBMSes. Strong consistency works well in systems that need transactions. 在写入后,访问立即可见。数据被同步复制。
### Source(s) and further reading 文件系统和关系型数据库RDBMS中使用的是此种方式。强一致性在需要记录的系统中运作良好。
### 来源及延伸阅读
* [Transactions across data centers](http://snarfed.org/transactions_across_datacenters_io.html) * [Transactions across data centers](http://snarfed.org/transactions_across_datacenters_io.html)
## Availability patterns ## 可用性模式
There are two main patterns to support high availability: **fail-over** and **replication**. 有两种支持高可用性的模式: **故障切换fail-over**和**复制replication**。
### Fail-over ### 故障切换
#### Active-passive #### 工作到备用切换(Active-passive
With active-passive fail-over, heartbeats are sent between the active and the passive server on standby. If the heartbeat is interrupted, the passive server takes over the active's IP address and resumes service. 关于工作到备用的故障切换流程是,工作服务器发送周期信号给待机中的备用服务器。如果周期信号中断,备用服务器切换成工作服务器的 IP 地址并恢复服务。
The length of downtime is determined by whether the passive server is already running in 'hot' standby or whether it needs to start up from 'cold' standby. Only the active server handles traffic. 宕机时间取决于备用服务器处于“热”待机状态还是需要从“冷”待机状态进行启动。只有工作服务器处理流量。
Active-passive failover can also be referred to as master-slave failover. 工作到备用的故障切换也被称为主从切换。
#### Active-active #### 双工作切换(Active-active
In active-active, both servers are managing traffic, spreading the load between them. 在双工作切换中,双方都在管控流量,在它们之间分散负载。
If the servers are public-facing, the DNS would need to know about the public IPs of both servers. If the servers are internal-facing, application logic would need to know about both servers. 如果是外网服务器DNS 将需要对两方都了解。如果是内网服务器,应用程序逻辑将需要对两方都了解。
Active-active failover can also be referred to as master-master failover. 双工作切换也可以称为主主切换。
### Disadvantage(s): failover ### 缺陷:故障切换
* Fail-over adds more hardware and additional complexity. * 故障切换需要添加额外硬件并增加复杂性。
* There is a potential for loss of data if the active system fails before any newly written data can be replicated to the passive. * 如果新写入数据在能被复制到备用系统之前,工作系统出现了故障,则有可能会丢失数据。
### Replication ### 复制
#### Master-slave and master-master #### 主─从复制和主─主复制
This topic is further discussed in the [Database](#database) section: 这个主题进一步探讨了[数据库](#database)部分:
* [Master-slave replication](#master-slave-replication) * [主─从复制](#master-slave-replication)
* [Master-master replication](#master-master-replication) * [主─主复制](#master-master-replication)
## Domain name system ## 域名系统
<p align="center"> <p align="center">
<img src="http://i.imgur.com/IOyLj4i.jpg"> <img src="http://i.imgur.com/IOyLj4i.jpg">
<br/> <br/>
<i><a href=http://www.slideshare.net/srikrupa5/dns-security-presentation-issa>Source: DNS security presentation</a></i> <i><a href=http://www.slideshare.net/srikrupa5/dns-security-presentation-issa>来源DNS 安全介绍</a></i>
</p> </p>
A Domain Name System (DNS) translates a domain name such as www.example.com to an IP address. 域名系统是把 www.example.com 等域名转换成 IP 地址。
DNS is hierarchical, with a few authoritative servers at the top level. Your router or ISP provides information about which DNS server(s) to contact when doing a lookup. Lower level DNS servers cache mappings, which could become stale due to DNS propagation delays. DNS results can also be cached by your browser or OS for a certain period of time, determined by the [time to live (TTL)](https://en.wikipedia.org/wiki/Time_to_live). 域名系统是分层次的,一些 DNS 服务器位于顶层。当查询(域名) IP 时,路由或 ISP 提供连接 DNS 服务器的信息。较底层的 DNS 服务器缓存映射,它可能会因为 DNS 传播延时而失效。DNS 结果可以缓存在浏览器或操作系统中一段时间,时间长短取决于[存活时间 TTL](https://en.wikipedia.org/wiki/Time_to_live)。
* **NS record (name server)** - Specifies the DNS servers for your domain/subdomain. * **NS 记录(域名服务)** ─ 指定解析域名或子域名的 DNS 服务器。
* **MX record (mail exchange)** - Specifies the mail servers for accepting messages. * **MX 记录(邮件交换)** ─ 指定接收信息的邮件服务器。
* **A record (address)** - Points a name to an IP address. * **A 记录(地址)** ─ 指定域名对应的 IP 地址记录。
* **CNAME (canonical)** - Points a name to another name or `CNAME` (example.com to www.example.com) or to an `A` record. * **CNAME(规范)** ─ 一个域名映射到另一个域名或 `CNAME` 记录example.com 指向 www.example.com或映射到一个 `A` 记录。
Services such as [CloudFlare](https://www.cloudflare.com/dns/) and [Route 53](https://aws.amazon.com/route53/) provide managed DNS services. Some DNS services can route traffic through various methods: [CloudFlare](https://www.cloudflare.com/dns/) 和 [Route 53](https://aws.amazon.com/route53/) 等平台提供管理 DNS 的功能。某些 DNS 服务通过集中方式来路由流量:
* [Weighted round robin](http://g33kinfo.com/info/archives/2657) * [加权轮询调度](http://g33kinfo.com/info/archives/2657)
* Prevent traffic from going to servers under maintenance * 防止流量进入维护中的服务器
* Balance between varying cluster sizes * 在不同大小集群间负载均衡
* A/B testing * A/B 测试
* Latency-based * 基于延迟路由
* Geolocation-based * 基于地理位置路由
### Disadvantage(s): DNS ### 缺陷:DNS
* Accessing a DNS server introduces a slight delay, although mitigated by caching described above. * 虽说缓存可以减轻 DNS 延迟,但连接 DNS 服务器还是带来了轻微的延迟。
* DNS server management could be complex, although they are generally managed by [governments, ISPs, and large companies](http://superuser.com/questions/472695/who-controls-the-dns-servers/472729). * 虽然它们通常由[政府,网络服务提供商和大公司](http://superuser.com/questions/472695/who-controls-the-dns-servers/472729)管理,但 DNS 服务管理仍可能是复杂的。
* DNS services have recently come under [DDoS attack](http://dyn.com/blog/dyn-analysis-summary-of-friday-october-21-attack/), preventing users from accessing websites such as Twitter without knowing Twitter's IP address(es). * DNS 服务最近遭受 [DDoS 攻击](http://dyn.com/blog/dyn-analysis-summary-of-friday-october-21-attack/),阻止不知道 Twtter IP 地址的用户访问 Twiiter。
### Source(s) and further reading ### 来源及延伸阅读
* [DNS architecture](https://technet.microsoft.com/en-us/library/dd197427(v=ws.10).aspx) * [DNS 架构](https://technet.microsoft.com/en-us/library/dd197427(v=ws.10).aspx)
* [Wikipedia](https://en.wikipedia.org/wiki/Domain_Name_System) * [Wikipedia](https://en.wikipedia.org/wiki/Domain_Name_System)
* [DNS articles](https://support.dnsimple.com/categories/dns/) * [关于 DNS 的文章](https://support.dnsimple.com/categories/dns/)
## Content delivery network ## 内容分发网络
<p align="center"> <p align="center">
<img src="http://i.imgur.com/h9TAuGI.jpg"> <img src="http://i.imgur.com/h9TAuGI.jpg">
<br/> <br/>
<i><a href=https://www.creative-artworks.eu/why-use-a-content-delivery-network-cdn/>Source: Why use a CDN</a></i> <i><a href=https://www.creative-artworks.eu/why-use-a-content-delivery-network-cdn/>来源:为什么使用 CDN</a></i>
</p> </p>
A content delivery network (CDN) is a globally distributed network of proxy servers, serving content from locations closer to the user. Generally, static files such as HTML/CSS/JS, photos, and videos are served from CDN, although some CDNs such as Amazon's CloudFront support dynamic content. The site's DNS resolution will tell clients which server to contact. 内容分发网络是一个全球性的代理服务器分布式网络它从靠近用户的位置提供内容。通常HTML/CSS/JS图片和视频等静态内容由 CDN 提供,虽然亚马逊 CloudFront 等也支持动态内容。CDN 的 DNS 解析会告知客户端连接哪台服务器。
Serving content from CDNs can significantly improve performance in two ways: 将内容存储在 CDN 上可以从两个方面来提供性能:
* Users receive content at data centers close to them * 从靠近用户的数据中心提供资源
* Your servers do not have to serve requests that the CDN fulfills * 通过 CDN 你的服务器不必真的处理请求
### Push CDNs ### CDN 推送push
Push CDNs receive new content whenever changes occur on your server. You take full responsibility for providing content, uploading directly to the CDN and rewriting URLs to point to the CDN. You can configure when content expires and when it is updated. Content is uploaded only when it is new or changed, minimizing traffic, but maximizing storage. 当你服务器上内容发生变动时,推送 CDN 接受新内容。你负责提供内容,直接推送给 CDN 并重写 URL 地址以指向 CDN 地址。你可以配置内容到期时间及何时更新。内容只有在更改或新增是才推送,最小化流量,但最大化存储空间。
Sites with a small amount of traffic or sites with content that isn't often updated work well with push CDNs. Content is placed on the CDNs once, instead of being re-pulled at regular intervals.
### Pull CDNs
Pull CDNs grab new content from your server when the first user requests the content. You leave the content on your server and rewrite URLs to point to the CDN. This results in a slower request until the content is cached on the server.
A [time-to-live (TTL)](https://en.wikipedia.org/wiki/Time_to_live) determines how long content is cached. Pull CDNs minimize storage space on the CDN, but can create redundant traffic if files expire and are pulled before they have actually changed. ### CDN 拉取pull
Sites with heavy traffic work well with pull CDNs, as traffic is spread out more evenly with only recently-requested content remaining on the CDN. CDN 拉取是当第一个用户请求该资源时,从服务器上拉取资源。你将内容留在自己的服务器上并重写 URL 指向 CDN 地址。这样请求会更慢,直到内容被缓存在 CDN 上。
### Disadvantage(s): CDN [存活时间TTL](https://en.wikipedia.org/wiki/Time_to_live)决定缓存多久时间。CDN 拉取方式最小化 CDN 上的储存空间,但如果过期文件并在实际更改之前被拉取,则会导致冗余的流量。
* CDN costs could be significant depending on traffic, although this should be weighed with additional costs you would incur not using a CDN. 高流量站点使用 CDN 拉取效果不错,因为只有最近请求的内容保存在 CDN 中,流量才能更平衡地分散。
* Content might be stale if it is updated before the TTL expires it.
* CDNs require changing URLs for static content to point to the CDN.
### Source(s) and further reading ### 缺陷CDN
* [Globally distributed content delivery](http://repository.cmu.edu/cgi/viewcontent.cgi?article=2112&context=compsci) * CDN 成本可能因流量而异,可能在权衡之后你将不会使用 CDN。
* [The differences between push and pull CDNs](http://www.travelblogadvice.com/technical/the-differences-between-push-and-pull-cdns/) * 如果在 TTL 过期之前更新内容CDN 缓存内容可能会过时。
* CDN 需要更改静态内容的 URL 地址以指向 CDN。
### 来源及延伸阅读
* [全球性内容分发网络](http://repository.cmu.edu/cgi/viewcontent.cgi?article=2112&context=compsci)
* [CDN 拉取和 CDN 推送的区别](http://www.travelblogadvice.com/technical/the-differences-between-push-and-pull-cdns/)
* [Wikipedia](https://en.wikipedia.org/wiki/Content_delivery_network) * [Wikipedia](https://en.wikipedia.org/wiki/Content_delivery_network)
## Load balancer ## 负载均衡器
<p align="center"> <p align="center">
<img src="http://i.imgur.com/h81n9iK.png"> <img src="http://i.imgur.com/h81n9iK.png">
@ -608,67 +609,66 @@ Sites with heavy traffic work well with pull CDNs, as traffic is spread out more
<i><a href=http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html>Source: Scalable system design patterns</a></i> <i><a href=http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html>Source: Scalable system design patterns</a></i>
</p> </p>
Load balancers distribute incoming client requests to computing resources such as application servers and databases. In each case, the load balancer returns the response from the computing resource to the appropriate client. Load balancers are effective at: 负载均衡器将传入的请求分发到应用服务器和数据库等计算资源。无论哪种情况,负载均衡器将从计算资源来的响应返回给恰当的客户端。负载均衡器的效用在于:
* Preventing requests from going to unhealthy servers * 防止请求进入不好的服务器
* Preventing overloading resources * 防止资源过载
* Helping eliminate single points of failure * 帮助消除单一的故障点
Load balancers can be implemented with hardware (expensive) or with software such as HAProxy. 负载均衡器可以通过硬件(昂贵)或 HAProxy 等软件来实现。
增加的好处包括:
Additional benefits include: * **SSL 终结** ─ 解密传入的请求并加密服务器响应,这样的话后端服务器就不必再执行这些潜在高消耗运算了。
* 不需要再每台服务器上安装 [X.509 证书](https://en.wikipedia.org/wiki/X.509)。
* **Session 留存** ─ 如果 Web 应用程序不追踪会话,发出 cookie 并将特定客户端的请求路由到同一实例。
* **SSL termination** - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations 通常会设置采用[工作─备用](#active-passive) 或 [双工作](#active-active) 模式的多个负载均衡器,以免发生故障。
* Removes the need to install [X.509 certificates](https://en.wikipedia.org/wiki/X.509) on each server
* **Session persistence** - Issue cookies and route a specific client's requests to same instance if the web apps do not keep track of sessions
To protect against failures, it's common to set up multiple load balancers, either in [active-passive](#active-passive) or [active-active](#active-active) mode. 负载均衡器能基于多种方式来路由流量:
Load balancers can route traffic based on various metrics, including: * 随机
* 最少负载
* Session/cookie
* [轮询调度或加权轮询调度算法](http://g33kinfo.com/info/archives/2657)
* [四层负载均衡](#layer-4-load-balancing)
* [七层负载均衡](#layer-7-load-balancing)
* Random ### 四层负载均衡
* Least loaded
* Session/cookies
* [Round robin or weighted round robin](http://g33kinfo.com/info/archives/2657)
* [Layer 4](#layer-4-load-balancing)
* [Layer 7](#layer-7-load-balancing)
### Layer 4 load balancing 四层负载均衡根据监看[传输层](#communication)的信息来决定如何分发请求。通常,这会涉及来源,目标 IP 地址和请求头中的端口,但不包括数据包(报文)内容。四层负载均衡执行[网络地址转换NAT](https://www.nginx.com/resources/glossary/layer-4-load-balancing/)来向上游服务器转发网络数据包。
Layer 4 load balancers look at info at the [transport layer](#communication) to decide how to distribute requests. Generally, this involves the source, destination IP addresses, and ports in the header, but not the contents of the packet. Layer 4 load balancers forward network packets to and from the upstream server, performing [Network Address Translation (NAT)](https://www.nginx.com/resources/glossary/layer-4-load-balancing/). ### 七层负载均衡器
### layer 7 load balancing 七层负载均衡器根据监控[应用层](#communication)来决定怎样分发请求。这会涉及请求头的内容,消息和 cookie。七层负载均衡器终结网络流量读取消息做出负载均衡判定然后传送给特定服务器。比如一个七层负载均衡器能直接将视频流量连接到托管视频的服务器同时将更敏感的用户账单流量引导到安全性更强的服务器。
Layer 7 load balancers look at the [application layer](#communication) to decide how to distribute requests. This can involve contents of the header, message, and cookies. Layer 7 load balancers terminates network traffic, reads the message, makes a load-balancing decision, then opens a connection to the selected server. For example, a layer 7 load balancer can direct video traffic to servers that host videos while directing more sensitive user billing traffic to security-hardened servers. 以损失灵活性为代价,四层负载均衡比七层负载均衡花费更少时间和计算资源,虽然这对现代商用硬件的性能影响甚微。
At the cost of flexibility, layer 4 load balancing requires less time and computing resources than Layer 7, although the performance impact can be minimal on modern commodity hardware. ### 水平扩展
### Horizontal scaling 负载均衡器还能帮助水平扩展,提高性能和可用性。使用商业硬件的性价比更高,并且比在单台硬件上**垂直扩展**更贵的硬件具有更高的可用性。相比招聘特定企业系统人才,招聘商业硬件方面的人才更加容易。
Load balancers can also help with horizontal scaling, improving performance and availability. Scaling out using commodity machines is more cost efficient and results in higher availability than scaling up a single server on more expensive hardware, called **Vertical Scaling**. It is also easier to hire for talent working on commodity hardware than it is for specialized enterprise systems. #### 缺陷:水平扩展
#### Disadvantage(s): horizontal scaling * 水平扩展引入了复杂度并涉及服务器复制
* 服务器应该是无状态的:它们也不该包含像 session 或资料图片等与用户关联的数据。
* session 可以集中存储在数据库或持久化[缓存](#cache)Redis, Memcached的数据存储区中。
* 缓存和数据库等下游服务器需要随着上游服务器进行扩展,以处理更多的并发连接。
* Scaling horizontally introduces complexity and involves cloning servers ### 缺陷:负载均衡器
* Servers should be stateless: they should not contain any user-related data like sessions or profile pictures
* Sessions can be stored in a centralized data store such as a [database](#database) (SQL, NoSQL) or a persistent [cache](#cache) (Redis, Memcached)
* Downstream servers such as caches and databases need to handle more simultaneous connections as upstream servers scale out
### Disadvantage(s): load balancer * 如果没有足够的资源配置或配置错误,负载均衡器会变成一个性能瓶颈。
* 引入负载均衡器以帮助消除单点故障但导致了额外的复杂性。
* 单个负载均衡器会导致单点故障,但配置多个负载均衡器会进一步增加复杂性。
* The load balancer can become a performance bottleneck if it does not have enough resources or if it is not configured properly. ### 来源及延伸阅读
* Introducing a load balancer to help eliminate single points of failure results in increased complexity.
* A single load balancer is a single point of failure, configuring multiple load balancers further increases complexity.
### Source(s) and further reading * [NGINX 架构](https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/)
* [HAProxy 架构指南](http://www.haproxy.org/download/1.2/doc/architecture.txt)
* [NGINX architecture](https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/) * [可扩展性](http://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones)
* [HAProxy architecture guide](http://www.haproxy.org/download/1.2/doc/architecture.txt)
* [Scalability](http://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones)
* [Wikipedia](https://en.wikipedia.org/wiki/Load_balancing_(computing)) * [Wikipedia](https://en.wikipedia.org/wiki/Load_balancing_(computing))
* [Layer 4 load balancing](https://www.nginx.com/resources/glossary/layer-4-load-balancing/) * [四层负载平衡](https://www.nginx.com/resources/glossary/layer-4-load-balancing/)
* [Layer 7 load balancing](https://www.nginx.com/resources/glossary/layer-7-load-balancing/) * [七层负载平衡](https://www.nginx.com/resources/glossary/layer-7-load-balancing/)
* [ELB listener config](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-listener-config.html) * [ELB 监听器配置](http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-listener-config.html)
## Reverse proxy (web server) ## Reverse proxy (web server)
@ -1018,21 +1018,21 @@ In a graph database, each node is a record and each arc is a relationship betwee
Graphs databases offer high performance for data models with complex relationships, such as a social network. They are relatively new and are not yet widely-used; it might be more difficult to find development tools and resources. Many graphs can only be accessed with [REST APIs](#representational-state-transfer-rest). Graphs databases offer high performance for data models with complex relationships, such as a social network. They are relatively new and are not yet widely-used; it might be more difficult to find development tools and resources. Many graphs can only be accessed with [REST APIs](#representational-state-transfer-rest).
##### Source(s) and further reading: graph ##### 相关资源和延伸阅读:图
* [Graph database](https://en.wikipedia.org/wiki/Graph_database) - [图数据库](https://en.wikipedia.org/wiki/Graph_database)
* [Neo4j](https://neo4j.com/) - [Neo4j](https://neo4j.com/)
* [FlockDB](https://blog.twitter.com/2010/introducing-flockdb) - [FlockDB](https://blog.twitter.com/2010/introducing-flockdb)
#### Source(s) and further reading: NoSQL #### 相关资源和延伸阅读:NoSQL
* [Explanation of base terminology](http://stackoverflow.com/questions/3342497/explanation-of-base-terminology) - [基础术语解释](http://stackoverflow.com/questions/3342497/explanation-of-base-terminology)
* [NoSQL databases a survey and decision guidance](https://medium.com/baqend-blog/nosql-databases-a-survey-and-decision-guidance-ea7823a822d#.wskogqenq) - [NoSQL 数据库 — 调查与决策指导](https://medium.com/baqend-blog/nosql-databases-a-survey-and-decision-guidance-ea7823a822d#.wskogqenq)
* [Scalability](http://www.lecloud.net/post/7994751381/scalability-for-dummies-part-2-database) - [可扩展性](http://www.lecloud.net/post/7994751381/scalability-for-dummies-part-2-database)
* [Introduction to NoSQL](https://www.youtube.com/watch?v=qI_g07C_Q5I) - [NoSQL 的介绍](https://www.youtube.com/watch?v=qI_g07C_Q5I)
* [NoSQL patterns](http://horicky.blogspot.com/2009/11/nosql-patterns.html) - [NoSQL 模式](http://horicky.blogspot.com/2009/11/nosql-patterns.html)
### SQL or NoSQL ### SQL 还是 NoSQL
<p align="center"> <p align="center">
<img src="http://i.imgur.com/wXGqG5f.png"> <img src="http://i.imgur.com/wXGqG5f.png">
@ -1040,41 +1040,41 @@ Graphs databases offer high performance for data models with complex relationshi
<i><a href=https://www.infoq.com/articles/Transition-RDBMS-NoSQL/>Source: Transitioning from RDBMS to NoSQL</a></i> <i><a href=https://www.infoq.com/articles/Transition-RDBMS-NoSQL/>Source: Transitioning from RDBMS to NoSQL</a></i>
</p> </p>
Reasons for **SQL**: 选择 **SQL** 的原因:
* Structured data - 结构化数据
* Strict schema - 严格的架构
* Relational data - 关系型数据
* Need for complex joins - 需要复杂的 joins
* Transactions - 事务
* Clear patterns for scaling - 清晰的缩放模式
* More established: developers, community, code, tools, etc - 更成熟的开发人员,社区,代码,工具等等
* Lookups by index are very fast - 通过索引查找非常快
Reasons for **NoSQL**: 选择 **NoSQL** 的原因:
* Semi-structured data - 半结构化数据
* Dynamic or flexible schema - 动态/灵活的模式
* Non relational data - 非关系型数据
* No need for complex joins - 不需要复杂的 joins 操作
* Store many TB (or PB) of data - 可以存储大量 TB/PB 数据
* Very data intensive workload - 非常数据密集的工作量
* Very high throughput for IOPS - 非常高的 IOPS 吞吐量
Sample data well-suited for NoSQL: 适合 NoSQL 操作的数据:
* Rapid ingest of clickstream and log data - 埋点数据以及日志数据
* Leaderboard or scoring data - 排行榜或者得分数据
* Temporary data, such as a shopping cart - 临时数据,比如购物车
* Frequently accessed ('hot') tables - 需要频繁访问的表
* Metadata/lookup tables - 元数据/查找表
##### Source(s) and further reading: SQL or NoSQL ##### 相关资源和延伸阅读SQL 还是 NoSQL
* [Scaling up to your first 10 million users](https://www.youtube.com/watch?v=vg5onp8TU6Q) - [扩大您的用户到第一个1000万](https://www.youtube.com/watch?v=vg5onp8TU6Q)
* [SQL vs NoSQL differences](https://www.sitepoint.com/sql-vs-nosql-differences/) - [SQL 和 NoSQL 的不同](https://www.sitepoint.com/sql-vs-nosql-differences/)
## Cache ## 缓存
<p align="center"> <p align="center">
<img src="http://i.imgur.com/Q6z24La.png"> <img src="http://i.imgur.com/Q6z24La.png">
@ -1082,70 +1082,70 @@ Sample data well-suited for NoSQL:
<i><a href=http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html>Source: Scalable system design patterns</a></i> <i><a href=http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html>Source: Scalable system design patterns</a></i>
</p> </p>
Caching improves page load times and can reduce the load on your servers and databases. In this model, the dispatcher will first lookup if the request has been made before and try to find the previous result to return, in order to save the actual execution. 缓存可以提高页面加载速度,并可以减少服务器和数据库的负载。在这个模型中,分发器先查看请求之前是否被响应过,如果有则将之前的结果直接返回,来省掉真正的处理。
Databases often benefit from a uniform distribution of reads and writes across its partitions. Popular items can skew the distribution, causing bottlenecks. Putting a cache in front of a database can help absorb uneven loads and spikes in traffic. 数据库分片均匀分布的读取是最好的。但是热门数据会让读取分布不均匀,这样就会造成瓶颈,如果在数据库前加个缓存,就会抹平不均匀的负载和突发流量对数据库的影响。
### Client caching ### 客户端缓存
Caches can be located on the client side (OS or browser), [server side](#reverse-proxy), or in a distinct cache layer. 缓存可以位于客户端(操作系统或者浏览器),[服务端](#reverse-proxy)或者不同的缓存层。
### CDN caching ### CDN 缓存
[CDNs](#content-delivery-network) are considered a type of cache. [CDNs](#content-delivery-network) 也被视为一种缓存。
### Web server caching ### Web 服务器缓存
[Reverse proxies](#reverse-proxy-web-server) and caches such as [Varnish](https://www.varnish-cache.org/) can serve static and dynamic content directly. Web servers can also cache requests, returning responses without having to contact application servers. [反向代理](#reverse-proxy-web-server)和缓存(比如 [Varnish](https://www.varnish-cache.org/)可以直接提供静态和动态内容。Web 服务器同样也可以缓存请求,返回相应结果而不必连接应用服务器。
### Database caching ### 数据库缓存
Your database usually includes some level of caching in a default configuration, optimized for a generic use case. Tweaking these settings for specific usage patterns can further boost performance. 数据库的默认配置中通常包含缓存级别,针对一般用例进行了优化。调整配置,在不同情况下使用不同的模式可以进一步提高性能。
### Application caching ### 应用缓存
In-memory caches such as Memcached and Redis are key-value stores between your application and your data storage. Since the data is held in RAM, it is much faster than typical databases where data is stored on disk. RAM is more limited than disk, so [cache invalidation](https://en.wikipedia.org/wiki/Cache_algorithms) algorithms such as [least recently used (LRU)](https://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used) can help invalidate 'cold' entries and keep 'hot' data in RAM. 基于内存的缓存比如 Memcached 和 Redis 是应用程序和数据存储之间的一种键值存储。由于数据保存在 RAM 中它比存储在磁盘上的典型数据库要快多了。RAM 比磁盘限制更多,所以例如 [least recently used (LRU)](https://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used) 的[缓存无效算法](https://en.wikipedia.org/wiki/Cache_algorithms)可以将「热门数据」放在 RAM 中,而对一些比较「冷门」的数据不做处理。
Redis has the following additional features: Redis 有下列附加功能:
* Persistence option - 持久性选项
* Built-in data structures such as sorted sets and lists - 内置数据结构比如有序集合和列表
There are multiple levels you can cache that fall into two general categories: **database queries** and **objects**: 有多个缓存级别,分为两大类:**数据库查询**和**对象**
* Row level - 行级别
* Query-level - 查询级别
* Fully-formed serializable objects - 完整的可序列化对象
* Fully-rendered HTML - 完全渲染的 HTML
Generally, you should try to avoid file-based caching, as it makes cloning and auto-scaling more difficult. 一般来说,你应该尽量避免基于文件的缓存,因为这使得复制和自动缩放很困难。
### Caching at the database query level ### 数据库查询级别的缓存
Whenever you query the database, hash the query as a key and store the result to the cache. This approach suffers from expiration issues: 当你查询数据库的时候,将查询语句的哈希值与查询结果存储到缓存中。这种方法会遇到以下问题:
* Hard to delete a cached result with complex queries - 很难用复杂的查询删除已缓存结果。
* If one piece of data changes such as a table cell, you need to delete all cached queries that might include the changed cell - 如果一条数据比如表中某条数据的一项被改变,则需要删除所有可能包含已更改项的缓存结果。
### Caching at the object level ### 对象级别的缓存
See your data as an object, similar to what you do with your application code. Have your application assemble the dataset from the database into a class instance or a data structure(s): 将您的数据视为对象,就像对待你的应用代码一样。让应用程序将数据从数据库中组合到类实例或数据结构中:
* Remove the object from cache if its underlying data has changed - 如果对象的基础数据已经更改了,那么从缓存中删掉这个对象。
* Allows for asynchronous processing: workers assemble objects by consuming the latest cached object - 允许异步处理workers 通过使用最新的缓存对象来组装对象。
Suggestions of what to cache: 建议缓存的内容:
* User sessions - 用户会话
* Fully rendered web pages - 完全渲染的 Web 页面
* Activity streams - 活动流
* User graph data - 用户图数据
### When to update the cache ### 何时更新缓存
Since you can only store a limited amount of data in cache, you'll need to determine which cache update strategy works best for your use case. 由于你只能在缓存中存储有限的数据,所以你需要选择一个适用于你用例的缓存更新策略。
#### Cache-aside #### 缓存
<p align="center"> <p align="center">
<img src="http://i.imgur.com/ONjORqk.png"> <img src="http://i.imgur.com/ONjORqk.png">
@ -1153,12 +1153,12 @@ Since you can only store a limited amount of data in cache, you'll need to deter
<i><a href=http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast>Source: From cache to in-memory data grid</a></i> <i><a href=http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast>Source: From cache to in-memory data grid</a></i>
</p> </p>
The application is responsible for reading and writing from storage. The cache does not interact with storage directly. The application does the following: 应用从存储器读写。缓存不和存储器直接交互,应用执行以下操作:
* Look for entry in cache, resulting in a cache miss - 在缓存中查找记录,如果所需数据不在缓存中
* Load entry from the database - 从数据库中加载所需内容
* Add entry to cache - 将查找到的结果存储到缓存中
* Return entry - 返回所需内容
``` ```
def get_user(self, user_id): def get_user(self, user_id):
@ -1171,17 +1171,17 @@ def get_user(self, user_id):
return user return user
``` ```
[Memcached](https://memcached.org/) is generally used in this manner. [Memcached](https://memcached.org/) 通常用这种方式使用。
Subsequent reads of data added to cache are fast. Cache-aside is also referred to as lazy loading. Only requested data is cached, which avoids filling up the cache with data that isn't requested. 添加到缓存中的数据读取速度很快。缓存模式也称为延迟加载。只缓存所请求的数据,这避免了没有被请求的数据占满了缓存空间。
##### Disadvantage(s): cache-aside ##### 缓存的缺点:
* Each cache miss results in three trips, which can cause a noticeable delay. - 请求的数据如果不在缓存中就需要经过三个步骤来获取数据,这会导致明显的延迟。
* Data can become stale if it is updated in the database. This issue is mitigated by setting a time-to-live (TTL) which forces an update of the cache entry, or by using write-through. - 如果数据库中的数据更新了会导致缓存中的数据过时。这个问题需要通过设置 TTL 强制更新缓存或者直写模式来缓解这种情况。
* When a node fails, it is replaced by a new, empty node, increasing latency. - 当一个节点出现故障的时候,它将会被一个新的节点替代,这增加了延迟的时间。
#### Write-through #### 直写模式
<p align="center"> <p align="center">
<img src="http://i.imgur.com/0vBc0hN.png"> <img src="http://i.imgur.com/0vBc0hN.png">
@ -1189,19 +1189,19 @@ Subsequent reads of data added to cache are fast. Cache-aside is also referred
<i><a href=http://www.slideshare.net/jboner/scalability-availability-stability-patterns/>Source: Scalability, availability, stability, patterns</a></i> <i><a href=http://www.slideshare.net/jboner/scalability-availability-stability-patterns/>Source: Scalability, availability, stability, patterns</a></i>
</p> </p>
The application uses the cache as the main data store, reading and writing data to it, while the cache is responsible for reading and writing to the database: 应用使用缓存作为主要的数据存储,将数据读写到缓存中,而缓存负责从数据库中读写数据。
* Application adds/updates entry in cache - 应用向缓存中添加/更新数据
* Cache synchronously writes entry to data store - 缓存同步地写入数据存储
* Return - 返回所需内容
Application code: 应用代码:
``` ```
set_user(12345, {"foo":"bar"}) set_user(12345, {"foo":"bar"})
``` ```
Cache code: 缓存代码:
``` ```
def set_user(user_id, values): def set_user(user_id, values):
@ -1209,14 +1209,14 @@ def set_user(user_id, values):
cache.set(user_id, user) cache.set(user_id, user)
``` ```
Write-through is a slow overall operation due to the write operation, but subsequent reads of just written data are fast. Users are generally more tolerant of latency when updating data than reading data. Data in the cache is not stale. 由于存写操作所以直写模式整体是一种很慢的操作,但是读取刚写入的数据很快。相比读取数据,用户通常比较能接受更新数据时速度较慢。缓存中的数据不会过时。
##### Disadvantage(s): write through ##### 直写模式的缺点:
* When a new node is created due to failure or scaling, the new node will not cache entries until the entry is updated in the database. Cache-aside in conjunction with write through can mitigate this issue. - 由于故障或者缩放而创建的新的节点,新的节点不会缓存,直到数据库更新为止。缓存应用直写模式可以缓解这个问题。
* Most data written might never read, which can be minimized with a TTL. - 写入的大多数数据可能永远都不会被读取,用 TTL 可以最小化这种情况的出现。
#### Write-behind (write-back) #### 回写模式
<p align="center"> <p align="center">
<img src="http://i.imgur.com/rgSrvjG.png"> <img src="http://i.imgur.com/rgSrvjG.png">
@ -1224,17 +1224,17 @@ Write-through is a slow overall operation due to the write operation, but subseq
<i><a href=http://www.slideshare.net/jboner/scalability-availability-stability-patterns/>Source: Scalability, availability, stability, patterns</a></i> <i><a href=http://www.slideshare.net/jboner/scalability-availability-stability-patterns/>Source: Scalability, availability, stability, patterns</a></i>
</p> </p>
In write-behind, tha application does the following: 在回写模式中,应用执行以下操作:
* Add/update entry in cache - 在缓存中增加或者更新条目
* Asynchronously write entry to the data store, improving write performance - 异步写入数据,提高写入性能。
##### Disadvantage(s): write-behind ##### 回写模式的缺点:
* There could be data loss if the cache goes down prior to its contents hitting the data store. - 缓存可能在其内容成功存储之前丢失数据。
* It is more complex to implement write-behind than it is to implement cache-aside or write-through. - 执行直写模式比缓存或者回写模式更复杂。
#### Refresh-ahead #### 刷新
<p align="center"> <p align="center">
<img src="http://i.imgur.com/kxtjqgE.png"> <img src="http://i.imgur.com/kxtjqgE.png">
@ -1242,31 +1242,31 @@ In write-behind, tha application does the following:
<i><a href=http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast>Source: From cache to in-memory data grid</a></i> <i><a href=http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast>Source: From cache to in-memory data grid</a></i>
</p> </p>
You can configure the cache to automatically refresh any recently accessed cache entry prior to its expiration. 你可以将缓存配置成在到期之前自动刷新最近访问过的内容。
Refresh-ahead can result in reduced latency vs read-through if the cache can accurately predict which items are likely to be needed in the future. 如果缓存可以准确预测将来可能请求哪些数据,那么刷新可能会导致延迟与读取时间的降低。
##### Disadvantage(s): refresh-ahead ##### 刷新的缺点:
* Not accurately predicting which items are likely to be needed in the future can result in reduced performance than without refresh-ahead. - 不能准确预测到未来需要用到的数据可能会导致性能不如不使用刷新。
### Disadvantage(s): cache ### 缓存的缺点:
* Need to maintain consistency between caches and the source of truth such as the database through [cache invalidation](https://en.wikipedia.org/wiki/Cache_algorithms). - 需要保持缓存和真实数据源之间的一致性,比如数据库根据[缓存无效](https://en.wikipedia.org/wiki/Cache_algorithms)。
* Need to make application changes such as adding Redis or memcached. - 需要改变应用程序比如增加 Redis 或者 memcached。
* Cache invalidation is a difficult problem, there is additional complexity associated with when to update the cache. - 无效缓存是个难题,什么时候更新缓存是与之相关的复杂问题。
### Source(s) and further reading ### 相关资源和延伸阅读
* [From cache to in-memory data grid](http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast) - [从缓存到内存数据](http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast)
* [Scalable system design patterns](http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html) - [可扩展系统设计模式](http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html)
* [Introduction to architecting systems for scale](http://lethain.com/introduction-to-architecting-systems-for-scale/) - [大型系统架构介绍](http://lethain.com/introduction-to-architecting-systems-for-scale/)
* [Scalability, availability, stability, patterns](http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) - [可扩展性,可用性,稳定性和模式](http://www.slideshare.net/jboner/scalability-availability-stability-patterns/)
* [Scalability](http://www.lecloud.net/post/9246290032/scalability-for-dummies-part-3-cache) - [可扩展性](http://www.lecloud.net/post/9246290032/scalability-for-dummies-part-3-cache)
* [AWS ElastiCache strategies](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Strategies.html) - [AWS ElastiCache 策略](http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Strategies.html)
* [Wikipedia](https://en.wikipedia.org/wiki/Cache_(computing)) - [维基百科](https://en.wikipedia.org/wiki/Cache_(computing))
## Asynchronism ## 异步
<p align="center"> <p align="center">
<img src="http://i.imgur.com/54GYsSx.png"> <img src="http://i.imgur.com/54GYsSx.png">
@ -1274,45 +1274,45 @@ Refresh-ahead can result in reduced latency vs read-through if the cache can acc
<i><a href=http://lethain.com/introduction-to-architecting-systems-for-scale/#platform_layer>Source: Intro to architecting systems for scale</a></i> <i><a href=http://lethain.com/introduction-to-architecting-systems-for-scale/#platform_layer>Source: Intro to architecting systems for scale</a></i>
</p> </p>
Asynchronous workflows help reduce request times for expensive operations that would otherwise be performed in-line. They can also help by doing time-consuming work in advance, such as periodic aggregation of data. 异步工作流有助于减少那些原本顺序执行的请求时间。它们可以通过提前进行一些耗时的工作来帮助减少请求时间,比如定期汇总数据。
### Message queues ### 消息队列
Message queues receive, hold, and deliver messages. If an operation is too slow to perform inline, you can use a message queue with the following workflow: 消息队列接收,保留和传递消息。如果按顺序执行操作太慢的话,你可以使用有以下工作流的消息队列:
* An application publishes a job to the queue, then notifies the user of job status - 应用程序将作业发布到队列,然后通知用户作业状态
* A worker picks up the job from the queue, processes it, then signals the job is complete - 一个 worker 从队列中取出该作业,对其进行处理,然后显示该作业完成
The user is not blocked and the job is processed in the background. During this time, the client might optionally do a small amount of processing to make it seem like the task has completed. For example, if posting a tweet, the tweet could be instantly posted to your timeline, but it could take some time before your tweet is actually delivered to all of your followers. 不去阻塞用户操作,作业在后台处理。在此期间,客户端可能会进行一些处理使得看上去像是任务已经完成了。例如,如果要发送一条推文,推文可能会马上出现在你的时间线上,但是可能需要一些时间才能将你的推文推送到你的所有关注者那里去。
**Redis** is useful as a simple message broker but messages can be lost. **Redis** 是一个令人满意的简单的消息代理,但是消息有可能会丢失。
**RabbitMQ** is popular but requires you to adapt to the 'AMQP' protocol and manage your own nodes. **RabbitMQ** 很受欢迎但是要求你适应「AMQP」协议并且管理你自己的节点。
**Amazon SQS**, is hosted but can have high latency and has the possibility of messages being delivered twice. **Amazon SQS** 是被托管的,但可能具有高延迟,并且消息可能会被传送两次。
### Task queues ### 任务队列
Tasks queues receive tasks and their related data, runs them, then delivers their results. They can support scheduling and can be used to run computationally-intensive jobs in the background. 任务队列接收任务及其相关数据,运行它们,然后传递其结果。 它们可以支持调度,并可用于在后台运行计算密集型作业。
**Celery** has support for scheduling and primarily has python support. **Celery** 支持调度,主要是用 Python 开发的。
### Back pressure ### 背压
If queues start to grow significantly, the queue size can become larger than memory, resulting in cache misses, disk reads, and even slower performance. [Back pressure](http://mechanical-sympathy.blogspot.com/2012/05/apply-back-pressure-when-overloaded.html) can help by limiting the queue size, thereby maintaining a high throughput rate and good response times for jobs already in the queue. Once the queue fills up, clients get a server busy or HTTP 503 status code to try again later. Clients can retry the request at a later time, perhaps with [exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff). 如果队列开始明显增长,那么队列大小可能会超过内存大小,导致高速缓存未命中,磁盘读取,甚至性能更慢。[背压](http://mechanical-sympathy.blogspot.com/2012/05/apply-back-pressure-when-overloaded.html)可以通过限制队列大小来帮助我们,从而为队列中的作业保持高吞吐率和良好的响应时间。一旦队列填满,客户端将得到服务器忙活着 HTTP 503 状态码,以便稍后重试。客户端可以在稍后时间重试该请求,也许是[指数退避](https://en.wikipedia.org/wiki/Exponential_backoff)。
### Disadvantage(s): asynchronism ### 异步的缺点:
* Use cases such as inexpensive calculations and realtime workflows might be better suited for synchronous operations, as introducing queues can add delays and complexity. - 简单的计算和实时工作流等用例可能更适用于同步操作,因为引入队列可能会增加延迟和复杂性。
### Source(s) and further reading ### 相关资源和延伸阅读
* [It's all a numbers game](https://www.youtube.com/watch?v=1KRYH75wgy4) - [这是一个数字游戏](https://www.youtube.com/watch?v=1KRYH75wgy4)
* [Applying back pressure when overloaded](http://mechanical-sympathy.blogspot.com/2012/05/apply-back-pressure-when-overloaded.html) - [超载时应用背压](http://mechanical-sympathy.blogspot.com/2012/05/apply-back-pressure-when-overloaded.html)
* [Little's law](https://en.wikipedia.org/wiki/Little%27s_law) - [利特尔法则](https://en.wikipedia.org/wiki/Little%27s_law)
* [What is the difference between a message queue and a task queue?](https://www.quora.com/What-is-the-difference-between-a-message-queue-and-a-task-queue-Why-would-a-task-queue-require-a-message-broker-like-RabbitMQ-Redis-Celery-or-IronMQ-to-function) - [消息队列与任务队列有什么区别?](https://www.quora.com/What-is-the-difference-between-a-message-queue-and-a-task-queue-Why-would-a-task-queue-require-a-message-broker-like-RabbitMQ-Redis-Celery-or-IronMQ-to-function)
## Communication ## 通讯
<p align="center"> <p align="center">
<img src="http://i.imgur.com/5KeocQs.jpg"> <img src="http://i.imgur.com/5KeocQs.jpg">
@ -1320,28 +1320,27 @@ If queues start to grow significantly, the queue size can become larger than mem
<i><a href=http://www.escotal.com/osilayer.html>Source: OSI 7 layer model</a></i> <i><a href=http://www.escotal.com/osilayer.html>Source: OSI 7 layer model</a></i>
</p> </p>
### Hypertext transfer protocol (HTTP) ### 超文本传输协议HTTP
HTTP is a method for encoding and transporting data between a client and a server. It is a request/response protocol: clients issue requests and servers issue responses with relevant content and completion status info about the request. HTTP is self-contained, allowing requests and responses to flow through many intermediate routers and servers that perform load balancing, caching, encryption, and compression. HTTP 是一种在客户端和服务器之间编码和传输数据的方法。它是一个请求/响应协议客户端和服务端针对相关内容和完成状态信息的请求和响应。HTTP 是独立的,允许请求和响应流经许多执行负载均衡,缓存,加密和压缩的中间路由器和服务器。
A basic HTTP request consists of a verb (method) and a resource (endpoint). Below are common HTTP verbs: 一个基本的 HTTP 请求由一个动词(方法)和一个资源(端点)组成。 以下是常见的 HTTP 动词:
| Verb | Description | Idempotent* | Safe | Cacheable | | 动词 | 描述 | *幂等 | 安全性 | 可缓存 |
| ------ | ---------------------------------------- | ----------- | ---- | --------------------------------------- | | ------ | -------------- | ---- | ---- | -------------- |
| GET | 获取一个资源 | Yes | Yes | Yes | | GET | 读取资源 | Yes | Yes | Yes |
| POST | 创建资源或触发处理数据的进程 | No | No | Yes if response contains freshness info | | POST | 创建资源或触发处理数据的进程 | No | No | Yes如果回应包含刷新信息 |
| PUT | 创建或替换一个资源 | Yes | No | No | | PUT | 创建或替换资源 | Yes | No | No |
| PATCH | 更新部分资源 | No | No | Yes if response contains freshness info | | PATCH | 部分更新资源 | No | No | Yes如果回应包含刷新信息 |
| DELETE | 删除一个资源 | Yes | No | No | | DELETE | 删除资源 | Yes | No | No |
*多次执行不会产生不同的结果。
*Can be called many times without different outcomes. HTTP 是依赖于较低级协议(如 **TCP****UDP**)的应用层协议。
HTTP is an application layer protocol relying on lower-level protocols such as **TCP** and **UDP**. - [HTTP](https://www.nginx.com/resources/glossary/http/)
- [README](https://www.quora.com/What-is-the-difference-between-HTTP-protocol-and-TCP-protocol)
* [HTTP](https://www.nginx.com/resources/glossary/http/) ### 传输控制协议TCP
* [README](https://www.quora.com/What-is-the-difference-between-HTTP-protocol-and-TCP-protocol)
### Transmission control protocol (TCP)
<p align="center"> <p align="center">
<img src="http://i.imgur.com/JdAsdvG.jpg"> <img src="http://i.imgur.com/JdAsdvG.jpg">
@ -1349,21 +1348,21 @@ HTTP is an application layer protocol relying on lower-level protocols such as *
<i><a href=http://www.wildbunny.co.uk/blog/2012/10/09/how-to-make-a-multi-player-game-part-1/>Source: How to make a multiplayer game</a></i> <i><a href=http://www.wildbunny.co.uk/blog/2012/10/09/how-to-make-a-multi-player-game-part-1/>Source: How to make a multiplayer game</a></i>
</p> </p>
TCP is a connection-oriented protocol over an [IP network](https://en.wikipedia.org/wiki/Internet_Protocol). Connection is established and terminated using a [handshake](https://en.wikipedia.org/wiki/Handshaking). All packets sent are guaranteed to reach the destination in the original order and without corruption through: TCP 是通过 [IP 网络](https://en.wikipedia.org/wiki/Internet_Protocol)的面向连接的协议。 使用[握手](https://en.wikipedia.org/wiki/Handshaking)建立和断开连接。 发送的所有数据包保证以原始顺序到达目的地,用以下措施保证数据包不被损坏:
* Sequence numbers and [checksum fields](https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Checksum_computation) for each packet - 每个数据包的序列号和[校验码](https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Checksum_computation)。
* [Acknowledgement](https://en.wikipedia.org/wiki/Acknowledgement_(data_networks)) packets and automatic retransmission - [确认包](https://en.wikipedia.org/wiki/Acknowledgement_(data_networks))和自动重传
If the sender does not receive a correct response, it will resend the packets. If there are multiple timeouts, the connection is dropped. TCP also implements [flow control](https://en.wikipedia.org/wiki/Flow_control_(data)) and [congestion control](https://en.wikipedia.org/wiki/Network_congestion#Congestion_control). These guarantees cause delays and generally results in less efficient transmission than UDP. 如果发送者没有收到正确的响应它将重新发送数据包。如果多次超时连接就会断开。TCP 实行[流量控制](https://en.wikipedia.org/wiki/Flow_control_(data))和[拥塞控制](https://en.wikipedia.org/wiki/Network_congestion#Congestion_control)。这些确保措施会导致延迟,而且通常导致传输效率比 UDP 低。
To ensure high throughput, web servers can keep a large number of TCP connections open, resulting in high memory usage. It can be expensive to have a large number of open connections between web server threads and say, a [memcached](#memcached) server. [Connection pooling](https://en.wikipedia.org/wiki/Connection_pool) can help in addition to switching to UDP where applicable. 为了确保高吞吐量Web 服务器可以保持大量的 TCP 连接,从而导致高内存使用。在 Web 服务器线程间拥有大量开放连接可能开销巨大,消耗资源过多,也就是说,一个 [memcached](#memcached) 服务器。[连接池](https://en.wikipedia.org/wiki/Connection_pool) 可以帮助除了在适用的情况下切换到 UDP。
TCP is useful for applications that require high reliability but are less time critical. Some examples include web servers, database info, SMTP, FTP, and SSH. TCP 对于需要高可靠性但时间紧迫的应用程序很有用。比如包括 Web 服务器数据库信息SMTPFTP 和 SSH。
Use TCP over UDP when: 以下情况使用 TCP 代替 UDP
* You need all of the data to arrive intact - 你需要数据完好无损。
* You want to automatically make a best estimate use of the network throughput - 你想对网络吞吐量自动进行最佳评估。
### 用户数据报协议UDP ### 用户数据报协议UDP