查看: 9433| 回复: 5
跳转到指定楼层
上一主题 下一主题
收起左侧

[经验总结] 系统设计Step By Step

 
全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 JerryYang1120 于 2021-9-30 13:42 编辑

How to design system in interview step by step? 这是自己整理的系统设计学习笔记,Reference to* https://www.youtube.com/watch?v=bUHFg8CZFws&t=692s
md格式图片不好粘贴,同时附上pdf版,供君参考。



---

Below is a list of some practical questions potentially discussed in interview.
Let's take an example of design video view counting system.

[Interviewer:]  Let's Design a video view counting system.
## 1. Requirement Clarification
The purpose to figure out how candidate deals with ambiguity.

As a candidate, you should start asking questions below:

### Users/Customers
  • * Who will use the system?
  • * How the system will be used?
### Scale (Read/Write)
  • * How many read queries per second?
  • * How much data is queried per request?
  • * How many video views are processed per second?
  • * Can there be spikes in traffic?
### Performance
  • * What is expected write-to-read data delay?
  • * What is expected p99 latency for read queue?

### Cost
  • * Should the design minimize the cost of development?
  • * Should the design minimize the cost of maintenance?

### Functional Requirements - API
The system has to count video view events.
  1. countViewEvent(videoId);
  2. countViewEvent(videoId, eventType); // eventType = "view", "like", "share"
  3. // We want our API process not just count, but also for sum or average by providing lambda function.
  4. processEvent(videoId, eventType, function);// function = count, sum, average
  5. // batch operation
  6. processEvents(ListOfEvents);
复制代码
The system has to return video views for a time period
  1. getViewCount(videoId, startTime, endTime);
  2. getViewCount(videoId, eventType, startTime, endTime);
  3. // We want our API return not just count statistics, but also for sum or average.
  4. getStats(videoId, eventType, function, startTime, endTime, eventType);
复制代码
### Non-functional Requirements
[Interviewer:]  Let's Design a system that can handle YouTube scale.
[Interviewer:]  Let's try to make it as fast as possible.
  • Scalable
>
Tens of thousands of video views per second.


  • High Performance
Few tens of milliseconds to return total views count for a video.


  • * High Availability
  1. Survives hardware/network failures, no single point of failure.
复制代码
## 2. High level Design

[Candidate:]
Let's start design from something simple.



User->Browser -> Processing Service -> DataBase <-- Query Service <-- Browser -> User


### 2.1 What we store

Option 1 : Raw Individual Events (Every click)

  | VideoId | Timestamp | ... |
  | --- | --- | --- |
  | A | 2021-09-29 14:18:17 | ... |
  | A | 2021-09-29 14:18:32 | ... |
  | B | 2021-09-29 14:20:08 | ... |
  | B | 2021-09-29 14:20:56 | ... |
Pros:
  • * Fast writes
  • * Can slice and dice data however we need
  • * Can recalculate numbers if needed

Cons:
  • * Slow reads
  • * Costly for a large scale (many events)

Option 2 : Aggregated data (e.g. per minute) in real time

  | VideoId | Timestamp | Count |
  | --- | --- | --- |
  | A | 2021-09-29 14:18 | 2 |
  | B | 2021-09-29 14:20 | 2 |
Pros:
  • * Fast reads
  • * Data is ready for decision making

Cons:
  • * Can only query the data in the way data was aggregated
  • * Requires data aggregation pipeline
  • * Hard or even impossible to fix errors/bugs

Tips:
  • - Batch vs Streaming

| Batch processing           | Streaming |
| delayed to process data | near real time |



  • - Storage optimization by combining both raw data and aggregated data.
> We can store raw data in last 24 hours, aggregate data in last week per minute
> aggregate data per hour in last month, and per day for last year.we can archieve cold data into S3.



### 2.2 Where we store
SQL vs NoSQL? It is a question.
[Interviewer:]  :
Can you please give me specific database name? and explain your choice.



[Candidate:]
I know that both MySQL and NoSQL (like Cassandra) database may scale and perform well for this case.
Let me evaluate both options.



Questions for you to answer
  • * How to scale write?
  • * How to scale read?
  • * How to make both write and read fast?
  • * How not to lose data in case of hardware faults and network partitions?
  • * How to achieve strong consistency? What are the tradeoffs?
  • * How to recover data in case of outage?
  • * How to ensure data security?
  • * How to make it extensible for data model changes in future?

#### 2.2.1 SQL solution
V1 :

The problem of V1 is that Processing Service needs to know the config of MySQL and monitor the config change in case
some MySQL service is down and rejoining. This is heavily coupling.
Let's decouple MySQL and Processing Service, then we got V2.

V2:

V2 is introducing Cluster proxy to decouple PS and DB, and also using ZK to manage the configuration. This is good.
We also have replicas for MySQL. Primary and Read Replicas are segergated. but if a single SQL server is overwhelmed,
we need more than one and hence sharding.

V3 : MySQL Primary and Read Replica sharding.


### 2.2.2 NoSQL solution
##### Pick which node to store data
* Consistent Hash
* Cassandra
> Quorum
>
> Gossip

### 2.3 How we store
* For SQL, we define different tables and use `join` to get the data.
normalization is good in Relational Databases.



Video_info:

| Video_Id | Name | Channel_Id |
|---|---|---|
|A| System Design Course Video | 111 |

Video_stats:

| Video_Id | Timestamp | Count |
|---|---|---|
|A| 15:00 | 2 |
|A| 16:00 | 3 |
|A| 17:00 | 8 |

Channel_Info:

| Channel_Id | Name |
|---|---|
|111| this channel


* NoSQL - Denormalization.

## 3. Detail Design
### 3.1 Processing Service detail
#### 3.1.1 Basic
We need a hash map in memory for counter. we increase the counter for each event.
We either
  • * Option 1: Increase count right away whenever we receive an event.
  • * Option 2: Data aggregation in memory and send every other second.

#### 3.1.2 Detail
* Checkpointing
* Partition consumer.
1. We have multiple queues, each queue for each partition. We can consume multiple queues by either single thread or
  multi-thread.
Let's use single thread consume. A infinite loop is used to poll the queue.
2. Consume also need to deduplication the request in case of retry. We can use distributed cache to dedup it.
3. Database Writer - write data to Database
4. Dead letter queue - DLQ.


* Ingestion Path components

  | Partition Service Client | Load Balance | Partitioner Service and Partitions |
  |---|---|---|
  | Blocking vs Non-Blocking I/O | Software vs hardware balancing | Partition Strategy |
  | Buffering and Batching | Network protocols | Service discovery |
  | Timeouts | Load balancing algo | Replication |
  | Retries | DNS | Message Format |
  | Exponential backoff and jitter | Health checking | |
  | Circuit breaker | High Availability | |

* Data retrieval path
We need `Query Service` to query DB.
> How you wrote determines how you read

Read from `distributed cache` (hot data) / `DB` /`S3` (cold data)

### 3.2. Technical stack
* Client: Netty, Netflix Hystrix, Polly
* Load Balance : NetScaler, NGINX, AWS ELB
* Messaging System : Apache Kafka, AWS Kinesis
* Data Processing : Spark, Flink, AWS Kinesis Data Analytics
* Storage : Cassandra, HBase, Hadoop, Redshift, S3
* Other : Vitess, Redis, AWS SQS/RabbitMQ, Zookeeper, Netflix Eureka, AWS CloudWatch /ELK.

### 3.3 Bottlenecks, tradeoff and more
Interviewer may ask below questions:
#### 3.3.1 How to identify bottlenecks?
* Load test
* Stress test
#### 3.3.2 How to make sure system is healthy?
Alarm/Monitor
#### 3.3.3 How to make sure the system produces accurate results?
Answer : Have two systems to produces results and compare them.
* Weak consistency
* Eventual consistency
* Strong consistency
* TLA+

Quote from Apache Kafka's author Jay Kreps:
> We should use a batch processing framework like MapReduce if we aren't latency sensitive, and use a streaming
> processing framework if we are, but not to try to do both at the same time.


#### 3.3.4 What if processing service can not keep up with the speed new message arrival?
#### 3.3.5 Let's say we've got a hugely popular video. Will it become a bottleneck?
Hot partition or not?

### 4. Summary

### 4.1 Functional Requirement
* Write Down verbs
* Define input parameters and return values
* Make several iterations
### 4.2 Non-Functional Requirement (Qualities)
* Scalability
* Availability
* Performance
* Other
### 4.3 High Level design
* How data gets in
* How data gets out
* Try to drive the conversation
### 4.4 Detail design
* It's all about data (Storage, transfer, processing)
* Use fundaments concepts
* Apply relevant technologies
### 4.5 Bottleneck and tradeoff
* Listen to the interviewer
* Know the tradeoff
---

SystemDesignNotes.pdf

337.8 KB, 阅读权限: 50, 下载次数: 86, 下载积分: 大米 -1 颗

系统设计学习笔记

评分

参与人数 8大米 +9 收起 理由
SallyWu + 1 赞一个
oldfatcrab + 2 谢谢分享!
zjspm + 1 很有用的信息!
yagougou + 1 很有用的信息!
liusong123 + 1 欢迎分享你知道的情况,会给更多积分奖励!

查看全部评分


上一篇:设计tinyUrl详细总结
下一篇:搞笑帖: facebook 最新面筋
全局:
这个大哥说的不错,可惜就几个视频,我都看了一遍
回复

使用道具 举报

🔗
xiaobaimao 2021-10-1 08:22:50 | 只看该作者
全局:
大哥听口音像北边的
回复

使用道具 举报

🔗
lilyvalley 2021-10-1 13:44:25 | 只看该作者
全局:
已mark   
回复

使用道具 举报

🔗
shark999 2021-10-2 00:54:09 | 只看该作者
全局:
态度端正!能写。。。
回复

使用道具 举报

全局:
大哥说的真不错 反复看了好几遍 虽然比较high level但面试里面拎出来也绝对够用了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表