[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-244":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":25,"hasPages":23,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":40,"readmeContent":41,"aiSummary":42,"trendingCount":16,"starSnapshotCount":16,"syncStatus":43,"lastSyncTime":44,"discoverSource":45},244,"system-design-primer","donnemartin\u002Fsystem-design-primer","donnemartin","Learn how to design large-scale systems. Prep for the system design interview.  Includes Anki flashcards.","",null,"Python",351980,56607,6855,251,0,100,972,4640,572,120,"Other",false,"master",true,[27,28,29,30,31,32,33,34,35,36,37,38,39],"design","design-patterns","design-system","development","interview","interview-practice","interview-questions","programming","python","system","web","web-application","webapp","2026-06-07 04:00:14","*[English](README.md) ∙ [日本語](README-ja.md) ∙ [简体中文](README-zh-Hans.md) ∙ [繁體中文](README-zh-TW.md) | [العَرَبِيَّة‎](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F170) ∙ [বাংলা](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F220) ∙ [Português do Brasil](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F40) ∙ [Deutsch](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F186) ∙ [ελληνικά](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F130) ∙ [עברית](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F272) ∙ [Italiano](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F104) ∙ [한국어](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F102) ∙ [فارسی](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F110) ∙ [Polski](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F68) ∙ [русский язык](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F87) ∙ [Español](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F136) ∙ [ภาษาไทย](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F187) ∙ [Türkçe](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F39) ∙ [tiếng Việt](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F127) ∙ [Français](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F250) | [Add Translation](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F28)*\n\n**Help [translate](TRANSLATIONS.md) this guide!**\n\n# The System Design Primer\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002Fjj3A5N8.png\">\n  \u003Cbr\u002F>\n\u003C\u002Fp>\n\n## Motivation\n\n> Learn how to design large-scale systems.\n>\n> Prep for the system design interview.\n\n### Learn how to design large-scale systems\n\nLearning how to design scalable systems will help you become a better engineer.\n\nSystem design is a broad topic.  There are a **vast number of resources scattered throughout the web** on system design principles.\n\nThis repo is an **organized collection** of resources to help you learn how to build systems at scale.\n\n### Learn from the open source community\n\nThis is a continually updated, open source project.\n\n[Contributions](#contributing) are welcome!\n\n### Prep for the system design interview\n\nIn addition to coding interviews, system design is a **required component** of the **technical interview process** at many tech companies.\n\n**Practice common system design interview questions** and **compare** your results with **sample solutions**: discussions, code, and diagrams.\n\nAdditional topics for interview prep:\n\n* [Study guide](#study-guide)\n* [How to approach a system design interview question](#how-to-approach-a-system-design-interview-question)\n* [System design interview questions, **with solutions**](#system-design-interview-questions-with-solutions)\n* [Object-oriented design interview questions, **with solutions**](#object-oriented-design-interview-questions-with-solutions)\n* [Additional system design interview questions](#additional-system-design-interview-questions)\n\n## Anki flashcards\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FzdCAkB3.png\">\n  \u003Cbr\u002F>\n\u003C\u002Fp>\n\nThe provided [Anki flashcard decks](https:\u002F\u002Fapps.ankiweb.net\u002F) use spaced repetition to help you retain key system design concepts.\n\n* [System design deck](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Ftree\u002Fmaster\u002Fresources\u002Fflash_cards\u002FSystem%20Design.apkg)\n* [System design exercises deck](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Ftree\u002Fmaster\u002Fresources\u002Fflash_cards\u002FSystem%20Design%20Exercises.apkg)\n* [Object oriented design exercises deck](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Ftree\u002Fmaster\u002Fresources\u002Fflash_cards\u002FOO%20Design.apkg)\n\nGreat for use while on-the-go.\n\n### Coding Resource: Interactive Coding Challenges\n\nLooking for resources to help you prep for the [**Coding Interview**](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Finteractive-coding-challenges)?\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002Fb4YtAEN.png\">\n  \u003Cbr\u002F>\n\u003C\u002Fp>\n\nCheck out the sister repo [**Interactive Coding Challenges**](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Finteractive-coding-challenges), which contains an additional Anki deck:\n\n* [Coding deck](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Finteractive-coding-challenges\u002Ftree\u002Fmaster\u002Fanki_cards\u002FCoding.apkg)\n\n## Contributing\n\n> Learn from the community.\n\nFeel free to submit pull requests to help:\n\n* Fix errors\n* Improve sections\n* Add new sections\n* [Translate](https:\u002F\u002Fgithub.com\u002Fdonnemartin\u002Fsystem-design-primer\u002Fissues\u002F28)\n\nContent that needs some polishing is placed [under development](#under-development).\n\nReview the [Contributing Guidelines](CONTRIBUTING.md).\n\n## Index of system design topics\n\n> Summaries of various system design topics, including pros and cons.  **Everything is a trade-off**.\n>\n> Each section contains links to more in-depth resources.\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FjrUBAF7.png\">\n  \u003Cbr\u002F>\n\u003C\u002Fp>\n\n* [System design topics: start here](#system-design-topics-start-here)\n    * [Step 1: Review the scalability video lecture](#step-1-review-the-scalability-video-lecture)\n    * [Step 2: Review the scalability article](#step-2-review-the-scalability-article)\n    * [Next steps](#next-steps)\n* [Performance vs scalability](#performance-vs-scalability)\n* [Latency vs throughput](#latency-vs-throughput)\n* [Availability vs consistency](#availability-vs-consistency)\n    * [CAP theorem](#cap-theorem)\n        * [CP - consistency and partition tolerance](#cp---consistency-and-partition-tolerance)\n        * [AP - availability and partition tolerance](#ap---availability-and-partition-tolerance)\n* [Consistency patterns](#consistency-patterns)\n    * [Weak consistency](#weak-consistency)\n    * [Eventual consistency](#eventual-consistency)\n    * [Strong consistency](#strong-consistency)\n* [Availability patterns](#availability-patterns)\n    * [Fail-over](#fail-over)\n    * [Replication](#replication)\n    * [Availability in numbers](#availability-in-numbers)\n* [Domain name system](#domain-name-system)\n* [Content delivery network](#content-delivery-network)\n    * [Push CDNs](#push-cdns)\n    * [Pull CDNs](#pull-cdns)\n* [Load balancer](#load-balancer)\n    * [Active-passive](#active-passive)\n    * [Active-active](#active-active)\n    * [Layer 4 load balancing](#layer-4-load-balancing)\n    * [Layer 7 load balancing](#layer-7-load-balancing)\n    * [Horizontal scaling](#horizontal-scaling)\n* [Reverse proxy (web server)](#reverse-proxy-web-server)\n    * [Load balancer vs reverse proxy](#load-balancer-vs-reverse-proxy)\n* [Application layer](#application-layer)\n    * [Microservices](#microservices)\n    * [Service discovery](#service-discovery)\n* [Database](#database)\n    * [Relational database management system (RDBMS)](#relational-database-management-system-rdbms)\n        * [Master-slave replication](#master-slave-replication)\n        * [Master-master replication](#master-master-replication)\n        * [Federation](#federation)\n        * [Sharding](#sharding)\n        * [Denormalization](#denormalization)\n        * [SQL tuning](#sql-tuning)\n    * [NoSQL](#nosql)\n        * [Key-value store](#key-value-store)\n        * [Document store](#document-store)\n        * [Wide column store](#wide-column-store)\n        * [Graph Database](#graph-database)\n    * [SQL or NoSQL](#sql-or-nosql)\n* [Cache](#cache)\n    * [Client caching](#client-caching)\n    * [CDN caching](#cdn-caching)\n    * [Web server caching](#web-server-caching)\n    * [Database caching](#database-caching)\n    * [Application caching](#application-caching)\n    * [Caching at the database query level](#caching-at-the-database-query-level)\n    * [Caching at the object level](#caching-at-the-object-level)\n    * [When to update the cache](#when-to-update-the-cache)\n        * [Cache-aside](#cache-aside)\n        * [Write-through](#write-through)\n        * [Write-behind (write-back)](#write-behind-write-back)\n        * [Refresh-ahead](#refresh-ahead)\n* [Asynchronism](#asynchronism)\n    * [Message queues](#message-queues)\n    * [Task queues](#task-queues)\n    * [Back pressure](#back-pressure)\n* [Communication](#communication)\n    * [Transmission control protocol (TCP)](#transmission-control-protocol-tcp)\n    * [User datagram protocol (UDP)](#user-datagram-protocol-udp)\n    * [Remote procedure call (RPC)](#remote-procedure-call-rpc)\n    * [Representational state transfer (REST)](#representational-state-transfer-rest)\n* [Security](#security)\n* [Appendix](#appendix)\n    * [Powers of two table](#powers-of-two-table)\n    * [Latency numbers every programmer should know](#latency-numbers-every-programmer-should-know)\n    * [Additional system design interview questions](#additional-system-design-interview-questions)\n    * [Real world architectures](#real-world-architectures)\n    * [Company architectures](#company-architectures)\n    * [Company engineering blogs](#company-engineering-blogs)\n* [Under development](#under-development)\n* [Credits](#credits)\n* [Contact info](#contact-info)\n* [License](#license)\n\n## Study guide\n\n> Suggested topics to review based on your interview timeline (short, medium, long).\n\n![Imgur](images\u002FOfVllex.png)\n\n**Q: For interviews, do I need to know everything here?**\n\n**A: No, you don't need to know everything here to prepare for the interview**.\n\nWhat you are asked in an interview depends on variables such as:\n\n* How much experience you have\n* What your technical background is\n* What positions you are interviewing for\n* Which companies you are interviewing with\n* Luck\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.\n\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\n* **Short timeline** - Aim for **breadth** with system design topics.  Practice by solving **some** interview questions.\n* **Medium timeline** - Aim for **breadth** and **some depth** with system design topics.  Practice by solving **many** interview questions.\n* **Long timeline** - Aim for **breadth** and **more depth** with system design topics.  Practice by solving **most** interview questions.\n\n| | Short | Medium | Long |\n|---|---|---|---|\n| Read through the [System design topics](#index-of-system-design-topics) to get a broad understanding of how systems work | :+1: | :+1: | :+1: |\n| Read through a few articles in the [Company engineering blogs](#company-engineering-blogs) for the companies you are interviewing with | :+1: | :+1: | :+1: |\n| Read through a few [Real world architectures](#real-world-architectures) | :+1: | :+1: | :+1: |\n| Review [How to approach a system design interview question](#how-to-approach-a-system-design-interview-question) | :+1: | :+1: | :+1: |\n| Work through [System design interview questions with solutions](#system-design-interview-questions-with-solutions) | Some | Many | Most |\n| Work through [Object-oriented design interview questions with solutions](#object-oriented-design-interview-questions-with-solutions) | Some | Many | Most |\n| Review [Additional system design interview questions](#additional-system-design-interview-questions) | Some | Many | Most |\n\n## How to approach a system design interview question\n\n> How to tackle a system design interview question.\n\nThe system design interview is an **open-ended conversation**.  You are expected to lead it.\n\nYou can use the following steps to guide the discussion.  To help solidify this process, work through the [System design interview questions with solutions](#system-design-interview-questions-with-solutions) section using the following steps.\n\n### Step 1: Outline use cases, constraints, and assumptions\n\nGather requirements and scope the problem.  Ask questions to clarify use cases and constraints.  Discuss assumptions.\n\n* Who is going to use it?\n* How are they going to use it?\n* How many users are there?\n* What does the system do?\n* What are the inputs and outputs of the system?\n* How much data do we expect to handle?\n* How many requests per second do we expect?\n* What is the expected read to write ratio?\n\n### Step 2: Create a high level design\n\nOutline a high level design with all important components.\n\n* Sketch the main components and connections\n* Justify your ideas\n\n### Step 3: Design core components\n\nDive into details for each core component.  For example, if you were asked to [design a url shortening service](solutions\u002Fsystem_design\u002Fpastebin\u002FREADME.md), discuss:\n\n* Generating and storing a hash of the full url\n    * [MD5](solutions\u002Fsystem_design\u002Fpastebin\u002FREADME.md) and [Base62](solutions\u002Fsystem_design\u002Fpastebin\u002FREADME.md)\n    * Hash collisions\n    * SQL or NoSQL\n    * Database schema\n* Translating a hashed url to the full url\n    * Database lookup\n* API and object-oriented design\n\n### Step 4: Scale the design\n\nIdentify and address bottlenecks, given the constraints.  For example, do you need the following to address scalability issues?\n\n* Load balancer\n* Horizontal scaling\n* Caching\n* Database sharding\n\nDiscuss potential solutions and trade-offs.  Everything is a trade-off.  Address bottlenecks using [principles of scalable system design](#index-of-system-design-topics).\n\n### Back-of-the-envelope calculations\n\nYou might be asked to do some estimates by hand.  Refer to the [Appendix](#appendix) for the following resources:\n\n* [Use back of the envelope calculations](http:\u002F\u002Fhighscalability.com\u002Fblog\u002F2011\u002F1\u002F26\u002Fgoogle-pro-tip-use-back-of-the-envelope-calculations-to-choo.html)\n* [Powers of two table](#powers-of-two-table)\n* [Latency numbers every programmer should know](#latency-numbers-every-programmer-should-know)\n\n### Source(s) and further reading\n\nCheck out the following links to get a better idea of what to expect:\n\n* [How to ace a systems design interview](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20210505130322\u002Fhttps:\u002F\u002Fwww.palantir.com\u002F2011\u002F10\u002Fhow-to-rock-a-systems-design-interview\u002F)\n* [The system design interview](http:\u002F\u002Fwww.hiredintech.com\u002Fsystem-design)\n* [Intro to Architecture and Systems Design Interviews](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=ZgdS0EUmn70)\n* [System design template](https:\u002F\u002Fleetcode.com\u002Fdiscuss\u002Fcareer\u002F229177\u002FMy-System-Design-Template)\n\n## System design interview questions with solutions\n\n> Common system design interview questions with sample discussions, code, and diagrams.\n>\n> Solutions linked to content in the `solutions\u002F` folder.\n\n| Question | |\n|---|---|\n| Design Pastebin.com (or Bit.ly) | [Solution](solutions\u002Fsystem_design\u002Fpastebin\u002FREADME.md) |\n| Design the Twitter timeline and search (or Facebook feed and search) | [Solution](solutions\u002Fsystem_design\u002Ftwitter\u002FREADME.md) |\n| Design a web crawler | [Solution](solutions\u002Fsystem_design\u002Fweb_crawler\u002FREADME.md) |\n| Design Mint.com | [Solution](solutions\u002Fsystem_design\u002Fmint\u002FREADME.md) |\n| Design the data structures for a social network | [Solution](solutions\u002Fsystem_design\u002Fsocial_graph\u002FREADME.md) |\n| Design a key-value store for a search engine | [Solution](solutions\u002Fsystem_design\u002Fquery_cache\u002FREADME.md) |\n| Design Amazon's sales ranking by category feature | [Solution](solutions\u002Fsystem_design\u002Fsales_rank\u002FREADME.md) |\n| Design a system that scales to millions of users on AWS | [Solution](solutions\u002Fsystem_design\u002Fscaling_aws\u002FREADME.md) |\n| Add a system design question | [Contribute](#contributing) |\n\n### Design Pastebin.com (or Bit.ly)\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Fpastebin\u002FREADME.md)\n\n![Imgur](images\u002F4edXG0T.png)\n\n### Design the Twitter timeline and search (or Facebook feed and search)\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Ftwitter\u002FREADME.md)\n\n![Imgur](images\u002FjrUBAF7.png)\n\n### Design a web crawler\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Fweb_crawler\u002FREADME.md)\n\n![Imgur](images\u002FbWxPtQA.png)\n\n### Design Mint.com\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Fmint\u002FREADME.md)\n\n![Imgur](images\u002FV5q57vU.png)\n\n### Design the data structures for a social network\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Fsocial_graph\u002FREADME.md)\n\n![Imgur](images\u002FcdCv5g7.png)\n\n### Design a key-value store for a search engine\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Fquery_cache\u002FREADME.md)\n\n![Imgur](images\u002F4j99mhe.png)\n\n### Design Amazon's sales ranking by category feature\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Fsales_rank\u002FREADME.md)\n\n![Imgur](images\u002FMzExP06.png)\n\n### Design a system that scales to millions of users on AWS\n\n[View exercise and solution](solutions\u002Fsystem_design\u002Fscaling_aws\u002FREADME.md)\n\n![Imgur](images\u002Fjj3A5N8.png)\n\n## Object-oriented design interview questions with solutions\n\n> Common object-oriented design interview questions with sample discussions, code, and diagrams.\n>\n> Solutions linked to content in the `solutions\u002F` folder.\n\n>**Note: This section is under development**\n\n| Question | |\n|---|---|\n| Design a hash map | [Solution](solutions\u002Fobject_oriented_design\u002Fhash_table\u002Fhash_map.ipynb)  |\n| Design a least recently used cache | [Solution](solutions\u002Fobject_oriented_design\u002Flru_cache\u002Flru_cache.ipynb)  |\n| Design a call center | [Solution](solutions\u002Fobject_oriented_design\u002Fcall_center\u002Fcall_center.ipynb)  |\n| Design a deck of cards | [Solution](solutions\u002Fobject_oriented_design\u002Fdeck_of_cards\u002Fdeck_of_cards.ipynb)  |\n| Design a parking lot | [Solution](solutions\u002Fobject_oriented_design\u002Fparking_lot\u002Fparking_lot.ipynb)  |\n| Design a chat server | [Solution](solutions\u002Fobject_oriented_design\u002Fonline_chat\u002Fonline_chat.ipynb)  |\n| Design a circular array | [Contribute](#contributing)  |\n| Add an object-oriented design question | [Contribute](#contributing) |\n\n## System design topics: start here\n\nNew to system design?\n\nFirst, you'll need a basic understanding of common principles, learning about what they are, how they are used, and their pros and cons.\n\n### Step 1: Review the scalability video lecture\n\n[Scalability Lecture at Harvard](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=-W9F__D3oY4)\n\n* Topics covered:\n    * Vertical scaling\n    * Horizontal scaling\n    * Caching\n    * Load balancing\n    * Database replication\n    * Database partitioning\n\n### Step 2: Review the scalability article\n\n[Scalability](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20221030091841\u002Fhttp:\u002F\u002Fwww.lecloud.net\u002Ftagged\u002Fscalability\u002Fchrono)\n\n* Topics covered:\n    * [Clones](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20220530193911\u002Fhttps:\u002F\u002Fwww.lecloud.net\u002Fpost\u002F7295452622\u002Fscalability-for-dummies-part-1-clones)\n    * [Databases](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20220602114024\u002Fhttps:\u002F\u002Fwww.lecloud.net\u002Fpost\u002F7994751381\u002Fscalability-for-dummies-part-2-database)\n    * [Caches](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20230126233752\u002Fhttps:\u002F\u002Fwww.lecloud.net\u002Fpost\u002F9246290032\u002Fscalability-for-dummies-part-3-cache)\n    * [Asynchronism](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20220926171507\u002Fhttps:\u002F\u002Fwww.lecloud.net\u002Fpost\u002F9699762917\u002Fscalability-for-dummies-part-4-asynchronism)\n\n### Next steps\n\nNext, we'll look at high-level trade-offs:\n\n* **Performance** vs **scalability**\n* **Latency** vs **throughput**\n* **Availability** vs **consistency**\n\nKeep in mind that **everything is a trade-off**.\n\nThen we'll dive into more specific topics such as DNS, CDNs, and load balancers.\n\n## Performance vs scalability\n\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.\u003Csup>\u003Ca href=http:\u002F\u002Fwww.allthingsdistributed.com\u002F2006\u002F03\u002Fa_word_on_scalability.html>1\u003C\u002Fa>\u003C\u002Fsup>\n\nAnother way to look at performance vs scalability:\n\n* If you have a **performance** problem, your system is slow for a single user.\n* If you have a **scalability** problem, your system is fast for a single user but slow under heavy load.\n\n### Source(s) and further reading\n\n* [A word on scalability](http:\u002F\u002Fwww.allthingsdistributed.com\u002F2006\u002F03\u002Fa_word_on_scalability.html)\n* [Scalability, availability, stability, patterns](http:\u002F\u002Fwww.slideshare.net\u002Fjboner\u002Fscalability-availability-stability-patterns\u002F)\n\n## Latency vs throughput\n\n**Latency** is the time to perform some action or to produce some result.\n\n**Throughput** is the number of such actions or results per unit of time.\n\nGenerally, you should aim for **maximal throughput** with **acceptable latency**.\n\n### Source(s) and further reading\n\n* [Understanding latency vs throughput](https:\u002F\u002Fcommunity.cadence.com\u002Fcadence_blogs_8\u002Fb\u002Ffv\u002Fposts\u002Funderstanding-latency-vs-throughput)\n\n## Availability vs consistency\n\n### CAP theorem\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FbgLMI2u.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=\"https:\u002F\u002Frobertgreiner.com\u002Fcap-theorem-revisited\">Source: CAP theorem revisited\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\nIn a distributed computer system, you can only support two of the following guarantees:\n\n* **Consistency** - Every read receives the most recent write or an error\n* **Availability** - Every request receives a response, without guarantee that it contains the most recent version of the information\n* **Partition Tolerance** - The system continues to operate despite arbitrary partitioning due to network failures\n\n*Networks aren't reliable, so you'll need to support partition tolerance.  You'll need to make a software tradeoff between consistency and availability.*\n\n#### CP - consistency and partition tolerance\n\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.\n\n#### AP - availability and partition tolerance\n\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.\n\nAP is a good choice if the business needs to allow for [eventual consistency](#eventual-consistency) or when the system needs to continue working despite external errors.\n\n### Source(s) and further reading\n\n* [CAP theorem revisited](https:\u002F\u002Frobertgreiner.com\u002Fcap-theorem-revisited\u002F)\n* [A plain english introduction to CAP theorem](http:\u002F\u002Fksat.me\u002Fa-plain-english-introduction-to-cap-theorem)\n* [CAP FAQ](https:\u002F\u002Fgithub.com\u002Fhenryr\u002Fcap-faq)\n* [The CAP theorem](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=k-Yaq8AHlFA)\n\n## Consistency patterns\n\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](#cap-theorem) - Every read receives the most recent write or an error.\n\n### Weak consistency\n\nAfter a write, reads may or may not see it.  A best effort approach is taken.\n\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.\n\n### Eventual consistency\n\nAfter a write, reads will eventually see it (typically within milliseconds).  Data is replicated asynchronously.\n\nThis approach is seen in systems such as DNS and email.  Eventual consistency works well in highly available systems.\n\n### Strong consistency\n\nAfter a write, reads will see it.  Data is replicated synchronously.\n\nThis approach is seen in file systems and RDBMSes.  Strong consistency works well in systems that need transactions.\n\n### Source(s) and further reading\n\n* [Transactions across data centers](http:\u002F\u002Fsnarfed.org\u002Ftransactions_across_datacenters_io.html)\n\n## Availability patterns\n\nThere are two complementary patterns to support high availability: **fail-over** and **replication**.\n\n### Fail-over\n\n#### Active-passive\n\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.\n\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.\n\nActive-passive failover can also be referred to as master-slave failover.\n\n#### Active-active\n\nIn active-active, both servers are managing traffic, spreading the load between them.\n\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.\n\nActive-active failover can also be referred to as master-master failover.\n\n### Disadvantage(s): failover\n\n* Fail-over adds more hardware and additional complexity.\n* There is a potential for loss of data if the active system fails before any newly written data can be replicated to the passive.\n\n### Replication\n\n#### Master-slave and master-master\n\nThis topic is further discussed in the [Database](#database) section:\n\n* [Master-slave replication](#master-slave-replication)\n* [Master-master replication](#master-master-replication)\n\n### Availability in numbers\n\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.\n\n#### 99.9% availability - three 9s\n\n| Duration            | Acceptable downtime|\n|---------------------|--------------------|\n| Downtime per year   | 8h 45min 57s       |\n| Downtime per month  | 43m 49.7s          |\n| Downtime per week   | 10m 4.8s           |\n| Downtime per day    | 1m 26.4s           |\n\n#### 99.99% availability - four 9s\n\n| Duration            | Acceptable downtime|\n|---------------------|--------------------|\n| Downtime per year   | 52min 35.7s        |\n| Downtime per month  | 4m 23s             |\n| Downtime per week   | 1m 5s              |\n| Downtime per day    | 8.6s               |\n\n#### Availability in parallel vs in sequence\n\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.\n\n###### In sequence\n\nOverall availability decreases when two components with availability \u003C 100% are in sequence:\n\n```\nAvailability (Total) = Availability (Foo) * Availability (Bar)\n```\n\nIf both `Foo` and `Bar` each had 99.9% availability, their total availability in sequence would be 99.8%.\n\n###### In parallel\n\nOverall availability increases when two components with availability \u003C 100% are in parallel:\n\n```\nAvailability (Total) = 1 - (1 - Availability (Foo)) * (1 - Availability (Bar))\n```\n\nIf both `Foo` and `Bar` each had 99.9% availability, their total availability in parallel would be 99.9999%.\n\n## Domain name system\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FIOyLj4i.jpg\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Fwww.slideshare.net\u002Fsrikrupa5\u002Fdns-security-presentation-issa>Source: DNS security presentation\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\nA Domain Name System (DNS) translates a domain name such as www.example.com to an IP address.\n\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)](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FTime_to_live).\n\n* **NS record (name server)** - Specifies the DNS servers for your domain\u002Fsubdomain.\n* **MX record (mail exchange)** - Specifies the mail servers for accepting messages.\n* **A record (address)** - Points a name to an IP address.\n* **CNAME (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](https:\u002F\u002Fwww.cloudflare.com\u002Fdns\u002F) and [Route 53](https:\u002F\u002Faws.amazon.com\u002Froute53\u002F) provide managed DNS services.  Some DNS services can route traffic through various methods:\n\n* [Weighted round robin](https:\u002F\u002Fwww.jscape.com\u002Fblog\u002Fload-balancing-algorithms)\n    * Prevent traffic from going to servers under maintenance\n    * Balance between varying cluster sizes\n    * A\u002FB testing\n* [Latency-based](https:\u002F\u002Fdocs.aws.amazon.com\u002FRoute53\u002Flatest\u002FDeveloperGuide\u002Frouting-policy-latency.html)\n* [Geolocation-based](https:\u002F\u002Fdocs.aws.amazon.com\u002FRoute53\u002Flatest\u002FDeveloperGuide\u002Frouting-policy-geo.html)\n\n### Disadvantage(s): DNS\n\n* Accessing a DNS server introduces a slight delay, although mitigated by caching described above.\n* DNS server management could be complex and is generally managed by [governments, ISPs, and large companies](http:\u002F\u002Fsuperuser.com\u002Fquestions\u002F472695\u002Fwho-controls-the-dns-servers\u002F472729).\n* DNS services have recently come under [DDoS attack](http:\u002F\u002Fdyn.com\u002Fblog\u002Fdyn-analysis-summary-of-friday-october-21-attack\u002F), preventing users from accessing websites such as Twitter without knowing Twitter's IP address(es).\n\n### Source(s) and further reading\n\n* [DNS architecture](https:\u002F\u002Ftechnet.microsoft.com\u002Fen-us\u002Flibrary\u002Fdd197427(v=ws.10).aspx)\n* [Wikipedia](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FDomain_Name_System)\n* [DNS articles](https:\u002F\u002Fsupport.dnsimple.com\u002Fcategories\u002Fdns\u002F)\n\n## Content delivery network\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002Fh9TAuGI.jpg\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=https:\u002F\u002Fwww.creative-artworks.eu\u002Fwhy-use-a-content-delivery-network-cdn\u002F>Source: Why use a CDN\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\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\u002FCSS\u002FJS, 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.\n\nServing content from CDNs can significantly improve performance in two ways:\n\n* Users receive content from data centers close to them\n* Your servers do not have to serve requests that the CDN fulfills\n\n### Push CDNs\n\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.\n\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.\n\n### Pull CDNs\n\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.\n\nA [time-to-live (TTL)](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FTime_to_live) 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.\n\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.\n\n### Disadvantage(s): CDN\n\n* CDN costs could be significant depending on traffic, although this should be weighed with additional costs you would incur not using a CDN.\n* Content might be stale if it is updated before the TTL expires it.\n* CDNs require changing URLs for static content to point to the CDN.\n\n### Source(s) and further reading\n\n* [Globally distributed content delivery](https:\u002F\u002Ffigshare.com\u002Farticles\u002FGlobally_distributed_content_delivery\u002F6605972)\n* [The differences between push and pull CDNs](https:\u002F\u002Fwww.geeksforgeeks.org\u002Fsystem-design\u002Fpull-cdn-vs-push-cdn\u002F)\n* [Wikipedia](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FContent_delivery_network)\n\n## Load balancer\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002Fh81n9iK.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Fhoricky.blogspot.com\u002F2010\u002F10\u002Fscalable-system-design-patterns.html>Source: Scalable system design patterns\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\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\n* Preventing requests from going to unhealthy servers\n* Preventing overloading resources\n* Helping to eliminate a single point of failure\n\nLoad balancers can be implemented with hardware (expensive) or with software such as HAProxy.\n\nAdditional benefits include:\n\n* **SSL termination** - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations\n    * Removes the need to install [X.509 certificates](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FX.509) on each server\n* **Session 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](#active-passive) or [active-active](#active-active) mode.\n\nLoad balancers can route traffic based on various metrics, including:\n\n* Random\n* Least loaded\n* Session\u002Fcookies\n* [Round robin or weighted round robin](https:\u002F\u002Fwww.g33kinfo.com\u002Finfo\u002Fround-robin-vs-weighted-round-robin-lb)\n* [Layer 4](#layer-4-load-balancing)\n* [Layer 7](#layer-7-load-balancing)\n\n### Layer 4 load balancing\n\nLayer 4 load balancers look at info at the [transport layer](#communication) 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)](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20240117134735\u002Fhttps:\u002F\u002Fwww.nginx.com\u002Fresources\u002Fglossary\u002Flayer-4-load-balancing\u002F).\n\n### Layer 7 load balancing\n\nLayer 7 load balancers look at the [application layer](#communication) 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.\n\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.\n\n### Horizontal scaling\n\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.\n\n#### Disadvantage(s): horizontal scaling\n\n* Scaling horizontally introduces complexity and involves cloning servers\n    * Servers should be stateless: they should not contain any user-related data like sessions or profile pictures\n    * Sessions can be stored in a centralized data store such as a [database](#database) (SQL, NoSQL) or a persistent [cache](#cache) (Redis, Memcached)\n* Downstream servers such as caches and databases need to handle more simultaneous connections as upstream servers scale out\n\n### Disadvantage(s): load balancer\n\n* The load balancer can become a performance bottleneck if it does not have enough resources or if it is not configured properly.\n* Introducing a load balancer to help eliminate a single point of failure results in increased complexity.\n* A single load balancer is a single point of failure, configuring multiple load balancers further increases complexity.\n\n### Source(s) and further reading\n\n* [NGINX architecture](https:\u002F\u002Fwww.nginx.com\u002Fblog\u002Finside-nginx-how-we-designed-for-performance-scale\u002F)\n* [HAProxy architecture guide](http:\u002F\u002Fwww.haproxy.org\u002Fdownload\u002F1.2\u002Fdoc\u002Farchitecture.txt)\n* [Scalability](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20220530193911\u002Fhttps:\u002F\u002Fwww.lecloud.net\u002Fpost\u002F7295452622\u002Fscalability-for-dummies-part-1-clones)\n* [Wikipedia](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FLoad_balancing_(computing))\n* [Layer 4 load balancing](https:\u002F\u002Fwww.nginx.com\u002Fresources\u002Fglossary\u002Flayer-4-load-balancing\u002F)\n* [Layer 7 load balancing](https:\u002F\u002Fwww.nginx.com\u002Fresources\u002Fglossary\u002Flayer-7-load-balancing\u002F)\n* [ELB listener config](http:\u002F\u002Fdocs.aws.amazon.com\u002Felasticloadbalancing\u002Flatest\u002Fclassic\u002Felb-listener-config.html)\n\n## Reverse proxy (web server)\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002Fn41Azff.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=https:\u002F\u002Fupload.wikimedia.org\u002Fwikipedia\u002Fcommons\u002F6\u002F67\u002FReverse_proxy_h2g2bob.svg>Source: Wikipedia\u003C\u002Fa>\u003C\u002Fi>\n  \u003Cbr\u002F>\n\u003C\u002Fp>\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.\n\nAdditional benefits include:\n\n* **Increased security** - Hide information about backend servers, blacklist IPs, limit number of connections per client\n* **Increased scalability and flexibility** - Clients only see the reverse proxy's IP, allowing you to scale servers or change their configuration\n* **SSL termination** - Decrypt incoming requests and encrypt server responses so backend servers do not have to perform these potentially expensive operations\n    * Removes the need to install [X.509 certificates](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FX.509) on each server\n* **Compression** - Compress server responses\n* **Caching** - Return the response for cached requests\n* **Static content** - Serve static content directly\n    * HTML\u002FCSS\u002FJS\n    * Photos\n    * Videos\n    * Etc\n\n### Load balancer vs reverse proxy\n\n* 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.\n* Reverse proxies can be useful even with just one web server or application server, opening up the benefits described in the previous section.\n* Solutions such as NGINX and HAProxy can support both layer 7 reverse proxying and load balancing.\n\n### Disadvantage(s): reverse proxy\n\n* Introducing a reverse proxy results in increased complexity.\n* A single reverse proxy is a single point of failure, configuring multiple reverse proxies (ie a [failover](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FFailover)) further increases complexity.\n\n### Source(s) and further reading\n\n* [Reverse proxy vs load balancer](https:\u002F\u002Fwww.nginx.com\u002Fresources\u002Fglossary\u002Freverse-proxy-vs-load-balancer\u002F)\n* [NGINX architecture](https:\u002F\u002Fwww.nginx.com\u002Fblog\u002Finside-nginx-how-we-designed-for-performance-scale\u002F)\n* [HAProxy architecture guide](http:\u002F\u002Fwww.haproxy.org\u002Fdownload\u002F1.2\u002Fdoc\u002Farchitecture.txt)\n* [Wikipedia](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FReverse_proxy)\n\n## Application layer\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FyB5SYwm.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Flethain.com\u002Fintroduction-to-architecting-systems-for-scale\u002F#platform_layer>Source: Intro to architecting systems for scale\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\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.\n\nWorkers in the application layer also help enable [asynchronism](#asynchronism).\n\n### Microservices\n\nRelated to this discussion are [microservices](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FMicroservices), 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. \u003Csup>\u003Ca href=https:\u002F\u002Fsmartbear.com\u002Flearn\u002Fapi-design\u002Fwhat-are-microservices>1\u003C\u002Fa>\u003C\u002Fsup>\n\nPinterest, for example, could have the following microservices: user profile, follower, feed, search, photo upload, etc.\n\n### Service Discovery\n\nSystems such as [Consul](https:\u002F\u002Fwww.consul.io\u002Fdocs\u002Findex.html), [Etcd](https:\u002F\u002Fcoreos.com\u002Fetcd\u002Fdocs\u002Flatest), and [Zookeeper](http:\u002F\u002Fwww.slideshare.net\u002Fsauravhaloi\u002Fintroduction-to-apache-zookeeper) can help services find each other by keeping track of registered names, addresses, and ports.  [Health checks](https:\u002F\u002Fwww.consul.io\u002Fintro\u002Fgetting-started\u002Fchecks.html) help verify service integrity and are often done using an [HTTP](#hypertext-transfer-protocol-http) endpoint.  Both Consul and Etcd have a built in [key-value store](#key-value-store) that can be useful for storing config values and other shared data.\n\n### Disadvantage(s): application layer\n\n* Adding an application layer with loosely coupled services requires a different approach from an architectural, operations, and process viewpoint (vs a monolithic system).\n* Microservices can add complexity in terms of deployments and operations.\n\n### Source(s) and further reading\n\n* [Intro to architecting systems for scale](http:\u002F\u002Flethain.com\u002Fintroduction-to-architecting-systems-for-scale)\n* [Crack the system design interview](http:\u002F\u002Fwww.puncsky.com\u002Fblog\u002F2016-02-13-crack-the-system-design-interview)\n* [Service oriented architecture](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FService-oriented_architecture)\n* [Introduction to Zookeeper](http:\u002F\u002Fwww.slideshare.net\u002Fsauravhaloi\u002Fintroduction-to-apache-zookeeper)\n* [Here's what you need to know about building microservices](https:\u002F\u002Fcloudncode.wordpress.com\u002F2016\u002F07\u002F22\u002Fmsa-getting-started\u002F)\n\n## Database\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FXkm5CXz.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=kKjm4ehYiMs>Source: Scaling up to your first 10 million users\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\n### Relational database management system (RDBMS)\n\nA relational database like SQL is a collection of data items organized in tables.\n\n**ACID** is a set of properties of relational database [transactions](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FDatabase_transaction).\n\n* **Atomicity** - Each transaction is all or nothing\n* **Consistency** - Any transaction will bring the database from one valid state to another\n* **Isolation** - Executing transactions concurrently has the same results as if the transactions were executed serially\n* **Durability** - 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**.\n\n#### Master-slave replication\n\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\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FC9ioGtn.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Fwww.slideshare.net\u002Fjboner\u002Fscalability-availability-stability-patterns\u002F>Source: Scalability, availability, stability, patterns\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\n##### Disadvantage(s): master-slave replication\n\n* Additional logic is needed to promote a slave to a master.\n* See [Disadvantage(s): replication](#disadvantages-replication) for points related to **both** master-slave and master-master.\n\n#### Master-master replication\n\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\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FkrAHLGg.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Fwww.slideshare.net\u002Fjboner\u002Fscalability-availability-stability-patterns\u002F>Source: Scalability, availability, stability, patterns\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\n##### Disadvantage(s): master-master replication\n\n* You'll need a load balancer or you'll need to make changes to your application logic to determine where to write.\n* Most master-master systems are either loosely consistent (violating ACID) or have increased write latency due to synchronization.\n* Conflict resolution comes more into play as more write nodes are added and as latency increases.\n* See [Disadvantage(s): replication](#disadvantages-replication) for points related to **both** master-slave and master-master.\n\n##### Disadvantage(s): replication\n\n* There is a potential for loss of data if the master fails before any newly written data can be replicated to other nodes.\n* 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.\n* The more read slaves, the more you have to replicate, which leads to greater replication lag.\n* 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.\n* Replication adds more hardware and additional complexity.\n\n##### Source(s) and further reading: replication\n\n* [Scalability, availability, stability, patterns](http:\u002F\u002Fwww.slideshare.net\u002Fjboner\u002Fscalability-availability-stability-patterns\u002F)\n* [Multi-master replication](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FMulti-master_replication)\n\n#### Federation\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FU3qV33e.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=kKjm4ehYiMs>Source: Scaling up to your first 10 million users\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\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.\n\n##### Disadvantage(s): federation\n\n* Federation is not effective if your schema requires huge functions or tables.\n* You'll need to update your application logic to determine which database to read and write.\n* Joining data from two databases is more complex with a [server link](http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F5145637\u002Fquerying-data-by-joining-two-tables-in-two-database-on-different-servers).\n* Federation adds more hardware and additional complexity.\n\n##### Source(s) and further reading: federation\n\n* [Scaling up to your first 10 million users](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=kKjm4ehYiMs)\n\n#### Sharding\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FwU8x5Id.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Fwww.slideshare.net\u002Fjboner\u002Fscalability-availability-stability-patterns\u002F>Source: Scalability, availability, stability, patterns\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\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.\n\nSimilar to the advantages of [federation](#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.\n\nCommon ways to shard a table of users is either through the user's last name initial or the user's geographic location.\n\n##### Disadvantage(s): sharding\n\n* You'll need to update your application logic to work with shards, which could result in complex SQL queries.\n* 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.\n    * Rebalancing adds additional complexity.  A sharding function based on [consistent hashing](http:\u002F\u002Fwww.paperplanes.de\u002F2011\u002F12\u002F9\u002Fthe-magic-of-consistent-hashing.html) can reduce the amount of transferred data.\n* Joining data from multiple shards is more complex.\n* Sharding adds more hardware and additional complexity.\n\n##### Source(s) and further reading: sharding\n\n* [The coming of the shard](http:\u002F\u002Fhighscalability.com\u002Fblog\u002F2009\u002F8\u002F6\u002Fan-unorthodox-approach-to-database-design-the-coming-of-the.html)\n* [Shard database architecture](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FShard_(database_architecture))\n* [Consistent hashing](http:\u002F\u002Fwww.paperplanes.de\u002F2011\u002F12\u002F9\u002Fthe-magic-of-consistent-hashing.html)\n\n#### Denormalization\n\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](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FPostgreSQL) and Oracle support [materialized views](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FMaterialized_view) which handle the work of storing redundant information and keeping redundant copies consistent.\n\nOnce data becomes distributed with techniques such as [federation](#federation) and [sharding](#sharding), managing joins across data centers further increases complexity.  Denormalization might circumvent the need for such complex joins.\n\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.\n\n##### Disadvantage(s): denormalization\n\n* Data is duplicated.\n* Constraints can help redundant copies of information stay in sync, which increases complexity of the database design.\n* A denormalized database under heavy write load might perform worse than its normalized counterpart.\n\n###### Source(s) and further reading: denormalization\n\n* [Denormalization](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FDenormalization)\n\n#### SQL tuning\n\nSQL tuning is a broad topic and many [books](https:\u002F\u002Fwww.amazon.com\u002Fs\u002Fref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=sql+tuning) have been written as reference.\n\nIt's important to **benchmark** and **profile** to simulate and uncover bottlenecks.\n\n* **Benchmark** - Simulate high-load situations with tools such as [ab](http:\u002F\u002Fhttpd.apache.org\u002Fdocs\u002F2.2\u002Fprograms\u002Fab.html).\n* **Profile** - Enable tools such as the [slow query log](http:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F5.7\u002Fen\u002Fslow-query-log.html) to help track performance issues.\n\nBenchmarking and profiling might point you to the following optimizations.\n\n##### Tighten up the schema\n\n* MySQL dumps to disk in contiguous blocks for fast access.\n* Use `CHAR` instead of `VARCHAR` for fixed-length fields.\n    * `CHAR` effectively allows for fast, random access, whereas with `VARCHAR`, you must find the end of a string before moving onto the next one.\n* 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.\n* Use `INT` for larger numbers up to 2^32 or 4 billion.\n* Use `DECIMAL` for currency to avoid floating point representation errors.\n* Avoid storing large `BLOBS`, store the location of where to get the object instead.\n* `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.\n* Set the `NOT NULL` constraint where applicable to [improve search performance](http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F1017239\u002Fhow-do-null-values-affect-performance-in-a-database-search).\n\n##### Use good indices\n\n* Columns that you are querying (`SELECT`, `GROUP BY`, `ORDER BY`, `JOIN`) could be faster with indices.\n* Indices are usually represented as self-balancing [B-tree](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FB-tree) that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time.\n* Placing an index can keep the data in memory, requiring more space.\n* Writes could also be slower since the index also needs to be updated.\n* When loading large amounts of data, it might be faster to disable indices, load the data, then rebuild the indices.\n\n##### Avoid expensive joins\n\n* [Denormalize](#denormalization) where performance demands it.\n\n##### Partition tables\n\n* Break up a table by putting hot spots in a separate table to help keep it in memory.\n\n##### Tune the query cache\n\n* In some cases, the [query cache](https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F5.7\u002Fen\u002Fquery-cache.html) could lead to [performance issues](https:\u002F\u002Fwww.percona.com\u002Fblog\u002F2016\u002F10\u002F12\u002Fmysql-5-7-performance-tuning-immediately-after-installation\u002F).\n\n##### Source(s) and further reading: SQL tuning\n\n* [Tips for optimizing MySQL queries](http:\u002F\u002Faiddroid.com\u002F10-tips-optimizing-mysql-queries-dont-suck\u002F)\n* [Is there a good reason i see VARCHAR(255) used so often?](http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F1217466\u002Fis-there-a-good-reason-i-see-varchar255-used-so-often-as-opposed-to-another-l)\n* [How do null values affect performance?](http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F1017239\u002Fhow-do-null-values-affect-performance-in-a-database-search)\n* [Slow query log](http:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F5.7\u002Fen\u002Fslow-query-log.html)\n\n### NoSQL\n\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](#eventual-consistency).\n\n**BASE** is often used to describe the properties of NoSQL databases.  In comparison with the [CAP Theorem](#cap-theorem), BASE chooses availability over consistency.\n\n* **Basically available** - the system guarantees availability.\n* **Soft state** - the state of the system may change over time, even without input.\n* **Eventual 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](#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.\n\n#### Key-value store\n\n> Abstraction: 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](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FLexicographical_order), allowing efficient retrieval of key ranges.  Key-value stores can allow for storing of metadata with a value.\n\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.\n\nA key-value store is the basis for more complex systems such as a document store, and in some cases, a graph database.\n\n##### Source(s) and further reading: key-value store\n\n* [Key-value database](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FKey-value_database)\n* [Disadvantages of key-value stores](http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F4056093\u002Fwhat-are-the-disadvantages-of-using-a-key-value-table-over-nullable-columns-or)\n* [Redis architecture](http:\u002F\u002Fqnimate.com\u002Foverview-of-redis-architecture\u002F)\n* [Memcached architecture](https:\u002F\u002Fadayinthelifeof.nl\u002F2011\u002F02\u002F06\u002Fmemcache-internals\u002F)\n\n#### Document store\n\n> Abstraction: 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.*\n\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.\n\nSome document stores like [MongoDB](https:\u002F\u002Fwww.mongodb.com\u002Fmongodb-architecture) and [CouchDB](https:\u002F\u002Fblog.couchdb.org\u002F2016\u002F08\u002F01\u002Fcouchdb-2-0-architecture\u002F) also provide a SQL-like language to perform complex queries.  [DynamoDB](http:\u002F\u002Fwww.read.seas.harvard.edu\u002F~kohler\u002Fclass\u002Fcs239-w08\u002Fdecandia07dynamo.pdf) supports both key-values and documents.\n\nDocument stores provide high flexibility and are often used for working with occasionally changing data.\n\n##### Source(s) and further reading: document store\n\n* [Document-oriented database](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FDocument-oriented_database)\n* [MongoDB architecture](https:\u002F\u002Fwww.mongodb.com\u002Fmongodb-architecture)\n* [CouchDB architecture](https:\u002F\u002Fblog.couchdb.org\u002F2016\u002F08\u002F01\u002Fcouchdb-2-0-architecture\u002F)\n* [Elasticsearch architecture](https:\u002F\u002Fwww.elastic.co\u002Fblog\u002Ffound-elasticsearch-from-the-bottom-up)\n\n#### Wide column store\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002Fn16iOGk.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Fblog.grio.com\u002F2015\u002F11\u002Fsql-nosql-a-brief-history.html>Source: SQL & NoSQL, a brief history\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\n> Abstraction: nested map `ColumnFamily\u003CRowKey, Columns\u003CColKey, Value, Timestamp>>`\n\nA wide column store's basic unit of data is a column (name\u002Fvalue 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.\n\nGoogle introduced [Bigtable](http:\u002F\u002Fwww.read.seas.harvard.edu\u002F~kohler\u002Fclass\u002Fcs239-w08\u002Fchang06bigtable.pdf) as the first wide column store, which influenced the open-source [HBase](https:\u002F\u002Fwww.edureka.co\u002Fblog\u002Fhbase-architecture\u002F) often-used in the Hadoop ecosystem, and [Cassandra](http:\u002F\u002Fdocs.datastax.com\u002Fen\u002Fcassandra\u002F3.0\u002Fcassandra\u002Farchitecture\u002FarchIntro.html) from Facebook.  Stores such as BigTable, HBase, and Cassandra maintain keys in lexicographic order, allowing efficient retrieval of selective key ranges.\n\nWide column stores offer high availability and high scalability.  They are often used for very large data sets.\n\n##### Source(s) and further reading: wide column store\n\n* [SQL & NoSQL, a brief history](http:\u002F\u002Fblog.grio.com\u002F2015\u002F11\u002Fsql-nosql-a-brief-history.html)\n* [Bigtable architecture](http:\u002F\u002Fwww.read.seas.harvard.edu\u002F~kohler\u002Fclass\u002Fcs239-w08\u002Fchang06bigtable.pdf)\n* [HBase architecture](https:\u002F\u002Fwww.edureka.co\u002Fblog\u002Fhbase-architecture\u002F)\n* [Cassandra architecture](http:\u002F\u002Fdocs.datastax.com\u002Fen\u002Fcassandra\u002F3.0\u002Fcassandra\u002Farchitecture\u002FarchIntro.html)\n\n#### Graph database\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FfNcl65g.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FFile:GraphDatabase_PropertyGraph.png>Source: Graph database\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\n> Abstraction: 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.\n\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](#representational-state-transfer-rest).\n\n##### Source(s) and further reading: graph\n\n* [Graph database](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FGraph_database)\n* [Neo4j](https:\u002F\u002Fneo4j.com\u002F)\n* [FlockDB](https:\u002F\u002Fblog.twitter.com\u002F2010\u002Fintroducing-flockdb)\n\n#### Source(s) and further reading: NoSQL\n\n* [Explanation of base terminology](http:\u002F\u002Fstackoverflow.com\u002Fquestions\u002F3342497\u002Fexplanation-of-base-terminology)\n* [NoSQL databases a survey and decision guidance](https:\u002F\u002Fmedium.com\u002Fbaqend-blog\u002Fnosql-databases-a-survey-and-decision-guidance-ea7823a822d#.wskogqenq)\n* [Scalability](https:\u002F\u002Fweb.archive.org\u002Fweb\u002F20220602114024\u002Fhttps:\u002F\u002Fwww.lecloud.net\u002Fpost\u002F7994751381\u002Fscalability-for-dummies-part-2-database)\n* [Introduction to NoSQL](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=qI_g07C_Q5I)\n* [NoSQL patterns](http:\u002F\u002Fhoricky.blogspot.com\u002F2009\u002F11\u002Fnosql-patterns.html)\n\n### SQL or NoSQL\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FwXGqG5f.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=https:\u002F\u002Fwww.infoq.com\u002Farticles\u002FTransition-RDBMS-NoSQL\u002F>Source: Transitioning from RDBMS to NoSQL\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\n\nReasons for **SQL**:\n\n* Structured data\n* Strict schema\n* Relational data\n* Need for complex joins\n* Transactions\n* Clear patterns for scaling\n* More established: developers, community, code, tools, etc\n* Lookups by index are very fast\n\nReasons for **NoSQL**:\n\n* Semi-structured data\n* Dynamic or flexible schema\n* Non-relational data\n* No need for complex joins\n* Store many TB (or PB) of data\n* Very data intensive workload\n* Very high throughput for IOPS\n\nSample data well-suited for NoSQL:\n\n* Rapid ingest of clickstream and log data\n* Leaderboard or scoring data\n* Temporary data, such as a shopping cart\n* Frequently accessed ('hot') tables\n* Metadata\u002Flookup tables\n\n##### Source(s) and further reading: SQL or NoSQL\n\n* [Scaling up to your first 10 million users](https:\u002F\u002Fwww.youtube.com\u002Fwatch?v=kKjm4ehYiMs)\n* [SQL vs NoSQL differences](https:\u002F\u002Fwww.sitepoint.com\u002Fsql-vs-nosql-differences\u002F)\n\n## Cache\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FQ6z24La.png\">\n  \u003Cbr\u002F>\n  \u003Ci>\u003Ca href=http:\u002F\u002Fhoricky.blogspot.com\u002F2010\u002F10\u002Fscalable-system-design-patterns.html>Source: Scalable system design patterns\u003C\u002Fa>\u003C\u002Fi>\n\u003C\u002Fp>\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.\n\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.\n\n### Client caching\n\nCaches can be located on the client side (OS or browser), [server side](#reverse-proxy-web-server), or in a distinct cache layer.\n\n### CDN caching\n\n[CDNs](#content-delivery-network) are considered a type of cache.\n\n### Web server caching\n\n[Reverse proxies](#reverse-proxy-web-server) and caches such as [Varnish](https:\u002F\u002Fwww.varnish-cache.org\u002F) can serve static and dynamic content directly.  Web servers can also cache requests, returning responses without having to contact application servers.\n\n### Database caching\n\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.\n\n### Application caching\n\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](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCache_algorithms) algorithms such as [least recently used (LRU)](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FCache_replacement_policies#Least_recently_used_(LRU)) can help invalidate 'cold' entries and keep 'hot' data in RAM.\n\nRedis has the following additional features:\n\n* Persistence option\n* Built-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\n* Row level\n* Query-level\n* Fully-formed serializable objects\n* Fully-rendered HTML\n\nGenerally, you should try to avoid file-based caching, as it makes cloning and auto-scaling more difficult.\n\n### Caching at the database query level\n\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\n* Hard to delete a cached result with complex queries\n* If one piece of data changes such as a table cell, you need to delete all cached queries that might include the changed cell\n\n### Caching at the object level\n\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\n* Remove the object from cache if its underlying data has changed\n* Allows for asynchronous processing: workers assemble objects by consuming the latest cached object\n\nSuggestions of what to cache:\n\n* User sessions\n* Fully rendered web pages\n* Activity streams\n* User graph data\n\n### When to update the cache\n\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.\n\n#### Cache-aside\n\n\u003Cp align=\"center\">\n  \u003Cimg src=\"images\u002FONjORqk.png\"","donnemartin\u002Fsystem-design-primer 是一个专注于大规模系统设计学习与面试准备的资源库。项目提供了从基础到高级的系统设计知识，包括常用的设计模式、架构原则以及具体的实现案例，采用Python语言编写示例，并附带Anki记忆卡片帮助记忆关键概念。它适合希望提升自身系统设计能力的软件工程师，特别是那些正在为技术面试做准备的人士使用。通过这个项目，用户可以系统地学习如何构建可扩展的应用程序，同时也能针对常见的系统设计面试题目进行有效的练习和准备。",2,"2026-06-01 02:31:52","top_all"]