{
    "archive_path": "archive/1736015745.591257",
    "base_url": "github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here",
    "basename": "system-design-primer",
    "bookmarked_date": "2025-01-04 18:35",
    "canonical": {
        "archive_org_path": "https://web.archive.org/web/github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here",
        "dom_path": "output.html",
        "favicon_path": "favicon.ico",
        "git_path": "git/",
        "google_favicon_path": "https://www.google.com/s2/favicons?domain=github.com",
        "headers_path": "headers.json",
        "htmltotext_path": "htmltotext.txt",
        "index_path": "index.html",
        "media_path": "media/",
        "mercury_path": "mercury/content.html",
        "pdf_path": "output.pdf",
        "readability_path": "readability/content.html",
        "screenshot_path": "screenshot.png",
        "singlefile_path": "singlefile.html",
        "warc_path": "warc/",
        "wget_path": null
    },
    "domain": "github.com",
    "downloaded_at": "2025-01-04T18:37:55.083597+00:00",
    "downloaded_datestr": "2025-01-04 18:37",
    "extension": "",
    "hash": "1WDGCCXRKNZWBR445YRX",
    "history": {
        "archive_org": [
            {
                "cmd": [
                    "/usr/bin/curl",
                    "--silent",
                    "--location",
                    "--compressed",
                    "--proxy",
                    "socks5://tor-socks-proxy:9150",
                    "--head",
                    "--max-time",
                    "60",
                    "--user-agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 ArchiveBox/{VERSION} (+https://github.com/ArchiveBox/ArchiveBox/)",
                    "https://web.archive.org/save/https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
                ],
                "cmd_version": "8.10.1",
                "end_ts": "2025-01-04T18:39:08.966538+00:00",
                "index_texts": null,
                "output": "ArchiveError: Failed to find \"content-location\" URL header in Archive.org response.",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:39:07.241481+00:00",
                "status": "failed"
            }
        ],
        "dom": [
            {
                "cmd": [
                    "/usr/bin/chromium-browser",
                    "--proxy-server=socks5://tor-socks-proxy:9150",
                    "--disable-features=DarkMode",
                    "--run-all-compositor-stages-before-draw",
                    "--hide-scrollbars",
                    "--autoplay-policy=no-user-gesture-required",
                    "--no-first-run",
                    "--use-fake-ui-for-media-stream",
                    "--use-fake-device-for-media-stream",
                    "--simulate-outdated-no-au='Tue, 31 Dec 2099 23:59:59 GMT'",
                    "--headless=new",
                    "--no-sandbox",
                    "--no-zygote",
                    "--disable-dev-shm-usage",
                    "--disable-software-rasterizer",
                    "--disable-sync",
                    "--window-size=1440,2000",
                    "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 ArchiveBox/{VERSION} (+https://github.com/ArchiveBox/ArchiveBox/)",
                    "--user-data-dir=/data/personas/Default/chrome_profile",
                    "--profile-directory=Default",
                    "--dump-dom",
                    "https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
                ],
                "cmd_version": "131.0.6778",
                "end_ts": "2025-01-04T18:38:20.550535+00:00",
                "index_texts": null,
                "output": "output.html",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:37:59.004490+00:00",
                "status": "succeeded"
            }
        ],
        "favicon": [
            {
                "cmd": [
                    "/usr/bin/curl",
                    "--silent",
                    "--location",
                    "--compressed",
                    "--proxy",
                    "socks5://tor-socks-proxy:9150",
                    "--max-time",
                    "60",
                    "--output",
                    "favicon.ico",
                    "--user-agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 ArchiveBox/{VERSION} (+https://github.com/ArchiveBox/ArchiveBox/)",
                    "https://www.google.com/s2/favicons?domain=github.com"
                ],
                "cmd_version": "8.10.1",
                "end_ts": "2025-01-04T18:37:58.253389+00:00",
                "index_texts": null,
                "output": "favicon.ico",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:37:55.102609+00:00",
                "status": "succeeded"
            }
        ],
        "git": [],
        "headers": [
            {
                "cmd": [
                    "/usr/bin/curl",
                    "--silent",
                    "--location",
                    "--compressed",
                    "--proxy",
                    "socks5://tor-socks-proxy:9150",
                    "--head",
                    "--max-time",
                    "60",
                    "--user-agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 ArchiveBox/{VERSION} (+https://github.com/ArchiveBox/ArchiveBox/)",
                    "https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
                ],
                "cmd_version": "8.10.1",
                "end_ts": "2025-01-04T18:37:58.831835+00:00",
                "index_texts": null,
                "output": "headers.json",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:37:58.295244+00:00",
                "status": "succeeded"
            }
        ],
        "htmltotext": [
            {
                "cmd": [
                    "(internal) archivebox.extractors.htmltotext",
                    "./{singlefile,dom}.html"
                ],
                "cmd_version": "0.8.5rc51",
                "end_ts": "2025-01-04T18:38:55.196716+00:00",
                "index_texts": [
                    "(https://github.githubassets.com) (https://avatars.githubusercontent.com) (https://github-cloud.s3.amazonaws.com) (https://user-images.githubusercontent.com/) (https://github.githubassets.com) (https://avatars.githubusercontent.com) (https://github.githubassets.com/assets/light-0cfd1fd8509e.css) (https://github.githubassets.com/assets/dark-d782f59290e2.css) (https://github.githubassets.com/assets/primer-primitives-953961b66e63.css) (https://github.githubassets.com/assets/primer-4430d3c2c150.css) (https://github.githubassets.com/assets/global-47b8b2ca21ae.css) (https://github.githubassets.com/assets/github-e72829f5538b.css) (https://github.githubassets.com/assets/staff-0aa284f91bc2.css) (https://github.githubassets.com/assets/devtools-ed3c56d5f6b2.css) (https://github.githubassets.com/assets/repository-d031bcc14e1b.css) (https://github.githubassets.com/assets/code-9e1913b328be.css) (https://github.githubassets.com/assets/primer-react.797c8ec006b327590422.module.css) (https://github.githubassets.com/assets/notifications-subscriptions-menu.1bcff9205c241e99cff2.module.css) (https://github.githubassets.com/assets/primer-react.797c8ec006b327590422.module.css) (https://github.githubassets.com/assets/notifications-subscriptions-menu.1bcff9205c241e99cff2.module.css) GitHub - donnemartin/system-design-primer: Learn how to design large-scale systems. Prep for the system design interview.  Includes Anki flashcards. (repo_source) (https://github.githubassets.com/) (/opensearch.xml) (GitHub) (https://github.com/fluidicon.png) (GitHub) (https://github.com/donnemartin/system-design-primer) (https://github.githubassets.com/assets/pinned-octocat-093da3e6fa40.svg) (https://github.githubassets.com/favicons/favicon.png) (https://github.githubassets.com/favicons/favicon.svg) (/manifest.json)  Skip to content   (https://github.githubassets.com/assets/primer-react.797c8ec006b327590422.module.css)    Navigation Menu Toggle navigation         (/)    (/login?return_to=https%3A%2F%2Fgithub.com%2Fdonnemartin%2Fsystem-design-primer%3Ftab%3Dreadme-ov-file) Sign in    Product    (https://github.com/features/copilot)    GitHub Copilot Write better code with AI    (https://github.com/features/security)    Security Find and fix vulnerabilities    (https://github.com/features/actions)   Actions Automate any workflow    (https://github.com/features/codespaces)    Codespaces Instant dev environments    (https://github.com/features/issues)   Issues Plan and track work    (https://github.com/features/code-review)    Code Review Manage code changes    (https://github.com/features/discussions)    Discussions Collaborate outside of code    (https://github.com/features/code-search)    Code Search Find more, search less       Explore (https://github.com/features) All features   (https://docs.github.com) Documentation     (https://skills.github.com) GitHub Skills     (https://github.blog) Blog          Solutions    By company size (https://github.com/enterprise) Enterprises   (https://github.com/team) Small and medium teams   (https://github.com/enterprise/startups) Startups     By use case (/solutions/use-case/devsecops) DevSecOps   (/solutions/use-case/devops) DevOps   (/solutions/use-case/ci-cd) CI/CD   (/solutions/use-case) View all use cases      By industry (/solutions/industry/healthcare) Healthcare   (/solutions/industry/financial-services) Financial services   (/solutions/industry/manufacturing) Manufacturing   (/solutions/industry/government) Government   (/solutions/industry) View all industries      (/solutions) View all solutions       Resources    Topics (/resources/articles/ai) AI   (/resources/articles/devops) DevOps   (/resources/articles/security) Security   (/resources/articles/software-development) Software Development   (/resources/articles) View all      Explore (https://resources.github.com/learn/pathways) Learning Pathways     (https://resources.github.com) White papers, Ebooks, Webinars     (https://github.com/customer-stories) Customer Stories   (https://partner.github.com) Partners     (https://github.com/solutions/executive-insights) Executive Insights        Open Source    (/sponsors) GitHub Sponsors Fund open source developers      (https://github.com/readme) The ReadME Project GitHub community articles      Repositories (https://github.com/topics) Topics   (https://github.com/trending) Trending   (https://github.com/collections) Collections        Enterprise    (/enterprise)     Enterprise platform AI-powered developer platform      Available add-ons (https://github.com/enterprise/advanced-security)    Advanced Security Enterprise-grade security features    (/features/copilot#enterprise)    GitHub Copilot Enterprise-grade AI features    (/premium-support)    Premium Support Enterprise-grade 24/7 support         (https://github.com/pricing) Pricing    (Search or jump to...)    Search or jump to...      Search code, repositories, users, issues, pull requests... Search        ()   Clear                (https://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax) Search syntax tips          Provide feedback         (wQfIhS0Uifx5Dc4sdBQ6gEzK/wT4rCPVN+P2zoVVzkmu37qqFu0iOXzeuHC1mzthG61QZtNbiZU6OyKoSQ1/Kg==) We read every piece of feedback, and take your input very seriously.  Include my email address so I can be contacted    Cancel  Submit feedback     Saved searches  Use saved searches to filter your results more quickly         (pzL9DzxO+NpafNABYBzcoL0j6t5sGq4F3KdWSbEEFPUGnlVozEDpxn1YnV0vyKQt+2mRitQTYIaB4zdXWUYVRA==)  Name (github-ruby) (WyOBRYUdHqeUzfE71wlRiaBkvR//Odh+/Cgn3GQfW+/skFcG/rNg+mfUSTg4u/6fWpMDnHv63GcBP7/T2h8nqQ==)   Query ((repo:mona/a OR repo:mona/b) AND lang:python)  To see all available qualifiers, see our (https://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax) documentation .        Cancel  Create saved search        (/login?return_to=https%3A%2F%2Fgithub.com%2Fdonnemartin%2Fsystem-design-primer%3Ftab%3Dreadme-ov-file) Sign in   (/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E&source=header-repo&source_repo=donnemartin%2Fsystem-design-primer) Sign up  Reseting focus        You signed in with another tab or window. () Reload to refresh your session. You signed out in another tab or window. () Reload to refresh your session. You switched accounts on another tab or window. () Reload to refresh your session.    Dismiss alert       (/donnemartin) donnemartin   / (/donnemartin/system-design-primer) system-design-primer   Public   (/login?return_to=%2Fdonnemartin%2Fsystem-design-primer)   Notifications  You must be signed in to change notification settings  (/login?return_to=%2Fdonnemartin%2Fsystem-design-primer)   Fork (47,491) 47.5k   (/login?return_to=%2Fdonnemartin%2Fsystem-design-primer)   Star  (284,381) 284k       Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.  License (/donnemartin/system-design-primer/blob/master/LICENSE.txt)   View license   (/donnemartin/system-design-primer/stargazers)   284k stars  (/donnemartin/system-design-primer/forks)   47.5k forks  (/donnemartin/system-design-primer/branches)   Branches  (/donnemartin/system-design-primer/tags)   Tags  (/donnemartin/system-design-primer/activity)   Activity   (/login?return_to=%2Fdonnemartin%2Fsystem-design-primer)   Star     (/login?return_to=%2Fdonnemartin%2Fsystem-design-primer)   Notifications  You must be signed in to change notification settings      (/donnemartin/system-design-primer)   Code (Not available)    (/donnemartin/system-design-primer/issues)    Issues (230) 230   (/donnemartin/system-design-primer/pulls)   Pull requests (244) 244   (/donnemartin/system-design-primer/actions)   Actions (Not available)    (/donnemartin/system-design-primer/projects)   Projects (0) 0   (/donnemartin/system-design-primer/security)   Security   (/donnemartin/system-design-primer/pulse)   Insights (Not available)        Additional navigation options (/donnemartin/system-design-primer)    Code    (/donnemartin/system-design-primer/issues)     Issues    (/donnemartin/system-design-primer/pulls)    Pull requests    (/donnemartin/system-design-primer/actions)    Actions    (/donnemartin/system-design-primer/projects)    Projects    (/donnemartin/system-design-primer/security)    Security    (/donnemartin/system-design-primer/pulse)    Insights               donnemartin/system-design-primer (https://github.githubassets.com/assets/primer-react.797c8ec006b327590422.module.css) (https://github.githubassets.com/assets/repos-overview.9cc263aa0716ce801059.module.css)      master           (/donnemartin/system-design-primer/branches)    2  Branches    (/donnemartin/system-design-primer/tags)    0  Tags     (/donnemartin/system-design-primer/branches)    (/donnemartin/system-design-primer/tags)         (Go to file) ()     Go to file          Code              Folders and files Name  Name  (Last commit message) Last commit message   (Last commit date) Last commit date     Latest commit (/satya-vinay) (satya-vinay)  (/donnemartin/system-design-primer/commits?author=satya-vinay) satya-vinay    (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) Add Stripe engineering blog ( (https://github.com/donnemartin/system-design-primer/pull/592) #592 (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) )    (Dec 2, 2024, 1:10 AM UTC) Dec 2, 2024   (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) 40d5d2e \u00b7 (Dec 2, 2024, 1:10 AM UTC) Dec 2, 2024   History (/donnemartin/system-design-primer/commits/master/)    332 Commits        (/donnemartin/system-design-primer/commits/master/)               (.github) (/donnemartin/system-design-primer/tree/master/.github) .github        (.github) (/donnemartin/system-design-primer/tree/master/.github) .github      (Fix translations link in PR template (#451)) (/donnemartin/system-design-primer/commit/53c0cf7de874b4aeb3e45cf8674fe07a3370c0cb) Fix translations link in PR template ( (https://github.com/donnemartin/system-design-primer/pull/451) #451 (Fix translations link in PR template (#451)) (/donnemartin/system-design-primer/commit/53c0cf7de874b4aeb3e45cf8674fe07a3370c0cb) )    (Aug 2, 2020, 6:13 PM UTC) Aug 2, 2020      (images) (/donnemartin/system-design-primer/tree/master/images) images        (images) (/donnemartin/system-design-primer/tree/master/images) images      (Fix #335: Update OSI image to Open Systems Interconnection (#447)) (/donnemartin/system-design-primer/commit/b7f255e469d0274b4e5c21fb6234cb918d5b0bde) Fix  (https://github.com/donnemartin/system-design-primer/issues/335) #335 (Fix #335: Update OSI image to Open Systems Interconnection (#447)) (/donnemartin/system-design-primer/commit/b7f255e469d0274b4e5c21fb6234cb918d5b0bde) : Update OSI image to Open Systems Interconnection ( (https://github.com/donnemartin/system-design-primer/pull/447) #447 (Fix #335: Update OSI image to Open Systems Interconnection (#447)) (/donnemartin/system-design-primer/commit/b7f255e469d0274b4e5c21fb6234cb918d5b0bde) )    (Aug 2, 2020, 6:10 PM UTC) Aug 2, 2020      (resources) (/donnemartin/system-design-primer/tree/master/resources) resources        (resources) (/donnemartin/system-design-primer/tree/master/resources) resources      (Update system design flashcards (#56)) (/donnemartin/system-design-primer/commit/aecb070eb2bbc9ec4890de77cdbb6f9077b994df) Update system design flashcards ( (https://github.com/donnemartin/system-design-primer/pull/56) #56 (Update system design flashcards (#56)) (/donnemartin/system-design-primer/commit/aecb070eb2bbc9ec4890de77cdbb6f9077b994df) )    (Apr 9, 2017, 5:15 PM UTC) Apr 9, 2017      (solutions) (/donnemartin/system-design-primer/tree/master/solutions) solutions        (solutions) (/donnemartin/system-design-primer/tree/master/solutions) solutions      (Remove extraneous __init__.py (#393)) (/donnemartin/system-design-primer/commit/828014aaac217f66ef2183fc65655440c672cf9c) Remove extraneous __init__.py ( (https://github.com/donnemartin/system-design-primer/pull/393) #393 (Remove extraneous __init__.py (#393)) (/donnemartin/system-design-primer/commit/828014aaac217f66ef2183fc65655440c672cf9c) )    (Jul 12, 2020, 4:02 PM UTC) Jul 12, 2020      (.gitattributes) (/donnemartin/system-design-primer/blob/master/.gitattributes) .gitattributes        (.gitattributes) (/donnemartin/system-design-primer/blob/master/.gitattributes) .gitattributes      (Add .gitattributes) (/donnemartin/system-design-primer/commit/547db248d83d012fa58308237873a74f77f802b1) Add .gitattributes    (Mar 6, 2017, 3:25 AM UTC) Mar 6, 2017      (.gitignore) (/donnemartin/system-design-primer/blob/master/.gitignore) .gitignore        (.gitignore) (/donnemartin/system-design-primer/blob/master/.gitignore) .gitignore      (Add Ebook generation script (#207)) (/donnemartin/system-design-primer/commit/55d09f611d6c5ab1463365cb3079c35b13c5d700) Add Ebook generation script ( (https://github.com/donnemartin/system-design-primer/pull/207) #207 (Add Ebook generation script (#207)) (/donnemartin/system-design-primer/commit/55d09f611d6c5ab1463365cb3079c35b13c5d700) )    (May 12, 2019, 10:21 AM UTC) May 12, 2019      (CONTRIBUTING.md) (/donnemartin/system-design-primer/blob/master/CONTRIBUTING.md) CONTRIBUTING.md        (CONTRIBUTING.md) (/donnemartin/system-design-primer/blob/master/CONTRIBUTING.md) CONTRIBUTING.md      (Fix typos (#661)) (/donnemartin/system-design-primer/commit/7a094cec63795a3ebbaacebdf9dc4294cd3179b2) Fix typos ( (https://github.com/donnemartin/system-design-primer/pull/661) #661 (Fix typos (#661)) (/donnemartin/system-design-primer/commit/7a094cec63795a3ebbaacebdf9dc4294cd3179b2) )    (Apr 23, 2022, 1:14 PM UTC) Apr 23, 2022      (LICENSE.txt) (/donnemartin/system-design-primer/blob/master/LICENSE.txt) LICENSE.txt        (LICENSE.txt) (/donnemartin/system-design-primer/blob/master/LICENSE.txt) LICENSE.txt      (Add license disclaimer (#76)\n\nClearly denote the repository license is from me, not my employer (Facebook).) (/donnemartin/system-design-primer/commit/019eaafe5b9ad79d9c1a0c9ba06db2dc6a05cfc2) Add license disclaimer ( (https://github.com/donnemartin/system-design-primer/pull/76) #76 (Add license disclaimer (#76)\n\nClearly denote the repository license is from me, not my employer (Facebook).) (/donnemartin/system-design-primer/commit/019eaafe5b9ad79d9c1a0c9ba06db2dc6a05cfc2) )    (May 12, 2017, 4:49 AM UTC) May 12, 2017      (README-ja.md) (/donnemartin/system-design-primer/blob/master/README-ja.md) README-ja.md        (README-ja.md) (/donnemartin/system-design-primer/blob/master/README-ja.md) README-ja.md      (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) Add Stripe engineering blog ( (https://github.com/donnemartin/system-design-primer/pull/592) #592 (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) )    (Dec 2, 2024, 1:10 AM UTC) Dec 2, 2024      (README-zh-Hans.md) (/donnemartin/system-design-primer/blob/master/README-zh-Hans.md) README-zh-Hans.md        (README-zh-Hans.md) (/donnemartin/system-design-primer/blob/master/README-zh-Hans.md) README-zh-Hans.md      (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) Add Stripe engineering blog ( (https://github.com/donnemartin/system-design-primer/pull/592) #592 (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) )    (Dec 2, 2024, 1:10 AM UTC) Dec 2, 2024      (README-zh-TW.md) (/donnemartin/system-design-primer/blob/master/README-zh-TW.md) README-zh-TW.md        (README-zh-TW.md) (/donnemartin/system-design-primer/blob/master/README-zh-TW.md) README-zh-TW.md      (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) Add Stripe engineering blog ( (https://github.com/donnemartin/system-design-primer/pull/592) #592 (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) )    (Dec 2, 2024, 1:10 AM UTC) Dec 2, 2024      (README.md) (/donnemartin/system-design-primer/blob/master/README.md) README.md        (README.md) (/donnemartin/system-design-primer/blob/master/README.md) README.md      (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) Add Stripe engineering blog ( (https://github.com/donnemartin/system-design-primer/pull/592) #592 (Add Stripe engineering blog (#592)) (/donnemartin/system-design-primer/commit/40d5d2edccd00b4a66fb0e24d887d8b1a0d7ea0e) )    (Dec 2, 2024, 1:10 AM UTC) Dec 2, 2024      (TRANSLATIONS.md) (/donnemartin/system-design-primer/blob/master/TRANSLATIONS.md) TRANSLATIONS.md        (TRANSLATIONS.md) (/donnemartin/system-design-primer/blob/master/TRANSLATIONS.md) TRANSLATIONS.md      (Add status of translations (#436)) (/donnemartin/system-design-primer/commit/661c029b574c0b419f0736a30e4e2e44adf4d1fd) Add status of translations ( (https://github.com/donnemartin/system-design-primer/pull/436) #436 (Add status of translations (#436)) (/donnemartin/system-design-primer/commit/661c029b574c0b419f0736a30e4e2e44adf4d1fd) )    (Jul 3, 2020, 1:11 AM UTC) Jul 3, 2020      (epub-metadata.yaml) (/donnemartin/system-design-primer/blob/master/epub-metadata.yaml) epub-metadata.yaml        (epub-metadata.yaml) (/donnemartin/system-design-primer/blob/master/epub-metadata.yaml) epub-metadata.yaml      (Add Ebook generation script (#207)) (/donnemartin/system-design-primer/commit/55d09f611d6c5ab1463365cb3079c35b13c5d700) Add Ebook generation script ( (https://github.com/donnemartin/system-design-primer/pull/207) #207 (Add Ebook generation script (#207)) (/donnemartin/system-design-primer/commit/55d09f611d6c5ab1463365cb3079c35b13c5d700) )    (May 12, 2019, 10:21 AM UTC) May 12, 2019      (generate-epub.sh) (/donnemartin/system-design-primer/blob/master/generate-epub.sh) generate-epub.sh        (generate-epub.sh) (/donnemartin/system-design-primer/blob/master/generate-epub.sh) generate-epub.sh      (Fix typos (#661)) (/donnemartin/system-design-primer/commit/7a094cec63795a3ebbaacebdf9dc4294cd3179b2) Fix typos ( (https://github.com/donnemartin/system-design-primer/pull/661) #661 (Fix typos (#661)) (/donnemartin/system-design-primer/commit/7a094cec63795a3ebbaacebdf9dc4294cd3179b2) )    (Apr 23, 2022, 1:14 PM UTC) Apr 23, 2022    View all files       Repository files navigation    README      License         (/donnemartin/system-design-primer/blob/master/README.md) English \u2219 (/donnemartin/system-design-primer/blob/master/README-ja.md) \u65e5\u672c\u8a9e \u2219 (/donnemartin/system-design-primer/blob/master/README-zh-Hans.md) \u7b80\u4f53\u4e2d\u6587 \u2219 (/donnemartin/system-design-primer/blob/master/README-zh-TW.md) \u7e41\u9ad4\u4e2d\u6587 | (https://github.com/donnemartin/system-design-primer/issues/170) \u0627\u0644\u0639\u064e\u0631\u064e\u0628\u0650\u064a\u064e\u0651\u0629\u200e \u2219 (https://github.com/donnemartin/system-design-primer/issues/220) \u09ac\u09be\u0982\u09b2\u09be \u2219 (https://github.com/donnemartin/system-design-primer/issues/40) Portugu\u00eas do Brasil \u2219 (https://github.com/donnemartin/system-design-primer/issues/186) Deutsch \u2219 (https://github.com/donnemartin/system-design-primer/issues/130) \u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac \u2219 (https://github.com/donnemartin/system-design-primer/issues/272) \u05e2\u05d1\u05e8\u05d9\u05ea \u2219 (https://github.com/donnemartin/system-design-primer/issues/104) Italiano \u2219 (https://github.com/donnemartin/system-design-primer/issues/102) \ud55c\uad6d\uc5b4 \u2219 (https://github.com/donnemartin/system-design-primer/issues/110) \u0641\u0627\u0631\u0633\u06cc \u2219 (https://github.com/donnemartin/system-design-primer/issues/68) Polski \u2219 (https://github.com/donnemartin/system-design-primer/issues/87) \u0440\u0443\u0441\u0441\u043a\u0438\u0439 \u044f\u0437\u044b\u043a \u2219 (https://github.com/donnemartin/system-design-primer/issues/136) Espa\u00f1ol \u2219 (https://github.com/donnemartin/system-design-primer/issues/187) \u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22 \u2219 (https://github.com/donnemartin/system-design-primer/issues/39) T\u00fcrk\u00e7e \u2219 (https://github.com/donnemartin/system-design-primer/issues/127) ti\u1ebfng Vi\u1ec7t \u2219 (https://github.com/donnemartin/system-design-primer/issues/250) Fran\u00e7ais | (https://github.com/donnemartin/system-design-primer/issues/28) Add Translation   Help (/donnemartin/system-design-primer/blob/master/TRANSLATIONS.md) translate this guide!  The System Design Primer     (/donnemartin/system-design-primer/blob/master/images/jj3A5N8.png)   Motivation     Learn how to design large-scale systems. Prep for the system design interview.  Learn how to design large-scale systems     Learning how to design scalable systems will help you become a better engineer. System design is a broad topic.  There is a vast amount of resources scattered throughout the web on system design principles. This repo is an organized collection of resources to help you learn how to build systems at scale. Learn from the open source community     This is a continually updated, open source project. Contributions are welcome! Prep for the system design interview     In addition to coding interviews, system design is a required component of the technical interview process at many tech companies. Practice common system design interview questions and compare your results with sample solutions : discussions, code, and diagrams. Additional topics for interview prep: Study guide  How to approach a system design interview question  System design interview questions, with solutions   Object-oriented design interview questions, with solutions   Additional system design interview questions   Anki flashcards     (/donnemartin/system-design-primer/blob/master/images/zdCAkB3.png)   The provided (https://apps.ankiweb.net/) Anki flashcard decks use spaced repetition to help you retain key system design concepts. (https://github.com/donnemartin/system-design-primer/tree/master/resources/flash_cards/System%20Design.apkg) System design deck  (https://github.com/donnemartin/system-design-primer/tree/master/resources/flash_cards/System%20Design%20Exercises.apkg) System design exercises deck  (https://github.com/donnemartin/system-design-primer/tree/master/resources/flash_cards/OO%20Design.apkg) Object oriented design exercises deck   Great for use while on-the-go. Coding Resource: Interactive Coding Challenges     Looking for resources to help you prep for the (https://github.com/donnemartin/interactive-coding-challenges) Coding Interview  ? (/donnemartin/system-design-primer/blob/master/images/b4YtAEN.png)   Check out the sister repo (https://github.com/donnemartin/interactive-coding-challenges) Interactive Coding Challenges  , which contains an additional Anki deck: (https://github.com/donnemartin/interactive-coding-challenges/tree/master/anki_cards/Coding.apkg) Coding deck   Contributing     Learn from the community.  Feel free to submit pull requests to help: Fix errors Improve sections Add new sections (https://github.com/donnemartin/system-design-primer/issues/28) Translate   Content that needs some polishing is placed under development . Review the (/donnemartin/system-design-primer/blob/master/CONTRIBUTING.md) Contributing Guidelines . Index of system design topics     Summaries of various system design topics, including pros and cons. Everything is a trade-off . Each section contains links to more in-depth resources.  (/donnemartin/system-design-primer/blob/master/images/jrUBAF7.png)   System design topics: start here Step 1: Review the scalability video lecture  Step 2: Review the scalability article  Next steps    Performance vs scalability  Latency vs throughput  Availability vs consistency CAP theorem CP - consistency and partition tolerance  AP - availability and partition tolerance      Consistency patterns Weak consistency  Eventual consistency  Strong consistency    Availability patterns Fail-over  Replication  Availability in numbers    Domain name system  Content delivery network Push CDNs  Pull CDNs    Load balancer Active-passive  Active-active  Layer 4 load balancing  Layer 7 load balancing  Horizontal scaling    Reverse proxy (web server) Load balancer vs reverse proxy    Application layer Microservices  Service discovery    Database Relational database management system (RDBMS) Master-slave replication  Master-master replication  Federation  Sharding  Denormalization  SQL tuning    NoSQL Key-value store  Document store  Wide column store  Graph Database    SQL or NoSQL    Cache Client caching  CDN caching  Web server caching  Database caching  Application caching  Caching at the database query level  Caching at the object level  When to update the cache Cache-aside  Write-through  Write-behind (write-back)  Refresh-ahead      Asynchronism Message queues  Task queues  Back pressure    Communication Transmission control protocol (TCP)  User datagram protocol (UDP)  Remote procedure call (RPC)  Representational state transfer (REST)    Security  Appendix Powers of two table  Latency numbers every programmer should know  Additional system design interview questions  Real world architectures  Company architectures  Company engineering blogs    Under development  Credits  Contact info  License   Study guide     Suggested topics to review based on your interview timeline (short, medium, long).  (/donnemartin/system-design-primer/blob/master/images/OfVllex.png) (Imgur)   Q: For interviews, do I need to know everything here?  A: No, you don't need to know everything here to prepare for the interview . What you are asked in an interview depends on variables such as: How much experience you have What your technical background is What positions you are interviewing for Which companies you are interviewing with Luck  More experienced candidates are generally expected to know more about system design.  Architects or team leads might be expected to know more than individual contributors.  Top tech companies are likely to have one or more design interview rounds. Start broad and go deeper in a few areas.  It helps to know a little about various key system design topics.  Adjust the following guide based on your timeline, experience, what positions you are interviewing for, and which companies you are interviewing with. Short timeline - Aim for breadth with system design topics.  Practice by solving some interview questions. Medium timeline - Aim for breadth and some depth with system design topics.  Practice by solving many interview questions. Long timeline - Aim for breadth and more depth with system design topics.  Practice by solving most interview questions.   Short Medium Long   Read through the System design topics to get a broad understanding of how systems work \ud83d\udc4d \ud83d\udc4d \ud83d\udc4d  Read through a few articles in the Company engineering blogs for the companies you are interviewing with \ud83d\udc4d \ud83d\udc4d \ud83d\udc4d  Read through a few Real world architectures  \ud83d\udc4d \ud83d\udc4d \ud83d\udc4d  Review How to approach a system design interview question  \ud83d\udc4d \ud83d\udc4d \ud83d\udc4d  Work through System design interview questions with solutions  Some Many Most  Work through Object-oriented design interview questions with solutions  Some Many Most  Review Additional system design interview questions  Some Many Most     How to approach a system design interview question     How to tackle a system design interview question.  The system design interview is an open-ended conversation .  You are expected to lead it. You can use the following steps to guide the discussion.  To help solidify this process, work through the System design interview questions with solutions section using the following steps. Step 1: Outline use cases, constraints, and assumptions     Gather requirements and scope the problem.  Ask questions to clarify use cases and constraints.  Discuss assumptions. Who is going to use it? How are they going to use it? How many users are there? What does the system do? What are the inputs and outputs of the system? How much data do we expect to handle? How many requests per second do we expect? What is the expected read to write ratio?  Step 2: Create a high level design     Outline a high level design with all important components. Sketch the main components and connections Justify your ideas  Step 3: Design core components     Dive into details for each core component.  For example, if you were asked to (/donnemartin/system-design-primer/blob/master/solutions/system_design/pastebin/README.md) design a url shortening service , discuss: Generating and storing a hash of the full url (/donnemartin/system-design-primer/blob/master/solutions/system_design/pastebin/README.md) MD5 and (/donnemartin/system-design-primer/blob/master/solutions/system_design/pastebin/README.md) Base62  Hash collisions SQL or NoSQL Database schema   Translating a hashed url to the full url Database lookup   API and object-oriented design  Step 4: Scale the design     Identify and address bottlenecks, given the constraints.  For example, do you need the following to address scalability issues? Load balancer Horizontal scaling Caching Database sharding  Discuss potential solutions and trade-offs.  Everything is a trade-off.  Address bottlenecks using principles of scalable system design . Back-of-the-envelope calculations     You might be asked to do some estimates by hand.  Refer to the Appendix for the following resources: (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  Powers of two table  Latency numbers every programmer should know   Source(s) and further reading     Check out the following links to get a better idea of what to expect: (https://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/) How to ace a systems design interview  (http://www.hiredintech.com/system-design) The system design interview  (https://www.youtube.com/watch?v=ZgdS0EUmn70) Intro to Architecture and Systems Design Interviews  (https://leetcode.com/discuss/career/229177/My-System-Design-Template) System design template   System design interview questions with solutions     Common system design interview questions with sample discussions, code, and diagrams. Solutions linked to content in the solutions/ folder.  Question    Design Pastebin.com (or Bit.ly) (/donnemartin/system-design-primer/blob/master/solutions/system_design/pastebin/README.md) Solution   Design the Twitter timeline and search (or Facebook feed and search) (/donnemartin/system-design-primer/blob/master/solutions/system_design/twitter/README.md) Solution   Design a web crawler (/donnemartin/system-design-primer/blob/master/solutions/system_design/web_crawler/README.md) Solution   Design Mint.com (/donnemartin/system-design-primer/blob/master/solutions/system_design/mint/README.md) Solution   Design the data structures for a social network (/donnemartin/system-design-primer/blob/master/solutions/system_design/social_graph/README.md) Solution   Design a key-value store for a search engine (/donnemartin/system-design-primer/blob/master/solutions/system_design/query_cache/README.md) Solution   Design Amazon's sales ranking by category feature (/donnemartin/system-design-primer/blob/master/solutions/system_design/sales_rank/README.md) Solution   Design a system that scales to millions of users on AWS (/donnemartin/system-design-primer/blob/master/solutions/system_design/scaling_aws/README.md) Solution   Add a system design question Contribute      Design Pastebin.com (or Bit.ly)     (/donnemartin/system-design-primer/blob/master/solutions/system_design/pastebin/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/4edXG0T.png) (Imgur)   Design the Twitter timeline and search (or Facebook feed and search)     (/donnemartin/system-design-primer/blob/master/solutions/system_design/twitter/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/jrUBAF7.png) (Imgur)   Design a web crawler     (/donnemartin/system-design-primer/blob/master/solutions/system_design/web_crawler/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/bWxPtQA.png) (Imgur)   Design Mint.com     (/donnemartin/system-design-primer/blob/master/solutions/system_design/mint/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/V5q57vU.png) (Imgur)   Design the data structures for a social network     (/donnemartin/system-design-primer/blob/master/solutions/system_design/social_graph/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/cdCv5g7.png) (Imgur)   Design a key-value store for a search engine     (/donnemartin/system-design-primer/blob/master/solutions/system_design/query_cache/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/4j99mhe.png) (Imgur)   Design Amazon's sales ranking by category feature     (/donnemartin/system-design-primer/blob/master/solutions/system_design/sales_rank/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/MzExP06.png) (Imgur)   Design a system that scales to millions of users on AWS     (/donnemartin/system-design-primer/blob/master/solutions/system_design/scaling_aws/README.md) View exercise and solution  (/donnemartin/system-design-primer/blob/master/images/jj3A5N8.png) (Imgur)   Object-oriented design interview questions with solutions     Common object-oriented design interview questions with sample discussions, code, and diagrams. Solutions linked to content in the solutions/ folder.  Note: This section is under development   Question    Design a hash map (/donnemartin/system-design-primer/blob/master/solutions/object_oriented_design/hash_table/hash_map.ipynb) Solution   Design a least recently used cache (/donnemartin/system-design-primer/blob/master/solutions/object_oriented_design/lru_cache/lru_cache.ipynb) Solution   Design a call center (/donnemartin/system-design-primer/blob/master/solutions/object_oriented_design/call_center/call_center.ipynb) Solution   Design a deck of cards (/donnemartin/system-design-primer/blob/master/solutions/object_oriented_design/deck_of_cards/deck_of_cards.ipynb) Solution   Design a parking lot (/donnemartin/system-design-primer/blob/master/solutions/object_oriented_design/parking_lot/parking_lot.ipynb) Solution   Design a chat server (/donnemartin/system-design-primer/blob/master/solutions/object_oriented_design/online_chat/online_chat.ipynb) Solution   Design a circular array Contribute   Add an object-oriented design question Contribute      System design topics: start here     New to system design? First, you'll need a basic understanding of common principles, learning about what they are, how they are used, and their pros and cons. Step 1: Review the scalability video lecture     (https://www.youtube.com/watch?v=-W9F__D3oY4) Scalability Lecture at Harvard  Topics covered: Vertical scaling Horizontal scaling Caching Load balancing Database replication Database partitioning    Step 2: Review the scalability article     (https://web.archive.org/web/20221030091841/http://www.lecloud.net/tagged/scalability/chrono) Scalability  Topics covered: (https://web.archive.org/web/20220530193911/https://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones) Clones  (https://web.archive.org/web/20220602114024/https://www.lecloud.net/post/7994751381/scalability-for-dummies-part-2-database) Databases  (https://web.archive.org/web/20230126233752/https://www.lecloud.net/post/9246290032/scalability-for-dummies-part-3-cache) Caches  (https://web.archive.org/web/20220926171507/https://www.lecloud.net/post/9699762917/scalability-for-dummies-part-4-asynchronism) Asynchronism     Next steps     Next, we'll look at high-level trade-offs: Performance vs scalability  Latency vs throughput  Availability vs consistency   Keep in mind that everything is a trade-off . Then we'll dive into more specific topics such as DNS, CDNs, and load balancers. Performance vs scalability     A service is scalable if it results in increased performance in a manner proportional to resources added. Generally, increasing performance means serving more units of work, but it can also be to handle larger units of work, such as when datasets grow.(http://www.allthingsdistributed.com/2006/03/a_word_on_scalability.html) 1   Another way to look at performance vs scalability: If you have a performance problem, your system is slow for a single user. If you have a scalability problem, your system is fast for a single user but slow under heavy load.  Source(s) and further reading     (http://www.allthingsdistributed.com/2006/03/a_word_on_scalability.html) A word on scalability  (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) Scalability, availability, stability, patterns   Latency vs throughput     Latency is the time to perform some action or to produce some result. Throughput is the number of such actions or results per unit of time. Generally, you should aim for maximal throughput with acceptable latency . Source(s) and further reading     (https://community.cadence.com/cadence_blogs_8/b/fv/posts/understanding-latency-vs-throughput) Understanding latency vs throughput   Availability vs consistency     CAP theorem     (/donnemartin/system-design-primer/blob/master/images/bgLMI2u.png)  (http://robertgreiner.com/2014/08/cap-theorem-revisited) Source: CAP theorem revisited   In a distributed computer system, you can only support two of the following guarantees: Consistency - Every read receives the most recent write or an error Availability - Every request receives a response, without guarantee that it contains the most recent version of the information Partition Tolerance - The system continues to operate despite arbitrary partitioning due to network failures  Networks aren't reliable, so you'll need to support partition tolerance.  You'll need to make a software tradeoff between consistency and availability.  CP - consistency and partition tolerance     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. AP - availability and partition tolerance     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. AP is a good choice if the business needs to allow for eventual consistency or when the system needs to continue working despite external errors. Source(s) and further reading     (http://robertgreiner.com/2014/08/cap-theorem-revisited/) CAP theorem revisited  (http://ksat.me/a-plain-english-introduction-to-cap-theorem) A plain english introduction to CAP theorem  (https://github.com/henryr/cap-faq) CAP FAQ  (https://www.youtube.com/watch?v=k-Yaq8AHlFA) The CAP theorem   Consistency patterns     With multiple copies of the same data, we are faced with options on how to synchronize them so clients have a consistent view of the data.  Recall the definition of consistency from the CAP theorem - Every read receives the most recent write or an error. Weak consistency     After a write, reads may or may not see it.  A best effort approach is taken. This approach is seen in systems such as memcached.  Weak consistency works well in real time use cases such as VoIP, video chat, and realtime multiplayer games.  For example, if you are on a phone call and lose reception for a few seconds, when you regain connection you do not hear what was spoken during connection loss. Eventual consistency     After a write, reads will eventually see it (typically within milliseconds).  Data is replicated asynchronously. This approach is seen in systems such as DNS and email.  Eventual consistency works well in highly available systems. Strong consistency     After a write, reads will see it.  Data is replicated synchronously. This approach is seen in file systems and RDBMSes.  Strong consistency works well in systems that need transactions. Source(s) and further reading     (http://snarfed.org/transactions_across_datacenters_io.html) Transactions across data centers   Availability patterns     There are two complementary patterns to support high availability: fail-over and replication . Fail-over     Active-passive     With active-passive fail-over, heartbeats are sent between the active and the passive server on standby.  If the heartbeat is interrupted, the passive server takes over the active's IP address and resumes service. The length of downtime is determined by whether the passive server is already running in 'hot' standby or whether it needs to start up from 'cold' standby.  Only the active server handles traffic. Active-passive failover can also be referred to as master-slave failover. Active-active     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. Active-active failover can also be referred to as master-master failover. Disadvantage(s): failover     Fail-over adds more hardware and additional complexity. There is a potential for loss of data if the active system fails before any newly written data can be replicated to the passive.  Replication     Master-slave and master-master     This topic is further discussed in the Database section: Master-slave replication  Master-master replication   Availability in numbers     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. 99.9% availability - three 9s     Duration Acceptable downtime   Downtime per year 8h 45min 57s  Downtime per month 43m 49.7s  Downtime per week 10m 4.8s  Downtime per day 1m 26.4s     99.99% availability - four 9s     Duration Acceptable downtime   Downtime per year 52min 35.7s  Downtime per month 4m 23s  Downtime per week 1m 5s  Downtime per day 8.6s     Availability in parallel vs in sequence     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. In sequence     Overall availability decreases when two components with availability < 100% are in sequence: Availability (Total) = Availability (Foo) * Availability (Bar)   (Availability (Total) = Availability (Foo) * Availability (Bar))         If both Foo and Bar each had 99.9% availability, their total availability in sequence would be 99.8%. In parallel     Overall availability increases when two components with availability < 100% are in parallel: Availability (Total) = 1 - (1 - Availability (Foo)) * (1 - Availability (Bar))   (Availability (Total) = 1 - (1 - Availability (Foo)) * (1 - Availability (Bar)))         If both Foo and Bar each had 99.9% availability, their total availability in parallel would be 99.9999%. Domain name system     (/donnemartin/system-design-primer/blob/master/images/IOyLj4i.jpg)  (http://www.slideshare.net/srikrupa5/dns-security-presentation-issa) Source: DNS security presentation   A Domain Name System (DNS) translates a domain name such as (http://www.example.com) www.example.com to an IP address. 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 (https://en.wikipedia.org/wiki/Time_to_live) time to live (TTL) . NS record (name server) - Specifies the DNS servers for your domain/subdomain. MX record (mail exchange) - Specifies the mail servers for accepting messages. A record (address) - Points a name to an IP address. CNAME (canonical) - Points a name to another name or CNAME (example.com to (http://www.example.com) www.example.com ) or to an A record.  Services such as (https://www.cloudflare.com/dns/) CloudFlare and (https://aws.amazon.com/route53/) Route 53 provide managed DNS services.  Some DNS services can route traffic through various methods: (https://www.jscape.com/blog/load-balancing-algorithms) Weighted round robin Prevent traffic from going to servers under maintenance Balance between varying cluster sizes A/B testing   (https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-latency.html) Latency-based  (https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-geo.html) Geolocation-based   Disadvantage(s): DNS     Accessing a DNS server introduces a slight delay, although mitigated by caching described above. DNS server management could be complex and is generally managed by (http://superuser.com/questions/472695/who-controls-the-dns-servers/472729) governments, ISPs, and large companies . DNS services have recently come under (http://dyn.com/blog/dyn-analysis-summary-of-friday-october-21-attack/) DDoS attack , preventing users from accessing websites such as Twitter without knowing Twitter's IP address(es).  Source(s) and further reading     (https://technet.microsoft.com/en-us/library/dd197427(v=ws.10).aspx) DNS architecture  (https://en.wikipedia.org/wiki/Domain_Name_System) Wikipedia  (https://support.dnsimple.com/categories/dns/) DNS articles   Content delivery network     (/donnemartin/system-design-primer/blob/master/images/h9TAuGI.jpg)  (https://www.creative-artworks.eu/why-use-a-content-delivery-network-cdn/) Source: Why use a CDN   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. Serving content from CDNs can significantly improve performance in two ways: Users receive content from data centers close to them Your servers do not have to serve requests that the CDN fulfills  Push CDNs     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. Sites with a small amount of traffic or sites with content that isn't often updated work well with push CDNs.  Content is placed on the CDNs once, instead of being re-pulled at regular intervals. Pull CDNs     Pull CDNs grab new content from your server when the first user requests the content.  You leave the content on your server and rewrite URLs to point to the CDN.  This results in a slower request until the content is cached on the CDN. A (https://en.wikipedia.org/wiki/Time_to_live) time-to-live (TTL) 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. 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. Disadvantage(s): CDN     CDN costs could be significant depending on traffic, although this should be weighed with additional costs you would incur not using a CDN. Content might be stale if it is updated before the TTL expires it. CDNs require changing URLs for static content to point to the CDN.  Source(s) and further reading     (https://figshare.com/articles/Globally_distributed_content_delivery/6605972) Globally distributed content delivery  (http://www.travelblogadvice.com/technical/the-differences-between-push-and-pull-cdns/) The differences between push and pull CDNs  (https://en.wikipedia.org/wiki/Content_delivery_network) Wikipedia   Load balancer     (/donnemartin/system-design-primer/blob/master/images/h81n9iK.png)  (http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html) Source: Scalable system design patterns   Load balancers distribute incoming client requests to computing resources such as application servers and databases.  In each case, the load balancer returns the response from the computing resource to the appropriate client.  Load balancers are effective at: Preventing requests from going to unhealthy servers Preventing overloading resources Helping to eliminate a single point of failure  Load balancers can be implemented with hardware (expensive) or with software such as HAProxy. Additional benefits include: SSL termination - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations Removes the need to install (https://en.wikipedia.org/wiki/X.509) X.509 certificates on each server   Session persistence - Issue cookies and route a specific client's requests to same instance if the web apps do not keep track of sessions  To protect against failures, it's common to set up multiple load balancers, either in active-passive or active-active mode. Load balancers can route traffic based on various metrics, including: Random Least loaded Session/cookies (https://www.g33kinfo.com/info/round-robin-vs-weighted-round-robin-lb) Round robin or weighted round robin  Layer 4  Layer 7   Layer 4 load balancing     Layer 4 load balancers look at info at the transport layer 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 (https://www.nginx.com/resources/glossary/layer-4-load-balancing/) Network Address Translation (NAT) . Layer 7 load balancing     Layer 7 load balancers look at the application layer 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. At the cost of flexibility, layer 4 load balancing requires less time and computing resources than Layer 7, although the performance impact can be minimal on modern commodity hardware. Horizontal scaling     Load balancers can also help with horizontal scaling, improving performance and availability.  Scaling out using commodity machines is more cost efficient and results in higher availability than scaling up a single server on more expensive hardware, called Vertical Scaling .  It is also easier to hire for talent working on commodity hardware than it is for specialized enterprise systems. Disadvantage(s): horizontal scaling     Scaling horizontally introduces complexity and involves cloning servers Servers should be stateless: they should not contain any user-related data like sessions or profile pictures Sessions can be stored in a centralized data store such as a database (SQL, NoSQL) or a persistent cache (Redis, Memcached)   Downstream servers such as caches and databases need to handle more simultaneous connections as upstream servers scale out  Disadvantage(s): load balancer     The load balancer can become a performance bottleneck if it does not have enough resources or if it is not configured properly. Introducing a load balancer to help eliminate a single point of failure results in increased complexity. A single load balancer is a single point of failure, configuring multiple load balancers further increases complexity.  Source(s) and further reading     (https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/) NGINX architecture  (http://www.haproxy.org/download/1.2/doc/architecture.txt) HAProxy architecture guide  (http://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones) Scalability  (https://en.wikipedia.org/wiki/Load_balancing_(computing)) Wikipedia  (https://www.nginx.com/resources/glossary/layer-4-load-balancing/) Layer 4 load balancing  (https://www.nginx.com/resources/glossary/layer-7-load-balancing/) Layer 7 load balancing  (http://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-listener-config.html) ELB listener config   Reverse proxy (web server)     (/donnemartin/system-design-primer/blob/master/images/n41Azff.png)  (https://upload.wikimedia.org/wikipedia/commons/6/67/Reverse_proxy_h2g2bob.svg) Source: Wikipedia   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. Additional benefits include: Increased security - Hide information about backend servers, blacklist IPs, limit number of connections per client Increased scalability and flexibility - Clients only see the reverse proxy's IP, allowing you to scale servers or change their configuration SSL termination - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations Removes the need to install (https://en.wikipedia.org/wiki/X.509) X.509 certificates on each server   Compression - Compress server responses Caching - Return the response for cached requests Static content - Serve static content directly HTML/CSS/JS Photos Videos Etc    Load balancer vs reverse proxy     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. Reverse proxies can be useful even with just one web server or application server, opening up the benefits described in the previous section. Solutions such as NGINX and HAProxy can support both layer 7 reverse proxying and load balancing.  Disadvantage(s): reverse proxy     Introducing a reverse proxy results in increased complexity. A single reverse proxy is a single point of failure, configuring multiple reverse proxies (ie a (https://en.wikipedia.org/wiki/Failover) failover ) further increases complexity.  Source(s) and further reading     (https://www.nginx.com/resources/glossary/reverse-proxy-vs-load-balancer/) Reverse proxy vs load balancer  (https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/) NGINX architecture  (http://www.haproxy.org/download/1.2/doc/architecture.txt) HAProxy architecture guide  (https://en.wikipedia.org/wiki/Reverse_proxy) Wikipedia   Application layer     (/donnemartin/system-design-primer/blob/master/images/yB5SYwm.png)  (http://lethain.com/introduction-to-architecting-systems-for-scale/#platform_layer) Source: Intro to architecting systems for scale   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 single responsibility principle advocates for small and autonomous services that work together.  Small teams with small services can plan more aggressively for rapid growth. Workers in the application layer also help enable asynchronism . Microservices     Related to this discussion are (https://en.wikipedia.org/wiki/Microservices) microservices , 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. (https://smartbear.com/learn/api-design/what-are-microservices) 1   Pinterest, for example, could have the following microservices: user profile, follower, feed, search, photo upload, etc. Service Discovery     Systems such as (https://www.consul.io/docs/index.html) Consul , (https://coreos.com/etcd/docs/latest) Etcd , and (http://www.slideshare.net/sauravhaloi/introduction-to-apache-zookeeper) Zookeeper can help services find each other by keeping track of registered names, addresses, and ports. (https://www.consul.io/intro/getting-started/checks.html) Health checks help verify service integrity and are often done using an HTTP endpoint.  Both Consul and Etcd have a built in key-value store that can be useful for storing config values and other shared data. Disadvantage(s): application layer     Adding an application layer with loosely coupled services requires a different approach from an architectural, operations, and process viewpoint (vs a monolithic system). Microservices can add complexity in terms of deployments and operations.  Source(s) and further reading     (http://lethain.com/introduction-to-architecting-systems-for-scale) Intro to architecting systems for scale  (http://www.puncsky.com/blog/2016-02-13-crack-the-system-design-interview) Crack the system design interview  (https://en.wikipedia.org/wiki/Service-oriented_architecture) Service oriented architecture  (http://www.slideshare.net/sauravhaloi/introduction-to-apache-zookeeper) Introduction to Zookeeper  (https://cloudncode.wordpress.com/2016/07/22/msa-getting-started/) Here's what you need to know about building microservices   Database     (/donnemartin/system-design-primer/blob/master/images/Xkm5CXz.png)  (https://www.youtube.com/watch?v=kKjm4ehYiMs) Source: Scaling up to your first 10 million users   Relational database management system (RDBMS)     A relational database like SQL is a collection of data items organized in tables. ACID is a set of properties of relational database (https://en.wikipedia.org/wiki/Database_transaction) transactions . Atomicity - Each transaction is all or nothing Consistency - Any transaction will bring the database from one valid state to another Isolation - Executing transactions concurrently has the same results as if the transactions were executed serially Durability - Once a transaction has been committed, it will remain so  There are many techniques to scale a relational database: master-slave replication , master-master replication , federation , sharding , denormalization , and SQL tuning . Master-slave replication     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. (/donnemartin/system-design-primer/blob/master/images/C9ioGtn.png)  (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) Source: Scalability, availability, stability, patterns   Disadvantage(s): master-slave replication     Additional logic is needed to promote a slave to a master. See Disadvantage(s): replication for points related to both master-slave and master-master.  Master-master replication     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. (/donnemartin/system-design-primer/blob/master/images/krAHLGg.png)  (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) Source: Scalability, availability, stability, patterns   Disadvantage(s): master-master replication     You'll need a load balancer or you'll need to make changes to your application logic to determine where to write. Most master-master systems are either loosely consistent (violating ACID) or have increased write latency due to synchronization. Conflict resolution comes more into play as more write nodes are added and as latency increases. See Disadvantage(s): replication for points related to both master-slave and master-master.  Disadvantage(s): replication     There is a potential for loss of data if the master fails before any newly written data can be replicated to other nodes. 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. The more read slaves, the more you have to replicate, which leads to greater replication lag. 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. Replication adds more hardware and additional complexity.  Source(s) and further reading: replication     (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) Scalability, availability, stability, patterns  (https://en.wikipedia.org/wiki/Multi-master_replication) Multi-master replication   Federation     (/donnemartin/system-design-primer/blob/master/images/U3qV33e.png)  (https://www.youtube.com/watch?v=kKjm4ehYiMs) 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 (http://stackoverflow.com/questions/5145637/querying-data-by-joining-two-tables-in-two-database-on-different-servers) server link . Federation adds more hardware and additional complexity.  Source(s) and further reading: federation     (https://www.youtube.com/watch?v=kKjm4ehYiMs) Scaling up to your first 10 million users   Sharding     (/donnemartin/system-design-primer/blob/master/images/wU8x5Id.png)  (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) 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 (http://www.paperplanes.de/2011/12/9/the-magic-of-consistent-hashing.html) 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     (http://highscalability.com/blog/2009/8/6/an-unorthodox-approach-to-database-design-the-coming-of-the.html) The coming of the shard  (https://en.wikipedia.org/wiki/Shard_(database_architecture)) Shard database architecture  (http://www.paperplanes.de/2011/12/9/the-magic-of-consistent-hashing.html) Consistent hashing   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 (https://en.wikipedia.org/wiki/PostgreSQL) PostgreSQL and Oracle support (https://en.wikipedia.org/wiki/Materialized_view) 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     (https://en.wikipedia.org/wiki/Denormalization) Denormalization   SQL tuning     SQL tuning is a broad topic and many (https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=sql+tuning) 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 (http://httpd.apache.org/docs/2.2/programs/ab.html) ab . Profile - Enable tools such as the (http://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html) 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 of VARCHAR for fixed-length fields. CHAR effectively allows for fast, random access, whereas with VARCHAR , 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 a TEXT 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 (http://stackoverflow.com/questions/1017239/how-do-null-values-affect-performance-in-a-database-search) 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 (https://en.wikipedia.org/wiki/B-tree) 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 (https://dev.mysql.com/doc/refman/5.7/en/query-cache.html) query cache could lead to (https://www.percona.com/blog/2016/10/12/mysql-5-7-performance-tuning-immediately-after-installation/) performance issues .  Source(s) and further reading: SQL tuning     (http://aiddroid.com/10-tips-optimizing-mysql-queries-dont-suck/) Tips for optimizing MySQL queries  (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?  (http://stackoverflow.com/questions/1017239/how-do-null-values-affect-performance-in-a-database-search) How do null values affect performance?  (http://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html) 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 (https://en.wikipedia.org/wiki/Lexicographical_order) 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     (https://en.wikipedia.org/wiki/Key-value_database) Key-value database  (http://stackoverflow.com/questions/4056093/what-are-the-disadvantages-of-using-a-key-value-table-over-nullable-columns-or) Disadvantages of key-value stores  (http://qnimate.com/overview-of-redis-architecture/) Redis architecture  (https://adayinthelifeof.nl/2011/02/06/memcache-internals/) Memcached architecture   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 by 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 (https://www.mongodb.com/mongodb-architecture) MongoDB and (https://blog.couchdb.org/2016/08/01/couchdb-2-0-architecture/) CouchDB also provide a SQL-like language to perform complex queries. (http://www.read.seas.harvard.edu/~kohler/class/cs239-w08/decandia07dynamo.pdf) 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     (https://en.wikipedia.org/wiki/Document-oriented_database) Document-oriented database  (https://www.mongodb.com/mongodb-architecture) MongoDB architecture  (https://blog.couchdb.org/2016/08/01/couchdb-2-0-architecture/) CouchDB architecture  (https://www.elastic.co/blog/found-elasticsearch-from-the-bottom-up) Elasticsearch architecture   Wide column store     (/donnemartin/system-design-primer/blob/master/images/n16iOGk.png)  (http://blog.grio.com/2015/11/sql-nosql-a-brief-history.html) 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 (http://www.read.seas.harvard.edu/~kohler/class/cs239-w08/chang06bigtable.pdf) Bigtable as the first wide column store, which influenced the open-source (https://www.edureka.co/blog/hbase-architecture/) HBase often-used in the Hadoop ecosystem, and (http://docs.datastax.com/en/cassandra/3.0/cassandra/architecture/archIntro.html) 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     (http://blog.grio.com/2015/11/sql-nosql-a-brief-history.html) SQL & NoSQL, a brief history  (http://www.read.seas.harvard.edu/~kohler/class/cs239-w08/chang06bigtable.pdf) Bigtable architecture  (https://www.edureka.co/blog/hbase-architecture/) HBase architecture  (http://docs.datastax.com/en/cassandra/3.0/cassandra/architecture/archIntro.html) Cassandra architecture   Graph database     (/donnemartin/system-design-primer/blob/master/images/fNcl65g.png)  (https://en.wikipedia.org/wiki/File:GraphDatabase_PropertyGraph.png) Source: 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     (https://en.wikipedia.org/wiki/Graph_database) Graph database  (https://neo4j.com/) Neo4j  (https://blog.twitter.com/2010/introducing-flockdb) FlockDB   Source(s) and further reading: NoSQL     (http://stackoverflow.com/questions/3342497/explanation-of-base-terminology) Explanation of base terminology  (https://medium.com/baqend-blog/nosql-databases-a-survey-and-decision-guidance-ea7823a822d#.wskogqenq) NoSQL databases a survey and decision guidance  (http://www.lecloud.net/post/7994751381/scalability-for-dummies-part-2-database) Scalability  (https://www.youtube.com/watch?v=qI_g07C_Q5I) Introduction to NoSQL  (http://horicky.blogspot.com/2009/11/nosql-patterns.html) NoSQL patterns   SQL or NoSQL     (/donnemartin/system-design-primer/blob/master/images/wXGqG5f.png)  (https://www.infoq.com/articles/Transition-RDBMS-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     (https://www.youtube.com/watch?v=kKjm4ehYiMs) Scaling up to your first 10 million users  (https://www.sitepoint.com/sql-vs-nosql-differences/) SQL vs NoSQL differences   Cache     (/donnemartin/system-design-primer/blob/master/images/Q6z24La.png)  (http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html) 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 (https://www.varnish-cache.org/) 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 (https://en.wikipedia.org/wiki/Cache_algorithms) cache invalidation algorithms such as (https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)) 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     (/donnemartin/system-design-primer/blob/master/images/ONjORqk.png)  (http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast) 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  (def get_user(self, user_id):\n    user = cache.get(\"user.{0}\", user_id)\n    if user is None:\n        user = db.query(\"SELECT * FROM users WHERE user_id = {0}\", user_id)\n        if user is not None:\n            key = \"user.{0}\".format(user_id)\n            cache.set(key, json.dumps(user))\n    return user)         (https://memcached.org/) 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     (/donnemartin/system-design-primer/blob/master/images/0vBc0hN.png)  (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) 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\" }) (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 ) (def set_user(user_id, values):\n    user = db.query(\"UPDATE Users WHERE id = {0}\", user_id, values)\n    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 be read, which can be minimized with a TTL.  Write-behind (write-back)     (/donnemartin/system-design-primer/blob/master/images/rgSrvjG.png)  (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) 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     (/donnemartin/system-design-primer/blob/master/images/kxtjqgE.png)  (http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast) 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 (https://en.wikipedia.org/wiki/Cache_algorithms) cache invalidation . Cache invalidation is a difficult problem, there is additional complexity associated with when to update the cache. Need to make application changes such as adding Redis or memcached.  Source(s) and further reading     (http://www.slideshare.net/tmatyashovsky/from-cache-to-in-memory-data-grid-introduction-to-hazelcast) From cache to in-memory data grid  (http://horicky.blogspot.com/2010/10/scalable-system-design-patterns.html) Scalable system design patterns  (http://lethain.com/introduction-to-architecting-systems-for-scale/) Introduction to architecting systems for scale  (http://www.slideshare.net/jboner/scalability-availability-stability-patterns/) Scalability, availability, stability, patterns  (http://www.lecloud.net/post/9246290032/scalability-for-dummies-part-3-cache) Scalability  (http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/Strategies.html) AWS ElastiCache strategies  (https://en.wikipedia.org/wiki/Cache_(computing)) Wikipedia   Asynchronism     (/donnemartin/system-design-primer/blob/master/images/54GYsSx.png)  (http://lethain.com/introduction-to-architecting-systems-for-scale/#platform_layer) 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. (https://redis.io/) Redis  is useful as a simple message broker but messages can be lost. (https://www.rabbitmq.com/) RabbitMQ  is popular but requires you to adapt to the 'AMQP' protocol and manage your own nodes. (https://aws.amazon.com/sqs/) 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. (https://docs.celeryproject.org/en/stable/) 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. (http://mechanical-sympathy.blogspot.com/2012/05/apply-back-pressure-when-overloaded.html) 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 (https://en.wikipedia.org/wiki/Exponential_backoff) 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     (https://www.youtube.com/watch?v=1KRYH75wgy4) It's all a numbers game  (http://mechanical-sympathy.blogspot.com/2012/05/apply-back-pressure-when-overloaded.html) Applying back pressure when overloaded  (https://en.wikipedia.org/wiki/Little%27s_law) Little's law  (https://www.quora.com/What-is-the-difference-between-a-message-queue-and-a-task-queue-Why-would-a-task-queue-require-a-message-broker-like-RabbitMQ-Redis-Celery-or-IronMQ-to-function) What is the difference between a message queue and a task queue?   Communication     (/donnemartin/system-design-primer/blob/master/images/5KeocQs.jpg)  (http://www.escotal.com/osilayer.html) Source: OSI 7 layer model   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     (https://www.nginx.com/resources/glossary/http/) What is HTTP?  (https://www.quora.com/What-is-the-difference-between-HTTP-protocol-and-TCP-protocol) Difference between HTTP and TCP  (https://laracasts.com/discuss/channels/general-discussion/whats-the-differences-between-put-and-patch?page=1) Difference between PUT and PATCH   Transmission control protocol (TCP)     (/donnemartin/system-design-primer/blob/master/images/JdAsdvG.jpg)  (http://www.wildbunny.co.uk/blog/2012/10/09/how-to-make-a-multi-player-game-part-1/) Source: How to make a multiplayer game   TCP is a connection-oriented protocol over an (https://en.wikipedia.org/wiki/Internet_Protocol) IP network .  Connection is established and terminated using a (https://en.wikipedia.org/wiki/Handshaking) handshake .  All packets sent are guaranteed to reach the destination in the original order and without corruption through: Sequence numbers and (https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Checksum_computation) checksum fields for each packet (https://en.wikipedia.org/wiki/Acknowledgement_(data_networks)) 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 (https://en.wikipedia.org/wiki/Flow_control_(data)) flow control and (https://en.wikipedia.org/wiki/Network_congestion#Congestion_control) 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 (https://memcached.org/) memcached server. (https://en.wikipedia.org/wiki/Connection_pool) 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)     (/donnemartin/system-design-primer/blob/master/images/yzDrJtA.jpg)  (http://www.wildbunny.co.uk/blog/2012/10/09/how-to-make-a-multi-player-game-part-1/) Source: How to make a multiplayer game   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 (https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol) 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     (http://gafferongames.com/networking-for-game-programmers/udp-vs-tcp/) Networking for game programming  (http://www.cyberciti.biz/faq/key-differences-between-tcp-and-udp-protocols/) Key differences between TCP and UDP protocols  (http://stackoverflow.com/questions/5970383/difference-between-tcp-and-udp) Difference between TCP and UDP  (https://en.wikipedia.org/wiki/Transmission_Control_Protocol) Transmission control protocol  (https://en.wikipedia.org/wiki/User_Datagram_Protocol) User datagram protocol  (http://www.cs.bu.edu/~jappavoo/jappavoo.github.com/451/papers/memcache-fb.pdf) Scaling memcache at Facebook   Remote procedure call (RPC)     (/donnemartin/system-design-primer/blob/master/images/iF4Mkb5.png)  (http://www.puncsky.com/blog/2016-02-13-crack-the-system-design-interview) 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 (https://developers.google.com/protocol-buffers/) Protobuf , (https://thrift.apache.org/) Thrift , and (https://avro.apache.org/docs/current/) 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\n\nPOST /anotheroperation\n{\n  \"data\":\"anId\";\n  \"anotherdata\": \"another value\"\n}   (GET /someoperation?data=anId\n\nPOST /anotheroperation\n{\n  \"data\":\"anId\";\n  \"anotherdata\": \"another value\"\n})         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 (https://web.archive.org/web/20170608193645/http://etherealbits.com/2012/12/debunking-the-myths-of-rpc-rest/) RPC calls are properly cached on caching servers such as (http://www.squid-cache.org/) 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. (http://restcookbook.com/Basics/hateoas/) HATEOAS (HTML interface for HTTP) - your web service should be fully accessible in a browser.  Sample REST calls: GET /someresources/anId\n\nPUT /someresources/anId\n{\"anotherdata\": \"another value\"}   (GET /someresources/anId\n\nPUT /someresources/anId\n{\"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, (https://github.com/for-GET/know-your-http-well/blob/master/headers.md) 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\u2019s items list GET /readUsersItemsList?personid=1234 GET /persons/1234/items  Add an item to a person\u2019s 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     (https://apihandyman.io/do-you-really-know-why-you-prefer-rest-over-rpc/) Source: Do you really know why you prefer REST over RPC   Source(s) and further reading: REST and RPC     (https://apihandyman.io/do-you-really-know-why-you-prefer-rest-over-rpc/) Do you really know why you prefer REST over RPC  (http://programmers.stackexchange.com/a/181186) When are RPC-ish approaches more appropriate than REST?  (http://stackoverflow.com/questions/15056878/rest-vs-json-rpc) REST vs JSON-RPC  (https://web.archive.org/web/20170608193645/http://etherealbits.com/2012/12/debunking-the-myths-of-rpc-rest/) Debunking the myths of RPC and REST  (https://www.quora.com/What-are-the-drawbacks-of-using-RESTful-APIs) What are the drawbacks of using REST  (http://www.puncsky.com/blog/2016-02-13-crack-the-system-design-interview) Crack the system design interview  (https://code.facebook.com/posts/1468950976659943/) Thrift  (http://arstechnica.com/civis/viewtopic.php?t=1190508) 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 (https://en.wikipedia.org/wiki/Cross-site_scripting) XSS and (https://en.wikipedia.org/wiki/SQL_injection) SQL injection . Use parameterized queries to prevent SQL injection. Use the principle of (https://en.wikipedia.org/wiki/Principle_of_least_privilege) least privilege .  Source(s) and further reading     (https://github.com/shieldfy/API-Security-Checklist) API security checklist  (https://github.com/FallibleInc/security-guide-for-developers) Security guide for developers  (https://www.owasp.org/index.php/OWASP_Top_Ten_Cheat_Sheet) OWASP top ten   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\n---------------------------------------------------------------\n7                             128\n8                             256\n10                           1024   1 thousand           1 KB\n16                         65,536                       64 KB\n20                      1,048,576   1 million            1 MB\n30                  1,073,741,824   1 billion            1 GB\n32                  4,294,967,296                        4 GB\n40              1,099,511,627,776   1 trillion           1 TB   (Power           Exact Value         Approx Value        Bytes\n---------------------------------------------------------------\n7                             128\n8                             256\n10                           1024   1 thousand           1 KB\n16                         65,536                       64 KB\n20                      1,048,576   1 million            1 MB\n30                  1,073,741,824   1 billion            1 GB\n32                  4,294,967,296                        4 GB\n40              1,099,511,627,776   1 trillion           1 TB)         Source(s) and further reading     (https://en.wikipedia.org/wiki/Power_of_two) Powers of two   Latency numbers every programmer should know     Latency Comparison Numbers\n--------------------------\nL1 cache reference                           0.5 ns\nBranch mispredict                            5   ns\nL2 cache reference                           7   ns                      14x L1 cache\nMutex lock/unlock                           25   ns\nMain memory reference                      100   ns                      20x L2 cache, 200x L1 cache\nCompress 1K bytes with Zippy            10,000   ns       10 us\nSend 1 KB bytes over 1 Gbps network     10,000   ns       10 us\nRead 4 KB randomly from SSD*           150,000   ns      150 us          ~1GB/sec SSD\nRead 1 MB sequentially from memory     250,000   ns      250 us\nRound trip within same datacenter      500,000   ns      500 us\nRead 1 MB sequentially from SSD*     1,000,000   ns    1,000 us    1 ms  ~1GB/sec SSD, 4X memory\nHDD seek                            10,000,000   ns   10,000 us   10 ms  20x datacenter roundtrip\nRead 1 MB sequentially from 1 Gbps  10,000,000   ns   10,000 us   10 ms  40x memory, 10X SSD\nRead 1 MB sequentially from HDD     30,000,000   ns   30,000 us   30 ms 120x memory, 30X SSD\nSend packet CA->Netherlands->CA    150,000,000   ns  150,000 us  150 ms\n\nNotes\n-----\n1 ns = 10^-9 seconds\n1 us = 10^-6 seconds = 1,000 ns\n1 ms = 10^-3 seconds = 1,000 us = 1,000,000 ns   (Latency Comparison Numbers\n--------------------------\nL1 cache reference                           0.5 ns\nBranch mispredict                            5   ns\nL2 cache reference                           7   ns                      14x L1 cache\nMutex lock/unlock                           25   ns\nMain memory reference                      100   ns                      20x L2 cache, 200x L1 cache\nCompress 1K bytes with Zippy            10,000   ns       10 us\nSend 1 KB bytes over 1 Gbps network     10,000   ns       10 us\nRead 4 KB randomly from SSD*           150,000   ns      150 us          ~1GB/sec SSD\nRead 1 MB sequentially from memory     250,000   ns      250 us\nRound trip within same datacenter      500,000   ns      500 us\nRead 1 MB sequentially from SSD*     1,000,000   ns    1,000 us    1 ms  ~1GB/sec SSD, 4X memory\nHDD seek                            10,000,000   ns   10,000 us   10 ms  20x datacenter roundtrip\nRead 1 MB sequentially from 1 Gbps  10,000,000   ns   10,000 us   10 ms  40x memory, 10X SSD\nRead 1 MB sequentially from HDD     30,000,000   ns   30,000 us   30 ms 120x memory, 30X SSD\nSend packet CA->Netherlands->CA    150,000,000   ns  150,000 us  150 ms\n\nNotes\n-----\n1 ns = 10^-9 seconds\n1 us = 10^-6 seconds = 1,000 ns\n1 ms = 10^-3 seconds = 1,000 us = 1,000,000 ns)         Handy metrics based on numbers above: Read sequentially from HDD 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     (https://camo.githubusercontent.com/77f72259e1eb58596b564d1ad823af1853bc60a3/687474703a2f2f692e696d6775722e636f6d2f6b307431652e706e67) ()   Source(s) and further reading     (https://gist.github.com/jboner/2841832) Latency numbers every programmer should know - 1  (https://gist.github.com/hellerbarde/2843375) Latency numbers every programmer should know - 2  (http://www.cs.cornell.edu/projects/ladis2009/talks/dean-keynote-ladis2009.pdf) Designs, lessons, and advice from building large distributed systems  (https://static.googleusercontent.com/media/research.google.com/en//people/jeff/stanford-295-talk.pdf) 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 (https://www.youtube.com/watch?v=PE4gwstWhmc) youtube.com   Design a search engine like Google (http://queue.acm.org/detail.cfm?id=988407) queue.acm.org (http://programmers.stackexchange.com/questions/38324/interview-question-how-would-you-implement-google-search) stackexchange.com (http://www.ardendertat.com/2012/01/11/implementing-search-engines/) ardendertat.com (http://infolab.stanford.edu/~backrub/google.html) stanford.edu   Design a scalable web crawler like Google (https://www.quora.com/How-can-I-build-a-web-crawler-from-scratch) quora.com   Design Google docs (https://code.google.com/p/google-mobwrite/) code.google.com (https://neil.fraser.name/writing/sync/) neil.fraser.name   Design a key-value store like Redis (http://www.slideshare.net/dvirsky/introduction-to-redis) slideshare.net   Design a cache system like Memcached (http://www.slideshare.net/oemebamo/introduction-to-memcached) slideshare.net   Design a recommendation system like Amazon's (https://web.archive.org/web/20170406065247/http://tech.hulu.com/blog/2011/09/19/recommendation-system.html) hulu.com (http://ijcai13.org/files/tutorial_slides/td3.pdf) ijcai13.org   Design a tinyurl system like Bitly (http://n00tc0d3r.blogspot.com/) n00tc0d3r.blogspot.com   Design a chat app like WhatsApp (http://highscalability.com/blog/2014/2/26/the-whatsapp-architecture-facebook-bought-for-19-billion.html) highscalability.com   Design a picture sharing system like Instagram (http://highscalability.com/flickr-architecture) highscalability.com (http://highscalability.com/blog/2011/12/6/instagram-architecture-14-million-users-terabytes-of-photos.html) highscalability.com   Design the Facebook news feed function (http://www.quora.com/What-are-best-practices-for-building-something-like-a-News-Feed) quora.com (http://www.quora.com/Activity-Streams/What-are-the-scaling-issues-to-keep-in-mind-while-developing-a-social-network-feed) quora.com (http://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture) slideshare.net   Design the Facebook timeline function (https://www.facebook.com/note.php?note_id=10150468255628920) facebook.com (http://highscalability.com/blog/2012/1/23/facebook-timeline-brought-to-you-by-the-power-of-denormaliza.html) highscalability.com   Design the Facebook chat function (http://www.erlang-factory.com/upload/presentations/31/EugeneLetuchy-ErlangatFacebook.pdf) erlang-factory.com (https://www.facebook.com/note.php?note_id=14218138919&id=9445547199&index=0) facebook.com   Design a graph search function like Facebook's (https://www.facebook.com/notes/facebook-engineering/under-the-hood-building-out-the-infrastructure-for-graph-search/10151347573598920) facebook.com (https://www.facebook.com/notes/facebook-engineering/under-the-hood-indexing-and-ranking-in-graph-search/10151361720763920) facebook.com (https://www.facebook.com/notes/facebook-engineering/under-the-hood-the-natural-language-interface-of-graph-search/10151432733048920) facebook.com   Design a content delivery network like CloudFlare (https://figshare.com/articles/Globally_distributed_content_delivery/6605972) figshare.com   Design a trending topic system like Twitter's (http://www.michael-noll.com/blog/2013/01/18/implementing-real-time-trending-topics-in-storm/) michael-noll.com (http://snikolov.wordpress.com/2012/11/14/early-detection-of-twitter-trends/) snikolov .wordpress.com   Design a random ID generation system (https://blog.twitter.com/2010/announcing-snowflake) blog.twitter.com (https://github.com/twitter/snowflake/) github.com   Return the top k requests during a time interval (https://www.cs.ucsb.edu/sites/default/files/documents/2005-23.pdf) cs.ucsb.edu (http://davis.wpi.edu/xmdv/docs/EDBT11-diyang.pdf) wpi.edu   Design a system that serves data from multiple data centers (http://highscalability.com/blog/2009/8/24/how-google-serves-data-from-multiple-datacenters.html) highscalability.com   Design an online multiplayer card game (https://web.archive.org/web/20180929181117/http://www.indieflashblog.com/how-to-create-an-asynchronous-multiplayer-game.html) indieflashblog.com (http://buildnewgames.com/real-time-multiplayer/) buildnewgames.com   Design a garbage collection system (http://journal.stuffwithstuff.com/2013/12/08/babys-first-garbage-collector/) stuffwithstuff.com (http://courses.cs.washington.edu/courses/csep521/07wi/prj/rick.pdf) washington.edu   Design an API rate limiter (https://stripe.com/blog/rate-limiters) https://stripe.com/blog/   Design a Stock Exchange (like NASDAQ or Binance) (https://youtu.be/b1e4t2k2KJY) Jane Street (https://around25.com/blog/building-a-trading-engine-for-a-crypto-exchange/) Golang Implementation (http://bhomnick.net/building-a-simple-limit-order-in-go/) Go Implementation   Add a system design question Contribute      Real world architectures     Articles on how real world systems are designed.  (/donnemartin/system-design-primer/blob/master/images/TcUo2fw.png)  (https://www.infoq.com/presentations/Twitter-Timeline-Scalability) 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 (http://static.googleusercontent.com/media/research.google.com/zh-CN/us/archive/mapreduce-osdi04.pdf) research.google.com   Data processing Spark - Distributed data processing from Databricks (http://www.slideshare.net/AGrishchenko/apache-spark-architecture) slideshare.net   Data processing Storm - Distributed data processing from Twitter (http://www.slideshare.net/previa/storm-16094009) slideshare.net       Data store Bigtable - Distributed column-oriented database from Google (http://www.read.seas.harvard.edu/~kohler/class/cs239-w08/chang06bigtable.pdf) harvard.edu   Data store HBase - Open source implementation of Bigtable (http://www.slideshare.net/alexbaranau/intro-to-hbase) slideshare.net   Data store Cassandra - Distributed column-oriented database from Facebook (http://www.slideshare.net/planetcassandra/cassandra-introduction-features-30103666) slideshare.net   Data store DynamoDB - Document-oriented database from Amazon (http://www.read.seas.harvard.edu/~kohler/class/cs239-w08/decandia07dynamo.pdf) harvard.edu   Data store MongoDB - Document-oriented database (http://www.slideshare.net/mdirolf/introduction-to-mongodb) slideshare.net   Data store Spanner - Globally-distributed database from Google (http://research.google.com/archive/spanner-osdi2012.pdf) research.google.com   Data store Memcached - Distributed memory caching system (http://www.slideshare.net/oemebamo/introduction-to-memcached) slideshare.net   Data store Redis - Distributed memory caching system with persistence and value types (http://www.slideshare.net/dvirsky/introduction-to-redis) slideshare.net       File system Google File System (GFS) - Distributed file system (http://static.googleusercontent.com/media/research.google.com/zh-CN/us/archive/gfs-sosp2003.pdf) research.google.com   File system Hadoop File System (HDFS) - Open source implementation of GFS (http://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/HdfsDesign.html) apache.org       Misc Chubby - Lock service for loosely-coupled distributed systems from Google (http://static.googleusercontent.com/external_content/untrusted_dlcp/research.google.com/en/us/archive/chubby-osdi06.pdf) research.google.com   Misc Dapper - Distributed systems tracing infrastructure (http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36356.pdf) research.google.com   Misc Kafka - Pub/sub message queue from LinkedIn (http://www.slideshare.net/mumrah/kafka-talk-tri-hug) slideshare.net   Misc Zookeeper - Centralized infrastructure and services enabling synchronization (http://www.slideshare.net/sauravhaloi/introduction-to-apache-zookeeper) slideshare.net    Add an architecture Contribute      Company architectures     Company Reference(s)   Amazon (http://highscalability.com/amazon-architecture) Amazon architecture   Cinchcast (http://highscalability.com/blog/2012/7/16/cinchcast-architecture-producing-1500-hours-of-audio-every-d.html) Producing 1,500 hours of audio every day   DataSift (http://highscalability.com/blog/2011/11/29/datasift-architecture-realtime-datamining-at-120000-tweets-p.html) Realtime datamining At 120,000 tweets per second   Dropbox (https://www.youtube.com/watch?v=PE4gwstWhmc) How we've scaled Dropbox   ESPN (http://highscalability.com/blog/2013/11/4/espns-architecture-at-scale-operating-at-100000-duh-nuh-nuhs.html) Operating At 100,000 duh nuh nuhs per second   Google (http://highscalability.com/google-architecture) Google architecture   Instagram (http://highscalability.com/blog/2011/12/6/instagram-architecture-14-million-users-terabytes-of-photos.html) 14 million users, terabytes of photos (http://instagram-engineering.tumblr.com/post/13649370142/what-powers-instagram-hundreds-of-instances) What powers Instagram   Justin.tv (http://highscalability.com/blog/2010/3/16/justintvs-live-video-broadcasting-architecture.html) Justin.Tv's live video broadcasting architecture   Facebook (https://cs.uwaterloo.ca/~brecht/courses/854-Emerging-2014/readings/key-value/fb-memcached-nsdi-2013.pdf) Scaling memcached at Facebook (https://cs.uwaterloo.ca/~brecht/courses/854-Emerging-2014/readings/data-store/tao-facebook-distributed-datastore-atc-2013.pdf) TAO: Facebook\u2019s distributed data store for the social graph (https://www.usenix.org/legacy/event/osdi10/tech/full_papers/Beaver.pdf) Facebook\u2019s photo storage (http://highscalability.com/blog/2016/6/27/how-facebook-live-streams-to-800000-simultaneous-viewers.html) How Facebook Live Streams To 800,000 Simultaneous Viewers   Flickr (http://highscalability.com/flickr-architecture) Flickr architecture   Mailbox (http://highscalability.com/blog/2013/6/18/scaling-mailbox-from-0-to-one-million-users-in-6-weeks-and-1.html) From 0 to one million users in 6 weeks   Netflix (http://highscalability.com/blog/2015/11/9/a-360-degree-view-of-the-entire-netflix-stack.html) A 360 Degree View Of The Entire Netflix Stack (http://highscalability.com/blog/2017/12/11/netflix-what-happens-when-you-press-play.html) Netflix: What Happens When You Press Play?   Pinterest (http://highscalability.com/blog/2013/4/15/scaling-pinterest-from-0-to-10s-of-billions-of-page-views-a.html) From 0 To 10s of billions of page views a month (http://highscalability.com/blog/2012/5/21/pinterest-architecture-update-18-million-visitors-10x-growth.html) 18 million visitors, 10x growth, 12 employees   Playfish (http://highscalability.com/blog/2010/9/21/playfishs-social-gaming-architecture-50-million-monthly-user.html) 50 million monthly users and growing   PlentyOfFish (http://highscalability.com/plentyoffish-architecture) PlentyOfFish architecture   Salesforce (http://highscalability.com/blog/2013/9/23/salesforce-architecture-how-they-handle-13-billion-transacti.html) How they handle 1.3 billion transactions a day   Stack Overflow (http://highscalability.com/blog/2009/8/5/stack-overflow-architecture.html) Stack Overflow architecture   TripAdvisor (http://highscalability.com/blog/2011/6/27/tripadvisor-architecture-40m-visitors-200m-dynamic-page-view.html) 40M visitors, 200M dynamic page views, 30TB data   Tumblr (http://highscalability.com/blog/2012/2/13/tumblr-architecture-15-billion-page-views-a-month-and-harder.html) 15 billion page views a month   Twitter (http://highscalability.com/scaling-twitter-making-twitter-10000-percent-faster) Making Twitter 10000 percent faster (http://highscalability.com/blog/2011/12/19/how-twitter-stores-250-million-tweets-a-day-using-mysql.html) Storing 250 million tweets a day using MySQL (http://highscalability.com/blog/2013/7/8/the-architecture-twitter-uses-to-deal-with-150m-active-users.html) 150M active users, 300K QPS, a 22 MB/S firehose (https://www.infoq.com/presentations/Twitter-Timeline-Scalability) Timelines at scale (https://www.youtube.com/watch?v=5cKTP36HVgI) Big and small data at Twitter (https://www.youtube.com/watch?v=z8LU0Cj6BOU) Operations at Twitter: scaling beyond 100 million users (http://highscalability.com/blog/2016/4/20/how-twitter-handles-3000-images-per-second.html) How Twitter Handles 3,000 Images Per Second   Uber (http://highscalability.com/blog/2015/9/14/how-uber-scales-their-real-time-market-platform.html) How Uber scales their real-time market platform (http://highscalability.com/blog/2016/10/12/lessons-learned-from-scaling-uber-to-2000-engineers-1000-ser.html) Lessons Learned From Scaling Uber To 2000 Engineers, 1000 Services, And 8000 Git Repositories   WhatsApp (http://highscalability.com/blog/2014/2/26/the-whatsapp-architecture-facebook-bought-for-19-billion.html) The WhatsApp architecture Facebook bought for $19 billion   YouTube (https://www.youtube.com/watch?v=w5WVu624fY8) YouTube scalability (http://highscalability.com/youtube-architecture) YouTube architecture      Company engineering blogs     Architectures for companies you are interviewing with. Questions you encounter might be from the same domain.  (http://nerds.airbnb.com/) Airbnb Engineering  (https://developer.atlassian.com/blog/) Atlassian Developers  (https://aws.amazon.com/blogs/aws/) AWS Blog  (http://word.bitly.com/) Bitly Engineering Blog  (https://blog.box.com/blog/category/engineering) Box Blogs  (http://blog.cloudera.com/) Cloudera Developer Blog  (https://tech.dropbox.com/) Dropbox Tech Blog  (https://www.quora.com/q/quoraengineering) Engineering at Quora  (http://www.ebaytechblog.com/) Ebay Tech Blog  (https://blog.evernote.com/tech/) Evernote Tech Blog  (http://codeascraft.com/) Etsy Code as Craft  (https://www.facebook.com/Engineering) Facebook Engineering  (http://code.flickr.net/) Flickr Code  (http://engineering.foursquare.com/) Foursquare Engineering Blog  (https://github.blog/category/engineering) GitHub Engineering Blog  (http://googleresearch.blogspot.com/) Google Research Blog  (https://engineering.groupon.com/) Groupon Engineering Blog  (https://engineering.heroku.com/) Heroku Engineering Blog  (http://product.hubspot.com/blog/topic/engineering) Hubspot Engineering Blog  (http://highscalability.com/) High Scalability  (http://instagram-engineering.tumblr.com/) Instagram Engineering  (https://software.intel.com/en-us/blogs/) Intel Software Blog  (https://blogs.janestreet.com/category/ocaml/) Jane Street Tech Blog  (http://engineering.linkedin.com/blog) LinkedIn Engineering  (https://engineering.microsoft.com/) Microsoft Engineering  (https://blogs.msdn.microsoft.com/pythonengineering/) Microsoft Python Engineering  (http://techblog.netflix.com/) Netflix Tech Blog  (https://medium.com/paypal-engineering) Paypal Developer Blog  (https://medium.com/@Pinterest_Engineering) Pinterest Engineering Blog  (http://www.redditblog.com/) Reddit Blog  (https://developer.salesforce.com/blogs/engineering/) Salesforce Engineering Blog  (https://slack.engineering/) Slack Engineering Blog  (https://labs.spotify.com/) Spotify Labs  (https://stripe.com/blog/engineering) Stripe Engineering Blog  (http://www.twilio.com/engineering) Twilio Engineering Blog  (https://blog.twitter.com/engineering/) Twitter Engineering  (http://eng.uber.com/) Uber Engineering Blog  (http://yahooeng.tumblr.com/) Yahoo Engineering Blog  (http://engineeringblog.yelp.com/) Yelp Engineering Blog  (https://www.zynga.com/blogs/engineering) Zynga Engineering Blog   Source(s) and further reading     Looking to add a blog?  To avoid duplicating work, consider adding your company blog to the following repo: (https://github.com/kilimchoi/engineering-blogs) kilimchoi/engineering-blogs   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: (http://www.hiredintech.com/system-design/the-system-design-process/) Hired in tech  (https://www.amazon.com/dp/0984782850/) Cracking the coding interview  (http://highscalability.com/) High scalability  (https://github.com/checkcheckzz/system-design-interview) checkcheckzz/system-design-interview  (https://github.com/shashank88/system_design) shashank88/system_design  (https://github.com/mmcgrana/services-engineering) mmcgrana/services-engineering  (https://gist.github.com/vasanthk/485d1c25737e8e72759f) System design cheat sheet  (http://dancres.github.io/Pages/) A distributed systems reading list  (http://www.puncsky.com/blog/2016-02-13-crack-the-system-design-interview) 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 (https://github.com/donnemartin) 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\n\nCreative Commons Attribution 4.0 International License (CC BY 4.0)\n\nhttp://creativecommons.org/licenses/by/4.0/   (Copyright 2017 Donne Martin\n\nCreative Commons Attribution 4.0 International License (CC BY 4.0)\n\nhttp://creativecommons.org/licenses/by/4.0/)                 (e41JbUi3u/2N6WOvhEQQfplPtzn+rldcwYqO2pe9tF7RckKHCky6ZbdjCcMW3WKZEZMRAfPDh36BG63ZXP8fnQ==)  About Learn how to design large-scale systems. Prep for the system design interview. Includes Anki flashcards.  Topics (/topics/python) (Topic: python) python  (/topics/design) (Topic: design) design  (/topics/development) (Topic: development) development  (/topics/programming) (Topic: programming) programming  (/topics/web) (Topic: web) web  (/topics/system) (Topic: system) system  (/topics/design-patterns) (Topic: design-patterns) design-patterns  (/topics/interview) (Topic: interview) interview  (/topics/web-application) (Topic: web-application) web-application  (/topics/webapp) (Topic: webapp) webapp  (/topics/interview-practice) (Topic: interview-practice) interview-practice  (/topics/interview-questions) (Topic: interview-questions) interview-questions  (/topics/design-system) (Topic: design-system) design-system    Resources   Readme   License   View license    (/donnemartin/system-design-primer/activity)   Activity   Stars (/donnemartin/system-design-primer/stargazers)   284k stars  Watchers (/donnemartin/system-design-primer/watchers)   6.6k watching  Forks (/donnemartin/system-design-primer/forks)   47.5k forks  (/contact/report-content?content_url=https%3A%2F%2Fgithub.com%2Fdonnemartin%2Fsystem-design-primer&report=donnemartin+%28user%29) Report repository      (/donnemartin/system-design-primer/releases) Releases  No releases published   (/users/donnemartin/packages?repo_name=system-design-primer) Packages (0) 0   No packages published       (/donnemartin/system-design-primer/graphs/contributors) Contributors (119) 119   (https://github.com/donnemartin) (@donnemartin)   (https://github.com/cclauss) (@cclauss)   (https://github.com/satob) (@satob)   (https://github.com/fluency03) (@fluency03)   (https://github.com/linhe0x0) (@linhe0x0)   (https://github.com/luisbg) (@luisbg)   (https://github.com/manaskarekar) (@manaskarekar)   (https://github.com/kevingo) (@kevingo)   (https://github.com/yangshun) (@yangshun)   (https://github.com/ralphite) (@ralphite)   (https://github.com/glusa8) (@glusa8)   (https://github.com/ianpark) (@ianpark)   (https://github.com/hulikau) (@hulikau)   (https://github.com/bryanjenningz) (@bryanjenningz)    (/donnemartin/system-design-primer/graphs/contributors) + 105 contributors    Languages     (/donnemartin/system-design-primer/search?l=python)   Python 98.0%   (/donnemartin/system-design-primer/search?l=shell)   Shell 2.0%                Footer (GitHub) (https://github.com)    \u00a9 2025 GitHub,\u00a0Inc.   Footer navigation (https://docs.github.com/site-policy/github-terms/github-terms-of-service) Terms  (https://docs.github.com/site-policy/privacy-policies/github-privacy-statement) Privacy  (https://github.com/security) Security  (https://www.githubstatus.com/) Status  (https://docs.github.com/) Docs  (https://support.github.com?tags=dotcom-footer) Contact  Manage cookies    Do not share my personal information              You can\u2019t perform that action at this time.         "
                ],
                "output": "htmltotext.txt",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:38:53.833520+00:00",
                "status": "succeeded"
            }
        ],
        "media": [
            {
                "cmd": [
                    "/usr/local/bin/yt-dlp",
                    "--restrict-filenames",
                    "--trim-filenames",
                    "128",
                    "--write-description",
                    "--write-info-json",
                    "--write-annotations",
                    "--write-thumbnail",
                    "--no-call-home",
                    "--write-sub",
                    "--write-auto-subs",
                    "--convert-subs=srt",
                    "--yes-playlist",
                    "--continue",
                    "--no-abort-on-error",
                    "--ignore-errors",
                    "--geo-bypass",
                    "--add-metadata",
                    "--format=(bv*+ba/b)[filesize<=750m][filesize_approx<=?750m]/(bv*+ba/b)",
                    "--skip-download",
                    "--cache-dir=/data/yt-dlp-cache/",
                    "--cookies=/data/yt-dlp-cache/cookies.txt",
                    "--proxy=socks5://tor-socks-proxy:9150",
                    "--no-playlist",
                    "https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
                ],
                "cmd_version": "2024.10.7",
                "end_ts": "2025-01-04T18:39:07.192796+00:00",
                "index_texts": [],
                "output": "media/",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:38:55.930384+00:00",
                "status": "succeeded"
            }
        ],
        "mercury": [
            {
                "cmd": [
                    "/home/archivebox/.npm/bin/postlight-parser",
                    "https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
                ],
                "cmd_version": "2.2.3",
                "end_ts": "2025-01-04T18:38:53.756819+00:00",
                "index_texts": null,
                "output": "mercury/",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:38:37.032911+00:00",
                "status": "succeeded"
            }
        ],
        "pdf": [],
        "readability": [
            {
                "cmd": [
                    "/home/archivebox/.npm/bin/readability-extractor",
                    "/tmp/tmps1d92e7i",
                    "https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
                ],
                "cmd_version": "0.0.11",
                "end_ts": "2025-01-04T18:38:36.901614+00:00",
                "index_texts": [
                    "English \u2219 \u65e5\u672c\u8a9e \u2219 \u7b80\u4f53\u4e2d\u6587 \u2219 \u7e41\u9ad4\u4e2d\u6587 | \u0627\u0644\u0639\u064e\u0631\u064e\u0628\u0650\u064a\u064e\u0651\u0629\u200e \u2219 \u09ac\u09be\u0982\u09b2\u09be \u2219 Portugu\u00eas do Brasil \u2219 Deutsch \u2219 \u03b5\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac \u2219 \u05e2\u05d1\u05e8\u05d9\u05ea \u2219 Italiano \u2219 \ud55c\uad6d\uc5b4 \u2219 \u0641\u0627\u0631\u0633\u06cc \u2219 Polski \u2219 \u0440\u0443\u0441\u0441\u043a\u0438\u0439 \u044f\u0437\u044b\u043a \u2219 Espa\u00f1ol \u2219 \u0e20\u0e32\u0e29\u0e32\u0e44\u0e17\u0e22 \u2219 T\u00fcrk\u00e7e \u2219 ti\u1ebfng Vi\u1ec7t \u2219 Fran\u00e7ais | Add Translation\nHelp translate this guide!\nThe System Design Primer\n\n  \n  \n\nMotivation\n\nLearn how to design large-scale systems.\nPrep for the system design interview.\n\nLearn how to design large-scale systems\nLearning how to design scalable systems will help you become a better engineer.\nSystem design is a broad topic.  There is a vast amount of resources scattered throughout the web on system design principles.\nThis repo is an organized collection of resources to help you learn how to build systems at scale.\nLearn from the open source community\nThis is a continually updated, open source project.\nContributions are welcome!\nPrep for the system design interview\nIn addition to coding interviews, system design is a required component of the technical interview process at many tech companies.\nPractice common system design interview questions and compare your results with sample solutions: discussions, code, and diagrams.\nAdditional topics for interview prep:\n\nStudy guide\nHow to approach a system design interview question\nSystem design interview questions, with solutions\nObject-oriented design interview questions, with solutions\nAdditional system design interview questions\n\nAnki flashcards\n\n  \n  \n\nThe provided Anki flashcard decks use spaced repetition to help you retain key system design concepts.\n\nSystem design deck\nSystem design exercises deck\nObject oriented design exercises deck\n\nGreat for use while on-the-go.\nCoding Resource: Interactive Coding Challenges\nLooking for resources to help you prep for the Coding Interview?\n\n  \n  \n\nCheck out the sister repo Interactive Coding Challenges, which contains an additional Anki deck:\n\nCoding deck\n\nContributing\n\nLearn from the community.\n\nFeel free to submit pull requests to help:\n\nFix errors\nImprove sections\nAdd new sections\nTranslate\n\nContent that needs some polishing is placed under development.\nReview the Contributing Guidelines.\nIndex of system design topics\n\nSummaries of various system design topics, including pros and cons.  Everything is a trade-off.\nEach section contains links to more in-depth resources.\n\n\n  \n  \n\n\nSystem design topics: start here\n\nStep 1: Review the scalability video lecture\nStep 2: Review the scalability article\nNext steps\n\n\nPerformance vs scalability\nLatency vs throughput\nAvailability vs consistency\n\nCAP theorem\n\nCP - consistency and partition tolerance\nAP - availability and partition tolerance\n\n\n\n\nConsistency patterns\n\nWeak consistency\nEventual consistency\nStrong consistency\n\n\nAvailability patterns\n\nFail-over\nReplication\nAvailability in numbers\n\n\nDomain name system\nContent delivery network\n\nPush CDNs\nPull CDNs\n\n\nLoad balancer\n\nActive-passive\nActive-active\nLayer 4 load balancing\nLayer 7 load balancing\nHorizontal scaling\n\n\nReverse proxy (web server)\n\nLoad balancer vs reverse proxy\n\n\nApplication layer\n\nMicroservices\nService discovery\n\n\nDatabase\n\nRelational database management system (RDBMS)\n\nMaster-slave replication\nMaster-master replication\nFederation\nSharding\nDenormalization\nSQL tuning\n\n\nNoSQL\n\nKey-value store\nDocument store\nWide column store\nGraph Database\n\n\nSQL or NoSQL\n\n\nCache\n\nClient caching\nCDN caching\nWeb server caching\nDatabase caching\nApplication caching\nCaching at the database query level\nCaching at the object level\nWhen to update the cache\n\nCache-aside\nWrite-through\nWrite-behind (write-back)\nRefresh-ahead\n\n\n\n\nAsynchronism\n\nMessage queues\nTask queues\nBack pressure\n\n\nCommunication\n\nTransmission control protocol (TCP)\nUser datagram protocol (UDP)\nRemote procedure call (RPC)\nRepresentational state transfer (REST)\n\n\nSecurity\nAppendix\n\nPowers of two table\nLatency numbers every programmer should know\nAdditional system design interview questions\nReal world architectures\nCompany architectures\nCompany engineering blogs\n\n\nUnder development\nCredits\nContact info\nLicense\n\nStudy guide\n\nSuggested topics to review based on your interview timeline (short, medium, long).\n\n\nQ: For interviews, do I need to know everything here?\nA: No, you don't need to know everything here to prepare for the interview.\nWhat you are asked in an interview depends on variables such as:\n\nHow much experience you have\nWhat your technical background is\nWhat positions you are interviewing for\nWhich companies you are interviewing with\nLuck\n\nMore experienced candidates are generally expected to know more about system design.  Architects or team leads might be expected to know more than individual contributors.  Top tech companies are likely to have one or more design interview rounds.\nStart broad and go deeper in a few areas.  It helps to know a little about various key system design topics.  Adjust the following guide based on your timeline, experience, what positions you are interviewing for, and which companies you are interviewing with.\n\nShort timeline - Aim for breadth with system design topics.  Practice by solving some interview questions.\nMedium timeline - Aim for breadth and some depth with system design topics.  Practice by solving many interview questions.\nLong timeline - Aim for breadth and more depth with system design topics.  Practice by solving most interview questions.\n\n\n\n\n\nShort\nMedium\nLong\n\n\n\n\nRead through the System design topics to get a broad understanding of how systems work\n\ud83d\udc4d\n\ud83d\udc4d\n\ud83d\udc4d\n\n\nRead through a few articles in the Company engineering blogs for the companies you are interviewing with\n\ud83d\udc4d\n\ud83d\udc4d\n\ud83d\udc4d\n\n\nRead through a few Real world architectures\n\ud83d\udc4d\n\ud83d\udc4d\n\ud83d\udc4d\n\n\nReview How to approach a system design interview question\n\ud83d\udc4d\n\ud83d\udc4d\n\ud83d\udc4d\n\n\nWork through System design interview questions with solutions\nSome\nMany\nMost\n\n\nWork through Object-oriented design interview questions with solutions\nSome\nMany\nMost\n\n\nReview Additional system design interview questions\nSome\nMany\nMost\n\n\n\nHow to approach a system design interview question\n\nHow to tackle a system design interview question.\n\nThe system design interview is an open-ended conversation.  You are expected to lead it.\nYou can use the following steps to guide the discussion.  To help solidify this process, work through the System design interview questions with solutions section using the following steps.\nStep 1: Outline use cases, constraints, and assumptions\nGather requirements and scope the problem.  Ask questions to clarify use cases and constraints.  Discuss assumptions.\n\nWho is going to use it?\nHow are they going to use it?\nHow many users are there?\nWhat does the system do?\nWhat are the inputs and outputs of the system?\nHow much data do we expect to handle?\nHow many requests per second do we expect?\nWhat is the expected read to write ratio?\n\nStep 2: Create a high level design\nOutline a high level design with all important components.\n\nSketch the main components and connections\nJustify your ideas\n\nStep 3: Design core components\nDive into details for each core component.  For example, if you were asked to design a url shortening service, discuss:\n\nGenerating and storing a hash of the full url\n\nMD5 and Base62\nHash collisions\nSQL or NoSQL\nDatabase schema\n\n\nTranslating a hashed url to the full url\n\nDatabase lookup\n\n\nAPI and object-oriented design\n\nStep 4: Scale the design\nIdentify and address bottlenecks, given the constraints.  For example, do you need the following to address scalability issues?\n\nLoad balancer\nHorizontal scaling\nCaching\nDatabase sharding\n\nDiscuss potential solutions and trade-offs.  Everything is a trade-off.  Address bottlenecks using principles of scalable system design.\nBack-of-the-envelope calculations\nYou might be asked to do some estimates by hand.  Refer to the Appendix for the following resources:\n\nUse back of the envelope calculations\nPowers of two table\nLatency numbers every programmer should know\n\nSource(s) and further reading\nCheck out the following links to get a better idea of what to expect:\n\nHow to ace a systems design interview\nThe system design interview\nIntro to Architecture and Systems Design Interviews\nSystem design template\n\nSystem design interview questions with solutions\n\nCommon system design interview questions with sample discussions, code, and diagrams.\nSolutions linked to content in the solutions/ folder.\n\n\n\n\nQuestion\n\n\n\n\n\nDesign Pastebin.com (or Bit.ly)\nSolution\n\n\nDesign the Twitter timeline and search (or Facebook feed and search)\nSolution\n\n\nDesign a web crawler\nSolution\n\n\nDesign Mint.com\nSolution\n\n\nDesign the data structures for a social network\nSolution\n\n\nDesign a key-value store for a search engine\nSolution\n\n\nDesign Amazon's sales ranking by category feature\nSolution\n\n\nDesign a system that scales to millions of users on AWS\nSolution\n\n\nAdd a system design question\nContribute\n\n\n\nDesign Pastebin.com (or Bit.ly)\nView exercise and solution\n\nDesign the Twitter timeline and search (or Facebook feed and search)\nView exercise and solution\n\nDesign a web crawler\nView exercise and solution\n\nDesign Mint.com\nView exercise and solution\n\nDesign the data structures for a social network\nView exercise and solution\n\nDesign a key-value store for a search engine\nView exercise and solution\n\nDesign Amazon's sales ranking by category feature\nView exercise and solution\n\nDesign a system that scales to millions of users on AWS\nView exercise and solution\n\nObject-oriented design interview questions with solutions\n\nCommon object-oriented design interview questions with sample discussions, code, and diagrams.\nSolutions linked to content in the solutions/ folder.\n\n\nNote: This section is under development\n\n\n\n\nQuestion\n\n\n\n\n\nDesign a hash map\nSolution\n\n\nDesign a least recently used cache\nSolution\n\n\nDesign a call center\nSolution\n\n\nDesign a deck of cards\nSolution\n\n\nDesign a parking lot\nSolution\n\n\nDesign a chat server\nSolution\n\n\nDesign a circular array\nContribute\n\n\nAdd an object-oriented design question\nContribute\n\n\n\nSystem design topics: start here\nNew to system design?\nFirst, you'll need a basic understanding of common principles, learning about what they are, how they are used, and their pros and cons.\nStep 1: Review the scalability video lecture\nScalability Lecture at Harvard\n\nTopics covered:\n\nVertical scaling\nHorizontal scaling\nCaching\nLoad balancing\nDatabase replication\nDatabase partitioning\n\n\n\nStep 2: Review the scalability article\nScalability\n\nTopics covered:\n\nClones\nDatabases\nCaches\nAsynchronism\n\n\n\nNext steps\nNext, we'll look at high-level trade-offs:\n\nPerformance vs scalability\nLatency vs throughput\nAvailability vs consistency\n\nKeep in mind that everything is a trade-off.\nThen we'll dive into more specific topics such as DNS, CDNs, and load balancers.\nPerformance vs scalability\nA service is scalable if it results in increased performance in a manner proportional to resources added. Generally, increasing performance means serving more units of work, but it can also be to handle larger units of work, such as when datasets grow.1\nAnother way to look at performance vs scalability:\n\nIf you have a performance problem, your system is slow for a single user.\nIf you have a scalability problem, your system is fast for a single user but slow under heavy load.\n\nSource(s) and further reading\n\nA word on scalability\nScalability, availability, stability, patterns\n\nLatency vs throughput\nLatency is the time to perform some action or to produce some result.\nThroughput is the number of such actions or results per unit of time.\nGenerally, you should aim for maximal throughput with acceptable latency.\nSource(s) and further reading\n\nUnderstanding latency vs throughput\n\nAvailability vs consistency\nCAP theorem\n\n  \n  \n  Source: CAP theorem revisited\n\nIn a distributed computer system, you can only support two of the following guarantees:\n\nConsistency - Every read receives the most recent write or an error\nAvailability - Every request receives a response, without guarantee that it contains the most recent version of the information\nPartition Tolerance - The system continues to operate despite arbitrary partitioning due to network failures\n\nNetworks aren't reliable, so you'll need to support partition tolerance.  You'll need to make a software tradeoff between consistency and availability.\nCP - consistency and partition tolerance\nWaiting 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.\nAP - availability and partition tolerance\nResponses 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.\nAP is a good choice if the business needs to allow for eventual consistency or when the system needs to continue working despite external errors.\nSource(s) and further reading\n\nCAP theorem revisited\nA plain english introduction to CAP theorem\nCAP FAQ\nThe CAP theorem\n\nConsistency patterns\nWith multiple copies of the same data, we are faced with options on how to synchronize them so clients have a consistent view of the data.  Recall the definition of consistency from the CAP theorem - Every read receives the most recent write or an error.\nWeak consistency\nAfter a write, reads may or may not see it.  A best effort approach is taken.\nThis 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.\nEventual consistency\nAfter a write, reads will eventually see it (typically within milliseconds).  Data is replicated asynchronously.\nThis approach is seen in systems such as DNS and email.  Eventual consistency works well in highly available systems.\nStrong consistency\nAfter a write, reads will see it.  Data is replicated synchronously.\nThis approach is seen in file systems and RDBMSes.  Strong consistency works well in systems that need transactions.\nSource(s) and further reading\n\nTransactions across data centers\n\nAvailability patterns\nThere are two complementary patterns to support high availability: fail-over and replication.\nFail-over\nActive-passive\nWith 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.\nThe 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.\nActive-passive failover can also be referred to as master-slave failover.\nActive-active\nIn active-active, both servers are managing traffic, spreading the load between them.\nIf 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.\nActive-active failover can also be referred to as master-master failover.\nDisadvantage(s): failover\n\nFail-over adds more hardware and additional complexity.\nThere is a potential for loss of data if the active system fails before any newly written data can be replicated to the passive.\n\nReplication\nMaster-slave and master-master\nThis topic is further discussed in the Database section:\n\nMaster-slave replication\nMaster-master replication\n\nAvailability in numbers\nAvailability 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.\n99.9% availability - three 9s\n\n\n\nDuration\nAcceptable downtime\n\n\n\n\nDowntime per year\n8h 45min 57s\n\n\nDowntime per month\n43m 49.7s\n\n\nDowntime per week\n10m 4.8s\n\n\nDowntime per day\n1m 26.4s\n\n\n\n99.99% availability - four 9s\n\n\n\nDuration\nAcceptable downtime\n\n\n\n\nDowntime per year\n52min 35.7s\n\n\nDowntime per month\n4m 23s\n\n\nDowntime per week\n1m 5s\n\n\nDowntime per day\n8.6s\n\n\n\nAvailability in parallel vs in sequence\nIf 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.\nIn sequence\nOverall availability decreases when two components with availability < 100% are in sequence:\nAvailability (Total) = Availability (Foo) * Availability (Bar)\n\nIf both Foo and Bar each had 99.9% availability, their total availability in sequence would be 99.8%.\nIn parallel\nOverall availability increases when two components with availability < 100% are in parallel:\nAvailability (Total) = 1 - (1 - Availability (Foo)) * (1 - Availability (Bar))\n\nIf both Foo and Bar each had 99.9% availability, their total availability in parallel would be 99.9999%.\nDomain name system\n\n  \n  \n  Source: DNS security presentation\n\nA Domain Name System (DNS) translates a domain name such as www.example.com to an IP address.\nDNS is hierarchical, with a few authoritative servers at the top level.  Your router or ISP provides information about which DNS server(s) to contact when doing a lookup.  Lower level DNS servers cache mappings, which could become stale due to DNS propagation delays.  DNS results can also be cached by your browser or OS for a certain period of time, determined by the time to live (TTL).\n\nNS record (name server) - Specifies the DNS servers for your domain/subdomain.\nMX record (mail exchange) - Specifies the mail servers for accepting messages.\nA record (address) - Points a name to an IP address.\nCNAME (canonical) - Points a name to another name or CNAME (example.com to www.example.com) or to an A record.\n\nServices such as CloudFlare and Route 53 provide managed DNS services.  Some DNS services can route traffic through various methods:\n\nWeighted round robin\n\nPrevent traffic from going to servers under maintenance\nBalance between varying cluster sizes\nA/B testing\n\n\nLatency-based\nGeolocation-based\n\nDisadvantage(s): DNS\n\nAccessing a DNS server introduces a slight delay, although mitigated by caching described above.\nDNS server management could be complex and is generally managed by governments, ISPs, and large companies.\nDNS services have recently come under DDoS attack, preventing users from accessing websites such as Twitter without knowing Twitter's IP address(es).\n\nSource(s) and further reading\n\nDNS architecture\nWikipedia\nDNS articles\n\nContent delivery network\n\n  \n  \n  Source: Why use a CDN\n\nA 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.\nServing content from CDNs can significantly improve performance in two ways:\n\nUsers receive content from data centers close to them\nYour servers do not have to serve requests that the CDN fulfills\n\nPush CDNs\nPush 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.\nSites 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.\nPull CDNs\nPull 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.\nA time-to-live (TTL) 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.\nSites with heavy traffic work well with pull CDNs, as traffic is spread out more evenly with only recently-requested content remaining on the CDN.\nDisadvantage(s): CDN\n\nCDN costs could be significant depending on traffic, although this should be weighed with additional costs you would incur not using a CDN.\nContent might be stale if it is updated before the TTL expires it.\nCDNs require changing URLs for static content to point to the CDN.\n\nSource(s) and further reading\n\nGlobally distributed content delivery\nThe differences between push and pull CDNs\nWikipedia\n\nLoad balancer\n\n  \n  \n  Source: Scalable system design patterns\n\nLoad 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:\n\nPreventing requests from going to unhealthy servers\nPreventing overloading resources\nHelping to eliminate a single point of failure\n\nLoad balancers can be implemented with hardware (expensive) or with software such as HAProxy.\nAdditional benefits include:\n\nSSL termination - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations\n\nRemoves the need to install X.509 certificates on each server\n\n\nSession persistence - Issue cookies and route a specific client's requests to same instance if the web apps do not keep track of sessions\n\nTo protect against failures, it's common to set up multiple load balancers, either in active-passive or active-active mode.\nLoad balancers can route traffic based on various metrics, including:\n\nRandom\nLeast loaded\nSession/cookies\nRound robin or weighted round robin\nLayer 4\nLayer 7\n\nLayer 4 load balancing\nLayer 4 load balancers look at info at the transport layer to decide how to distribute requests.  Generally, this involves the source, destination IP addresses, and ports in the header, but not the contents of the packet.  Layer 4 load balancers forward network packets to and from the upstream server, performing Network Address Translation (NAT).\nLayer 7 load balancing\nLayer 7 load balancers look at the application layer 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.\nAt 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.\nHorizontal scaling\nLoad balancers can also help with horizontal scaling, improving performance and availability.  Scaling out using commodity machines is more cost efficient and results in higher availability than scaling up a single server on more expensive hardware, called Vertical Scaling.  It is also easier to hire for talent working on commodity hardware than it is for specialized enterprise systems.\nDisadvantage(s): horizontal scaling\n\nScaling horizontally introduces complexity and involves cloning servers\n\nServers should be stateless: they should not contain any user-related data like sessions or profile pictures\nSessions can be stored in a centralized data store such as a database (SQL, NoSQL) or a persistent cache (Redis, Memcached)\n\n\nDownstream servers such as caches and databases need to handle more simultaneous connections as upstream servers scale out\n\nDisadvantage(s): load balancer\n\nThe load balancer can become a performance bottleneck if it does not have enough resources or if it is not configured properly.\nIntroducing a load balancer to help eliminate a single point of failure results in increased complexity.\nA single load balancer is a single point of failure, configuring multiple load balancers further increases complexity.\n\nSource(s) and further reading\n\nNGINX architecture\nHAProxy architecture guide\nScalability\nWikipedia\nLayer 4 load balancing\nLayer 7 load balancing\nELB listener config\n\nReverse proxy (web server)\n\n  \n  \n  Source: Wikipedia\n  \n\nA 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.\nAdditional benefits include:\n\nIncreased security - Hide information about backend servers, blacklist IPs, limit number of connections per client\nIncreased scalability and flexibility - Clients only see the reverse proxy's IP, allowing you to scale servers or change their configuration\nSSL termination - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations\n\nRemoves the need to install X.509 certificates on each server\n\n\nCompression - Compress server responses\nCaching - Return the response for cached requests\nStatic content - Serve static content directly\n\nHTML/CSS/JS\nPhotos\nVideos\nEtc\n\n\n\nLoad balancer vs reverse proxy\n\nDeploying a load balancer is useful when you have multiple servers.  Often, load balancers  route traffic to a set of servers serving the same function.\nReverse proxies can be useful even with just one web server or application server, opening up the benefits described in the previous section.\nSolutions such as NGINX and HAProxy can support both layer 7 reverse proxying and load balancing.\n\nDisadvantage(s): reverse proxy\n\nIntroducing a reverse proxy results in increased complexity.\nA single reverse proxy is a single point of failure, configuring multiple reverse proxies (ie a failover) further increases complexity.\n\nSource(s) and further reading\n\nReverse proxy vs load balancer\nNGINX architecture\nHAProxy architecture guide\nWikipedia\n\nApplication layer\n\n  \n  \n  Source: Intro to architecting systems for scale\n\nSeparating 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 single responsibility principle advocates for small and autonomous services that work together.  Small teams with small services can plan more aggressively for rapid growth.\nWorkers in the application layer also help enable asynchronism.\nMicroservices\nRelated to this discussion are microservices, 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. 1\nPinterest, for example, could have the following microservices: user profile, follower, feed, search, photo upload, etc.\nService Discovery\nSystems such as Consul, Etcd, and Zookeeper can help services find each other by keeping track of registered names, addresses, and ports.  Health checks help verify service integrity and are often done using an HTTP endpoint.  Both Consul and Etcd have a built in key-value store that can be useful for storing config values and other shared data.\nDisadvantage(s): application layer\n\nAdding an application layer with loosely coupled services requires a different approach from an architectural, operations, and process viewpoint (vs a monolithic system).\nMicroservices can add complexity in terms of deployments and operations.\n\nSource(s) and further reading\n\nIntro to architecting systems for scale\nCrack the system design interview\nService oriented architecture\nIntroduction to Zookeeper\nHere's what you need to know about building microservices\n\nDatabase\n\n  \n  \n  Source: Scaling up to your first 10 million users\n\nRelational database management system (RDBMS)\nA relational database like SQL is a collection of data items organized in tables.\nACID is a set of properties of relational database transactions.\n\nAtomicity - Each transaction is all or nothing\nConsistency - Any transaction will bring the database from one valid state to another\nIsolation - Executing transactions concurrently has the same results as if the transactions were executed serially\nDurability - Once a transaction has been committed, it will remain so\n\nThere are many techniques to scale a relational database: master-slave replication, master-master replication, federation, sharding, denormalization, and SQL tuning.\nMaster-slave replication\nThe 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.\n\n  \n  \n  Source: Scalability, availability, stability, patterns\n\nDisadvantage(s): master-slave replication\n\nAdditional logic is needed to promote a slave to a master.\nSee Disadvantage(s): replication for points related to both master-slave and master-master.\n\nMaster-master replication\nBoth 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.\n\n  \n  \n  Source: Scalability, availability, stability, patterns\n\nDisadvantage(s): master-master replication\n\nYou'll need a load balancer or you'll need to make changes to your application logic to determine where to write.\nMost master-master systems are either loosely consistent (violating ACID) or have increased write latency due to synchronization.\nConflict resolution comes more into play as more write nodes are added and as latency increases.\nSee Disadvantage(s): replication for points related to both master-slave and master-master.\n\nDisadvantage(s): replication\n\nThere is a potential for loss of data if the master fails before any newly written data can be replicated to other nodes.\nWrites 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.\nThe more read slaves, the more you have to replicate, which leads to greater replication lag.\nOn 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.\nReplication adds more hardware and additional complexity.\n\nSource(s) and further reading: replication\n\nScalability, availability, stability, patterns\nMulti-master replication\n\nFederation\n\n  \n  \n  Source: Scaling up to your first 10 million users\n\nFederation (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.\nDisadvantage(s): federation\n\nFederation is not effective if your schema requires huge functions or tables.\nYou'll need to update your application logic to determine which database to read and write.\nJoining data from two databases is more complex with a server link.\nFederation adds more hardware and additional complexity.\n\nSource(s) and further reading: federation\n\nScaling up to your first 10 million users\n\nSharding\n\n  \n  \n  Source: Scalability, availability, stability, patterns\n\nSharding 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.\nSimilar 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.\nCommon ways to shard a table of users is either through the user's last name initial or the user's geographic location.\nDisadvantage(s): sharding\n\nYou'll need to update your application logic to work with shards, which could result in complex SQL queries.\nData 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.\n\nRebalancing adds additional complexity.  A sharding function based on consistent hashing can reduce the amount of transferred data.\n\n\nJoining data from multiple shards is more complex.\nSharding adds more hardware and additional complexity.\n\nSource(s) and further reading: sharding\n\nThe coming of the shard\nShard database architecture\nConsistent hashing\n\nDenormalization\nDenormalization 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.\nOnce 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.\nIn 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.\nDisadvantage(s): denormalization\n\nData is duplicated.\nConstraints can help redundant copies of information stay in sync, which increases complexity of the database design.\nA denormalized database under heavy write load might perform worse than its normalized counterpart.\n\nSource(s) and further reading: denormalization\n\nDenormalization\n\nSQL tuning\nSQL tuning is a broad topic and many books have been written as reference.\nIt's important to benchmark and profile to simulate and uncover bottlenecks.\n\nBenchmark - Simulate high-load situations with tools such as ab.\nProfile - Enable tools such as the slow query log to help track performance issues.\n\nBenchmarking and profiling might point you to the following optimizations.\nTighten up the schema\n\nMySQL dumps to disk in contiguous blocks for fast access.\nUse CHAR instead of VARCHAR for fixed-length fields.\n\nCHAR effectively allows for fast, random access, whereas with VARCHAR, you must find the end of a string before moving onto the next one.\n\n\nUse TEXT for large blocks of text such as blog posts.  TEXT also allows for boolean searches.  Using a TEXT field results in storing a pointer on disk that is used to locate the text block.\nUse INT for larger numbers up to 2^32 or 4 billion.\nUse DECIMAL for currency to avoid floating point representation errors.\nAvoid storing large BLOBS, store the location of where to get the object instead.\nVARCHAR(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.\nSet the NOT NULL constraint where applicable to improve search performance.\n\nUse good indices\n\nColumns that you are querying (SELECT, GROUP BY, ORDER BY, JOIN) could be faster with indices.\nIndices are usually represented as self-balancing B-tree that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time.\nPlacing an index can keep the data in memory, requiring more space.\nWrites could also be slower since the index also needs to be updated.\nWhen loading large amounts of data, it might be faster to disable indices, load the data, then rebuild the indices.\n\nAvoid expensive joins\n\nDenormalize where performance demands it.\n\nPartition tables\n\nBreak up a table by putting hot spots in a separate table to help keep it in memory.\n\nTune the query cache\n\nIn some cases, the query cache could lead to performance issues.\n\nSource(s) and further reading: SQL tuning\n\nTips for optimizing MySQL queries\nIs there a good reason i see VARCHAR(255) used so often?\nHow do null values affect performance?\nSlow query log\n\nNoSQL\nNoSQL 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.\nBASE is often used to describe the properties of NoSQL databases.  In comparison with the CAP Theorem, BASE chooses availability over consistency.\n\nBasically available - the system guarantees availability.\nSoft state - the state of the system may change over time, even without input.\nEventual consistency - the system will become consistent over a period of time, given that the system doesn't receive input during that period.\n\nIn 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.\nKey-value store\n\nAbstraction: hash table\n\nA 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.\nKey-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.\nA key-value store is the basis for more complex systems such as a document store, and in some cases, a graph database.\nSource(s) and further reading: key-value store\n\nKey-value database\nDisadvantages of key-value stores\nRedis architecture\nMemcached architecture\n\nDocument store\n\nAbstraction: key-value store with documents stored as values\n\nA 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.\nBased on the underlying implementation, documents are organized by collections, tags, metadata, or directories.  Although documents can be organized or grouped together, documents may have fields that are completely different from each other.\nSome document stores like MongoDB and CouchDB also provide a SQL-like language to perform complex queries.  DynamoDB supports both key-values and documents.\nDocument stores provide high flexibility and are often used for working with occasionally changing data.\nSource(s) and further reading: document store\n\nDocument-oriented database\nMongoDB architecture\nCouchDB architecture\nElasticsearch architecture\n\nWide column store\n\n  \n  \n  Source: SQL & NoSQL, a brief history\n\n\nAbstraction: nested map ColumnFamily<RowKey, Columns<ColKey, Value, Timestamp>>\n\nA 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.\nGoogle 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.\nWide column stores offer high availability and high scalability.  They are often used for very large data sets.\nSource(s) and further reading: wide column store\n\nSQL & NoSQL, a brief history\nBigtable architecture\nHBase architecture\nCassandra architecture\n\nGraph database\n\n  \n  \n  Source: Graph database\n\n\nAbstraction: graph\n\nIn 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.\nGraphs 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.\nSource(s) and further reading: graph\n\nGraph database\nNeo4j\nFlockDB\n\nSource(s) and further reading: NoSQL\n\nExplanation of base terminology\nNoSQL databases a survey and decision guidance\nScalability\nIntroduction to NoSQL\nNoSQL patterns\n\nSQL or NoSQL\n\n  \n  \n  Source: Transitioning from RDBMS to NoSQL\n\nReasons for SQL:\n\nStructured data\nStrict schema\nRelational data\nNeed for complex joins\nTransactions\nClear patterns for scaling\nMore established: developers, community, code, tools, etc\nLookups by index are very fast\n\nReasons for NoSQL:\n\nSemi-structured data\nDynamic or flexible schema\nNon-relational data\nNo need for complex joins\nStore many TB (or PB) of data\nVery data intensive workload\nVery high throughput for IOPS\n\nSample data well-suited for NoSQL:\n\nRapid ingest of clickstream and log data\nLeaderboard or scoring data\nTemporary data, such as a shopping cart\nFrequently accessed ('hot') tables\nMetadata/lookup tables\n\nSource(s) and further reading: SQL or NoSQL\n\nScaling up to your first 10 million users\nSQL vs NoSQL differences\n\nCache\n\n  \n  \n  Source: Scalable system design patterns\n\nCaching 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.\nDatabases 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.\nClient caching\nCaches can be located on the client side (OS or browser), server side, or in a distinct cache layer.\nCDN caching\nCDNs are considered a type of cache.\nWeb server caching\nReverse 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.\nDatabase caching\nYour 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.\nApplication caching\nIn-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.\nRedis has the following additional features:\n\nPersistence option\nBuilt-in data structures such as sorted sets and lists\n\nThere are multiple levels you can cache that fall into two general categories: database queries and objects:\n\nRow level\nQuery-level\nFully-formed serializable objects\nFully-rendered HTML\n\nGenerally, you should try to avoid file-based caching, as it makes cloning and auto-scaling more difficult.\nCaching at the database query level\nWhenever you query the database, hash the query as a key and store the result to the cache.  This approach suffers from expiration issues:\n\nHard to delete a cached result with complex queries\nIf one piece of data changes such as a table cell, you need to delete all cached queries that might include the changed cell\n\nCaching at the object level\nSee 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):\n\nRemove the object from cache if its underlying data has changed\nAllows for asynchronous processing: workers assemble objects by consuming the latest cached object\n\nSuggestions of what to cache:\n\nUser sessions\nFully rendered web pages\nActivity streams\nUser graph data\n\nWhen to update the cache\nSince 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.\nCache-aside\n\n  \n  \n  Source: From cache to in-memory data grid\n\nThe application is responsible for reading and writing from storage.  The cache does not interact with storage directly.  The application does the following:\n\nLook for entry in cache, resulting in a cache miss\nLoad entry from the database\nAdd entry to cache\nReturn entry\n\ndef get_user(self, user_id):\n    user = cache.get(\"user.{0}\", user_id)\n    if user is None:\n        user = db.query(\"SELECT * FROM users WHERE user_id = {0}\", user_id)\n        if user is not None:\n            key = \"user.{0}\".format(user_id)\n            cache.set(key, json.dumps(user))\n    return user\nMemcached is generally used in this manner.\nSubsequent 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.\nDisadvantage(s): cache-aside\n\nEach cache miss results in three trips, which can cause a noticeable delay.\nData 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.\nWhen a node fails, it is replaced by a new, empty node, increasing latency.\n\nWrite-through\n\n  \n  \n  Source: Scalability, availability, stability, patterns\n\nThe 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:\n\nApplication adds/updates entry in cache\nCache synchronously writes entry to data store\nReturn\n\nApplication code:\nset_user(12345, {\"foo\":\"bar\"})\nCache code:\ndef set_user(user_id, values):\n    user = db.query(\"UPDATE Users WHERE id = {0}\", user_id, values)\n    cache.set(user_id, user)\nWrite-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.\nDisadvantage(s): write through\n\nWhen 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.\nMost data written might never be read, which can be minimized with a TTL.\n\nWrite-behind (write-back)\n\n  \n  \n  Source: Scalability, availability, stability, patterns\n\nIn write-behind, the application does the following:\n\nAdd/update entry in cache\nAsynchronously write entry to the data store, improving write performance\n\nDisadvantage(s): write-behind\n\nThere could be data loss if the cache goes down prior to its contents hitting the data store.\nIt is more complex to implement write-behind than it is to implement cache-aside or write-through.\n\nRefresh-ahead\n\n  \n  \n  Source: From cache to in-memory data grid\n\nYou can configure the cache to automatically refresh any recently accessed cache entry prior to its expiration.\nRefresh-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.\nDisadvantage(s): refresh-ahead\n\nNot accurately predicting which items are likely to be needed in the future can result in reduced performance than without refresh-ahead.\n\nDisadvantage(s): cache\n\nNeed to maintain consistency between caches and the source of truth such as the database through cache invalidation.\nCache invalidation is a difficult problem, there is additional complexity associated with when to update the cache.\nNeed to make application changes such as adding Redis or memcached.\n\nSource(s) and further reading\n\nFrom cache to in-memory data grid\nScalable system design patterns\nIntroduction to architecting systems for scale\nScalability, availability, stability, patterns\nScalability\nAWS ElastiCache strategies\nWikipedia\n\nAsynchronism\n\n  \n  \n  Source: Intro to architecting systems for scale\n\nAsynchronous 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.\nMessage queues\nMessage 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:\n\nAn application publishes a job to the queue, then notifies the user of job status\nA worker picks up the job from the queue, processes it, then signals the job is complete\n\nThe 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.\nRedis is useful as a simple message broker but messages can be lost.\nRabbitMQ is popular but requires you to adapt to the 'AMQP' protocol and manage your own nodes.\nAmazon SQS is hosted but can have high latency and has the possibility of messages being delivered twice.\nTask queues\nTasks 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.\nCelery has support for scheduling and primarily has python support.\nBack pressure\nIf 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.\nDisadvantage(s): asynchronism\n\nUse cases such as inexpensive calculations and realtime workflows might be better suited for synchronous operations, as introducing queues can add delays and complexity.\n\nSource(s) and further reading\n\nIt's all a numbers game\nApplying back pressure when overloaded\nLittle's law\nWhat is the difference between a message queue and a task queue?\n\nCommunication\n\n  \n  \n  Source: OSI 7 layer model\n\nHypertext transfer protocol (HTTP)\nHTTP 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.\nA basic HTTP request consists of a verb (method) and a resource (endpoint).  Below are common HTTP verbs:\n\n\n\nVerb\nDescription\nIdempotent*\nSafe\nCacheable\n\n\n\n\nGET\nReads a resource\nYes\nYes\nYes\n\n\nPOST\nCreates a resource or trigger a process that handles data\nNo\nNo\nYes if response contains freshness info\n\n\nPUT\nCreates or replace a resource\nYes\nNo\nNo\n\n\nPATCH\nPartially updates a resource\nNo\nNo\nYes if response contains freshness info\n\n\nDELETE\nDeletes a resource\nYes\nNo\nNo\n\n\n\n*Can be called many times without different outcomes.\nHTTP is an application layer protocol relying on lower-level protocols such as TCP and UDP.\nSource(s) and further reading: HTTP\n\nWhat is HTTP?\nDifference between HTTP and TCP\nDifference between PUT and PATCH\n\nTransmission control protocol (TCP)\n\n  \n  \n  Source: How to make a multiplayer game\n\nTCP 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:\n\nSequence numbers and checksum fields for each packet\nAcknowledgement packets and automatic retransmission\n\nIf 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.\nTo 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.\nTCP is useful for applications that require high reliability but are less time critical.  Some examples include web servers, database info, SMTP, FTP, and SSH.\nUse TCP over UDP when:\n\nYou need all of the data to arrive intact\nYou want to automatically make a best estimate use of the network throughput\n\nUser datagram protocol (UDP)\n\n  \n  \n  Source: How to make a multiplayer game\n\nUDP 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.\nUDP 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.\nUDP is less reliable but works well in real time use cases such as VoIP, video chat, streaming, and realtime multiplayer games.\nUse UDP over TCP when:\n\nYou need the lowest latency\nLate data is worse than loss of data\nYou want to implement your own error correction\n\nSource(s) and further reading: TCP and UDP\n\nNetworking for game programming\nKey differences between TCP and UDP protocols\nDifference between TCP and UDP\nTransmission control protocol\nUser datagram protocol\nScaling memcache at Facebook\n\nRemote procedure call (RPC)\n\n  \n  \n  Source: Crack the system design interview\n\nIn 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.\nRPC is a request-response protocol:\n\nClient program - Calls the client stub procedure.  The parameters are pushed onto the stack like a local procedure call.\nClient stub procedure - Marshals (packs) procedure id and arguments into a request message.\nClient communication module - OS sends the message from the client to the server.\nServer communication module - OS passes the incoming packets to the server stub procedure.\nServer stub procedure -  Unmarshalls the results, calls the server procedure matching the procedure id and passes the given arguments.\nThe server response repeats the steps above in reverse order.\n\nSample RPC calls:\nGET /someoperation?data=anId\n\nPOST /anotheroperation\n{\n  \"data\":\"anId\";\n  \"anotherdata\": \"another value\"\n}\n\nRPC 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.\nChoose a native library (aka SDK) when:\n\nYou know your target platform.\nYou want to control how your \"logic\" is accessed.\nYou want to control how error control happens off your library.\nPerformance and end user experience is your primary concern.\n\nHTTP APIs following REST tend to be used more often for public APIs.\nDisadvantage(s): RPC\n\nRPC clients become tightly coupled to the service implementation.\nA new API must be defined for every new operation or use case.\nIt can be difficult to debug RPC.\nYou 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.\n\nRepresentational state transfer (REST)\nREST 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.\nThere are four qualities of a RESTful interface:\n\nIdentify resources (URI in HTTP) - use the same URI regardless of any operation.\nChange with representations (Verbs in HTTP) - use verbs, headers, and body.\nSelf-descriptive error message (status response in HTTP) - Use status codes, don't reinvent the wheel.\nHATEOAS (HTML interface for HTTP) - your web service should be fully accessible in a browser.\n\nSample REST calls:\nGET /someresources/anId\n\nPUT /someresources/anId\n{\"anotherdata\": \"another value\"}\n\nREST 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.\nDisadvantage(s): REST\n\nWith 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.\nREST 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.\nFetching 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.\nOver 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.\n\nRPC and REST calls comparison\n\n\n\nOperation\nRPC\nREST\n\n\n\n\nSignup\nPOST /signup\nPOST /persons\n\n\nResign\nPOST /resign{\"personid\": \"1234\"}\nDELETE /persons/1234\n\n\nRead a person\nGET /readPerson?personid=1234\nGET /persons/1234\n\n\nRead a person\u2019s items list\nGET /readUsersItemsList?personid=1234\nGET /persons/1234/items\n\n\nAdd an item to a person\u2019s items\nPOST /addItemToUsersItemsList{\"personid\": \"1234\";\"itemid\": \"456\"}\nPOST /persons/1234/items{\"itemid\": \"456\"}\n\n\nUpdate an item\nPOST /modifyItem{\"itemid\": \"456\";\"key\": \"value\"}\nPUT /items/456{\"key\": \"value\"}\n\n\nDelete an item\nPOST /removeItem{\"itemid\": \"456\"}\nDELETE /items/456\n\n\n\n\n  Source: Do you really know why you prefer REST over RPC\n\nSource(s) and further reading: REST and RPC\n\nDo you really know why you prefer REST over RPC\nWhen are RPC-ish approaches more appropriate than REST?\nREST vs JSON-RPC\nDebunking the myths of RPC and REST\nWhat are the drawbacks of using REST\nCrack the system design interview\nThrift\nWhy REST for internal use and not RPC\n\nSecurity\nThis section could use some updates.  Consider contributing!\nSecurity 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:\n\nEncrypt in transit and at rest.\nSanitize all user inputs or any input parameters exposed to user to prevent XSS and SQL injection.\nUse parameterized queries to prevent SQL injection.\nUse the principle of least privilege.\n\nSource(s) and further reading\n\nAPI security checklist\nSecurity guide for developers\nOWASP top ten\n\nAppendix\nYou'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.\nPowers of two table\nPower           Exact Value         Approx Value        Bytes\n---------------------------------------------------------------\n7                             128\n8                             256\n10                           1024   1 thousand           1 KB\n16                         65,536                       64 KB\n20                      1,048,576   1 million            1 MB\n30                  1,073,741,824   1 billion            1 GB\n32                  4,294,967,296                        4 GB\n40              1,099,511,627,776   1 trillion           1 TB\n\nSource(s) and further reading\n\nPowers of two\n\nLatency numbers every programmer should know\nLatency Comparison Numbers\n--------------------------\nL1 cache reference                           0.5 ns\nBranch mispredict                            5   ns\nL2 cache reference                           7   ns                      14x L1 cache\nMutex lock/unlock                           25   ns\nMain memory reference                      100   ns                      20x L2 cache, 200x L1 cache\nCompress 1K bytes with Zippy            10,000   ns       10 us\nSend 1 KB bytes over 1 Gbps network     10,000   ns       10 us\nRead 4 KB randomly from SSD*           150,000   ns      150 us          ~1GB/sec SSD\nRead 1 MB sequentially from memory     250,000   ns      250 us\nRound trip within same datacenter      500,000   ns      500 us\nRead 1 MB sequentially from SSD*     1,000,000   ns    1,000 us    1 ms  ~1GB/sec SSD, 4X memory\nHDD seek                            10,000,000   ns   10,000 us   10 ms  20x datacenter roundtrip\nRead 1 MB sequentially from 1 Gbps  10,000,000   ns   10,000 us   10 ms  40x memory, 10X SSD\nRead 1 MB sequentially from HDD     30,000,000   ns   30,000 us   30 ms 120x memory, 30X SSD\nSend packet CA->Netherlands->CA    150,000,000   ns  150,000 us  150 ms\n\nNotes\n-----\n1 ns = 10^-9 seconds\n1 us = 10^-6 seconds = 1,000 ns\n1 ms = 10^-3 seconds = 1,000 us = 1,000,000 ns\n\nHandy metrics based on numbers above:\n\nRead sequentially from HDD at 30 MB/s\nRead sequentially from 1 Gbps Ethernet at 100 MB/s\nRead sequentially from SSD at 1 GB/s\nRead sequentially from main memory at 4 GB/s\n6-7 world-wide round trips per second\n2,000 round trips per second within a data center\n\nLatency numbers visualized\n\nSource(s) and further reading\n\nLatency numbers every programmer should know - 1\nLatency numbers every programmer should know - 2\nDesigns, lessons, and advice from building large distributed systems\nSoftware Engineering Advice from Building Large-Scale Distributed Systems\n\nAdditional system design interview questions\n\nCommon system design interview questions, with links to resources on how to solve each.\n\n\n\n\nQuestion\nReference(s)\n\n\n\n\nDesign a file sync service like Dropbox\nyoutube.com\n\n\nDesign a search engine like Google\nqueue.acm.orgstackexchange.comardendertat.comstanford.edu\n\n\nDesign a scalable web crawler like Google\nquora.com\n\n\nDesign Google docs\ncode.google.comneil.fraser.name\n\n\nDesign a key-value store like Redis\nslideshare.net\n\n\nDesign a cache system like Memcached\nslideshare.net\n\n\nDesign a recommendation system like Amazon's\nhulu.comijcai13.org\n\n\nDesign a tinyurl system like Bitly\nn00tc0d3r.blogspot.com\n\n\nDesign a chat app like WhatsApp\nhighscalability.com\n\n\nDesign a picture sharing system like Instagram\nhighscalability.comhighscalability.com\n\n\nDesign the Facebook news feed function\nquora.comquora.comslideshare.net\n\n\nDesign the Facebook timeline function\nfacebook.comhighscalability.com\n\n\nDesign the Facebook chat function\nerlang-factory.comfacebook.com\n\n\nDesign a graph search function like Facebook's\nfacebook.comfacebook.comfacebook.com\n\n\nDesign a content delivery network like CloudFlare\nfigshare.com\n\n\nDesign a trending topic system like Twitter's\nmichael-noll.comsnikolov .wordpress.com\n\n\nDesign a random ID generation system\nblog.twitter.comgithub.com\n\n\nReturn the top k requests during a time interval\ncs.ucsb.eduwpi.edu\n\n\nDesign a system that serves data from multiple data centers\nhighscalability.com\n\n\nDesign an online multiplayer card game\nindieflashblog.combuildnewgames.com\n\n\nDesign a garbage collection system\nstuffwithstuff.comwashington.edu\n\n\nDesign an API rate limiter\nhttps://stripe.com/blog/\n\n\nDesign a Stock Exchange (like NASDAQ or Binance)\nJane StreetGolang ImplementationGo Implementation\n\n\nAdd a system design question\nContribute\n\n\n\nReal world architectures\n\nArticles on how real world systems are designed.\n\n\n  \n  \n  Source: Twitter timelines at scale\n\nDon't focus on nitty gritty details for the following articles, instead:\n\nIdentify shared principles, common technologies, and patterns within these articles\nStudy what problems are solved by each component, where it works, where it doesn't\nReview the lessons learned\n\n\n\n\nType\nSystem\nReference(s)\n\n\n\n\nData processing\nMapReduce - Distributed data processing from Google\nresearch.google.com\n\n\nData processing\nSpark - Distributed data processing from Databricks\nslideshare.net\n\n\nData processing\nStorm - Distributed data processing from Twitter\nslideshare.net\n\n\n\n\n\n\n\nData store\nBigtable - Distributed column-oriented database from Google\nharvard.edu\n\n\nData store\nHBase - Open source implementation of Bigtable\nslideshare.net\n\n\nData store\nCassandra - Distributed column-oriented database from Facebook\nslideshare.net\n\n\nData store\nDynamoDB - Document-oriented database from Amazon\nharvard.edu\n\n\nData store\nMongoDB - Document-oriented database\nslideshare.net\n\n\nData store\nSpanner - Globally-distributed database from Google\nresearch.google.com\n\n\nData store\nMemcached - Distributed memory caching system\nslideshare.net\n\n\nData store\nRedis - Distributed memory caching system with persistence and value types\nslideshare.net\n\n\n\n\n\n\n\nFile system\nGoogle File System (GFS) - Distributed file system\nresearch.google.com\n\n\nFile system\nHadoop File System (HDFS) - Open source implementation of GFS\napache.org\n\n\n\n\n\n\n\nMisc\nChubby - Lock service for loosely-coupled distributed systems from Google\nresearch.google.com\n\n\nMisc\nDapper - Distributed systems tracing infrastructure\nresearch.google.com\n\n\nMisc\nKafka - Pub/sub message queue from LinkedIn\nslideshare.net\n\n\nMisc\nZookeeper - Centralized infrastructure and services enabling synchronization\nslideshare.net\n\n\n\nAdd an architecture\nContribute\n\n\n\nCompany architectures\n\n\n\nCompany\nReference(s)\n\n\n\n\nAmazon\nAmazon architecture\n\n\nCinchcast\nProducing 1,500 hours of audio every day\n\n\nDataSift\nRealtime datamining At 120,000 tweets per second\n\n\nDropbox\nHow we've scaled Dropbox\n\n\nESPN\nOperating At 100,000 duh nuh nuhs per second\n\n\nGoogle\nGoogle architecture\n\n\nInstagram\n14 million users, terabytes of photosWhat powers Instagram\n\n\nJustin.tv\nJustin.Tv's live video broadcasting architecture\n\n\nFacebook\nScaling memcached at FacebookTAO: Facebook\u2019s distributed data store for the social graphFacebook\u2019s photo storageHow Facebook Live Streams To 800,000 Simultaneous Viewers\n\n\nFlickr\nFlickr architecture\n\n\nMailbox\nFrom 0 to one million users in 6 weeks\n\n\nNetflix\nA 360 Degree View Of The Entire Netflix StackNetflix: What Happens When You Press Play?\n\n\nPinterest\nFrom 0 To 10s of billions of page views a month18 million visitors, 10x growth, 12 employees\n\n\nPlayfish\n50 million monthly users and growing\n\n\nPlentyOfFish\nPlentyOfFish architecture\n\n\nSalesforce\nHow they handle 1.3 billion transactions a day\n\n\nStack Overflow\nStack Overflow architecture\n\n\nTripAdvisor\n40M visitors, 200M dynamic page views, 30TB data\n\n\nTumblr\n15 billion page views a month\n\n\nTwitter\nMaking Twitter 10000 percent fasterStoring 250 million tweets a day using MySQL150M active users, 300K QPS, a 22 MB/S firehoseTimelines at scaleBig and small data at TwitterOperations at Twitter: scaling beyond 100 million usersHow Twitter Handles 3,000 Images Per Second\n\n\nUber\nHow Uber scales their real-time market platformLessons Learned From Scaling Uber To 2000 Engineers, 1000 Services, And 8000 Git Repositories\n\n\nWhatsApp\nThe WhatsApp architecture Facebook bought for $19 billion\n\n\nYouTube\nYouTube scalabilityYouTube architecture\n\n\n\nCompany engineering blogs\n\nArchitectures for companies you are interviewing with.\nQuestions you encounter might be from the same domain.\n\n\nAirbnb Engineering\nAtlassian Developers\nAWS Blog\nBitly Engineering Blog\nBox Blogs\nCloudera Developer Blog\nDropbox Tech Blog\nEngineering at Quora\nEbay Tech Blog\nEvernote Tech Blog\nEtsy Code as Craft\nFacebook Engineering\nFlickr Code\nFoursquare Engineering Blog\nGitHub Engineering Blog\nGoogle Research Blog\nGroupon Engineering Blog\nHeroku Engineering Blog\nHubspot Engineering Blog\nHigh Scalability\nInstagram Engineering\nIntel Software Blog\nJane Street Tech Blog\nLinkedIn Engineering\nMicrosoft Engineering\nMicrosoft Python Engineering\nNetflix Tech Blog\nPaypal Developer Blog\nPinterest Engineering Blog\nReddit Blog\nSalesforce Engineering Blog\nSlack Engineering Blog\nSpotify Labs\nStripe Engineering Blog\nTwilio Engineering Blog\nTwitter Engineering\nUber Engineering Blog\nYahoo Engineering Blog\nYelp Engineering Blog\nZynga Engineering Blog\n\nSource(s) and further reading\nLooking to add a blog?  To avoid duplicating work, consider adding your company blog to the following repo:\n\nkilimchoi/engineering-blogs\n\nUnder development\nInterested in adding a section or helping complete one in-progress?  Contribute!\n\nDistributed computing with MapReduce\nConsistent hashing\nScatter gather\nContribute\n\nCredits\nCredits and sources are provided throughout this repo.\nSpecial thanks to:\n\nHired in tech\nCracking the coding interview\nHigh scalability\ncheckcheckzz/system-design-interview\nshashank88/system_design\nmmcgrana/services-engineering\nSystem design cheat sheet\nA distributed systems reading list\nCracking the system design interview\n\nContact info\nFeel free to contact me to discuss any issues, questions, or comments.\nMy contact info can be found on my GitHub page.\nLicense\nI 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).\nCopyright 2017 Donne Martin\n\nCreative Commons Attribution 4.0 International License (CC BY 4.0)\n\nhttp://creativecommons.org/licenses/by/4.0/"
                ],
                "output": "readability/",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:38:21.235821+00:00",
                "status": "succeeded"
            }
        ],
        "screenshot": [],
        "singlefile": [],
        "title": [
            {
                "cmd": [
                    "/usr/bin/curl",
                    "--silent",
                    "--location",
                    "--compressed",
                    "--proxy",
                    "socks5://tor-socks-proxy:9150",
                    "--max-time",
                    "60",
                    "--user-agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 ArchiveBox/{VERSION} (+https://github.com/ArchiveBox/ArchiveBox/)",
                    "https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
                ],
                "cmd_version": "8.10.1",
                "end_ts": "2025-01-04T18:38:21.001073+00:00",
                "index_texts": null,
                "output": "GitHub - donnemartin/system-design-primer: Learn how to design large-scale systems. Prep for the system design interview.  Includes Anki flashcards.",
                "pwd": "/data/archive/1736015745.591257",
                "schema": "ArchiveResult",
                "start_ts": "2025-01-04T18:38:20.692047+00:00",
                "status": "succeeded"
            }
        ],
        "wget": []
    },
    "icons": null,
    "is_archived": true,
    "is_static": false,
    "latest": {
        "archive_org": "ArchiveError: Failed to find \"content-location\" URL header in Archive.org response.",
        "dom": "output.html",
        "favicon": "favicon.ico",
        "git": null,
        "media": "media/",
        "pdf": null,
        "screenshot": null,
        "singlefile": null,
        "title": "GitHub - donnemartin/system-design-primer: Learn how to design large-scale systems. Prep for the system design interview.  Includes Anki flashcards.",
        "warc": null,
        "wget": null
    },
    "link_dir": "/data/archive/1736015745.591257",
    "newest_archive_date": "2025-01-04T18:39:07.241481+00:00",
    "num_failures": 1,
    "num_outputs": 8,
    "oldest_archive_date": "2025-01-04T18:37:55.102609+00:00",
    "path": "/donnemartin/system-design-primer",
    "schema": "Link",
    "scheme": "https",
    "snapshot_abid": "snp_01JGS9M5161039DB3201CJKVZG",
    "snapshot_id": "e4958c2e-c680-4ce5-b8e1-c1935929eff0",
    "sources": [
        "/data/sources/1736015744-import.txt"
    ],
    "tags": null,
    "tags_str": "",
    "timestamp": "1736015745.591257",
    "title": "GitHub - donnemartin/system-design-primer: Learn how to design large-scale systems. Prep for the system design interview.  Includes Anki flashcards.",
    "url": "https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#system-design-topics-start-here"
}