注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 milkis 于 2021-3-20 03:45 编辑
最近lz在准备 system design,正好开个贴来希望大家一起讨论。采用几个 grokking the system design interview 例子,来进行拓展讨论吧。^_^
最后写完,我真的发现是一个大型挖坑现场...同时也有种感觉 groking system design 有点像是作者参考了 engineering blog 然后拼接出来的. 🤔 如果原文就像 Data Intensive App 那本书囊括参考了那些文献,就要好方便我们扩展学习了。
原题:https://www.educative.io/courses ... terview/m2yDVZnQ8lG
1. What is Instagram?
Instagram is a social networking service that enables its users to upload and share their photos and videos with other users. Instagram users can choose to share information either publicly or privately. Anything shared publicly can be seen by any other user, whereas privately shared content can only be accessed by the specified set of people. Instagram also enables its users to share through many other social networking platforms, such as Facebook, Twitter, Flickr, and Tumblr.
We plan to design a simpler version of Instagram for this design problem, where a user can share photos and follow other users. The ‘News Feed’ for each user will consist of top photos of all the people the user follows.
2. Requirements and Goals of the System
We’ll focus on the following set of requirements while designing Instagram:
Functional Requirements
- Users should be able to upload/download/view photos.
- Users can perform searches based on photo/video titles.
- Users can follow other users.
The system should generate and display a user’s News Feed consisting of top photos from all the people the user follows.
这里总共有描述4个主要的功能,我们在后续的设计中应该都需要包含。
Non-functional Requirements
- Our service needs to be highly available.
如何定义 highly available? 什么样的 metrics 去衡量?- 个人觉得应该是面试官提供的
- The acceptable latency of the system is 200ms for News Feed generation
这个 200 ms latency,不知道大家谁知道有什么框架/架构设计能提供这样的保障嘛?个人觉得,这里可以说不能太慢,但是要求多少 ms latency 的限制,我不是很确定如何保障?顶多能确定 serverless 可能不太适合,基于其 cold start issue 等。
- Consistency can take a hit (in the interest of availability) if a user doesn’t see a photo for a while; it should be fine.
这算是暗示 eventual consistency 可以 apply 到前面提及的 generate and display a user's News Feed 功能。
- The system should be highly reliable; any uploaded photo or video should never be lost.
个人觉得这里应该是 Reliability 对应 fault tolerance; data never lost 对应 durability。lz 觉得这些算是我们在设计的时候,应该会都考虑到的:Availability, Reliability, Durablity 等。但是如何measure,如何设计 goal 这些不知道有什么“模版”思路不。
Not in scope: Adding tags to photos, searching photos on tags, commenting on photos, tagging users to photos, who to follow, etc.
3. Some Design Considerations
The system would be read-heavy, so we will focus on building a system that can retrieve photos quickly. Practically, users can upload as many photos as they like; therefore, efficient management of storage should be a crucial factor in designing this system. Low latency is expected while viewing photos. Data should be 100% reliable. If a user uploads a photo, the system will guarantee that it will never be lost.
这里的 read-heavy 应该就是对应着 Users should be able to view photo。但不知道,这里是不是也暗含 generate and display a user’s News Feed 和 Users can perform searches based on photo/video titles 两个功能。我们可以在稍后设计中去设想这个功能。
4. Capacity Estimation and Constraints
Let’s assume we have 500M total users, with 1M daily active users.
2M new photos every day, 23 new photos every second.
Average photo file size => 200KB
Total space required for 1 day of photos: 2M * 200KB => 400 GB
Total space required for 10 years: 400GB * 365 (days a year) * 10 (years) ~= 1425TB
5. High Level System Design
At a high-level, we need to support two scenarios, one to upload photos and the other to view/search photos.
Our service would need some object storage servers to store photos and some database servers to store metadata information about the photos, users and users relationships.
lz 看来这个 high level 应该要和上面的功能要求对应起来,并且我们这里只考虑后端:
Upload Photo:Client -> Photo Upload Service -> Photo Meta Data Store(database) + Photo Blob Store(s3)
Download/View Photo: Client -> Photo Service -> User Data Store(database) 这里可以展开来讲authentication/authorization,也可以简化,就说是直接从 CDN 拿照片。
Search Photo: Client -> Search Service -> Search Engine(Elatic Search) 这里又可以去展开聊 search engine,先mark一下:https://instagram-engineering.co ... ecture-eeb34a936d3a
Follow User: Client -> User Service -> User Data Store(database)
News Feed: Client -> News Feed Service -> News Feed Data Store(database/cache)
6. Data Schema
We need to store data about users, their uploaded photos, and the people they follow. The Photo table will store all data related to a photo; we need to have an index on (PhotoID, CreationDate) since we need to fetch recent photos first.
这里lz觉得应该是叫 Core Data Schema,也就是主要定义 User, Photo 这两个 model 以及 User Relationship 的大概设计。因为还没有进行 db 选型,所以我们可以不着急去讨论 table, index 等,这些都会依赖于我们选择什么样的 db。
A straightforward approach for storing the above schema would be to use an RDBMS like MySQL since we require joins. But relational databases come with their challenges, especially when we need to scale them. For details, please take a look at SQL vs. NoSQL.
We can store photos in a distributed file storage like HDFS or S3.
We can store the above schema in a distributed key-value store to enjoy the benefits offered by NoSQL. All the metadata related to photos can go to a table where the ‘key’ would be the ‘PhotoID’ and the ‘value’ would be an object containing PhotoLocation, UserLocation, CreationTimestamp, etc.
If we go with a NoSQL database, we need an additional table to store the relationships between users and photos to know who owns which photo. Let’s call this table ‘UserPhoto’. We also need to store the list of people a user follows. Let’s call it ‘UserFollow’. For both of these tables, we can use a wide-column datastore like Cassandra. For the ‘UserPhoto’ table, the ‘key’ would be ‘UserID’, and the ‘value’ would be the list of ‘PhotoIDs’ the user owns, stored in different columns. We will have a similar scheme for the ‘UserFollow’ table.
Cassandra or key-value stores, in general, always maintain a certain number of replicas to offer reliability. Also, in such data stores, deletes don’t get applied instantly; data is retained for certain days (to support undeleting) before getting removed from the system permanently.
这一部分,LZ 觉得应该单开一个 Choosing Database 的 section 讨论
Blob Storage
对于照片存储,我们可以用object storage system 例如 AWS S3, Google Cloud Storage etc; 或者使用 distributed file storage,例如 HDFS 等。相比起来,使用 S3 等云服务还是能让团队省出 HDFS 的 operation & maintenance 时间。(这里也想看看有没有案例,一开始就需要整上一个HDFS集群的,我能想到的场景是公司内部本身已经有这样的集群可以直接使用)。
实际上,本身Instagram最初就是用 AWS S3存储的。What Powers Instagram: Hundreds of Instances, Dozens of Technologies: https://instagram-engineering.com/what-powers-instagram-hundreds-of-instances-dozens-of-technologies-adf2e22da2ad
Core Data Storage
SQL: mysql, postgresql, etc
NoSQL: mongodb, dynamodb, Cassandra, etc
NewSQL: spanner, aurora, tidb, etc (这里有一篇阿里RDS team 讨论 newsql 的文章,比较推荐了解:http://mysql.taobao.org/monthly/2020/12/01/ 单独NewSQL是完全可以再展开讨论的,不过可能更加偏向于 db internal 这一块了)
首先,我们可以明确的一点是 One Size Does Not Fit All (https://www.allthingsdistributed ... tabases-in-aws.html),针对不同的场景我们可以使用不同的数据库满足我们的需求。对 database 选型的过程中,LZ觉得 nosql db 更多是去适用于某些特定场景,主要的数据库还是用 sql db。这篇关于 dynamodb 的 Single-Table Design(https://www.alexdebrie.com/posts/dynamodb-single-table/) 的讨论就很有借鉴作用,其也提到了 DynamoDB was built for large-scale, high-velocity applications that were outscaling the capabilities of relational databases。Amazon 最初也是先用在了 shopping cart 这个场景上,之后扩展到其它的应用场景。
所以在这里,我们可以把 User/Photo 以及 User Relationship 这样的数据放在 SQL/NewSQL 这样的数据库中,然后针对不同的场景需求来看是否采取其它的 db。这里有个小坑,关于如何选择是用 mysql 还是 postgresql。
How Instagram Implement It
大多数的 Instagram 数据(users, photo metadata, tags 等)都是保存在 PostgresSQL 中,并且采用了sharding。同时,也有采用 Cassandra 来实现 fraud detection, Feed and Direct Inbox 功能,而这一块在 2012 年之前,其实是采用 Redis 来支持的。
对于 users 数据等,未找到 Instagram 相关文章,但是可以借鉴 Facebook 的 TAO 来设想。我们可以通过 Mysql 或者 PostgreSQL 来方便的构建 social graph,但是会在数据量到达一定程度的时候,导致 query/write 变慢。TAO 则是在 mysql 之上构建了 cache graph 从而加快访问速度。
What Powers Instagram: Hundreds of Instances, Dozens of Technologies
https://instagram-engineering.com/what-powers-instagram-hundreds-of-instances-dozens-of-technologies-adf2e22da2ad
Open-sourcing a 10x reduction in Apache Cassandra tail latency
https://instagram-engineering.com/open-sourcing-a-10x-reduction-in-apache-cassandra-tail-latency-d64f86b43589
Facebook’s Instagram: Making the Switch to Cassandra from Redis, a 75% ‘Insta’ Savings
https://www.datastax.com/blog/facebooks-instagram-making-switch-cassandra-redis-75-insta-savings
TAO: Facebook’s Distributed Data Store for the Social Graph
https://www.usenix.org/conference/atc13/technical-sessions/presentation/bronson
7. Data Size Estimation
Let’s estimate how much data will be going into each table and how much total storage we will need for 10 years.
User: Assuming each “int” and “dateTime” is four bytes, each row in the User’s table will be of 68 bytes:
UserID (4 bytes) + Name (20 bytes) + Email (32 bytes) + DateOfBirth (4 bytes) + CreationDate (4 bytes) + LastLogin (4 bytes) = 68 bytes
If we have 500 million users, we will need 32GB of total storage.
500 million * 68 ~= 32GB
Photo: Each row in Photo’s table will be of 284 bytes:
PhotoID (4 bytes) + UserID (4 bytes) + PhotoPath (256 bytes) + PhotoLatitude (4 bytes) + PhotoLongitude(4 bytes) + UserLatitude (4 bytes) + UserLongitude (4 bytes) + CreationDate (4 bytes) = 284 bytes
If 2M new photos get uploaded every day, we will need 0.5GB of storage for one day:
2M * 284 bytes ~= 0.5GB per day
For 10 years we will need 1.88TB of storage.
UserFollow: Each row in the UserFollow table will consist of 8 bytes. If we have 500 million users and on average each user follows 500 users. We would need 1.82TB of storage for the UserFollow table:
500 million users * 500 followers * 8 bytes ~= 1.82TB
Total space required for all tables for 10 years will be 3.7TB:
32GB + 1.88TB + 1.82TB ~= 3.7TB
我觉得这个 data estimation 可能是我最不理解的部分....除开展现卓越的数学加减乘除能力,还可以干嘛...?
8. Component Design
Photo uploads (or writes) can be slow as they have to go to the disk, whereas reads will be faster, especially if they are being served from cache.
Uploading users can consume all the available connections, as uploading is a slow process. This means that ‘reads’ cannot be served if the system gets busy with all the ‘write’ requests. We should keep in mind that web servers have a connection limit before designing our system. If we assume that a web server can have a maximum of 500 connections at any time, then it can’t have more than 500 concurrent uploads or reads. To handle this bottleneck, we can split reads and writes into separate services. We will have dedicated servers for reads and different servers for writes to ensure that uploads don’t hog the system.
Separating photos’ read and write requests will also allow us to scale and optimize each of these operations independently.
这里可以参考之前的high level design,采取microservice architecture,自然会把这些service拆出来
9. Reliability and Redundancy
Losing files is not an option for our service. Therefore, we will store multiple copies of each file so that if one storage server dies, we can retrieve the photo from the other copy present on a different storage server.
这一点,如果使用 s3 或者任何 distribute file system,我们可以依赖于该系统提供的 reliability & redundancy。可以参考该 service 的 SLA。
This same principle also applies to other components of the system. If we want to have high availability of the system, we need to have multiple replicas of services running in the system so that even if a few services die down, the system remains available and running. Redundancy removes the single point of failure in the system.
If only one instance of a service is required to run at any point, we can run a redundant secondary copy of the service that is not serving any traffic, but it can take control after the failover when the primary has a problem.
Creating redundancy in a system can remove single points of failure and provide a backup or spare functionality if needed in a crisis. For example, if there are two instances of the same service running in production and one fails or degrades, the system can failover to the healthy copy. Failover can happen automatically or require manual intervention.
这里感觉就是在说 general concept,并没有觉得和题目相关。
10. Data Sharding
Let’s discuss different schemes for metadata sharding:
a. Partitioning based on UserID
Let’s assume we shard based on the ‘UserID’ so that we can keep all photos of a user on the same shard. If one DB shard is 1TB, we will need four shards to store 3.7TB of data. Let’s assume, for better performance and scalability, we keep 10 shards. So we’ll find the shard number by UserID % 10 and then store the data there. To uniquely identify any photo in our system, we can append the shard number with each PhotoID.
How can we generate PhotoIDs?
Each DB shard can have its own auto-increment sequence for PhotoIDs, and since we will append ShardID with each PhotoID, it will make it unique throughout our system.
What are the different issues with this partitioning scheme?
1. How would we handle hot users? Several people follow such hot users, and a lot of other people see any photo they upload.
2. Some users will have a lot of photos compared to others, thus making a non-uniform distribution of storage.
3. What if we cannot store all pictures of a user on one shard? If we distribute photos of a user onto multiple shards, will it cause higher latencies?
4. Storing all photos of a user on one shard can cause issues like unavailability of all of the user’s data if that shard is down or higher latency if it is serving high load etc.
b. Partitioning based on PhotoID
If we can generate unique PhotoIDs first and then find a shard number through “PhotoID % 10”, the above problems will have been solved. We would not need to append ShardID with PhotoID in this case, as PhotoID will itself be unique throughout the system.
How can we generate PhotoIDs?
Here, we cannot have an auto-incrementing sequence in each shard to define PhotoID because we need to know PhotoID first to find the shard where it will be stored. One solution could be that we dedicate a separate database instance to generate auto-incrementing IDs. If our PhotoID can fit into 64 bits, we can define a table containing only a 64 bit ID field. So whenever we would like to add a photo in our system, we can insert a new row in this table and take that ID to be our PhotoID of the new photo.
Wouldn’t this key generating DB be a single point of failure?
Yes, it would be. A workaround for that could be to define two such databases, one generating even-numbered IDs and the other odd-numbered. For MySQL, the following script can define such sequences:
KeyGeneratingServer1:
auto-increment-increment = 2
auto-increment-offset = 1
KeyGeneratingServer2:
auto-increment-increment = 2
auto-increment-offset = 2
We can put a load balancer in front of both of these databases to round-robin between them and to deal with downtime. Both these servers could be out of sync, with one generating more keys than the other, but this will not cause any issue in our system. We can extend this design by defining separate ID tables for Users, Photo-Comments, or other objects present in our system.
Alternately, we can implement a ‘key’ generation scheme similar to what we have discussed in Designing a URL Shortening service like TinyURL.
这里关于 sharding 的话其实可以单独扩展(挖坑)出来,Building Data Intensive Application 有单独的章节讲 parition,不过都是在理论层面以及对单表的分析。我们实际场景中,还是需要考虑到更多,比如这里 User table 和 Photo table 的 data collocation 的问题,如何检测数据库需要进行sharding了等。实践的话,我发现这个还挺有介绍作用的:https://cloud.tencent.com/developer/article/1623139
简单来说,辨别目前db瓶颈是啥,大多数case可能还是可以通过优化sql来解决的,不能的话,就看是IO还是CPU瓶颈,然后针对着选择:水平分库,水平分表,垂直分库,垂直分表。
sharding 这一块也和业务有关,airbnb/uber这种可以按region来划分,ins/fb这些相对来说就不行,还有很多游戏公司也是按region来分(所以我们需要选区呀)。
Instagram 有讲自己是如果 sharding photo 数据的:https://instagram-engineering.co ... tagram-1cf5a71e5a5c。个人觉得,以目前的规模,Photo 和 User 应该是拆成了两个service,各自进行scale。
How can we plan for the future growth of our system?
We can have a large number of logical partitions to accommodate future data growth, such that in the beginning, multiple logical partitions reside on a single physical database server. Since each database server can have multiple database instances running on it, we can have separate databases for each logical partition on any server. So whenever we feel that a particular database server has a lot of data, we can migrate some logical partitions from it to another server. We can maintain a config file (or a separate database) that can map our logical partitions to database servers; this will enable us to move partitions around easily. Whenever we want to move a partition, we only have to update the config file to announce the change.fe
关于sharding的limitation,以及 static sharding vs. dynamic sharding vs. consistent hashing,这些我们可以以后拓展(挖坑)。
11. Ranking and News Feed Generation
lz 觉得这应该是这个题目的主要考点了。
To create the News Feed for any given user, we need to fetch the latest, most popular, and relevant photos of the people the user follows.
这里是讲得 naive solution,个人觉得挺直观的。
For simplicity, let’s assume we need to fetch the top 100 photos for a user’s News Feed. Our application server will first get a list of people the user follows and then fetch metadata info of each user’s latest 100 photos. In the final step, the server will submit all these photos to our ranking algorithm, which will determine the top 100 photos (based on recency, likeness, etc.) and return them to the user. A possible problem with this approach would be higher latency as we have to query multiple tables and perform sorting/merging/ranking on the results. To improve the efficiency, we can pre-generate the News Feed and store it in a separate table.
这个其实就是得益于我们之前的 eventual consistency的需求点。
Pre-generating the News Feed: We can have dedicated servers that are continuously generating users’ News Feeds and storing them in a ‘UserNewsFeed’ table. So whenever any user needs the latest photos for their News-Feed, we will simply query this table and return the results to the user.
Whenever these servers need to generate the News Feed of a user, they will first query the UserNewsFeed table to find the last time the News Feed was generated for that user. Then, new News-Feed data will be generated from that time onwards (following the steps mentioned above).
这个理论层面的讨论,在Building Data Intensive App书上有详细展开的。
What are the different approaches for sending News Feed contents to the users?
1. Pull: Clients can pull the News-Feed contents from the server at a regular interval or manually whenever they need it. Possible problems with this approach are
a) New data might not be shown to the users until clients issue a pull request
b) Most of the time, pull requests will result in an empty response if there is no new data.
2. Push: Servers can push new data to the users as soon as it is available.
To efficiently manage this, users have to maintain a Long Poll request with the server for receiving the updates. A possible problem with this approach is a user who follows a lot of people or a celebrity user who has millions of followers; in this case, the server has to push updates quite frequently.
3. Hybrid: We can adopt a hybrid approach. We can move all the users who have a high number of followers to a pull-based model and only push data to those who have a few hundred (or thousand) follows. Another approach could be that the server pushes updates to all the users not more than a certain frequency and letting users with a lot of followers/updates to pull data regularly.
For a detailed discussion about News-Feed generation, take a look at Designing Facebook’s Newsfeed.
关于 Feeds 这一个功能,最开始Instagram是使用redis来存储的,后来迁移到了 Cassandra。简单来说,就是用户发送 photo 之后,会有个 async service 将该 photo info 放到Cassandra上该用户的followers的 user_id: [photo1, photo2, photo3...] 之上。这样用户在查询 news feed的时候,直接从 Cassandra 上拿到这些 photo info 就好。如果换上AWS的话,应该DynamoDB是可以做到相同的需求的。
Cassandra at Instagram 2016 (Dikang Gu, Facebook) | Cassandra Summit 2016
https://www.youtube.com/watch?v=_BfMH4GQWnk
12. News Feed Creation with Sharded Data
One of the most important requirements to create the News Feed for any given user is to fetch the latest photos from all people the user follows. For this, we need to have a mechanism to sort photos on their time of creation. To efficiently do this, we can make photo creation time part of the PhotoID. As we will have a primary index on PhotoID, it will be quite quick to find the latest PhotoIDs.
We can use epoch time for this. Let’s say our PhotoID will have two parts; the first part will be representing epoch time, and the second part will be an auto-incrementing sequence. So to make a new PhotoID, we can take the current epoch time and append an auto-incrementing ID from our key-generating DB. We can figure out the shard number from this PhotoID ( PhotoID % 10) and store the photo there.
What could be the size of our PhotoID? Let’s say our epoch time starts today; how many bits we would need to store the number of seconds for the next 50 years?
86400 sec/day * 365 (days a year) * 50 (years) => 1.6 billion seconds
We would need 31 bits to store this number. Since, on average, we are expecting 23 new photos per second, we can allocate 9 additional bits to store the auto-incremented sequence. So every second, we can store (2^9 => 512)(2
9
=>512) new photos. We are allocating 9 bits for the sequence number which is more than what we require; we are doing this to get a full byte number (as 40 bits = 5 bytes40bits=5bytes). We can reset our auto-incrementing sequence every second.
We will discuss this technique under ‘Data Sharding’ in Designing Twitter.
这一篇文章其实有提及,个人理解是这个地方是想阐述从Cassandra拿到photo info后,可以直接拿到 sort 好的 news feed 而不需要再去 query photo core data store拿详细的 photo info 来排序。
Sharding & IDs at Instagram
https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c
13. Cache and Load balancing
Our service would need a massive-scale photo delivery system to serve globally distributed users. Our service should push its content closer to the user using a large number of geographically distributed photo cache servers and use CDNs (for details, see Caching).
cache 不知道大家有什么扩展点可以提供?
We can introduce a cache for metadata servers to cache hot database rows. We can use Memcache to cache the data, and Application servers before hitting the database, can quickly check if the cache has desired rows. Least Recently Used (LRU) can be a reasonable cache eviction policy for our system. Under this policy, we discard the least recently viewed row first.
2/8 这个规则只是一个死规则,真实情况我们还是需要根据场景来看,可以了解那些数据是会经常需要访问且不会频繁改动的,查看这些所占比例。
How can we build a more intelligent cache? If we go with the eighty-twenty rule, i.e., 20% of daily read volume for photos is generating 80% of the traffic, which means that certain photos are so popular that most people read them. This dictates that we can try caching 20% of the daily read volume of photos and metadata.
14. Search
Instagram serves millions of requests per second. Many of these, such as signups, likes, and uploads, modify existing records and append new rows to our master PostgreSQL databases. To maintain the correct set of searchable documents, our search infrastructure needs to be notified of these changes. Furthermore, search typically needs more information than a single row in PostgreSQL — for example, the author’s account vintage is used as a search feature after a photo is uploaded.
To solve the problem of denormalization, we introduced a system called Slipstream where events on Instagram are encoded into a large Thrift structure containing more information than typical consumers would use. These events are binary-serialized and sent over an asynchronous pub/sub channel we call the Firehose. Consumers, such as search, subscribe to the Firehose, filter out irrelevant events and react to remaining events. The Firehose is implemented on top of Facebook’s Scribe which makes the messaging process asynchronous.
摘自:https://instagram-engineering.co ... ecture-eeb34a936d3a
这里其实也可以直接在 postgressql 连接一个 CDC,通过 kafka 来分发events到searching db,不过当时ins搭建这一套的时候,应该kafka和CDC这一套没有到production ready的状态。
|