116 KiB
English ∙ 简体中文 | Brazilian Portuguese ∙ Polish ∙ Russian ∙ Turkish | Add Translation
The System Design Primer
動機・目的
大規模システムのシステム設計を学ぶ
システム設計面接課題に備える
大規模システムの設計を学ぶ
スケーラブルなシステムのシステム設計を学ぶことは、より良いエンジニアになることに資するでしょう。
システム設計はとても広範なトピックを含みます。システム設計原理については インターネット上には膨大な量の文献が散らばっています
このレポジトリは大規模システム構築に必要な知識を学ぶことができる 文献リストを体系的にまとめたもの です。
オープンソースコミュニティから学ぶ
このプロジェクトは、これからもずっと更新されていくオープンソースプロジェクトの初期段階にすぎません。
Contributions は大歓迎です!
システム設計面接課題に備える
コード技術面接に加えて、システム設計に関する知識は、多くのテック企業における 技術採用面接プロセス で 必要不可欠な要素 です。
システム設計面接での頻出問題を練習し また、自分の解答と 模範解答:ディスカッション、コードそして図表などを 比較 することで勉強できるでしょう。
面接準備に役立つその他のトピック:
暗記カード
この暗記カードアプリケーション は、システム設計の主要な概念を学ぶのに役立つアプリケーションです。程よい間隔で同じ問題を繰り返し出題してくれます。
外出先や移動中の勉強に役立つでしょう。
コーディング技術課題用の問題: 練習用インタラクティブアプリケーション
コード技術面接用の問題を探している場合はこちら?
こちらの姉妹リポジトリも見てみてください Interactive Coding Challenges, 追加の暗記デッキカードも入っています。
コントリビュート
コミュニティから学ぶ
プルリクエスト等の貢献は積極的にお願いします:
- エラー修正
- セクション内容修正
- 新規セクション追加
- 翻訳する
依然、推敲と内容の向上が必要なコンテンツは以下の場所にあります 作業中.
コントリビュートする前にガイドラインを読みましょう Contributing Guidelines.
システム設計目次
賛否も含めた様々なシステム設計の各トピックの概要。 全てはトレードオフの関係にあります
それぞれのセクションはより学びを深めるような他の文献へのリンクが貼られています
- システム設計トピック: まずはここから
- パフォーマンス vs スケーラビリティ
- レイテンシー vs スループット
- 可用性 vs 一貫性
- 一貫性 パターン
- 可用性 パターン
- ドメインネームシステム(DNS)
- コンテントデリバリーネットワーク(CDN)
- ロードバランサー
- リバースプロキシ (WEBサーバー)
- アプリケーションレイヤー
- データベース
- キャッシュ
- 異時性
- 通信
- セキュリティ
- 補遺
- 作業中
- クレジット
- 連絡情報
- ライセンス
学習指針
学習スパンに応じてみるべきトピックス (short, medium, long).
Q: 面接のためには、ここにあるものすべてをやらないといけないのでしょうか?
A: いえ、ここにあるすべてをやる必要はありません。.
面接で何を聞かれるかは以下の条件によって変わってきます:
- どれだけの技術経験があるか
- あなたの技術背景が何であるか
- どのポジション職位のために面接を受けているか
- どの企業に面接しているか
- 運
より経験のある候補者は一般的にシステム設計についてより深い知識を有していることを要求されるでしょう。システムアーキテクトやチームリーダーは各メンバーの持つような知識よりは深い見識を持っているべきでしょう。一流テック企業では複数回の設計インタビュー面接を課されることが多いです。
まずは広く始めて、そこからいくつかの分野に絞って深めていくのがいいでしょう。少しずつでの様々なシステム設計のトピックについて知っておくことはいいことです。以下の学習ガイドを自分の学習に当てられる時間、技術経験、どの職位、どの会社に応募しているかなどを加味して自分用に調整して使うといいでしょう。
- 短期間 - Aim for breadth with system design topics. Practice by solving some interview questions.
- 中期間 - Aim for breadth and some depth with system design topics. Practice by solving many interview questions.
- 長期間 - Aim for breadth and more depth with system design topics. Practice by solving most interview questions.
短期間 | 中期間 | 長期間 | |
---|---|---|---|
次のページを読んで システム設計トピック システムがどのように動くかの大体の知識を入れる | 👍 | 👍 | 👍 |
次のリンク先のいくつかのページを読んで 各企業のエンジニアリングブログ 応募する会社について知る | 👍 | 👍 | 👍 |
次のリンク先のいくつかのページを読む 実世界でのアーキテキチャ | 👍 | 👍 | 👍 |
復習する システム設計面接課題にどのように準備するか | 👍 | 👍 | 👍 |
とりあえず一周する システム設計課題例 | Some | Many | Most |
とりあえず一周する Object-oriented design interview questions with solutions | Some | Many | Most |
復習する その他システム設計面接での質問例 | Some | Many | Most |
システム設計面接にどのようにして臨めばいいか
システム設計面接試験問題にどのように取り組むか
システム設計面接は open-ended conversation(Yes/Noでは答えられない口頭質問)です. 自分で会話を組み立てることを求められます。
以下のステップに従って議論を組み立てることができるでしょう。この過程を確かなものにするために、次のセクションシステム設計課題例とその解答 を以下の指針に従って読み込むといいでしょう。
ステップ 1: そのシステム使用例の概要、制約、推計値等を聞き出し、まとめる
システム仕様の要求事項を聞き出し、問題箇所を特定しましょう。使用例と制約を明確にするための質問を投げかけましょう。要求する推計値についても議論しておきましょう。
- 誰がそのサービスを使うのか?
- どのように使うのか?
- 何人のユーザーがいるのか?
- システムはどのような機能を果たすのか?
- システムへの入力と出力は?
- どれだけの容量のデータを捌く必要があるのか?
- 一秒間に何リクエストの送信が想定されるか?
- 読み書き比率の推定値はいくら程度か?
ステップ 2: より高レベルのシステム設計を組み立てる
重要なコンポーネントを全て考慮した高レベルのシステム設計概要を組み立てる。
- 主要なコンポーネントと接続をスケッチして書き出す
- 考えの裏付けをする
Step 3: 核となるコンポーネントを設計する
それぞれの主要なコンポーネントについての詳細を学ぶ。例えば、url短縮サービスの設計を問われた際には次のようにするといいでしょう:
- 元のURLのハッシュ化したものを作り、それを保存する
- ハッシュ化されたURLを元のURLに再翻訳する
- データベース参照
- API & オブジェクト指向の設計
ステップ 4: システム設計のスケール
与えられた制約条件からボトルネックとなりそうなところを割り出し、明確化する。 例えば、スケーラビリティの問題解決のために以下の要素を考慮する必要があるだろうか?
- ロードバランサー
- 水平スケーリング
- キャッシング
- データベースシャーディング
取りうる解決策とそのトレードオフについて議論をしよう。全てのことはトレードオフの関係にある。ボトルネックについては次の項を読むといい。スケーラブルなシステム設計の原理.
ちょっとした暗算問題
ちょっとした推計値を手計算ですることを求められることもあるかもしれません。索引の以下の項目が役に立つでしょう:
文献とその他の参考資料
以下のリンク先ページを見てどのような質問を投げかけられるか概要を頭に入れておきましょう:
システム設計課題例とその解答
頻出のシステム設計面接課題と参考解答、コード及びダイアグラム
解答は
solutions/
フォルダ以下にリンクが貼られている。
問題 | |
---|---|
Pastebin.com (もしくは Bit.ly) を設計する | 解答 |
Twitterタイムライン (もしくはFacebookフィード)を設計する Twitter検索(もしくはFacebook検索)機能を設計する |
解答 |
ウェブクローラーを設計する | 解答 |
Mint.comを設計する | 解答 |
SNSサービスのデータ構造を設計する | 解答 |
検索エンジンのキー/バリュー構造を設計する | 解答 |
Amazonのカテゴリ毎の売り上げランキングを設計する | 解答 |
AWS上で100万人規模のユーザーを捌くサービスを設計する | 解答 |
システム設計問題を追加する | Contribute |
Pastebin.com (もしくは Bit.ly) を設計する
Twitterタイムライン&検索 (もしくはFacebookフィード&検索)を設計する
ウェブクローラーの設計
Mint.comの設計
SNSサービスのデータ構造を設計する
検索エンジンのキー/バリュー構造を設計する
Amazonのカテゴリ毎の売り上げランキングを設計する
AWS上で100万人規模のユーザーを捌くサービスを設計する
オブジェクト志向設計問題と解答
頻出のオブジェクト志向システム設計面接課題と参考解答、コード及びダイアグラム
解答は
solutions/
フォルダ以下にリンクが貼られている。
備考: このセクションは作業中です
問題 | |
---|---|
ハッシュマップの設計 | 解答 |
LRUキャッシュの設計 | 解答 |
コールセンターの設計 | 解答 |
カードのデッキの設計 | 解答 |
駐車場の設計 | 解答 |
チャットサーバーの設計 | 解答 |
円形配列の設計 | Contribute |
オブジェクト志向システム設計問題を追加する | Contribute |
システム設計トピックス: まずはここから
システム設計の勉強は初めて?
まず初めに、よく使われる設計原理について、それらが何であるか、どのように用いられるか、長所短所について基本的な理解を得る必要があります
ステップ 1: スケーラビリティに関する動画を観て復習する
- ここで触れられているトピックス:
- 垂直スケーリング
- 水平スケーリング
- キャッシング
- ロードバランシング
- データベースレプリケーション
- データベースパーティション
ステップ 2: スケーラビリティに関する資料を読んで復習する
次のステップ
次に、ハイレベルでのトレードオフについてみていく:
- パフォーマンス vs スケーラビリティ
- レイテンシ vs スループット
- 可用性 vs 一貫性
全てはトレードオフの関係にあるというのを肝に命じておきましょう。
それから、より深い内容、DNSやCDNそしてロードバランサーなどについて学習を進めていきましょう。
パフォーマンス vs スケーラビリティ
リソースが追加されるのにつれて パフォーマンス が向上する場合そのサービスは scalable であると言えるでしょう。一般的に、パフォーマンスを向上させるというのはすなわち計算処理を増やすことを意味しますが、データセットが増えた時などより大きな処理を捌けるようになることでもあります。1
パフォーマンスvsスケーラビリティをとらえる他の考え方:
- パフォーマンス での問題を抱えている時、あなたのシステムは一人のユーザーにとって遅いと言えるでしょう。
- スケーラビリティ での問題を抱えているとき、一人のユーザーにとっては速いですが、多くのリクエストがある時には遅くなってしまうでしょう。
その他の参考資料、ページ
レイテンシー vs スループット
レイテンシー とはなにがしかの動作を行う、もしくは結果を算出するのに要する時間
スループット とはそのような動作や結果算出が単位時間に行われる回数
一般的に、 最大限のスループット を 許容範囲内のレイテンシー で実現することを目指すのが普通だ。
その他の参考資料、ページ
可用性 vs 一貫性
CAP 理論
分散型コンピュータシステムにおいては下の三つのうち二つまでしか同時に保証することはできない。:
- 一貫性 - 全ての読み込みは最新の書き込みもしくはエラーを受け取る
- 可用性 - 受け取る情報が最新のものだという保証はないが、全てのリクエストはレスポンスを必ず受け取る
- 分断耐性 - ネットワーク問題によって順不同の分断が起きてもシステムが動作を続ける
ネットワークは信頼できないので、分断耐性は必ず保証しなければなりません。つまりソフトウェアシステムとしてのトレードオフは、一貫性を取るか、可用性を取るかを考えなければなりません。
CP - 一貫性と分断耐性(consistency and partition tolerance)
分断されたノードからのレスポンスを待ち続けているとタイムアウトエラーに陥る可能性があります。CPはあなたのサービスがアトミックな読み書き(不可分操作)を必要とする際にはいい選択肢でしょう。
AP - 可用性と分断耐性(availability and partition tolerance)
レスポンスはノード上にあるデータで最新のものを返します。つまり、最新版のデータが返されるとは限りません。分断が解消された後も、書き込みが反映されるのには時間がかかります。
結果整合性 を求めるサービスの際にはAPを採用するのがいいでしょう。もしくは、外部エラーに関わらずシステムが稼働する必要がある際にも同様です。
その他の参考資料、ページ
一貫性パターン
同じデータの複製が複数ある状態では、クライアントが一貫したデータ表示を受け取るために、どのようにそれらを同期すればいいのかという課題があります。 CAP 理論 における一貫性の定義を思い出してみましょう。全ての読み取りは最新の書き込みデータもしくはエラーを受け取るはずです。
弱い一貫性
書き込み後の読み取りでは、その最新の書き込みを読めたり読めなかったりする。一番良いアプローチが選択される。
メムキャッシュなどのシステムにおいてこのアプローチは取られる。弱い一貫性はリアルタイム性が必要な使用例、例えばVoIP、ビデオチャット、リアルタイムマルチプレイヤーゲームなどと相性がいいでしょう。例えば、電話に出ていて、受信を数秒受け取れなかったとして、その後に接続回復してもその接続が切断されていた間に話されていたことは聞き取れないというような感じです。
結果整合性
書き込みの後、読み取りは最終的にはその結果を読み取ることができる。 (ミリ秒ほど遅れてというのが一般的です)。データは非同期的に複製されます。
このアプローチはDNSやメールシステムなどに採用されています。結果整合性は多くのリクエストを捌くサービスと相性がいいでしょう。
強い一貫性
書き込みの後、読み取りはそれを必ず読むことができます。データは同期的に複製されます。
このアプローチはファイルシステムやRDBMなどで採用されています。トランザクションを扱うサービスでは強い一貫性が必要でしょう。
その他の参考資料、ページ
可用性パターン
高い可用性を担保するには主に次の二つのパターンがあります: フェイルオーバー と レプリケーション です。
フェイルオーバー
アクティブ・パッシブ
アクティブ・パッシブフェイルオーバーにおいては、周期信号はアクティブもしくはスタンバイ中のパッシブなサーバーに送られます。周期信号が中断された時には、パッシブだったサーバーがアクティブサーバーのIPアドレスを引き継いでサービスを再開します。
起動までのダウンタイムはパッシブサーバーが「ホット」なスタンバイ状態にあるか、「コールド」なスタンバイ状態にあるかで変わります。アクティブなサーバーのみがトラフィックを捌きます。
Active-passive failover can also be referred to as master-slave failover.
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.
アクティブ・パッシブなフェイルオーバーはマスター・スレーブフェイルオーバーだとも言えるでしょう。
短所: フェイルオーバー
- フェイルオーバーではより多くのハードウェアを要し、複雑さが増します。
- 最新の書き込みがパッシブサーバーに複製される前にアクティブが落ちると、データ欠損が起きる潜在可能性があります。
レプリケーション
マスター・スレーブ と マスター・マスター
このトピックは Database セクションにおいてより詳細に解説されています:
ドメインネームシステム
Source: DNS security presentation
ドメインネームシステム (DNS) は www.example.com などのドメインネームをIPアドレスへと翻訳します。
DNSは少数のオーソライズされたサーバーが上位に位置する階層的構造です。あなたのルーターもしくはISPは検索をする際にどのDNSサーバーに接続するかという情報を提供します。低い階層のDNSサーバーはその経路マップをキャッシュします。ただ、この情報は伝搬遅延によって陳腐化する可能性があります。DNSの結果はあなたのブラウザもしくはOSに一定期間(time to live (TTL)に設定された期間)キャッシュされます。
- NS record (name server) - あなたのドメイン・サブドメインでのDNSサーバーを特定します。
- MX record (mail exchange) - メッセージを受け取るメールサーバーを特定します。
- A record (address) - IPアドレスに名前をつけます。
- CNAME (canonical) - 他の名前もしくは
CNAME
(example.com を www.example.com) もしくはA
recordへと名前を指し示す。
CloudFlare や Route 53 などのサービスはマネージドDNSサービスを提供しています。いくつかのDNSサービスでは様々な手法を使ってトラフィックを捌くことができます:
- 加重ラウンドロビン
- トラフィックがメンテナンス中のサーバーに行くのを防ぎます
- 様々なクラスターサイズに応じて調整します
- A/B テスト
- レイテンシーベース
- 地理ベース
欠点: DNS
- 上記で示されているようなキャッシングによって緩和されているとはいえ、DNSサーバーへの接続には少し遅延が生じる。
- DNSサーバーは、政府、ISP企業,そして大企業に管理されているが、それらの管理は複雑である。
- DNSサービスはDDoS attackの例で、IPアドレスなしにユーザーがTwitterなどにアクセスできなくなったように、攻撃を受ける可能性がある。
その他の参考資料、ページ
コンテントデリバリーネットワーク(Content delivery network)
コンテントデリバリーネットワーク(CDN)は世界中に配置されたプロキシサーバーのネットワークがユーザーに一番地理的に近いサーバーからコンテンツを配信するシステムのことです。AmazonのCloudFrontなどは例外的にダイナミックなコンテンツも配信しますが、一般的に、HTML/CSS/JS、写真、そして動画などの静的ファイルがCDNを通じて配信されます。そのサイトのDNSがクライアントにどのサーバーと交信するかという情報を伝えます。
CDNを用いてコンテンツを配信することで以下の二つの理由でパフォーマンスが劇的に向上します:
- ユーザーは近くにあるデータセンターから受信できる
- バックエンドサーバーはCDNが処理してくれるリクエストに関しては処理する必要がなくなります
プッシュCDN
プッシュCDNではサーバーデータに更新があった時には必ず、新しいコンテンツを受け取る方式です。コンテンツを配信し、CDNに直接アップロードし、URLをCDNを指すように指定するところまで全ての責任を負う形です。コンテンツがいつ期限切れになるのか更新されるのかを設定することができます。コンテンツは新規作成時、更新時のみアップロードされることでトラフィックは最小化される一方、ストレージは最大限費消されてしまいます。
トラフィックの少ない、もしくは頻繁にはコンテンツが更新されないサイトの場合にはプッシュCDNと相性がいいでしょう。コンテンツは定期的に再びプルされるのではなく、CDNに一度のみ配置されます。
プルCDNs
プルCDNでは一人目のユーザーがリクエストした時に、新しいコンテンツをサービスのサーバーから取得します。コンテンツは自分のサーバーに保存して、CDNを指すURLを書き換えます。結果として、CDNにコンテンツがキャッシュされるまではリクエスト処理が遅くなります。
time-to-live (TTL) はコンテンツがどれだけの期間キャッシュされるかを規定します。プルCDNはCDN 上でのストレージスペースを最小化しますが、有効期限が切れたファイルが更新前にプルされてしまうことで冗長なトラフィックに繋がってしまう可能性があります。
大規模なトラフィックのあるサイトではプルCDNが相性がいいでしょう。というのも、トラフィックの大部分は最近リクエストされ、CDNに残っているコンテンツにアクセスするものであることが多いからです。
欠点: CDN
- CDNのコストはトラフィック量によって変わります。もちろん、CDNを使わない場合のコストと比較するべきでしょう。
- TTLが切れる前にコンテンツが更新されると陳腐化する恐れがあります。
- CDNでは静的コンテンツがCDNを指すようにURLを更新する必要があります。
その他の参考資料、ページ
ロードバランサー
Source: Scalable system design patterns
ロードバランサーは入力されるクライアントのリクエストをアプリケーションサーバーやデータベースへと分散させる。どのケースでもロードバランサーはサーバー等計算リソースからのレスポンスを適切なクライアントに返す。ロードバランサーは以下のことに効果的です:
- リクエストが状態の良くないサーバーに行くのを防ぐ
- リクエストを過重に送るのを防ぐ
- 特定箇所の欠陥でサービスが落ちることを防ぐ
ロードバランサーはハードウェアを用いて (費用高い) もしくはHAProxyなどのソフトウェアで実現できる。
他の利点としては:
- SSL termination - 入力されるリクエストを解読する、また、サーバーレスポンスを暗号化することでバックエンドのサーバーがこのコストが高くつきがちな処理を請け負わなくていいように肩代わりします。
- X.509 certificates をそれぞれのサーバーにインストールする必要をなくします
- セッション管理 - クッキーを取り扱いウェブアプリがセッション情報を保持していない時などに、特定のクライアントのリクエストを同じインスタンスへと流します。
障害に対応するために、アクティブ・パッシブ もしくは アクティブ・アクティブ モードのいずれに限らず、複数のロードバランサーを配置するのが一般的です。
ロードバランサーは以下のような種々のメトリックを用いてとらふぃっくんルーティングを行うことができます:
- ランダム
- Least loaded
- セッション/クッキー
- ラウンドロビンもしくは荷重ラウンドロビン
- Layer 4
- Layer 7
Layer 4 ロードバランシング
Layer 4 ロードバランサーは トランスポートレイヤー を参照してどのようにリクエストを配分するか判断します。一般的に、トランスポートレイヤーとしては、ソース、送信先IPアドレス、ヘッダーに記述されたポート番号が含まれますが、パケットの中身のコンテンツは含みません Layer 4 ロードバランサーはネットワークパケットを上流サーバーへ届け、上流サーバーから配信することでネットワークアドレス変換 Network Address Translation (NAT) を実現します。
Layer 7 ロードバランシング
Layer 7 ロードバランサーは アプリケーションレイヤー を参照してどのようにリクエストを配分するか判断します。ヘッダー、メッセージ、クッキーなどのコンテンツのことです。Layer 7 ロードバランサーはネットワークトラフィックの終端を受け持ち メッセージを読み込み、ロードバランシングの判断をし、選択したサーバーとの接続を繋ぎます。例えば layer 7 ロードバランサーは動画のトラフィックを直接、そのデータをホストしているサーバーにつなぐと同時に、決済処理などのより繊細なトラフィックをセキュリティ強化されたサーバー流すということもできる。
柔軟性とのトレードオフになりますが、 layer 4 ロードバランサーではLayer 7ロードバランサーよりも所要時間、計算リソースを少なく済むことができます。ただし、昨今の汎用ハードウェアではパフォーマンスは最小限のみしか発揮できないでしょう。
水平スケーリング
ロードバランサーでは水平スケーリングによってパフォーマンスと可用性を向上させることができます。手頃な汎用マシンを追加することによってスケーリングさせる方が、 垂直スケーリング と言って、サーバーをよりハイパフォーマンスなマシンに載せ替えることよりもずっと費用対効果も可用性も高いでしょう。また、汎用ハードウェアを扱える人材を雇う方が、特化型の商用ハードウェアを扱える人材を雇うよりも簡単でしょう。
欠点: 水平スケーリング
- 水平的にスケーリングしていくと、複雑さが増す上に、サーバーのクローニングが必要になる
- キャッシュやデータベースなどの下流サーバーは上流サーバーがスケールアウトするにつれてより多くの同時接続を保たなければなりません。
欠点: ロードバランサー
- ロードバランサーはリソースが不足していたり、設定が適切でない場合、システム全体のボトルネックになる可能性があります。
- 単一障害点を除こうとしてロードバランサーを導入した結果、複雑さが増してしまうことになります。
- 単一ロードバランサーでは単一障害点が除かれたことにはなりませんが、複数のロードバランサーはそれすなわち複雑化です。
その他の参考資料、ページ
- NGINX アーキテキチャ
- HAProxy アーキテキチャガイド
- スケーラビリティ
- Wikipedia
- Layer 4 ロードバランシング
- Layer 7 ロードバランシング
- ELB listener config
リバースプロキシ(webサーバー)
リバースプロキシサーバーは内部サービスをまとめて外部に統一されたインターフェースを提供するウェブサーバーです。クライアントからのリクエストはそれに対応するサーバーに送られて、その後レスポンスをリバースプロキシがクライアントに返します。
他には以下のような利点があります:
- より堅牢なセキュリティ - バックエンドサーバーの情報、ブラックリストIP、クライアントごとの接続数などの情報を隠すことができます。
- スケーラビリティや柔軟性が増します - クライアントはリバースプロキシのIPしか見ないので、裏でサーバーをスケールしたり、設定を変えやすくなります。
- SSL termination - 入力’されるリクエストを解読し、サーバーのレスポンスを暗号化することでサーバーがこのコストのかかりうる処理をしなくて済むようになります。
- X.509 証明書 を各サーバーにインストールする必要がなくなります。
- 圧縮 - サーバーレスポンスを圧縮できます
- キャッシング - キャッシュされたリクエストに対して、レスポンスを返します
- 静的コンテンツ - 静的コンテンツを直接送信することができます。
- HTML/CSS/JS
- 写真
- 動画
- などなど
ロードバランサー vs リバースプロキシ
- 複数のサーバーがある時にはロードバランサーをデプロイすると役に立つでしょう。 しばしば、ロードバランサーは同じ機能を果たすサーバー群へのトラフィックを捌きます。
- リバースプロキシでは、上記に述べたような利点を、単一のウェブサーバーやアプリケーションレイヤーに対しても示すことができます。
- NGINX や HAProxy などの技術はlayer 7 リバースプロキシとロードバランサーの両方をサポートします。
欠点: リバースプロキシ
- リバースプロキシを導入するとシステムの複雑性が増します。
- 単一のリバースプロキシは単一障害点になりえます。一方で、複数のリバースプロキシを導入すると([フェイルオーバー]など(https://en.wikipedia.org/wiki/Failover)) 複雑性はより増します。
その他の参考資料、ページ
アプリケーション層
Source: Intro to architecting systems for scale
ウェブレイヤーをアプリケーション層 (プラットフォーム層とも言われる) と分離することでそれぞれの層を独立にスケール、設定することができるようにまります。新しいAPIをアプリケーション層に追加する際に、不必要にウェブサーバーを追加する必要がなくなります。
単一責任の原則 では、小さい自律的なサービスが協調して動くように提唱しています。小さいサービスの小さいチームが急成長のためにより積極的な計画を立てられるようにするためです。
アプリケーション層は異時性もサポートします。
マイクロサービス
独立してデプロイできる、小規模なモジュール様式であるマイクロサービスもこの議論に関係してくる技術でしょう。それぞれのサービスは独自のプロセスを処理し、明確で軽量なメカニズムで通信して、その目的とする機能を実現します。1
例えばPinterestでは以下のようなマイクロサービスに分かれています。ユーザープロフィール、フォロワー、フィード、検索、写真アップロードなどです。
Service Discovery
Consul、 Etcd、 そして Zookeeper などのシステムはそれぞれを見つけやすいように、登録された名前、アドレス、そしてポート番号などを監視しています。Health checks はサービスの統一性を証明するのに有用ですが、しばしばHTTP エンドポイントを用いています。 Consul と Etcd のいずれも組み込みの key-value store を持っており、設定データや共有データなどのデータを保存しておくことに使われます。
欠点: アプリケーション層
- 緩く結び付けられたアプリケーション層を追加することは、モノリシックなシステムとはアーキテキチャ、運用、そしてプロセスの観点からすると異なるアプローチを必要とします。
- マイクロサービスはデプロイと運用の点から見ると複雑性が増すことになります。
その他の参考資料、ページ
- スケールするシステムアーキテキチャを設計するためにイントロ
- システム設計インタビューを紐解く
- サービス指向アーキテキチャ
- Zookeeperのイントロダクション
- マイクロサービスを作るために知っておきたいこと
データベース
Source: Scaling up to your first 10 million users
リレーショナルデータベースマネジメントシステム (RDBMS)
SQLなどのリレーショナルデータベースはテーブルに整理されたデータの集合である。
ACID はリレーショナルデータベースにおけるプロパティの集合である トランザクション
- 不可分性 - それぞれのトランザクションはあるかないかである。
- 一貫性 - どんなトランザクションもデータベースをある確かな状態から次の状態に遷移させる。
- 独立性 - 同時にトランザクションを処理することは、連続的にトランザクションを処理するのと同じ結果をもたらす。
- 永続性 - トランザクションが処理されたら、そのように保存される
リレーショナルデータベースをスケールさせるためにはたくさんの技術がある: マスタースレーブ レプリケーション、 マスターマスター レプリケーション、 federation, シャーディング, denormalization, and SQL チューニング.
マスタースレーブ レプリケーション
マスターデータベースが読み取りと書き込みを処理し、書き込みを一つ以上のスレーブデータベースに複製します。スレーブデータベースは読み取りのみを処理します。スレーブデータベースは木構造のように追加のスレーブにデータを複製することもできます。マスターデータベースがオフラインになった場合には、いずれかのスレーブがマスターに昇格するか、新しいマスターデータベースが追加されるまでは読み取り専用モードで稼働します。
Source: Scalability, availability, stability, patterns
欠点: マスタースレーブ レプリケーション
- スレーブをマスターに昇格させるには追加のロジックが必要になる。
- マスタースレーブ レプリケーション、マスターマスター レプリケーションの 両方 の欠点は次を参照欠点: レプリケーション
マスターマスター レプリケーション
いずれのマスターも読み取り書き込みの両方に対応する。書き込みに関してはそれぞれ強調する。いずれかのマスターが落ちても、システム全体としては読み書き両方に対応したまま運用できる。
Source: Scalability, availability, stability, patterns
欠点: マスターマスター レプリケーション
- ロードバランサーを導入するか、アプリケーションロジックを変更することでどこに書き込むかを指定しなければならない。
- 大体のマスターマスターシステムは、一貫性が緩い(ACID原理を守っていない)もしくは、同期する時間がかかるために書き込みのレイテンシーが増加してしまっている。
- 書き込みノードが追加され、レイテンシーが増加するにつれ書き込みの衝突の可能性が増える。
- マスタースレーブ レプリケーション、マスターマスター レプリケーションの 両方 の欠点は次を参照欠点: レプリケーション
欠点: レプリケーション
- 新しいデータ書き込みを複製する前にマスターが落ちた場合にはそのデータが失われてしまう可能性がある。
- 書き込みは読み取りレプリカにおいてリプレイされる。書き込みが多い場合、複製ノードが書き込みの処理のみで行き詰まって、読み取りの処理を満足に行えない可能性がある。
- 読み取りスレーブノードの数が多ければ多いほど、複製しなければならない数も増え、複製時間が伸びてしまいます。
- システムによっては、マスターへの書き込みはマルチスレッドで並列処理できる一方、スレーブへの複製は単一スレッドで連続的に処理しなければならない場合があります。
- レプリケーションでは追加のハードウェアが必要になり、複雑性も増します。
その他の参考資料、ページ
Federation
Source: Scaling up to your first 10 million users
Federation (or functional partitioning) splits up databases by function. For example, instead of a single, monolithic database, you could have three databases: forums, users, and products, resulting in less read and write traffic to each database and therefore less replication lag. Smaller databases result in more data that can fit in memory, which in turn results in more cache hits due to improved cache locality. With no single central master serializing writes you can write in parallel, increasing throughput.
Disadvantage(s): federation
- Federation is not effective if your schema requires huge functions or tables.
- You'll need to update your application logic to determine which database to read and write.
- Joining data from two databases is more complex with a server link.
- Federation adds more hardware and additional complexity.
Source(s) and further reading: federation
Sharding
Source: Scalability, availability, stability, patterns
Sharding distributes data across different databases such that each database can only manage a subset of the data. Taking a users database as an example, as the number of users increases, more shards are added to the cluster.
Similar to the advantages of federation, sharding results in less read and write traffic, less replication, and more cache hits. Index size is also reduced, which generally improves performance with faster queries. If one shard goes down, the other shards are still operational, although you'll want to add some form of replication to avoid data loss. Like federation, there is no single central master serializing writes, allowing you to write in parallel with increased throughput.
Common ways to shard a table of users is either through the user's last name initial or the user's geographic location.
Disadvantage(s): sharding
- You'll need to update your application logic to work with shards, which could result in complex SQL queries.
- Data distribution can become lopsided in a shard. For example, a set of power users on a shard could result in increased load to that shard compared to others.
- Rebalancing adds additional complexity. A sharding function based on consistent hashing can reduce the amount of transferred data.
- Joining data from multiple shards is more complex.
- Sharding adds more hardware and additional complexity.
Source(s) and further reading: sharding
Denormalization
Denormalization attempts to improve read performance at the expense of some write performance. Redundant copies of the data are written in multiple tables to avoid expensive joins. Some RDBMS such as PostgreSQL and Oracle support materialized views which handle the work of storing redundant information and keeping redundant copies consistent.
Once data becomes distributed with techniques such as federation and sharding, managing joins across data centers further increases complexity. Denormalization might circumvent the need for such complex joins.
In most systems, reads can heavily outnumber writes 100:1 or even 1000:1. A read resulting in a complex database join can be very expensive, spending a significant amount of time on disk operations.
Disadvantage(s): denormalization
- Data is duplicated.
- Constraints can help redundant copies of information stay in sync, which increases complexity of the database design.
- A denormalized database under heavy write load might perform worse than its normalized counterpart.
Source(s) and further reading: denormalization
SQL tuning
SQL tuning is a broad topic and many books have been written as reference.
It's important to benchmark and profile to simulate and uncover bottlenecks.
- Benchmark - Simulate high-load situations with tools such as ab.
- Profile - Enable tools such as the slow query log to help track performance issues.
Benchmarking and profiling might point you to the following optimizations.
Tighten up the schema
- MySQL dumps to disk in contiguous blocks for fast access.
- Use
CHAR
instead ofVARCHAR
for fixed-length fields.CHAR
effectively allows for fast, random access, whereas withVARCHAR
, you must find the end of a string before moving onto the next one.
- Use
TEXT
for large blocks of text such as blog posts.TEXT
also allows for boolean searches. Using aTEXT
field results in storing a pointer on disk that is used to locate the text block. - Use
INT
for larger numbers up to 2^32 or 4 billion. - Use
DECIMAL
for currency to avoid floating point representation errors. - Avoid storing large
BLOBS
, store the location of where to get the object instead. VARCHAR(255)
is the largest number of characters that can be counted in an 8 bit number, often maximizing the use of a byte in some RDBMS.- Set the
NOT NULL
constraint where applicable to improve search performance.
Use good indices
- Columns that you are querying (
SELECT
,GROUP BY
,ORDER BY
,JOIN
) could be faster with indices. - Indices are usually represented as self-balancing B-tree that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time.
- Placing an index can keep the data in memory, requiring more space.
- Writes could also be slower since the index also needs to be updated.
- When loading large amounts of data, it might be faster to disable indices, load the data, then rebuild the indices.
Avoid expensive joins
- Denormalize where performance demands it.
Partition tables
- Break up a table by putting hot spots in a separate table to help keep it in memory.
Tune the query cache
- In some cases, the query cache could lead to performance issues.
Source(s) and further reading: SQL tuning
- Tips for optimizing MySQL queries
- Is there a good reason i see VARCHAR(255) used so often?
- How do null values affect performance?
- Slow query log
NoSQL
NoSQL is a collection of data items represented in a key-value store, document-store, wide column store, or a graph database. Data is denormalized, and joins are generally done in the application code. Most NoSQL stores lack true ACID transactions and favor eventual consistency.
BASE is often used to describe the properties of NoSQL databases. In comparison with the CAP Theorem, BASE chooses availability over consistency.
- Basically available - the system guarantees availability.
- Soft state - the state of the system may change over time, even without input.
- Eventual consistency - the system will become consistent over a period of time, given that the system doesn't receive input during that period.
In addition to choosing between SQL or NoSQL, it is helpful to understand which type of NoSQL database best fits your use case(s). We'll review key-value stores, document-stores, wide column stores, and graph databases in the next section.
Key-value store
Abstraction: hash table
A key-value store generally allows for O(1) reads and writes and is often backed by memory or SSD. Data stores can maintain keys in lexicographic order, allowing efficient retrieval of key ranges. Key-value stores can allow for storing of metadata with a value.
Key-value stores provide high performance and are often used for simple data models or for rapidly-changing data, such as an in-memory cache layer. Since they offer only a limited set of operations, complexity is shifted to the application layer if additional operations are needed.
A key-value store is the basis for more complex systems such as a document store, and in some cases, a graph database.
Source(s) and further reading: key-value store
Document store
Abstraction: key-value store with documents stored as values
A document store is centered around documents (XML, JSON, binary, etc), where a document stores all information for a given object. Document stores provide APIs or a query language to query based on the internal structure of the document itself. Note, many key-value stores include features for working with a value's metadata, blurring the lines between these two storage types.
Based on the underlying implementation, documents are organized in either collections, tags, metadata, or directories. Although documents can be organized or grouped together, documents may have fields that are completely different from each other.
Some document stores like MongoDB and CouchDB also provide a SQL-like language to perform complex queries. DynamoDB supports both key-values and documents.
Document stores provide high flexibility and are often used for working with occasionally changing data.
Source(s) and further reading: document store
Wide column store
Source: SQL & NoSQL, a brief history
Abstraction: nested map
ColumnFamily<RowKey, Columns<ColKey, Value, Timestamp>>
A wide column store's basic unit of data is a column (name/value pair). A column can be grouped in column families (analogous to a SQL table). Super column families further group column families. You can access each column independently with a row key, and columns with the same row key form a row. Each value contains a timestamp for versioning and for conflict resolution.
Google introduced Bigtable as the first wide column store, which influenced the open-source HBase often-used in the Hadoop ecosystem, and Cassandra from Facebook. Stores such as BigTable, HBase, and Cassandra maintain keys in lexicographic order, allowing efficient retrieval of selective key ranges.
Wide column stores offer high availability and high scalability. They are often used for very large data sets.
Source(s) and further reading: wide column store
Graph database
Abstraction: graph
In a graph database, each node is a record and each arc is a relationship between two nodes. Graph databases are optimized to represent complex relationships with many foreign keys or many-to-many relationships.
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.
Source(s) and further reading: graph
Source(s) and further reading: NoSQL
- Explanation of base terminology
- NoSQL databases a survey and decision guidance
- Scalability
- Introduction to NoSQL
- NoSQL patterns
SQL or NoSQL
Source: Transitioning from RDBMS to NoSQL
Reasons for SQL:
- Structured data
- Strict schema
- Relational data
- Need for complex joins
- Transactions
- Clear patterns for scaling
- More established: developers, community, code, tools, etc
- Lookups by index are very fast
Reasons for NoSQL:
- Semi-structured data
- Dynamic or flexible schema
- Non-relational data
- No need for complex joins
- Store many TB (or PB) of data
- Very data intensive workload
- Very high throughput for IOPS
Sample data well-suited for 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
Cache
Source: Scalable system design patterns
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, or in a distinct cache layer.
CDN caching
CDNs are considered a type of cache.
Web server caching
Reverse proxies and caches such as Varnish can serve static and dynamic content directly. Web servers can also cache requests, returning responses without having to contact application servers.
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 algorithms such as least recently used (LRU) can help invalidate 'cold' entries and keep 'hot' data in RAM.
Redis has the following additional features:
- 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
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
Suggestions of what to cache:
- User sessions
- Fully rendered web pages
- 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
Source: From cache to in-memory data grid
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):
user = cache.get("user.{0}", user_id)
if user is None:
user = db.query("SELECT * FROM users WHERE user_id = {0}", user_id)
if user is not None:
key = "user.{0}".format(user_id)
cache.set(key, json.dumps(user))
return user
Memcached is generally used in this manner.
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.
- When a node fails, it is replaced by a new, empty node, increasing latency.
Write-through
Source: Scalability, availability, stability, patterns
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"})
Cache code:
def set_user(user_id, values):
user = db.query("UPDATE Users WHERE id = {0}", user_id, values)
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.
Write-behind (write-back)
Source: Scalability, availability, stability, patterns
In write-behind, the 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
Source: From cache to in-memory data grid
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.
- Need to make application changes such as adding Redis or 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
- Scalable system design patterns
- Introduction to architecting systems for scale
- Scalability, availability, stability, patterns
- Scalability
- AWS ElastiCache strategies
- Wikipedia
Asynchronism
Source: Intro to architecting systems for scale
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
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.
RabbitMQ is popular but requires you to adapt to the 'AMQP' protocol and manage your own nodes.
Amazon SQS, is hosted but can have high latency and has the possibility of messages being delivered twice.
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.
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 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.
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
- Applying back pressure when overloaded
- Little's law
- What is the difference between a message queue and a task queue?
Communication
Hypertext transfer protocol (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.
A basic HTTP request consists of a verb (method) and a resource (endpoint). Below are common HTTP verbs:
Verb | Description | Idempotent* | Safe | Cacheable |
---|---|---|---|---|
GET | Reads a resource | Yes | Yes | Yes |
POST | Creates a resource or trigger a process that handles data | No | No | Yes if response contains freshness info |
PUT | Creates or replace a resource | Yes | No | No |
PATCH | Partially updates a resource | No | No | Yes if response contains freshness info |
DELETE | Deletes a resource | Yes | No | No |
*Can be called many times without different outcomes.
HTTP is an application layer protocol relying on lower-level protocols such as TCP and UDP.
Source(s) and further reading: HTTP
Transmission control protocol (TCP)
Source: How to make a multiplayer game
TCP is a connection-oriented protocol over an IP network. Connection is established and terminated using a handshake. All packets sent are guaranteed to reach the destination in the original order and without corruption through:
- Sequence numbers and checksum fields for each packet
- Acknowledgement packets and automatic retransmission
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 and congestion control. These guarantees cause delays and generally result in less efficient transmission than 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 server. Connection pooling can help in addition to switching to UDP where applicable.
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.
Use TCP over UDP when:
- You need all of the data to arrive intact
- You want to automatically make a best estimate use of the network throughput
User datagram protocol (UDP)
Source: How to make a multiplayer game
UDP is connectionless. Datagrams (analogous to packets) are guaranteed only at the datagram level. Datagrams might reach their destination out of order or not at all. UDP does not support congestion control. Without the guarantees that TCP support, UDP is generally more efficient.
UDP can broadcast, sending datagrams to all devices on the subnet. This is useful with DHCP because the client has not yet received an IP address, thus preventing a way for TCP to stream without the IP address.
UDP is less reliable but works well in real time use cases such as VoIP, video chat, streaming, and realtime multiplayer games.
Use UDP over TCP when:
- You need the lowest latency
- Late data is worse than loss of data
- You want to implement your own error correction
Source(s) and further reading: TCP and UDP
- Networking for game programming
- Key differences between TCP and UDP protocols
- Difference between TCP and UDP
- Transmission control protocol
- User datagram protocol
- Scaling memcache at Facebook
Remote procedure call (RPC)
Source: Crack the system design interview
In an RPC, a client causes a procedure to execute on a different address space, usually a remote server. The procedure is coded as if it were a local procedure call, abstracting away the details of how to communicate with the server from the client program. Remote calls are usually slower and less reliable than local calls so it is helpful to distinguish RPC calls from local calls. Popular RPC frameworks include Protobuf, Thrift, and Avro.
RPC is a request-response protocol:
- Client program - Calls the client stub procedure. The parameters are pushed onto the stack like a local procedure call.
- Client stub procedure - Marshals (packs) procedure id and arguments into a request message.
- Client communication module - OS sends the message from the client to the server.
- Server communication module - OS passes the incoming packets to the server stub procedure.
- Server stub procedure - Unmarshalls the results, calls the server procedure matching the procedure id and passes the given arguments.
- The server response repeats the steps above in reverse order.
Sample RPC calls:
GET /someoperation?data=anId
POST /anotheroperation
{
"data":"anId";
"anotherdata": "another value"
}
RPC is focused on exposing behaviors. RPCs are often used for performance reasons with internal communications, as you can hand-craft native calls to better fit your use cases.
Choose a native library (aka SDK) when:
- You know your target platform.
- You want to control how your "logic" is accessed.
- You want to control how error control happens off your library.
- Performance and end user experience is your primary concern.
HTTP APIs following REST tend to be used more often for public APIs.
Disadvantage(s): RPC
- RPC clients become tightly coupled to the service implementation.
- A new API must be defined for every new operation or use case.
- It can be difficult to debug RPC.
- You might not be able to leverage existing technologies out of the box. For example, it might require additional effort to ensure RPC calls are properly cached on caching servers such as Squid.
Representational state transfer (REST)
REST is an architectural style enforcing a client/server model where the client acts on a set of resources managed by the server. The server provides a representation of resources and actions that can either manipulate or get a new representation of resources. All communication must be stateless and cacheable.
There are four qualities of a RESTful interface:
- Identify resources (URI in HTTP) - use the same URI regardless of any operation.
- Change with representations (Verbs in HTTP) - use verbs, headers, and body.
- Self-descriptive error message (status response in HTTP) - Use status codes, don't reinvent the wheel.
- HATEOAS (HTML interface for HTTP) - your web service should be fully accessible in a browser.
Sample REST calls:
GET /someresources/anId
PUT /someresources/anId
{"anotherdata": "another value"}
REST is focused on exposing data. It minimizes the coupling between client/server and is often used for public HTTP APIs. REST uses a more generic and uniform method of exposing resources through URIs, representation through headers, and actions through verbs such as GET, POST, PUT, DELETE, and PATCH. Being stateless, REST is great for horizontal scaling and partitioning.
Disadvantage(s): REST
- With REST being focused on exposing data, it might not be a good fit if resources are not naturally organized or accessed in a simple hierarchy. For example, returning all updated records from the past hour matching a particular set of events is not easily expressed as a path. With REST, it is likely to be implemented with a combination of URI path, query parameters, and possibly the request body.
- REST typically relies on a few verbs (GET, POST, PUT, DELETE, and PATCH) which sometimes doesn't fit your use case. For example, moving expired documents to the archive folder might not cleanly fit within these verbs.
- Fetching complicated resources with nested hierarchies requires multiple round trips between the client and server to render single views, e.g. fetching content of a blog entry and the comments on that entry. For mobile applications operating in variable network conditions, these multiple roundtrips are highly undesirable.
- Over time, more fields might be added to an API response and older clients will receive all new data fields, even those that they do not need, as a result, it bloats the payload size and leads to larger latencies.
RPC and REST calls comparison
Operation | RPC | REST |
---|---|---|
Signup | POST /signup | POST /persons |
Resign | POST /resign { "personid": "1234" } |
DELETE /persons/1234 |
Read a person | GET /readPerson?personid=1234 | GET /persons/1234 |
Read a person’s items list | GET /readUsersItemsList?personid=1234 | GET /persons/1234/items |
Add an item to a person’s items | POST /addItemToUsersItemsList { "personid": "1234"; "itemid": "456" } |
POST /persons/1234/items { "itemid": "456" } |
Update an item | POST /modifyItem { "itemid": "456"; "key": "value" } |
PUT /items/456 { "key": "value" } |
Delete an item | POST /removeItem { "itemid": "456" } |
DELETE /items/456 |
Source: Do you really know why you prefer REST over RPC
Source(s) and further reading: REST and RPC
- Do you really know why you prefer REST over RPC
- When are RPC-ish approaches more appropriate than REST?
- REST vs JSON-RPC
- Debunking the myths of RPC and REST
- What are the drawbacks of using REST
- Crack the system design interview
- Thrift
- Why REST for internal use and not RPC
Security
This section could use some updates. Consider contributing!
Security is a broad topic. Unless you have considerable experience, a security background, or are applying for a position that requires knowledge of security, you probably won't need to know more than the basics:
- Encrypt in transit and at rest.
- Sanitize all user inputs or any input parameters exposed to user to prevent XSS and SQL injection.
- Use parameterized queries to prevent SQL injection.
- Use the principle of least privilege.
Source(s) and further reading
Appendix
You'll sometimes be asked to do 'back-of-the-envelope' estimates. For example, you might need to determine how long it will take to generate 100 image thumbnails from disk or how much memory a data structure will take. The Powers of two table and Latency numbers every programmer should know are handy references.
Powers of two table
Power Exact Value Approx Value Bytes
---------------------------------------------------------------
7 128
8 256
10 1024 1 thousand 1 KB
16 65,536 64 KB
20 1,048,576 1 million 1 MB
30 1,073,741,824 1 billion 1 GB
32 4,294,967,296 4 GB
40 1,099,511,627,776 1 trillion 1 TB
Source(s) and further reading
Latency numbers every programmer should know
Latency Comparison Numbers
--------------------------
L1 cache reference 0.5 ns
Branch mispredict 5 ns
L2 cache reference 7 ns 14x L1 cache
Mutex lock/unlock 100 ns
Main memory reference 100 ns 20x L2 cache, 200x L1 cache
Compress 1K bytes with Zippy 10,000 ns 10 us
Send 1 KB bytes over 1 Gbps network 10,000 ns 10 us
Read 4 KB randomly from SSD* 150,000 ns 150 us ~1GB/sec SSD
Read 1 MB sequentially from memory 250,000 ns 250 us
Round trip within same datacenter 500,000 ns 500 us
Read 1 MB sequentially from SSD* 1,000,000 ns 1,000 us 1 ms ~1GB/sec SSD, 4X memory
Disk seek 10,000,000 ns 10,000 us 10 ms 20x datacenter roundtrip
Read 1 MB sequentially from 1 Gbps 10,000,000 ns 10,000 us 10 ms 40x memory, 10X SSD
Read 1 MB sequentially from disk 30,000,000 ns 30,000 us 30 ms 120x memory, 30X SSD
Send packet CA->Netherlands->CA 150,000,000 ns 150,000 us 150 ms
Notes
-----
1 ns = 10^-9 seconds
1 us = 10^-6 seconds = 1,000 ns
1 ms = 10^-3 seconds = 1,000 us = 1,000,000 ns
Handy metrics based on numbers above:
- Read sequentially from disk at 30 MB/s
- Read sequentially from 1 Gbps Ethernet at 100 MB/s
- Read sequentially from SSD at 1 GB/s
- Read sequentially from main memory at 4 GB/s
- 6-7 world-wide round trips per second
- 2,000 round trips per second within a data center
Latency numbers visualized
Source(s) and further reading
- Latency numbers every programmer should know - 1
- Latency numbers every programmer should know - 2
- Designs, lessons, and advice from building large distributed systems
- Software Engineering Advice from Building Large-Scale Distributed Systems
Additional system design interview questions
Common system design interview questions, with links to resources on how to solve each.
Question | Reference(s) |
---|---|
Design a file sync service like Dropbox | youtube.com |
Design a search engine like Google | queue.acm.org stackexchange.com ardendertat.com stanford.edu |
Design a scalable web crawler like Google | quora.com |
Design Google docs | code.google.com neil.fraser.name |
Design a key-value store like Redis | slideshare.net |
Design a cache system like Memcached | slideshare.net |
Design a recommendation system like Amazon's | hulu.com ijcai13.org |
Design a tinyurl system like Bitly | n00tc0d3r.blogspot.com |
Design a chat app like WhatsApp | highscalability.com |
Design a picture sharing system like Instagram | highscalability.com highscalability.com |
Design the Facebook news feed function | quora.com quora.com slideshare.net |
Design the Facebook timeline function | facebook.com highscalability.com |
Design the Facebook chat function | erlang-factory.com facebook.com |
Design a graph search function like Facebook's | facebook.com facebook.com facebook.com |
Design a content delivery network like CloudFlare | cmu.edu |
Design a trending topic system like Twitter's | michael-noll.com snikolov .wordpress.com |
Design a random ID generation system | blog.twitter.com github.com |
Return the top k requests during a time interval | ucsb.edu wpi.edu |
Design a system that serves data from multiple data centers | highscalability.com |
Design an online multiplayer card game | indieflashblog.com buildnewgames.com |
Design a garbage collection system | stuffwithstuff.com washington.edu |
Add a system design question | Contribute |
Real world architectures
Articles on how real world systems are designed.
Source: Twitter timelines at scale
Don't focus on nitty gritty details for the following articles, instead:
- Identify shared principles, common technologies, and patterns within these articles
- Study what problems are solved by each component, where it works, where it doesn't
- Review the lessons learned
Type | System | Reference(s) |
---|---|---|
Data processing | MapReduce - Distributed data processing from Google | research.google.com |
Data processing | Spark - Distributed data processing from Databricks | slideshare.net |
Data processing | Storm - Distributed data processing from Twitter | slideshare.net |
Data store | Bigtable - Distributed column-oriented database from Google | harvard.edu |
Data store | HBase - Open source implementation of Bigtable | slideshare.net |
Data store | Cassandra - Distributed column-oriented database from Facebook | slideshare.net |
Data store | DynamoDB - Document-oriented database from Amazon | harvard.edu |
Data store | MongoDB - Document-oriented database | slideshare.net |
Data store | Spanner - Globally-distributed database from Google | research.google.com |
Data store | Memcached - Distributed memory caching system | slideshare.net |
Data store | Redis - Distributed memory caching system with persistence and value types | slideshare.net |
File system | Google File System (GFS) - Distributed file system | research.google.com |
File system | Hadoop File System (HDFS) - Open source implementation of GFS | apache.org |
Misc | Chubby - Lock service for loosely-coupled distributed systems from Google | research.google.com |
Misc | Dapper - Distributed systems tracing infrastructure | research.google.com |
Misc | Kafka - Pub/sub message queue from LinkedIn | slideshare.net |
Misc | Zookeeper - Centralized infrastructure and services enabling synchronization | slideshare.net |
Add an architecture | Contribute |
Company architectures
Company engineering blogs
Architectures for companies you are interviewing with.
Questions you encounter might be from the same domain.
- Airbnb Engineering
- Atlassian Developers
- Autodesk Engineering
- AWS Blog
- Bitly Engineering Blog
- Box Blogs
- Cloudera Developer Blog
- Dropbox Tech Blog
- Engineering at Quora
- Ebay Tech Blog
- Evernote Tech Blog
- Etsy Code as Craft
- Facebook Engineering
- Flickr Code
- Foursquare Engineering Blog
- GitHub Engineering Blog
- Google Research Blog
- Groupon Engineering Blog
- Heroku Engineering Blog
- Hubspot Engineering Blog
- High Scalability
- Instagram Engineering
- Intel Software Blog
- Jane Street Tech Blog
- LinkedIn Engineering
- Microsoft Engineering
- Microsoft Python Engineering
- Netflix Tech Blog
- Paypal Developer Blog
- Pinterest Engineering Blog
- Quora Engineering
- Reddit Blog
- Salesforce Engineering Blog
- Slack Engineering Blog
- Spotify Labs
- Twilio Engineering Blog
- Twitter Engineering
- Uber Engineering Blog
- Yahoo Engineering Blog
- Yelp Engineering Blog
- Zynga Engineering Blog
Source(s) and further reading
The list of blogs here will be kept relatively small and kilimchoi/engineering-blogs will contain the larger list to avoid duplicating work. Do consider adding your company blog to the engineering-blogs repo instead.
Under development
Interested in adding a section or helping complete one in-progress? Contribute!
- Distributed computing with MapReduce
- Consistent hashing
- Scatter gather
- Contribute
Credits
Credits and sources are provided throughout this repo.
Special thanks to:
- Hired in tech
- Cracking the coding interview
- High scalability
- checkcheckzz/system-design-interview
- shashank88/system_design
- mmcgrana/services-engineering
- System design cheat sheet
- A distributed systems reading list
- Cracking the system design interview
Contact info
Feel free to contact me to discuss any issues, questions, or comments.
My contact info can be found on my GitHub page.
License
I am providing code and resources in this repository to you under an open source license. Because this is my personal repository, the license you receive to my code and resources is from me and not my employer (Facebook).
Copyright 2017 Donne Martin
Creative Commons Attribution 4.0 International License (CC BY 4.0)
http://creativecommons.org/licenses/by/4.0/