-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsergeyleschev-system-architect-roadmap.html
2124 lines (2111 loc) · 143 KB
/
sergeyleschev-system-architect-roadmap.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
<meta name="description" content="Sergey Leschev, Team Lead (Swift, TypeScript, Database). Sergey is a professional who is responsible for the design and construction of websites and apps.">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@sergeyleschev">
<meta name="twitter:title" content="Sergey Leschev">
<meta name="twitter:description" content="Sergey Leschev, Team Lead (Swift, TypeScript, Database). Sergey is a professional who is responsible for the design and construction of websites and apps.">
<meta name="twitter:image" content="https://pbs.twimg.com/profile_images/1372479346225582088/Qek8o6vC_400x400.jpg">
<meta name="twitter:image:src" content="https://pbs.twimg.com/profile_images/1372479346225582088/Qek8o6vC_400x400.jpg">
<meta name="robots" content="index, archive" />
<meta property="cdc:template_version" content="4.0">
<title>Sergey Leschev - System Architect</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="shortcut icon" type="image/png" href="favicon-32x32.png"/>
<link rel="manifest" href="site.webmanifest">
<link rel="alternate" href="https://sergeyleschev.github.io/sergeyleschev-system-architect-roadmap.html" hreflang="en-gb"/>
<link rel="alternate" type="application/rss+xml" title="RSS feed: Sergey Leschev - Team Lead" href="https://sergeyleschev.github.io/rss.xml" />
<link rel="canonical" href="https://sergeyleschev.github.io/sergeyleschev-system-architect-roadmap.html" />
<!-- <script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '414247107560114');
fbq('track', 'Lead');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=414247107560114&ev=Lead&noscript=1"
/></noscript> -->
<script type="application/ld+json">
{
"@context": "https://schema.org/",
"@type": "Person",
"name": "Sergey Leschev, Team Lead",
"author": "Sergey Leschev",
"image": "https://avatars.githubusercontent.com/u/23653372?v=4&raw=true",
"description": "Sergey is a professional who is responsible for the design and construction of websites and apps.",
"aggregateRating": {
"@type": "AggregateRating",
"ratingValue": "5.0",
"reviewCount": "1427",
"bestRating": "5",
"worstRating": "3"
}
}
</script>
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
<meta name="color-scheme" content="light dark">
<meta name="author" content="Sergey Leschev">
<meta name="keywords" content="sergey leschev, siarhei liashchou, sergeyleschev, senior developer, team lead, cto, swift deverloper, typescript developer, near me job, jobs hiring near me, usaa jobs, jobs, work from home jobs, part time jobs near me, remote jobs, target jobs, hiring jobs, jobs online, jobs part time, google jobs, linked in jobs, linkedin jobs, home depot career, jobs from home, virtual assistant jobs, indeed jobs near me, leader, knowledge, qualifications, education, tips, skills, multitasking, references, success, work, job, tie, challenges, abilities, impress, responsibility, future, weeknesses, benefits, results, team player, strengths, interview, degress, examples, strengths, experienced, problem solver, candidate, agency, objective, initiative, team, dreams, conflict, can-do, training, questions, job, work, career, created, swift, typescript, javascript, sql, nosql, postgresql, oracle, sql server, react, redux, swiftui, objective-c, devops, aws, mongodb, pl/sql, angular, project management, nodejs, nextjs, nestjs, api, agile, amplitude, analytics, appclip, appstore, bash, css, jira, confluence, git, graphql, html, html5, mvp, mvvm, nginx, ssh, prime react, rest, teamcity, typeorm, uikit, uml, viper, widgets, xcode, json, linux, docker, mobx, tvOS, watchOS" />
<link rel="stylesheet" href="github-markdown.css">
<style>
body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 25px;
}
@media (prefers-color-scheme: dark) {
body {
background-color: #0d1117;
}
}
</style>
<style>
.github-fork-ribbon:before {
background-color: #121612;
}
</style>
</head>
<body>
<article id="personal-details" class="markdown-body"><h1> <a href="https://sergeyleschev.github.io"><img itemprop="image" alt="Sergey Leschev" src="apple-touch-icon.png" width=27/></a> Sergey Leschev</h1>
<img itemprop="image" alt="Sergey Leschev" src="https://sergeyleschev.github.io/sergeyleschev.png" width=300/>
<h3>System Architect</h3>
<p><a href="https://sergeyleschev.github.io/sergeyleschev-ios-roadmap.html">Swift (L6+)</a> | <a href="https://sergeyleschev.github.io/sergeyleschev-fullstack-roadmap.html">Full Stack (L6+)</a> | <a href="https://sergeyleschev.github.io/sergeyleschev-design-patterns.html">Design Patterns (L6+)</a> | <a href="https://sergeyleschev.github.io/sergeyleschev-system-architect-roadmap.html">System Architect (L7+)</a> | <a href="https://medium.com/@sergeyleschev/lists">Blog</a></p>
<p>Google Engineering Level: L7+</p>
<br>
<h2>🏆 Awards</h2>
<h3>Ranking #Dev: Global TOP 200 (<a href="https://leetcode.com/sergeyleschev/">Certificate</a>)</h3>
<p><a href="https://leetcode.com/sergeyleschev/"><img src="https://github.com/sergeyleschev/sergeyleschev/blob/main/leetcode-ranking.png?raw=true" alt="drawing" width="410"></a></p>
<h2>The System Design</h2>
<h3>Design large-scale systems</h3>
<p>System design is a broad topic. There is a <strong>vast amount of resources scattered throughout the web</strong> on system design principles.</p>
<p align="center">
<img alt="system design" src="images/jrUBAF7.png?raw=true" width="400">
<br>
</p>
<div style="page-break-after: always;"></div>
<h2>Index of system design topics</h2>
<blockquote>
<p>Summaries of various system design topics, including pros and cons. <strong>Everything is a trade-off</strong>.</p>
<p>Each section contains links to more in-depth resources.</p>
</blockquote>
<ul>
<li><a href="#system-design-topics-start-here">System design topics: start here</a>
<ul>
<li><a href="#step-1-review-the-scalability-video-lecture">Step 1: Review the scalability video lecture</a></li>
<li><a href="#step-2-review-the-scalability-article">Step 2: Review the scalability article</a></li>
<li><a href="#next-steps">Next steps</a></li>
</ul>
</li>
<li><a href="#performance-vs-scalability">Performance vs scalability</a></li>
<li><a href="#latency-vs-throughput">Latency vs throughput</a></li>
<li><a href="#availability-vs-consistency">Availability vs consistency</a>
<ul>
<li><a href="#cap-theorem">CAP theorem</a>
<ul>
<li><a href="#cp---consistency-and-partition-tolerance">CP - consistency and partition tolerance</a></li>
<li><a href="#ap---availability-and-partition-tolerance">AP - availability and partition tolerance</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#consistency-patterns">Consistency patterns</a>
<ul>
<li><a href="#weak-consistency">Weak consistency</a></li>
<li><a href="#eventual-consistency">Eventual consistency</a></li>
<li><a href="#strong-consistency">Strong consistency</a></li>
</ul>
</li>
<li><a href="#availability-patterns">Availability patterns</a>
<ul>
<li><a href="#fail-over">Fail-over</a></li>
<li><a href="#replication">Replication</a></li>
<li><a href="#availability-in-numbers">Availability in numbers</a></li>
</ul>
</li>
<li><a href="#domain-name-system">Domain name system</a></li>
<li><a href="#content-delivery-network">Content delivery network</a>
<ul>
<li><a href="#push-cdns">Push CDNs</a></li>
<li><a href="#pull-cdns">Pull CDNs</a></li>
</ul>
</li>
<li><a href="#load-balancer">Load balancer</a>
<ul>
<li><a href="#active-passive">Active-passive</a></li>
<li><a href="#active-active">Active-active</a></li>
<li><a href="#layer-4-load-balancing">Layer 4 load balancing</a></li>
<li><a href="#layer-7-load-balancing">Layer 7 load balancing</a></li>
<li><a href="#horizontal-scaling">Horizontal scaling</a></li>
</ul>
</li>
<li><a href="#reverse-proxy-web-server">Reverse proxy (web server)</a>
<ul>
<li><a href="#load-balancer-vs-reverse-proxy">Load balancer vs reverse proxy</a></li>
</ul>
</li>
<li><a href="#application-layer">Application layer</a>
<ul>
<li><a href="#microservices">Microservices</a></li>
<li><a href="#service-discovery">Service discovery</a></li>
</ul>
</li>
<li><a href="#database">Database</a>
<ul>
<li><a href="#relational-database-management-system-rdbms">Relational database management system (RDBMS)</a>
<ul>
<li><a href="#master-slave-replication">Master-slave replication</a></li>
<li><a href="#master-master-replication">Master-master replication</a></li>
<li><a href="#federation">Federation</a></li>
<li><a href="#sharding">Sharding</a></li>
<li><a href="#denormalization">Denormalization</a></li>
<li><a href="#sql-tuning">SQL tuning</a></li>
</ul>
</li>
<li><a href="#nosql">NoSQL</a>
<ul>
<li><a href="#key-value-store">Key-value store</a></li>
<li><a href="#document-store">Document store</a></li>
<li><a href="#wide-column-store">Wide column store</a></li>
<li><a href="#graph-database">Graph Database</a></li>
</ul>
</li>
<li><a href="#sql-or-nosql">SQL or NoSQL</a></li>
</ul>
</li>
<li><a href="#cache">Cache</a>
<ul>
<li><a href="#client-caching">Client caching</a></li>
<li><a href="#cdn-caching">CDN caching</a></li>
<li><a href="#web-server-caching">Web server caching</a></li>
<li><a href="#database-caching">Database caching</a></li>
<li><a href="#application-caching">Application caching</a></li>
<li><a href="#caching-at-the-database-query-level">Caching at the database query level</a></li>
<li><a href="#caching-at-the-object-level">Caching at the object level</a></li>
<li><a href="#when-to-update-the-cache">When to update the cache</a>
<ul>
<li><a href="#cache-aside">Cache-aside</a></li>
<li><a href="#write-through">Write-through</a></li>
<li><a href="#write-behind-write-back">Write-behind (write-back)</a></li>
<li><a href="#refresh-ahead">Refresh-ahead</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#asynchronism">Asynchronism</a>
<ul>
<li><a href="#message-queues">Message queues</a></li>
<li><a href="#task-queues">Task queues</a></li>
<li><a href="#back-pressure">Back pressure</a></li>
</ul>
</li>
<li><a href="#communication">Communication</a>
<ul>
<li><a href="#transmission-control-protocol-tcp">Transmission control protocol (TCP)</a></li>
<li><a href="#user-datagram-protocol-udp">User datagram protocol (UDP)</a></li>
<li><a href="#remote-procedure-call-rpc">Remote procedure call (RPC)</a></li>
<li><a href="#representational-state-transfer-rest">Representational state transfer (REST)</a></li>
</ul>
</li>
<li><a href="#security">Security</a></li>
<li><a href="#appendix">Appendix</a>
<ul>
<li><a href="#powers-of-two-table">Powers of two table</a></li>
<li><a href="#latency-numbers-every-programmer-should-know">Latency numbers every programmer should know</a></li>
<li><a href="#additional-system-design">Additional system design</a></li>
<li><a href="#real-world-architectures">Real world architectures</a></li>
<li><a href="#company-architectures">Company architectures</a></li>
<li><a href="#company-engineering-blogs">Company engineering blogs</a></li>
</ul>
</li>
</ul>
<div style="page-break-after: always;"></div>
<h2>How to approach a system design questions</h2>
<blockquote>
<p>How to tackle a system design question.s</p>
</blockquote>
<p>The system design is an <strong>open-ended conversation</strong>. You are expected to lead it.</p>
<p>You can use the following steps to guide the discussion. To help solidify this process, work through the <a href="#system-design-questions-with-solutions">System design questions with solutions</a> section using the following steps.</p>
<h3>Step 1: Outline use cases, constraints, and assumptions</h3>
<p>Gather requirements and scope the problem. Ask questions to clarify use cases and constraints. Discuss assumptions.</p>
<ul>
<li>Who is going to use it?</li>
<li>How are they going to use it?</li>
<li>How many users are there?</li>
<li>What does the system do?</li>
<li>What are the inputs and outputs of the system?</li>
<li>How much data do we expect to handle?</li>
<li>How many requests per second do we expect?</li>
<li>What is the expected read to write ratio?</li>
</ul>
<h3>Step 2: Create a high level design</h3>
<p>Outline a high level design with all important components.</p>
<ul>
<li>Sketch the main components and connections</li>
<li>Justify your ideas</li>
</ul>
<h3>Step 3: Design core components</h3>
<p>Dive into details for each core component. For example, if you were asked to <a href="solutions/system_design/pastebin/sergeyleschev-system-design-roadmap.md">design a url shortening service</a>, discuss:</p>
<ul>
<li>Generating and storing a hash of the full url
<ul>
<li><a href="solutions/system_design/pastebin/sergeyleschev-system-design-roadmap.md">MD5</a> and <a href="solutions/system_design/pastebin/sergeyleschev-system-design-roadmap.md">Base62</a></li>
<li>Hash collisions</li>
<li>SQL or NoSQL</li>
<li>Database schema</li>
</ul>
</li>
<li>Translating a hashed url to the full url
<ul>
<li>Database lookup</li>
</ul>
</li>
<li>API and object-oriented design</li>
</ul>
<h3>Step 4: Scale the design</h3>
<p>Identify and address bottlenecks, given the constraints. For example, do you need the following to address scalability issues?</p>
<ul>
<li>Load balancer</li>
<li>Horizontal scaling</li>
<li>Caching</li>
<li>Database sharding</li>
</ul>
<p>Discuss potential solutions and trade-offs. Everything is a trade-off. Address bottlenecks using <a href="#index-of-system-design-topics">principles of scalable system design</a>.</p>
<h3>Back-of-the-envelope calculations</h3>
<p>You might be asked to do some estimates by hand. Refer to the <a href="#appendix">Appendix</a> for the following resources:</p>
<ul>
<li><a href="http://highscalability.com/blog/2011/1/26/google-pro-tip-use-back-of-the-envelope-calculations-to-choo.html">Use back of the envelope calculations</a></li>
<li><a href="#powers-of-two-table">Powers of two table</a></li>
<li><a href="#latency-numbers-every-programmer-should-know">Latency numbers every programmer should know</a></li>
</ul>
<h3>Source(s) and further reading</h3>
<p>Check out the following links to get a better idea of what to expect:</p>
<ul>
<li><a href="https://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/">How to ace a systems design questions</a></li>
<li><a href="http://www.hiredintech.com/system-design">The system design questions</a></li>
<li><a href="https://www.youtube.com/watch?v=ZgdS0EUmn70">Intro to Architecture and Systems Design questions</a></li>
<li><a href="https://leetcode.com/discuss/career/229177/My-System-Design-Template">System design template</a></li>
</ul>
<h2>System design questions with solutions</h2>
<blockquote>
<p>Common system design questions with sample discussions, code, and diagrams.</p>
<p>Solutions linked to content in the <code>solutions/</code> folder.</p>
</blockquote>
<table>
<thead>
<tr>
<th>Question</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Design Pastebin.com (or Bit.ly)</td>
<td><a href="solutions/system_design/pastebin/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
<tr>
<td>Design the Twitter timeline and search (or Facebook feed and search)</td>
<td><a href="solutions/system_design/twitter/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
<tr>
<td>Design a web crawler</td>
<td><a href="solutions/system_design/web_crawler/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
<tr>
<td>Design Mint.com</td>
<td><a href="solutions/system_design/mint/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
<tr>
<td>Design the data structures for a social network</td>
<td><a href="solutions/system_design/social_graph/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
<tr>
<td>Design a key-value store for a search engine</td>
<td><a href="solutions/system_design/query_cache/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
<tr>
<td>Design Amazon’s sales ranking by category feature</td>
<td><a href="solutions/system_design/sales_rank/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
<tr>
<td>Design a system that scales to millions of users on AWS</td>
<td><a href="solutions/system_design/scaling_aws/sergeyleschev-system-design-roadmap.md">Solution</a></td>
</tr>
</tbody>
</table>
<div style="page-break-after: always;"></div>
<h3>Design Pastebin.com (or Bit.ly)</h3>
<p><a href="solutions/system_design/pastebin/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/4edXG0T.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h3>Design the Twitter timeline and search (or Facebook feed and search)</h3>
<p><a href="solutions/system_design/twitter/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/jrUBAF7.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h3>Design a web crawler</h3>
<p><a href="solutions/system_design/web_crawler/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/bWxPtQA.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h3>Design Mint.com</h3>
<p><a href="solutions/system_design/mint/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/V5q57vU.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h3>Design the data structures for a social network</h3>
<p><a href="solutions/system_design/social_graph/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/cdCv5g7.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h3>Design a key-value store for a search engine</h3>
<p><a href="solutions/system_design/query_cache/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/4j99mhe.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h3>Design Amazon’s sales ranking by category feature</h3>
<p><a href="solutions/system_design/sales_rank/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/MzExP06.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h3>Design a system that scales to millions of users on AWS</h3>
<p><a href="solutions/system_design/scaling_aws/sergeyleschev-system-design-roadmap.md">View solution</a></p>
<img alt="system design" src="images/jj3A5N8.png?raw=true" width="400">
<div style="page-break-after: always;"></div>
<h2>Object-oriented design questions with solutions</h2>
<blockquote>
<p>Common object-oriented design questions with sample discussions, code, and diagrams.</p>
<p>Solutions linked to content in the <code>solutions/</code> folder.</p>
</blockquote>
<blockquote>
<p><strong>Note: This section is under development</strong></p>
</blockquote>
<table>
<thead>
<tr>
<th>Question</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Design a hash map</td>
<td><a href="solutions/object_oriented_design/hash_table/hash_map.ipynb">Solution</a></td>
</tr>
<tr>
<td>Design a least recently used cache</td>
<td><a href="solutions/object_oriented_design/lru_cache/lru_cache.ipynb">Solution</a></td>
</tr>
<tr>
<td>Design a call center</td>
<td><a href="solutions/object_oriented_design/call_center/call_center.ipynb">Solution</a></td>
</tr>
<tr>
<td>Design a deck of cards</td>
<td><a href="solutions/object_oriented_design/deck_of_cards/deck_of_cards.ipynb">Solution</a></td>
</tr>
<tr>
<td>Design a parking lot</td>
<td><a href="solutions/object_oriented_design/parking_lot/parking_lot.ipynb">Solution</a></td>
</tr>
<tr>
<td>Design a chat server</td>
<td><a href="solutions/object_oriented_design/online_chat/online_chat.ipynb">Solution</a></td>
</tr>
</tbody>
</table>
<h2>System design topics: start here</h2>
<p>New to system design?</p>
<p>First, you’ll need a basic understanding of common principles, learning about what they are, how they are used, and their pros and cons.</p>
<h3>Step 1: Review the scalability video lecture</h3>
<p><a href="https://www.youtube.com/watch?v=-W9F__D3oY4">Scalability Lecture at Harvard</a></p>
<ul>
<li>Topics covered:
<ul>
<li>Vertical scaling</li>
<li>Horizontal scaling</li>
<li>Caching</li>
<li>Load balancing</li>
<li>Database replication</li>
<li>Database partitioning</li>
</ul>
</li>
</ul>
<h3>Step 2: Review the scalability article</h3>
<p><a href="http://www.lecloud.net/tagged/scalability/chrono">Scalability</a></p>
<ul>
<li>Topics covered:
<ul>
<li><a href="http://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones">Clones</a></li>
<li><a href="http://www.lecloud.net/post/7994751381/scalability-for-dummies-part-2-database">Databases</a></li>
<li><a href="http://www.lecloud.net/post/9246290032/scalability-for-dummies-part-3-cache">Caches</a></li>
<li><a href="http://www.lecloud.net/post/9699762917/scalability-for-dummies-part-4-asynchronism">Asynchronism</a></li>
</ul>
</li>
</ul>
<h3>Next steps</h3>
<p>Next, we’ll look at high-level trade-offs:</p>
<ul>
<li><strong>Performance</strong> vs <strong>scalability</strong></li>
<li><strong>Latency</strong> vs <strong>throughput</strong></li>
<li><strong>Availability</strong> vs <strong>consistency</strong></li>
</ul>
<p>Keep in mind that <strong>everything is a trade-off</strong>.</p>
<p>Then we’ll dive into more specific topics such as DNS, CDNs, and load balancers.</p>
<h2>Performance vs scalability</h2>
<p>A service is <strong>scalable</strong> if it results in increased <strong>performance</strong> 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></p>
<p>Another way to look at performance vs scalability:</p>
<ul>
<li>If you have a <strong>performance</strong> problem, your system is slow for a single user.</li>
<li>If you have a <strong>scalability</strong> problem, your system is fast for a single user but slow under heavy load.</li>
</ul>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="http://www.allthingsdistributed.com/2006/03/a_word_on_scalability.html">A word on scalability</a></li>
<li><a href="http://www.slideshare.net/jboner/scalability-availability-stability-patterns/">Scalability, availability, stability, patterns</a></li>
</ul>
<h2>Latency vs throughput</h2>
<p><strong>Latency</strong> is the time to perform some action or to produce some result.</p>
<p><strong>Throughput</strong> is the number of such actions or results per unit of time.</p>
<p>Generally, you should aim for <strong>maximal throughput</strong> with <strong>acceptable latency</strong>.</p>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="https://community.cadence.com/cadence_blogs_8/b/sd/archive/2010/09/13/understanding-latency-vs-throughput">Understanding latency vs throughput</a></li>
</ul>
<h2>Availability vs consistency</h2>
<h3>CAP theorem</h3>
<p align="center">
<img src="images/bgLMI2u.png?raw=true">
<br>
<i><a href="http://robertgreiner.com/2014/08/cap-theorem-revisited">Source: CAP theorem revisited</a></i>
</p>
<p>In a distributed computer system, you can only support two of the following guarantees:</p>
<ul>
<li><strong>Consistency</strong> - Every read receives the most recent write or an error</li>
<li><strong>Availability</strong> - Every request receives a response, without guarantee that it contains the most recent version of the information</li>
<li><strong>Partition Tolerance</strong> - The system continues to operate despite arbitrary partitioning due to network failures</li>
</ul>
<p><em>Networks aren’t reliable, so you’ll need to support partition tolerance. You’ll need to make a software tradeoff between consistency and availability.</em></p>
<h4>CP - consistency and partition tolerance</h4>
<p>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.</p>
<h4>AP - availability and partition tolerance</h4>
<p>Responses return the most readily available version of the data available on any node, which might not be the latest. Writes might take some time to propagate when the partition is resolved.</p>
<p>AP is a good choice if the business needs allow for <a href="#eventual-consistency">eventual consistency</a> or when the system needs to continue working despite external errors.</p>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="http://robertgreiner.com/2014/08/cap-theorem-revisited/">CAP theorem revisited</a></li>
<li><a href="http://ksat.me/a-plain-english-introduction-to-cap-theorem">A plain english introduction to CAP theorem</a></li>
<li><a href="https://github.com/henryr/cap-faq">CAP FAQ</a></li>
<li><a href="https://www.youtube.com/watch?v=k-Yaq8AHlFA">The CAP theorem</a></li>
</ul>
<h2>Consistency patterns</h2>
<p>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 <a href="#cap-theorem">CAP theorem</a> - Every read receives the most recent write or an error.</p>
<h3>Weak consistency</h3>
<p>After a write, reads may or may not see it. A best effort approach is taken.</p>
<p>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.</p>
<h3>Eventual consistency</h3>
<p>After a write, reads will eventually see it (typically within milliseconds). Data is replicated asynchronously.</p>
<p>This approach is seen in systems such as DNS and email. Eventual consistency works well in highly available systems.</p>
<h3>Strong consistency</h3>
<p>After a write, reads will see it. Data is replicated synchronously.</p>
<p>This approach is seen in file systems and RDBMSes. Strong consistency works well in systems that need transactions.</p>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="http://snarfed.org/transactions_across_datacenters_io.html">Transactions across data centers</a></li>
</ul>
<h2>Availability patterns</h2>
<p>There are two complementary patterns to support high availability: <strong>fail-over</strong> and <strong>replication</strong>.</p>
<h3>Fail-over</h3>
<h4>Active-passive</h4>
<p>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.</p>
<p>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.</p>
<p>Active-passive failover can also be referred to as master-slave failover.</p>
<h4>Active-active</h4>
<p>In active-active, both servers are managing traffic, spreading the load between them.</p>
<p>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.</p>
<p>Active-active failover can also be referred to as master-master failover.</p>
<h3>Disadvantage(s): failover</h3>
<ul>
<li>Fail-over adds more hardware and additional complexity.</li>
<li>There is a potential for loss of data if the active system fails before any newly written data can be replicated to the passive.</li>
</ul>
<h3>Replication</h3>
<h4>Master-slave and master-master</h4>
<p>This topic is further discussed in the <a href="#database">Database</a> section:</p>
<ul>
<li><a href="#master-slave-replication">Master-slave replication</a></li>
<li><a href="#master-master-replication">Master-master replication</a></li>
</ul>
<h3>Availability in numbers</h3>
<p>Availability is often quantified by uptime (or downtime) as a percentage of time the service is available. Availability is generally measured in number of 9s–a service with 99.99% availability is described as having four 9s.</p>
<h4>99.9% availability - three 9s</h4>
<table>
<thead>
<tr>
<th>Duration</th>
<th>Acceptable downtime</th>
</tr>
</thead>
<tbody>
<tr>
<td>Downtime per year</td>
<td>8h 45min 57s</td>
</tr>
<tr>
<td>Downtime per month</td>
<td>43m 49.7s</td>
</tr>
<tr>
<td>Downtime per week</td>
<td>10m 4.8s</td>
</tr>
<tr>
<td>Downtime per day</td>
<td>1m 26.4s</td>
</tr>
</tbody>
</table>
<h4>99.99% availability - four 9s</h4>
<table>
<thead>
<tr>
<th>Duration</th>
<th>Acceptable downtime</th>
</tr>
</thead>
<tbody>
<tr>
<td>Downtime per year</td>
<td>52min 35.7s</td>
</tr>
<tr>
<td>Downtime per month</td>
<td>4m 23s</td>
</tr>
<tr>
<td>Downtime per week</td>
<td>1m 5s</td>
</tr>
<tr>
<td>Downtime per day</td>
<td>8.6s</td>
</tr>
</tbody>
</table>
<h4>Availability in parallel vs in sequence</h4>
<p>If a service consists of multiple components prone to failure, the service’s overall availability depends on whether the components are in sequence or in parallel.</p>
<h6>In sequence</h6>
<p>Overall availability decreases when two components with availability < 100% are in sequence:</p>
<pre><code>Availability (Total) = Availability (Foo) * Availability (Bar)
</code></pre>
<p>If both <code>Foo</code> and <code>Bar</code> each had 99.9% availability, their total availability in sequence would be 99.8%.</p>
<h6>In parallel</h6>
<p>Overall availability increases when two components with availability < 100% are in parallel:</p>
<pre><code>Availability (Total) = 1 - (1 - Availability (Foo)) * (1 - Availability (Bar))
</code></pre>
<p>If both <code>Foo</code> and <code>Bar</code> each had 99.9% availability, their total availability in parallel would be 99.9999%.</p>
<h2>Domain name system</h2>
<p align="center">
<img src="images/IOyLj4i.png?raw=true">
<br>
<i><a href="http://www.slideshare.net/srikrupa5/dns-security-presentation-issa">Source: DNS security presentation</a></i>
</p>
<p>A Domain Name System (DNS) translates a domain name such as www.example.com to an IP address.</p>
<p>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 <a href="https://en.wikipedia.org/wiki/Time_to_live">time to live (TTL)</a>.</p>
<ul>
<li><strong>NS record (name server)</strong> - Specifies the DNS servers for your domain/subdomain.</li>
<li><strong>MX record (mail exchange)</strong> - Specifies the mail servers for accepting messages.</li>
<li><strong>A record (address)</strong> - Points a name to an IP address.</li>
<li><strong>CNAME (canonical)</strong> - Points a name to another name or <code>CNAME</code> (example.com to www.example.com) or to an <code>A</code> record.</li>
</ul>
<p>Services such as <a href="https://www.cloudflare.com/dns/">CloudFlare</a> and <a href="https://aws.amazon.com/route53/">Route 53</a> provide managed DNS services. Some DNS services can route traffic through various methods:</p>
<ul>
<li><a href="https://www.g33kinfo.com/info/round-robin-vs-weighted-round-robin-lb">Weighted round robin</a>
<ul>
<li>Prevent traffic from going to servers under maintenance</li>
<li>Balance between varying cluster sizes</li>
<li>A/B testing</li>
</ul>
</li>
<li><a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html#routing-policy-latency">Latency-based</a></li>
<li><a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html#routing-policy-geo">Geolocation-based</a></li>
</ul>
<h3>Disadvantage(s): DNS</h3>
<ul>
<li>Accessing a DNS server introduces a slight delay, although mitigated by caching described above.</li>
<li>DNS server management could be complex and is generally managed by <a href="http://superuser.com/questions/472695/who-controls-the-dns-servers/472729">governments, ISPs, and large companies</a>.</li>
<li>DNS services have recently come under <a href="http://dyn.com/blog/dyn-analysis-summary-of-friday-october-21-attack/">DDoS attack</a>, preventing users from accessing websites such as Twitter without knowing Twitter’s IP address(es).</li>
</ul>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="https://technet.microsoft.com/en-us/library/dd197427(v=ws.10).aspx">DNS architecture</a></li>
<li><a href="https://en.wikipedia.org/wiki/Domain_Name_System">Wikipedia</a></li>
<li><a href="https://support.dnsimple.com/categories/dns/">DNS articles</a></li>
</ul>
<div style="page-break-after: always;"></div>
<h2>Content delivery network</h2>
<p align="center">
<img src="images/h9TAuGI.png?raw=true">
<br>
<i><a href="https://www.creative-artworks.eu/why-use-a-content-delivery-network-cdn/">Source: Why use a 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.</p>
<p>Serving content from CDNs can significantly improve performance in two ways:</p>
<ul>
<li>Users receive content from data centers close to them</li>
<li>Your servers do not have to serve requests that the CDN fulfills</li>
</ul>
<h3>Push CDNs</h3>
<p>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.</p>
<p>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.</p>
<h3>Pull CDNs</h3>
<p>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 CDN.</p>
<p>A <a href="https://en.wikipedia.org/wiki/Time_to_live">time-to-live (TTL)</a> 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.</p>
<p>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.</p>
<h3>Disadvantage(s): CDN</h3>
<ul>
<li>CDN costs could be significant depending on traffic, although this should be weighed with additional costs you would incur not using a CDN.</li>
<li>Content might be stale if it is updated before the TTL expires it.</li>
<li>CDNs require changing URLs for static content to point to the CDN.</li>
</ul>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="https://figshare.com/articles/Globally_distributed_content_delivery/6605972">Globally distributed content delivery</a></li>
<li><a href="http://www.travelblogadvice.com/technical/the-differences-between-push-and-pull-cdns/">The differences between push and pull CDNs</a></li>
<li><a href="https://en.wikipedia.org/wiki/Content_delivery_network">Wikipedia</a></li>
</ul>
<div style="page-break-after: always;"></div>
<h2>Load balancer</h2>
<p align="center">
<img src="images/h81n9iK.png?raw=true">
<br>
<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:</p>
<ul>
<li>Preventing requests from going to unhealthy servers</li>
<li>Preventing overloading resources</li>
<li>Helping to eliminate a single point of failure</li>
</ul>
<p>Load balancers can be implemented with hardware (expensive) or with software such as HAProxy.</p>
<p>Additional benefits include:</p>
<ul>
<li><strong>SSL termination</strong> - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations
<ul>
<li>Removes the need to install <a href="https://en.wikipedia.org/wiki/X.509">X.509 certificates</a> on each server</li>
</ul>
</li>
<li><strong>Session persistence</strong> - Issue cookies and route a specific client’s requests to same instance if the web apps do not keep track of sessions</li>
</ul>
<p>To protect against failures, it’s common to set up multiple load balancers, either in <a href="#active-passive">active-passive</a> or <a href="#active-active">active-active</a> mode.</p>
<p>Load balancers can route traffic based on various metrics, including:</p>
<ul>
<li>Random</li>
<li>Least loaded</li>
<li>Session/cookies</li>
<li><a href="https://www.g33kinfo.com/info/round-robin-vs-weighted-round-robin-lb">Round robin or weighted round robin</a></li>
<li><a href="#layer-4-load-balancing">Layer 4</a></li>
<li><a href="#layer-7-load-balancing">Layer 7</a></li>
</ul>
<h3>Layer 4 load balancing</h3>
<p>Layer 4 load balancers look at info at the <a href="#communication">transport layer</a> 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 <a href="https://www.nginx.com/resources/glossary/layer-4-load-balancing/">Network Address Translation (NAT)</a>.</p>
<h3>Layer 7 load balancing</h3>
<p>Layer 7 load balancers look at the <a href="#communication">application layer</a> to decide how to distribute requests. This can involve contents of the header, message, and cookies. Layer 7 load balancers terminate 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.</p>
<p>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.</p>
<h3>Horizontal scaling</h3>
<p>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 <strong>Vertical Scaling</strong>. It is also easier to hire for talent working on commodity hardware than it is for specialized enterprise systems.</p>
<h4>Disadvantage(s): horizontal scaling</h4>
<ul>
<li>Scaling horizontally introduces complexity and involves cloning servers
<ul>
<li>Servers should be stateless: they should not contain any user-related data like sessions or profile pictures</li>
<li>Sessions can be stored in a centralized data store such as a <a href="#database">database</a> (SQL, NoSQL) or a persistent <a href="#cache">cache</a> (Redis, Memcached)</li>
</ul>
</li>
<li>Downstream servers such as caches and databases need to handle more simultaneous connections as upstream servers scale out</li>
</ul>
<h3>Disadvantage(s): load balancer</h3>
<ul>
<li>The load balancer can become a performance bottleneck if it does not have enough resources or if it is not configured properly.</li>
<li>Introducing a load balancer to help eliminate a single point of failure results in increased complexity.</li>
<li>A single load balancer is a single point of failure, configuring multiple load balancers further increases complexity.</li>
</ul>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/">NGINX architecture</a></li>
<li><a href="http://www.haproxy.org/download/1.2/doc/architecture.txt">HAProxy architecture guide</a></li>
<li><a href="http://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones">Scalability</a></li>
<li><a href="https://en.wikipedia.org/wiki/Load_balancing_(computing)">Wikipedia</a></li>
<li><a href="https://www.nginx.com/resources/glossary/layer-4-load-balancing/">Layer 4 load balancing</a></li>
<li><a href="https://www.nginx.com/resources/glossary/layer-7-load-balancing/">Layer 7 load balancing</a></li>
<li><a href="http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-listener-config.html">ELB listener config</a></li>
</ul>
<div style="page-break-after: always;"></div>
<h2>Reverse proxy (web server)</h2>
<p align="center">
<img src="images/n41Azff.png?raw=true">
<br>
<i><a href="https://upload.wikimedia.org/wikipedia/commons/6/67/Reverse_proxy_h2g2bob.svg">Source: Wikipedia</a></i>
<br>
</p>
<p>A reverse proxy is a web server that centralizes internal services and provides unified interfaces to the public. Requests from clients are forwarded to a server that can fulfill it before the reverse proxy returns the server’s response to the client.</p>
<p>Additional benefits include:</p>
<ul>
<li><strong>Increased security</strong> - Hide information about backend servers, blacklist IPs, limit number of connections per client</li>
<li><strong>Increased scalability and flexibility</strong> - Clients only see the reverse proxy’s IP, allowing you to scale servers or change their configuration</li>
<li><strong>SSL termination</strong> - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations
<ul>
<li>Removes the need to install <a href="https://en.wikipedia.org/wiki/X.509">X.509 certificates</a> on each server</li>
</ul>
</li>
<li><strong>Compression</strong> - Compress server responses</li>
<li><strong>Caching</strong> - Return the response for cached requests</li>
<li><strong>Static content</strong> - Serve static content directly
<ul>
<li>HTML/CSS/JS</li>
<li>Photos</li>
<li>Videos</li>
<li>Etc</li>
</ul>
</li>
</ul>
<h3>Load balancer vs reverse proxy</h3>
<ul>
<li>Deploying a load balancer is useful when you have multiple servers. Often, load balancers route traffic to a set of servers serving the same function.</li>
<li>Reverse proxies can be useful even with just one web server or application server, opening up the benefits described in the previous section.</li>
<li>Solutions such as NGINX and HAProxy can support both layer 7 reverse proxying and load balancing.</li>
</ul>
<h3>Disadvantage(s): reverse proxy</h3>
<ul>
<li>Introducing a reverse proxy results in increased complexity.</li>
<li>A single reverse proxy is a single point of failure, configuring multiple reverse proxies (ie a <a href="https://en.wikipedia.org/wiki/Failover">failover</a>) further increases complexity.</li>
</ul>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="https://www.nginx.com/resources/glossary/reverse-proxy-vs-load-balancer/">Reverse proxy vs load balancer</a></li>
<li><a href="https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/">NGINX architecture</a></li>
<li><a href="http://www.haproxy.org/download/1.2/doc/architecture.txt">HAProxy architecture guide</a></li>
<li><a href="https://en.wikipedia.org/wiki/Reverse_proxy">Wikipedia</a></li>
</ul>
<h2>Application layer</h2>
<p align="center">
<img src="images/yB5SYwm.png?raw=true">
<br>
<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>Separating out the web layer from the application layer (also known as platform layer) allows you to scale and configure both layers independently. Adding a new API results in adding application servers without necessarily adding additional web servers. The <strong>single responsibility principle</strong> advocates for small and autonomous services that work together. Small teams with small services can plan more aggressively for rapid growth.</p>
<p>Workers in the application layer also help enable <a href="#asynchronism">asynchronism</a>.</p>
<h3>Microservices</h3>
<p>Related to this discussion are <a href="https://en.wikipedia.org/wiki/Microservices">microservices</a>, which can be described as a suite of independently deployable, small, modular services. Each service runs a unique process and communicates through a well-defined, lightweight mechanism to serve a business goal. <sup><a href="https://smartbear.com/learn/api-design/what-are-microservices">1</a></sup></p>
<p>Pinterest, for example, could have the following microservices: user profile, follower, feed, search, photo upload, etc.</p>
<h3>Service Discovery</h3>
<p>Systems such as <a href="https://www.consul.io/docs/index.html">Consul</a>, <a href="https://coreos.com/etcd/docs/latest">Etcd</a>, and <a href="http://www.slideshare.net/sauravhaloi/introduction-to-apache-zookeeper">Zookeeper</a> can help services find each other by keeping track of registered names, addresses, and ports. <a href="https://www.consul.io/intro/getting-started/checks.html">Health checks</a> help verify service integrity and are often done using an <a href="#hypertext-transfer-protocol-http">HTTP</a> endpoint. Both Consul and Etcd have a built in <a href="#key-value-store">key-value store</a> that can be useful for storing config values and other shared data.</p>
<h3>Disadvantage(s): application layer</h3>
<ul>
<li>Adding an application layer with loosely coupled services requires a different approach from an architectural, operations, and process viewpoint (vs a monolithic system).</li>
<li>Microservices can add complexity in terms of deployments and operations.</li>
</ul>
<h3>Source(s) and further reading</h3>
<ul>
<li><a href="http://lethain.com/introduction-to-architecting-systems-for-scale">Intro to architecting systems for scale</a></li>
<li><a href="http://www.puncsky.com/blog/2016-02-13-crack-the-system-design-interview">Crack the system design questions</a></li>
<li><a href="https://en.wikipedia.org/wiki/Service-oriented_architecture">Service oriented architecture</a></li>
<li><a href="http://www.slideshare.net/sauravhaloi/introduction-to-apache-zookeeper">Introduction to Zookeeper</a></li>
<li><a href="https://cloudncode.wordpress.com/2016/07/22/msa-getting-started/">Here’s what you need to know about building microservices</a></li>
</ul>
<h2>Database</h2>
<p align="center">
<img src="images/Xkm5CXz.png?raw=true">
<br>
<i><a href="https://www.youtube.com/watch?v=kKjm4ehYiMs">Source: Scaling up to your first 10 million users</a></i>
</p>
<h3>Relational database management system (RDBMS)</h3>
<p>A relational database like SQL is a collection of data items organized in tables.</p>
<p><strong>ACID</strong> is a set of properties of relational database <a href="https://en.wikipedia.org/wiki/Database_transaction">transactions</a>.</p>
<ul>
<li><strong>Atomicity</strong> - Each transaction is all or nothing</li>
<li><strong>Consistency</strong> - Any transaction will bring the database from one valid state to another</li>
<li><strong>Isolation</strong> - Executing transactions concurrently has the same results as if the transactions were executed serially</li>
<li><strong>Durability</strong> - Once a transaction has been committed, it will remain so</li>
</ul>
<p>There are many techniques to scale a relational database: <strong>master-slave replication</strong>, <strong>master-master replication</strong>, <strong>federation</strong>, <strong>sharding</strong>, <strong>denormalization</strong>, and <strong>SQL tuning</strong>.</p>
<h4>Master-slave replication</h4>
<p>The master serves reads and writes, replicating writes to one or more slaves, which serve only reads. Slaves can also replicate to additional slaves in a tree-like fashion. If the master goes offline, the system can continue to operate in read-only mode until a slave is promoted to a master or a new master is provisioned.</p>
<p align="center">
<img src="images/C9ioGtn.png?raw=true">
<br>
<i><a href="http://www.slideshare.net/jboner/scalability-availability-stability-patterns/">Source: Scalability, availability, stability, patterns</a></i>
</p>
<h5>Disadvantage(s): master-slave replication</h5>
<ul>
<li>Additional logic is needed to promote a slave to a master.</li>
<li>See <a href="#disadvantages-replication">Disadvantage(s): replication</a> for points related to <strong>both</strong> master-slave and master-master.</li>
</ul>
<h4>Master-master replication</h4>
<p>Both masters serve reads and writes and coordinate with each other on writes. If either master goes down, the system can continue to operate with both reads and writes.</p>
<p align="center">
<img src="images/krAHLGg.png?raw=true">
<br>
<i><a href="http://www.slideshare.net/jboner/scalability-availability-stability-patterns/">Source: Scalability, availability, stability, patterns</a></i>
</p>
<h5>Disadvantage(s): master-master replication</h5>
<ul>
<li>You’ll need a load balancer or you’ll need to make changes to your application logic to determine where to write.</li>
<li>Most master-master systems are either loosely consistent (violating ACID) or have increased write latency due to synchronization.</li>
<li>Conflict resolution comes more into play as more write nodes are added and as latency increases.</li>
<li>See <a href="#disadvantages-replication">Disadvantage(s): replication</a> for points related to <strong>both</strong> master-slave and master-master.</li>
</ul>
<h5>Disadvantage(s): replication</h5>
<ul>
<li>There is a potential for loss of data if the master fails before any newly written data can be replicated to other nodes.</li>
<li>Writes are replayed to the read replicas. If there are a lot of writes, the read replicas can get bogged down with replaying writes and can’t do as many reads.</li>
<li>The more read slaves, the more you have to replicate, which leads to greater replication lag.</li>
<li>On some systems, writing to the master can spawn multiple threads to write in parallel, whereas read replicas only support writing sequentially with a single thread.</li>
<li>Replication adds more hardware and additional complexity.</li>
</ul>
<h5>Source(s) and further reading: replication</h5>
<ul>
<li><a href="http://www.slideshare.net/jboner/scalability-availability-stability-patterns/">Scalability, availability, stability, patterns</a></li>
<li><a href="https://en.wikipedia.org/wiki/Multi-master_replication">Multi-master replication</a></li>
</ul>
<h4>Federation</h4>
<p align="center">
<img src="images/U3qV33e.png?raw=true">
<br>
<i><a href="https://www.youtube.com/watch?v=kKjm4ehYiMs">Source: Scaling up to your first 10 million users</a></i>
</p>
<p>Federation (or functional partitioning) splits up databases by function. For example, instead of a single, monolithic database, you could have three databases: <strong>forums</strong>, <strong>users</strong>, and <strong>products</strong>, 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.</p>
<h5>Disadvantage(s): federation</h5>
<ul>
<li>Federation is not effective if your schema requires huge functions or tables.</li>
<li>You’ll need to update your application logic to determine which database to read and write.</li>
<li>Joining data from two databases is more complex with a <a href="http://stackoverflow.com/questions/5145637/querying-data-by-joining-two-tables-in-two-database-on-different-servers">server link</a>.</li>
<li>Federation adds more hardware and additional complexity.</li>
</ul>
<h5>Source(s) and further reading: federation</h5>
<ul>
<li><a href="https://www.youtube.com/watch?v=kKjm4ehYiMs">Scaling up to your first 10 million users</a></li>
</ul>
<div style="page-break-after: always;"></div>
<h4>Sharding</h4>
<p align="center">
<img src="images/wU8x5Id.png?raw=true">
<br>
<i><a href="http://www.slideshare.net/jboner/scalability-availability-stability-patterns/">Source: Scalability, availability, stability, patterns</a></i>
</p>
<p>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.</p>
<p>Similar to the advantages of <a href="#federation">federation</a>, 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.</p>
<p>Common ways to shard a table of users is either through the user’s last name initial or the user’s geographic location.</p>
<h5>Disadvantage(s): sharding</h5>
<ul>
<li>You’ll need to update your application logic to work with shards, which could result in complex SQL queries.</li>
<li>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.
<ul>
<li>Rebalancing adds additional complexity. A sharding function based on <a href="http://www.paperplanes.de/2011/12/9/the-magic-of-consistent-hashing.html">consistent hashing</a> can reduce the amount of transferred data.</li>
</ul>
</li>
<li>Joining data from multiple shards is more complex.</li>
<li>Sharding adds more hardware and additional complexity.</li>
</ul>
<h5>Source(s) and further reading: sharding</h5>
<ul>
<li><a href="http://highscalability.com/blog/2009/8/6/an-unorthodox-approach-to-database-design-the-coming-of-the.html">The coming of the shard</a></li>
<li><a href="https://en.wikipedia.org/wiki/Shard_(database_architecture)">Shard database architecture</a></li>
<li><a href="http://www.paperplanes.de/2011/12/9/the-magic-of-consistent-hashing.html">Consistent hashing</a></li>
</ul>
<h4>Denormalization</h4>
<p>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 <a href="https://en.wikipedia.org/wiki/PostgreSQL">PostgreSQL</a> and Oracle support <a href="https://en.wikipedia.org/wiki/Materialized_view">materialized views</a> which handle the work of storing redundant information and keeping redundant copies consistent.</p>
<p>Once data becomes distributed with techniques such as <a href="#federation">federation</a> and <a href="#sharding">sharding</a>, managing joins across data centers further increases complexity. Denormalization might circumvent the need for such complex joins.</p>
<p>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.</p>
<h5>Disadvantage(s): denormalization</h5>
<ul>
<li>Data is duplicated.</li>
<li>Constraints can help redundant copies of information stay in sync, which increases complexity of the database design.</li>
<li>A denormalized database under heavy write load might perform worse than its normalized counterpart.</li>
</ul>
<h6>Source(s) and further reading: denormalization</h6>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Denormalization">Denormalization</a></li>
</ul>
<h4>SQL tuning</h4>
<p>SQL tuning is a broad topic and many <a href="https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=sql+tuning">books</a> have been written as reference.</p>
<p>It’s important to <strong>benchmark</strong> and <strong>profile</strong> to simulate and uncover bottlenecks.</p>
<ul>
<li><strong>Benchmark</strong> - Simulate high-load situations with tools such as <a href="http://httpd.apache.org/docs/2.2/programs/ab.html">ab</a>.</li>
<li><strong>Profile</strong> - Enable tools such as the <a href="http://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html">slow query log</a> to help track performance issues.</li>
</ul>
<p>Benchmarking and profiling might point you to the following optimizations.</p>
<h5>Tighten up the schema</h5>
<ul>
<li>MySQL dumps to disk in contiguous blocks for fast access.</li>
<li>Use <code>CHAR</code> instead of <code>VARCHAR</code> for fixed-length fields.
<ul>
<li><code>CHAR</code> effectively allows for fast, random access, whereas with <code>VARCHAR</code>, you must find the end of a string before moving onto the next one.</li>
</ul>
</li>
<li>Use <code>TEXT</code> for large blocks of text such as blog posts. <code>TEXT</code> also allows for boolean searches. Using a <code>TEXT</code> field results in storing a pointer on disk that is used to locate the text block.</li>
<li>Use <code>INT</code> for larger numbers up to 2^32 or 4 billion.</li>
<li>Use <code>DECIMAL</code> for currency to avoid floating point representation errors.</li>
<li>Avoid storing large <code>BLOBS</code>, store the location of where to get the object instead.</li>
<li><code>VARCHAR(255)</code> 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.</li>
<li>Set the <code>NOT NULL</code> constraint where applicable to <a href="http://stackoverflow.com/questions/1017239/how-do-null-values-affect-performance-in-a-database-search">improve search performance</a>.</li>
</ul>
<h5>Use good indices</h5>
<ul>
<li>Columns that you are querying (<code>SELECT</code>, <code>GROUP BY</code>, <code>ORDER BY</code>, <code>JOIN</code>) could be faster with indices.</li>
<li>Indices are usually represented as self-balancing <a href="https://en.wikipedia.org/wiki/B-tree">B-tree</a> that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time.</li>
<li>Placing an index can keep the data in memory, requiring more space.</li>
<li>Writes could also be slower since the index also needs to be updated.</li>
<li>When loading large amounts of data, it might be faster to disable indices, load the data, then rebuild the indices.</li>
</ul>
<h5>Avoid expensive joins</h5>
<ul>
<li><a href="#denormalization">Denormalize</a> where performance demands it.</li>
</ul>
<h5>Partition tables</h5>
<ul>
<li>Break up a table by putting hot spots in a separate table to help keep it in memory.</li>
</ul>
<h5>Tune the query cache</h5>
<ul>
<li>In some cases, the <a href="https://dev.mysql.com/doc/refman/5.7/en/query-cache.html">query cache</a> could lead to <a href="https://www.percona.com/blog/2016/10/12/mysql-5-7-performance-tuning-immediately-after-installation/">performance issues</a>.</li>
</ul>
<h5>Source(s) and further reading: SQL tuning</h5>
<ul>
<li><a href="http://aiddroid.com/10-tips-optimizing-mysql-queries-dont-suck/">Tips for optimizing MySQL queries</a></li>
<li><a href="http://stackoverflow.com/questions/1217466/is-there-a-good-reason-i-see-varchar255-used-so-often-as-opposed-to-another-l">Is there a good reason i see VARCHAR(255) used so often?</a></li>
<li><a href="http://stackoverflow.com/questions/1017239/how-do-null-values-affect-performance-in-a-database-search">How do null values affect performance?</a></li>
<li><a href="http://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html">Slow query log</a></li>
</ul>
<h3>NoSQL</h3>
<p>NoSQL is a collection of data items represented in a <strong>key-value store</strong>, <strong>document store</strong>, <strong>wide column store</strong>, or a <strong>graph database</strong>. Data is denormalized, and joins are generally done in the application code. Most NoSQL stores lack true ACID transactions and favor <a href="#eventual-consistency">eventual consistency</a>.</p>
<p><strong>BASE</strong> is often used to describe the properties of NoSQL databases. In comparison with the <a href="#cap-theorem">CAP Theorem</a>, BASE chooses availability over consistency.</p>
<ul>
<li><strong>Basically available</strong> - the system guarantees availability.</li>
<li><strong>Soft state</strong> - the state of the system may change over time, even without input.</li>
<li><strong>Eventual consistency</strong> - the system will become consistent over a period of time, given that the system doesn’t receive input during that period.</li>
</ul>
<p>In addition to choosing between <a href="#sql-or-nosql">SQL or NoSQL</a>, it is helpful to understand which type of NoSQL database best fits your use case(s). We’ll review <strong>key-value stores</strong>, <strong>document stores</strong>, <strong>wide column stores</strong>, and <strong>graph databases</strong> in the next section.</p>