``` ├── LICENSE ├── README.md ├── diagrams/ ├── interview-template.png ├── system-design-github-logo.png ├── implementations/ ├── java/ ├── consistent_hashing/ ├── ConsistentHashing.java ├── load_balancing_algorithms/ ├── IPHash.java ├── LeastConnections.java ├── LeastResponseTime.java ├── RoundRobin.java ├── WeightedRoundRobin.java ├── rate_limiting/ ├── FixedWindowCounter.java ├── LeakyBucket.java ├── SlidingWindowCounter.java ├── SlidingWindowLog.java ├── TokenBucket.java ├── python/ ├── consistent_hashing/ ├── consistent-hashing.py ├── load_balancing_algorithms/ ├── ip_hash.py ├── least_connections.py ├── least_response_time.py ├── round_robin.py.py ├── weighted_round_robin.py ├── rate_limiting/ ├── fixed_window_counter.py ├── leaky_bucket.py ├── sliding_window_counter.py ├── sliding_window_log.py ├── token_bucket.py ``` ## /LICENSE ``` path="/LICENSE" GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ``` ## /README.md

This repository contains free resources to learn System Design concepts and prepare for interviews. 👉 Subscribe to my [AlgoMaster Newsletter](https://bit.ly/amghsd) and get a **FREE System Design Interview Handbook** in your inbox. ✅ If you are new to System Design, start here: [System Design was HARD until I Learned these 30 Concepts](https://blog.algomaster.io/p/30-system-design-concepts) ## 📌 System Design Key Concepts - [Scalability](https://blog.algomaster.io/p/scalability) - [Availability](https://blog.algomaster.io/p/system-design-what-is-availability) - [CAP Theorem](https://blog.algomaster.io/p/cap-theorem-explained) - [ACID Transactions](https://blog.algomaster.io/p/what-are-acid-transactions-in-databases) - [Consistent Hashing](https://blog.algomaster.io/p/consistent-hashing-explained) - [Rate Limiting](https://blog.algomaster.io/p/rate-limiting-algorithms-explained-with-code) - [SPOF](https://blog.algomaster.io/p/system-design-how-to-avoid-single-point-of-failures) - [Fault Tolerance](https://www.cockroachlabs.com/blog/what-is-fault-tolerance/) - [Consensus Algorithms](https://medium.com/@sourabhatta1819/consensus-in-distributed-system-ac79f8ba2b8c) - [Gossip Protocol](http://highscalability.com/blog/2023/7/16/gossip-protocol-explained.html) - [Service Discovery](https://blog.algomaster.io/p/service-discovery-in-distributed-systems) - [API Design](https://abdulrwahab.medium.com/api-architecture-best-practices-for-designing-rest-apis-bf907025f5f) - [Disaster Recovery](https://cloud.google.com/learn/what-is-disaster-recovery) - [Distributed Tracing](https://www.dynatrace.com/news/blog/what-is-distributed-tracing/) ## 🛠️ System Design Building Blocks - [APIs](https://blog.algomaster.io/p/whats-an-api) - [Content Delivery Network (CDN)](https://blog.algomaster.io/p/content-delivery-networks) - [Proxy vs Reverse Proxy](https://blog.algomaster.io/p/proxy-vs-reverse-proxy-explained) - [Domain Name System (DNS)](https://www.cloudflare.com/learning/dns/what-is-dns/) - [Caching](https://blog.algomaster.io/p/4d7d6f8a-6803-4c7b-85ca-864c87c2cbf2) - [Caching Strategies](https://blog.algomaster.io/p/top-5-caching-strategies-explained) - [Distributed Caching](https://blog.algomaster.io/p/distributed-caching) - [API Gateway](https://blog.algomaster.io/p/what-is-an-api-gateway) - [Load Balancing](https://blog.algomaster.io/p/load-balancing-algorithms-explained-with-code) - [Databases Types](https://blog.algomaster.io/p/15-types-of-databases) - [SQL vs NoSQL](https://blog.algomaster.io/p/sql-vs-nosql-7-key-differences) - [Database Indexes](https://blog.algomaster.io/p/a-detailed-guide-on-database-indexes) - [Consistency Patterns](https://systemdesign.one/consistency-patterns/) - [HeartBeats](https://blog.algomaster.io/p/heartbeats-in-distributed-systems) - [Circuit Breaker](https://medium.com/geekculture/design-patterns-for-microservices-circuit-breaker-pattern-276249ffab33) - [Idempotency](https://blog.algomaster.io/p/idempotency-in-distributed-systems) - [Database Scaling](https://blog.algomaster.io/p/system-design-how-to-scale-a-database) - [Data Replication](https://redis.com/blog/what-is-data-replication/) - [Data Redundancy](https://blog.algomaster.io/p/489440f1-9c80-4241-9ec8-de156964c3b9) - [Database Sharding](https://blog.algomaster.io/p/what-is-database-sharding) - [Database Architectures](https://www.mongodb.com/developer/products/mongodb/active-active-application-architectures/) - [Failover](https://www.druva.com/glossary/what-is-a-failover-definition-and-related-faqs) - [Bloom Filters](https://blog.algomaster.io/p/bloom-filters) - [Message Queues](https://blog.algomaster.io/p/message-queues) - [WebSockets](https://blog.algomaster.io/p/websockets) - [Checksums](https://blog.algomaster.io/p/what-are-checksums) - [Microservices Guidelines](https://newsletter.systemdesign.one/p/netflix-microservices) - [Distributed Locking](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html) ## ⚖️ System Design Tradeoffs - [Top 15 Tradeoffs](https://blog.algomaster.io/p/system-design-top-15-trade-offs) - [Vertical vs Horizontal Scaling](https://blog.algomaster.io/p/system-design-vertical-vs-horizontal-scaling) - [Concurrency vs Parallelism](https://blog.algomaster.io/p/concurrency-vs-parallelism) - [Long Polling vs WebSockets](https://blog.algomaster.io/p/long-polling-vs-websockets) - [Batch vs Stream Processing](https://blog.algomaster.io/p/batch-processing-vs-stream-processing) - [Stateful vs Stateless Design](https://blog.algomaster.io/p/741dff8e-10ea-413e-8dd2-be57434917d2) - [Strong vs Eventual Consistency](https://blog.algomaster.io/p/7d9da525-fe25-4e16-94e8-8056e7c57934) - [Read-Through vs Write-Through Cache](https://blog.algomaster.io/p/59cae60d-9717-4e20-a59e-759e370db4e5) - [Push vs Pull Architecture](https://blog.algomaster.io/p/af5fe2fe-9a4f-4708-af43-184945a243af) - [REST vs RPC](https://blog.algomaster.io/p/106604fb-b746-41de-88fb-60e932b2ff68) - [Synchronous vs. asynchronous communications](https://blog.algomaster.io/p/aec1cebf-6060-45a7-8e00-47364ca70761) - [Latency vs Throughput](https://aws.amazon.com/compare/the-difference-between-throughput-and-latency/) ## 🖇️ System Design Architectural Patterns - [Client-Server Architecture](https://blog.algomaster.io/p/4585cf8e-30a4-4295-936f-308a25cb716c) - [Microservices Architecture](https://medium.com/hashmapinc/the-what-why-and-how-of-a-microservices-architecture-4179579423a9) - [Serverless Architecture](https://blog.algomaster.io/p/2edeb23b-cfa5-4b24-845e-3f6f7a39d162) - [Event-Driven Architecture](https://www.confluent.io/learn/event-driven-architecture/) - [Peer-to-Peer (P2P) Architecture](https://www.spiceworks.com/tech/networking/articles/what-is-peer-to-peer/) ## ✅ How to Answer a System Design Interview Problem ### [Read the Full Article](https://blog.algomaster.io/p/how-to-answer-a-system-design-interview-problem) ## 💻 System Design Interview Problems ### Easy - [Design URL Shortener like TinyURL](https://blog.algomaster.io/p/design-a-url-shortener) - [Design Leaderboard](https://systemdesign.one/leaderboard-system-design/) - [Design Content Delivery Network (CDN)](https://www.youtube.com/watch?v=8zX0rue2Hic) - [Design Parking Garage](https://www.youtube.com/watch?v=NtMvNh0WFVM) - [Design Vending Machine](https://www.youtube.com/watch?v=D0kDMUgo27c) - [Design Distributed Key-Value Store](https://www.youtube.com/watch?v=rnZmdmlR-2M) - [Design Distributed Cache](https://www.youtube.com/watch?v=iuqZvajTOyA) - [Design Authentication System](https://www.youtube.com/watch?v=uj_4vxm9u90) - [Design Unified Payments Interface (UPI)](https://www.youtube.com/watch?v=QpLy0_c_RXk) ### Medium - [Design WhatsApp](https://blog.algomaster.io/p/design-a-chat-application-like-whatsapp) - [Design Spotify](https://blog.algomaster.io/p/design-spotify-system-design-interview) - [Design Distributed Job Scheduler](https://blog.algomaster.io/p/design-a-distributed-job-scheduler) - [Design a Scalable Notification Service](https://blog.algomaster.io/p/design-a-scalable-notification-service) - [Design Instagram](https://www.youtube.com/watch?v=VJpfO6KdyWE) - [Design Tinder](https://www.youtube.com/watch?v=tndzLznxq40) - [Design Facebook](https://www.youtube.com/watch?v=9-hjBGxuiEs) - [Design Twitter](https://www.youtube.com/watch?v=wYk0xPP_P_8) - [Design Reddit](https://www.youtube.com/watch?v=KYExYE_9nIY) - [Design Netflix](https://www.youtube.com/watch?v=psQzyFfsUGU) - [Design Youtube](https://www.youtube.com/watch?v=jPKTo1iGQiE) - [Design Google Search](https://www.youtube.com/watch?v=CeGtqouT8eA) - [Design E-commerce Store like Amazon](https://www.youtube.com/watch?v=EpASu_1dUdE) - [Design TikTok](https://www.youtube.com/watch?v=Z-0g_aJL5Fw) - [Design Shopify](https://www.youtube.com/watch?v=lEL4F_0J3l8) - [Design Airbnb](https://www.youtube.com/watch?v=YyOXt2MEkv4) - [Design Autocomplete for Search Engines](https://www.youtube.com/watch?v=us0qySiUsGU) - [Design Rate Limiter](https://www.youtube.com/watch?v=mhUQe4BKZXs) - [Design Distributed Message Queue like Kafka](https://www.youtube.com/watch?v=iJLL-KPqBpM) - [Design Flight Booking System](https://www.youtube.com/watch?v=qsGcfVGvFSs) - [Design Online Code Editor](https://www.youtube.com/watch?v=07jkn4jUtso) - [Design Stock Exchange System](https://www.youtube.com/watch?v=dUMWMZmMsVE) - [Design an Analytics Platform (Metrics & Logging)](https://www.youtube.com/watch?v=kIcq1_pBQSY) - [Design Payment System](https://www.youtube.com/watch?v=olfaBgJrUBI) - [Design a Digital Wallet](https://www.youtube.com/watch?v=4ijjIUeq6hE) ### Hard - [Design Location Based Service like Yelp](https://www.youtube.com/watch?v=M4lR_Va97cQ) - [Design Uber](https://www.youtube.com/watch?v=umWABit-wbk) - [Design Food Delivery App like Doordash](https://www.youtube.com/watch?v=iRhSAR3ldTw) - [Design Google Docs](https://www.youtube.com/watch?v=2auwirNBvGg) - [Design Google Maps](https://www.youtube.com/watch?v=jk3yvVfNvds) - [Design Zoom](https://www.youtube.com/watch?v=G32ThJakeHk) - [Design Distributed Counter](https://systemdesign.one/distributed-counter-system-design/) - [Design File Sharing System like Dropbox](https://www.youtube.com/watch?v=U0xTu6E2CT8) - [Design Ticket Booking System like BookMyShow](https://www.youtube.com/watch?v=lBAwJgoO3Ek) - [Design Distributed Web Crawler](https://www.youtube.com/watch?v=BKZxZwUgL3Y) - [Design Code Deployment System](https://www.youtube.com/watch?v=q0KGYwNbf-0) - [Design Distributed Cloud Storage like S3](https://www.youtube.com/watch?v=UmWtcgC96X8) - [Design Distributed Locking Service](https://www.youtube.com/watch?v=v7x75aN9liM) - [Design Slack](https://systemdesign.one/slack-architecture/) - [Design Live Comments](https://systemdesign.one/live-comment-system-design/) ## 📚 Books - [Designing Data-Intensive Applications](https://www.amazon.in/dp/9352135245) ## 📩 Newsletters - [AlgoMaster Newsletter](https://blog.algomaster.io/) ## 📺 YouTube Channels - [Tech Dummies Narendra L](https://www.youtube.com/@TechDummiesNarendraL) - [Gaurav Sen](https://www.youtube.com/@gkcs) - [codeKarle](https://www.youtube.com/@codeKarle) - [ByteByteGo](https://www.youtube.com/@ByteByteGo) - [System Design Interview](https://www.youtube.com/@SystemDesignInterview) - [sudoCODE](https://www.youtube.com/@sudocode) - [Success in Tech](https://www.youtube.com/@SuccessinTech/videos) ## 📜 Must-Read Engineering Articles - [How Discord stores trillions of messages](https://discord.com/blog/how-discord-stores-trillions-of-messages) - [Building In-Video Search at Netflix](https://netflixtechblog.com/building-in-video-search-936766f0017c) - [How Canva scaled Media uploads from Zero to 50 Million per Day](https://www.canva.dev/blog/engineering/from-zero-to-50-million-uploads-per-day-scaling-media-at-canva/) - [How Airbnb avoids double payments in a Distributed Payments System](https://medium.com/airbnb-engineering/avoiding-double-payments-in-a-distributed-payments-system-2981f6b070bb) - [Stripe’s payments APIs - The first 10 years](https://stripe.com/blog/payment-api-design) - [Real time messaging at Slack](https://slack.engineering/real-time-messaging/) ## 🗞️ Must-Read Distributed Systems Papers - [Paxos: The Part-Time Parliament](https://lamport.azurewebsites.net/pubs/lamport-paxos.pdf) - [MapReduce: Simplified Data Processing on Large Clusters](https://research.google.com/archive/mapreduce-osdi04.pdf) - [The Google File System](https://static.googleusercontent.com/media/research.google.com/en//archive/gfs-sosp2003.pdf) - [Dynamo: Amazon’s Highly Available Key-value Store](https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf) - [Kafka: a Distributed Messaging System for Log Processing](https://notes.stephenholiday.com/Kafka.pdf) - [Spanner: Google’s Globally-Distributed Database](https://static.googleusercontent.com/media/research.google.com/en//archive/spanner-osdi2012.pdf) - [Bigtable: A Distributed Storage System for Structured Data](https://static.googleusercontent.com/media/research.google.com/en//archive/bigtable-osdi06.pdf) - [ZooKeeper: Wait-free coordination for Internet-scale systems](https://www.usenix.org/legacy/event/usenix10/tech/full_papers/Hunt.pdf) - [The Log-Structured Merge-Tree (LSM-Tree)](https://www.cs.umb.edu/~poneil/lsmtree.pdf) - [The Chubby lock service for loosely-coupled distributed systems](https://static.googleusercontent.com/media/research.google.com/en//archive/chubby-osdi06.pdf) ---

If you find this resource helpful, please give it a star ⭐️ and share it with others!

## /diagrams/interview-template.png Binary file available at https://raw.githubusercontent.com/ashishps1/awesome-system-design-resources/refs/heads/main/diagrams/interview-template.png ## /diagrams/system-design-github-logo.png Binary file available at https://raw.githubusercontent.com/ashishps1/awesome-system-design-resources/refs/heads/main/diagrams/system-design-github-logo.png ## /implementations/java/consistent_hashing/ConsistentHashing.java ```java path="/implementations/java/consistent_hashing/ConsistentHashing.java" package implementations.java.consistent_hashing; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.*; public class ConsistentHashing { private final int numReplicas; // Number of virtual nodes per server private final TreeMap ring; // Hash ring storing virtual nodes private final Set servers; // Set of physical servers public ConsistentHashing(List servers, int numReplicas) { this.numReplicas = numReplicas; this.ring = new TreeMap<>(); this.servers = new HashSet<>(); // Add each server to the hash ring for (String server : servers) { addServer(server); } } private long hash(String key) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(key.getBytes()); byte[] digest = md.digest(); return ((long) (digest[0] & 0xFF) << 24) | ((long) (digest[1] & 0xFF) << 16) | ((long) (digest[2] & 0xFF) << 8) | ((long) (digest[3] & 0xFF)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 algorithm not found", e); } } public void addServer(String server) { servers.add(server); for (int i = 0; i < numReplicas; i++) { long hash = hash(server + "-" + i); // Unique hash for each virtual node ring.put(hash, server); } } public void removeServer(String server) { if (servers.remove(server)) { for (int i = 0; i < numReplicas; i++) { long hash = hash(server + "-" + i); ring.remove(hash); } } } public String getServer(String key) { if (ring.isEmpty()) { return null; // No servers available } long hash = hash(key); // Find the closest server in a clockwise direction Map.Entry entry = ring.ceilingEntry(hash); if (entry == null) { // If we exceed the highest node, wrap around to the first node entry = ring.firstEntry(); } return entry.getValue(); } public static void main(String[] args) { List servers = Arrays.asList("S0", "S1", "S2", "S3", "S4", "S5"); ConsistentHashing ch = new ConsistentHashing(servers, 3); // Step 2: Assign requests (keys) to servers System.out.println("UserA is assigned to: " + ch.getServer("UserA")); System.out.println("UserB is assigned to: " + ch.getServer("UserB")); // Step 3: Add a new server dynamically ch.addServer("S6"); System.out.println("UserA is now assigned to: " + ch.getServer("UserA")); // Step 4: Remove a server dynamically ch.removeServer("S2"); System.out.println("UserB is now assigned to: " + ch.getServer("UserB")); } } ``` ## /implementations/java/load_balancing_algorithms/IPHash.java ```java path="/implementations/java/load_balancing_algorithms/IPHash.java" import java.util.List; public class IPHash { private List servers; public IPHash(List servers) { this.servers = servers; } public String getNextServer(String clientIp) { int hash = clientIp.hashCode(); int serverIndex = Math.abs(hash) % servers.size(); return servers.get(serverIndex); } public static void main(String[] args) { List servers = List.of("Server1", "Server2", "Server3"); IPHash ipHash = new IPHash(servers); List clientIps = List.of("192.168.0.1", "192.168.0.2", "192.168.0.3"); for (String ip : clientIps) { System.out.println(ip + " is mapped to " + ipHash.getNextServer(ip)); } } } ``` ## /implementations/java/load_balancing_algorithms/LeastConnections.java ```java path="/implementations/java/load_balancing_algorithms/LeastConnections.java" import java.util.HashMap; import java.util.List; import java.util.Map; public class LeastConnections { private Map serverConnections; public LeastConnections(List servers) { serverConnections = new HashMap<>(); for (String server : servers) { serverConnections.put(server, 0); } } public String getNextServer() { return serverConnections.entrySet().stream() .min(Map.Entry.comparingByValue()) .map(Map.Entry::getKey) .orElse(null); } public void releaseConnection(String server) { serverConnections.computeIfPresent(server, (k, v) -> v > 0 ? v - 1 : 0); } public static void main(String[] args) { List servers = List.of("Server1", "Server2", "Server3"); LeastConnections leastConnectionsLB = new LeastConnections(servers); for (int i = 0; i < 6; i++) { String server = leastConnectionsLB.getNextServer(); System.out.println(server); leastConnectionsLB.releaseConnection(server); } } } ``` ## /implementations/java/load_balancing_algorithms/LeastResponseTime.java ```java path="/implementations/java/load_balancing_algorithms/LeastResponseTime.java" import java.util.ArrayList; import java.util.List; import java.util.Random; public class LeastResponseTime { private List servers; private List responseTimes; public LeastResponseTime(List servers) { this.servers = servers; this.responseTimes = new ArrayList<>(servers.size()); for (int i = 0; i < servers.size(); i++) responseTimes.add(0.0); } public String getNextServer() { double minResponseTime = responseTimes.get(0); int minIndex = 0; for (int i = 1; i < responseTimes.size(); i++) { if (responseTimes.get(i) < minResponseTime) { minResponseTime = responseTimes.get(i); minIndex = i; } } return servers.get(minIndex); } public void updateResponseTime(String server, double responseTime) { int index = servers.indexOf(server); responseTimes.set(index, responseTime); } public static double simulateResponseTime(String server) { // Simulating response time with random delay Random random = new Random(); double delay = 0.1 + (1.0 - 0.1) * random.nextDouble(); try { Thread.sleep((long) (delay * 1000)); } catch (InterruptedException e) { e.printStackTrace(); } return delay; } public static void main(String[] args) { List servers = List.of("Server1", "Server2", "Server3"); LeastResponseTime leastResponseTimeLB = new LeastResponseTime(servers); for (int i = 0; i < 6; i++) { String server = leastResponseTimeLB.getNextServer(); System.out.println("Request " + (i + 1) + " -> " + server); double responseTime = simulateResponseTime(server); leastResponseTimeLB.updateResponseTime(server, responseTime); System.out.println("Response Time: " + String.format("%.2f", responseTime) + "s"); } } } ``` ## /implementations/java/load_balancing_algorithms/RoundRobin.java ```java path="/implementations/java/load_balancing_algorithms/RoundRobin.java" import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class RoundRobin { private List servers; private AtomicInteger index; public RoundRobin(List servers) { this.servers = servers; this.index = new AtomicInteger(-1); } public String getNextServer() { int currentIndex = index.incrementAndGet() % servers.size(); return servers.get(currentIndex); } public static void main(String[] args) { List servers = List.of("Server1", "Server2", "Server3"); RoundRobin roundRobinLB = new RoundRobin(servers); for (int i = 0; i < 6; i++) { System.out.println(roundRobinLB.getNextServer()); } } } ``` ## /implementations/java/load_balancing_algorithms/WeightedRoundRobin.java ```java path="/implementations/java/load_balancing_algorithms/WeightedRoundRobin.java" import java.util.List; public class WeightedRoundRobin { private List servers; private List weights; private int currentIndex; private int currentWeight; public WeightedRoundRobin(List servers, List weights) { this.servers = servers; this.weights = weights; this.currentIndex = -1; this.currentWeight = 0; } public String getNextServer() { while (true) { currentIndex = (currentIndex + 1) % servers.size(); if (currentIndex == 0) { currentWeight--; if (currentWeight <= 0) { currentWeight = getMaxWeight(); } } if (weights.get(currentIndex) >= currentWeight) { return servers.get(currentIndex); } } } private int getMaxWeight() { return weights.stream().max(Integer::compare).orElse(0); } public static void main(String[] args) { List servers = List.of("Server1", "Server2", "Server3"); List weights = List.of(5, 1, 1); WeightedRoundRobin weightedRoundRobinLB = new WeightedRoundRobin(servers, weights); for (int i = 0; i < 7; i++) { System.out.println(weightedRoundRobinLB.getNextServer()); } } } ``` ## /implementations/java/rate_limiting/FixedWindowCounter.java ```java path="/implementations/java/rate_limiting/FixedWindowCounter.java" package implementations.java.rate_limiting; import java.time.Instant; public class FixedWindowCounter { private final long windowSizeInSeconds; // Size of each window in seconds private final long maxRequestsPerWindow; // Maximum number of requests allowed per window private long currentWindowStart; // Start time of the current window private long requestCount; // Number of requests in the current window public FixedWindowCounter(long windowSizeInSeconds, long maxRequestsPerWindow) { this.windowSizeInSeconds = windowSizeInSeconds; this.maxRequestsPerWindow = maxRequestsPerWindow; this.currentWindowStart = Instant.now().getEpochSecond(); this.requestCount = 0; } public synchronized boolean allowRequest() { long now = Instant.now().getEpochSecond(); // Check if we've moved to a new window if (now - currentWindowStart >= windowSizeInSeconds) { currentWindowStart = now; // Start a new window requestCount = 0; // Reset the count for the new window } if (requestCount < maxRequestsPerWindow) { requestCount++; // Increment the count for this window return true; // Allow the request } return false; // We've exceeded the limit for this window, deny the request } } ``` ## /implementations/java/rate_limiting/LeakyBucket.java ```java path="/implementations/java/rate_limiting/LeakyBucket.java" package implementations.java.rate_limiting; import java.time.Instant; import java.util.LinkedList; import java.util.Queue; public class LeakyBucket { private final long capacity; // Maximum number of requests the bucket can hold private final double leakRate; // Rate at which requests leak out of the bucket (requests per second) private final Queue bucket; // Queue to hold timestamps of requests private Instant lastLeakTimestamp; // Last time we leaked from the bucket public LeakyBucket(long capacity, double leakRate) { this.capacity = capacity; this.leakRate = leakRate; this.bucket = new LinkedList<>(); this.lastLeakTimestamp = Instant.now(); } public synchronized boolean allowRequest() { leak(); // First, leak out any requests based on elapsed time if (bucket.size() < capacity) { bucket.offer(Instant.now()); // Add the new request to the bucket return true; // Allow the request } return false; // Bucket is full, deny the request } private void leak() { Instant now = Instant.now(); long elapsedMillis = now.toEpochMilli() - lastLeakTimestamp.toEpochMilli(); int leakedItems = (int) (elapsedMillis * leakRate / 1000.0); // Calculate how many items should have leaked // Remove the leaked items from the bucket for (int i = 0; i < leakedItems && !bucket.isEmpty(); i++) { bucket.poll(); } lastLeakTimestamp = now; } } ``` ## /implementations/java/rate_limiting/SlidingWindowCounter.java ```java path="/implementations/java/rate_limiting/SlidingWindowCounter.java" package implementations.java.rate_limiting; import java.time.Instant; public class SlidingWindowCounter { private final long windowSizeInSeconds; // Size of the sliding window in seconds private final long maxRequestsPerWindow; // Maximum number of requests allowed in the window private long currentWindowStart; // Start time of the current window private long previousWindowCount; // Number of requests in the previous window private long currentWindowCount; // Number of requests in the current window public SlidingWindowCounter(long windowSizeInSeconds, long maxRequestsPerWindow) { this.windowSizeInSeconds = windowSizeInSeconds; this.maxRequestsPerWindow = maxRequestsPerWindow; this.currentWindowStart = Instant.now().getEpochSecond(); this.previousWindowCount = 0; this.currentWindowCount = 0; } public synchronized boolean allowRequest() { long now = Instant.now().getEpochSecond(); long timePassedInWindow = now - currentWindowStart; // Check if we've moved to a new window if (timePassedInWindow >= windowSizeInSeconds) { previousWindowCount = currentWindowCount; currentWindowCount = 0; currentWindowStart = now; timePassedInWindow = 0; } // Calculate the weighted count of requests double weightedCount = previousWindowCount * ((windowSizeInSeconds - timePassedInWindow) / (double) windowSizeInSeconds) + currentWindowCount; if (weightedCount < maxRequestsPerWindow) { currentWindowCount++; // Increment the count for this window return true; // Allow the request } return false; // We've exceeded the limit, deny the request } } ``` ## /implementations/java/rate_limiting/SlidingWindowLog.java ```java path="/implementations/java/rate_limiting/SlidingWindowLog.java" package implementations.java.rate_limiting; import java.time.Instant; import java.util.LinkedList; import java.util.Queue; public class SlidingWindowLog { private final long windowSizeInSeconds; // Size of the sliding window in seconds private final long maxRequestsPerWindow; // Maximum number of requests allowed in the window private final Queue requestLog; // Log of request timestamps public SlidingWindowLog(long windowSizeInSeconds, long maxRequestsPerWindow) { this.windowSizeInSeconds = windowSizeInSeconds; this.maxRequestsPerWindow = maxRequestsPerWindow; this.requestLog = new LinkedList<>(); } public synchronized boolean allowRequest() { long now = Instant.now().getEpochSecond(); long windowStart = now - windowSizeInSeconds; // Remove timestamps that are outside of the current window while (!requestLog.isEmpty() && requestLog.peek() <= windowStart) { requestLog.poll(); } if (requestLog.size() < maxRequestsPerWindow) { requestLog.offer(now); // Log this request return true; // Allow the request } return false; // We've exceeded the limit for this window, deny the request } } ``` ## /implementations/java/rate_limiting/TokenBucket.java ```java path="/implementations/java/rate_limiting/TokenBucket.java" package implementations.java.rate_limiting; import java.time.Instant; public class TokenBucket { private final long capacity; // Maximum number of tokens the bucket can hold private final double fillRate; // Rate at which tokens are added to the bucket (tokens per second) private double tokens; // Current number of tokens in the bucket private Instant lastRefillTimestamp; // Last time we refilled the bucket public TokenBucket(long capacity, double fillRate) { this.capacity = capacity; this.fillRate = fillRate; this.tokens = capacity; // Start with a full bucket this.lastRefillTimestamp = Instant.now(); } public synchronized boolean allowRequest(int tokens) { refill(); // First, add any new tokens based on elapsed time if (this.tokens < tokens) { return false; // Not enough tokens, deny the request } this.tokens -= tokens; // Consume the tokens return true; // Allow the request } private void refill() { Instant now = Instant.now(); // Calculate how many tokens to add based on the time elapsed double tokensToAdd = (now.toEpochMilli() - lastRefillTimestamp.toEpochMilli()) * fillRate / 1000.0; this.tokens = Math.min(capacity, this.tokens + tokensToAdd); // Add tokens, but don't exceed capacity this.lastRefillTimestamp = now; } } ``` ## /implementations/python/consistent_hashing/consistent-hashing.py ```py path="/implementations/python/consistent_hashing/consistent-hashing.py" import hashlib import bisect class ConsistentHashing: def __init__(self, servers, num_replicas=3): """ Initializes the consistent hashing ring. - servers: List of initial server names (e.g., ["S0", "S1", "S2"]) - num_replicas: Number of virtual nodes per server for better load balancing """ self.num_replicas = num_replicas # Number of virtual nodes per server self.ring = {} # Hash ring storing virtual node mappings self.sorted_keys = [] # Sorted list of hash values (positions) on the ring self.servers = set() # Set of physical servers (used for tracking) # Add each server to the hash ring for server in servers: self.add_server(server) def _hash(self, key): """Computes a hash value for a given key using MD5.""" return int(hashlib.md5(key.encode()).hexdigest(), 16) def add_server(self, server): """ Adds a server to the hash ring along with its virtual nodes. - Each virtual node is a different hash of the server ID to distribute load. - The server is hashed multiple times and placed at different positions. """ self.servers.add(server) for i in range(self.num_replicas): # Creating multiple virtual nodes hash_val = self._hash(f"{server}-{i}") # Unique hash for each virtual node self.ring[hash_val] = server # Map hash to the server bisect.insort(self.sorted_keys, hash_val) # Maintain a sorted list for efficient lookup def remove_server(self, server): """ Removes a server and all its virtual nodes from the hash ring. """ if server in self.servers: self.servers.remove(server) for i in range(self.num_replicas): hash_val = self._hash(f"{server}-{i}") # Remove each virtual node's hash self.ring.pop(hash_val, None) # Delete from hash ring self.sorted_keys.remove(hash_val) # Remove from sorted key list def get_server(self, key): """ Finds the closest server for a given key. - Hash the key to get its position on the ring. - Move clockwise to find the nearest server. - If it exceeds the last node, wrap around to the first node. """ if not self.ring: return None # No servers available hash_val = self._hash(key) # Hash the key index = bisect.bisect(self.sorted_keys, hash_val) % len(self.sorted_keys) # Locate nearest server return self.ring[self.sorted_keys[index]] # Return the assigned server # ----------------- Usage Example ------------------- # Step 1: Initialize Consistent Hashing with servers servers = ["S0", "S1", "S2", "S3", "S4", "S5"] ch = ConsistentHashing(servers) # Step 2: Assign requests (keys) to servers print(ch.get_server("UserA")) # Maps UserA to a server print(ch.get_server("UserB")) # Maps UserB to a server # Step 3: Add a new server dynamically ch.add_server("S6") print(ch.get_server("UserA")) # Might be reassigned if affected # Step 4: Remove a server dynamically ch.remove_server("S2") print(ch.get_server("UserB")) # Might be reassigned if affected ``` ## /implementations/python/load_balancing_algorithms/ip_hash.py ```py path="/implementations/python/load_balancing_algorithms/ip_hash.py" import hashlib class IPHash(): def __init__(self, servers): self.servers = servers def get_next_server(self, client_ip): hash_value = hashlib.md5(client_ip.encode()).hexdigest() index = int(hash_value, 16) % len(self.servers) return self.servers[index] # Example usage servers = ["Server1", "Server2", "Server3"] load_balancer = IPHash(servers) client_ips = ["192.168.0.1", "192.168.0.2", "192.168.0.3", "192.168.0.4"] for ip in client_ips: server = load_balancer.get_next_server(ip) print(f"Client {ip} -> {server}") ``` ## /implementations/python/load_balancing_algorithms/least_connections.py ```py path="/implementations/python/load_balancing_algorithms/least_connections.py" import random class LeastConnections: def __init__(self, servers): self.servers = {server: 0 for server in servers} def get_next_server(self): # Find the minimum number of connections min_connections = min(self.servers.values()) # Get all servers with the minimum number of connections least_loaded_servers = [server for server, connections in self.servers.items() if connections == min_connections] # Select a random server from the least loaded servers selected_server = random.choice(least_loaded_servers) self.servers[selected_server] += 1 return selected_server def release_connection(self, server): if self.servers[server] > 0: self.servers[server] -= 1 # Example usage servers = ["Server1", "Server2", "Server3"] load_balancer = LeastConnections(servers) for i in range(6): server = load_balancer.get_next_server() print(f"Request {i + 1} -> {server}") load_balancer.release_connection(server) ``` ## /implementations/python/load_balancing_algorithms/least_response_time.py ```py path="/implementations/python/load_balancing_algorithms/least_response_time.py" import time import random class LeastResponseTime: def __init__(self, servers): self.servers = servers self.response_times = [0] * len(servers) def get_next_server(self): min_response_time = min(self.response_times) min_index = self.response_times.index(min_response_time) return self.servers[min_index] def update_response_time(self, server, response_time): index = self.servers.index(server) self.response_times[index] = response_time # Simulated server response time function def simulate_response_time(): # Simulating response time with random delay delay = random.uniform(0.1, 1.0) time.sleep(delay) return delay # Example usage servers = ["Server1", "Server2", "Server3"] load_balancer = LeastResponseTime(servers) for i in range(6): server = load_balancer.get_next_server() print(f"Request {i + 1} -> {server}") response_time = simulate_response_time() load_balancer.update_response_time(server, response_time) print(f"Response Time: {response_time:.2f}s") ``` ## /implementations/python/load_balancing_algorithms/round_robin.py.py ```py path="/implementations/python/load_balancing_algorithms/round_robin.py.py" class RoundRobin: def __init__(self, servers): self.servers = servers self.current_index = -1 def get_next_server(self): self.current_index = (self.current_index + 1) % len(self.servers) return self.servers[self.current_index] # Example usage servers = ["Server1", "Server2", "Server3"] load_balancer = RoundRobin(servers) for i in range(6): server = load_balancer.get_next_server() print(f"Request {i + 1} -> {server}") ``` ## /implementations/python/load_balancing_algorithms/weighted_round_robin.py ```py path="/implementations/python/load_balancing_algorithms/weighted_round_robin.py" class WeightedRoundRobin: def __init__(self, servers, weights): self.servers = servers self.weights = weights self.current_index = -1 self.current_weight = 0 def get_next_server(self): while True: self.current_index = (self.current_index + 1) % len(self.servers) if self.current_index == 0: self.current_weight -= 1 if self.current_weight <= 0: self.current_weight = max(self.weights) if self.weights[self.current_index] >= self.current_weight: return self.servers[self.current_index] # Example usage servers = ["Server1", "Server2", "Server3"] weights = [5, 1, 1] load_balancer = WeightedRoundRobin(servers, weights) for i in range(7): server = load_balancer.get_next_server() print(f"Request {i + 1} -> {server}") ``` ## /implementations/python/rate_limiting/fixed_window_counter.py ```py path="/implementations/python/rate_limiting/fixed_window_counter.py" import time class FixedWindowCounter: def __init__(self, window_size, max_requests): self.window_size = window_size # Size of the window in seconds self.max_requests = max_requests # Maximum number of requests per window self.current_window = time.time() // window_size self.request_count = 0 def allow_request(self): current_time = time.time() window = current_time // self.window_size # If we've moved to a new window, reset the counter if window != self.current_window: self.current_window = window self.request_count = 0 # Check if we're still within the limit for this window if self.request_count < self.max_requests: self.request_count += 1 return True return False # Usage example limiter = FixedWindowCounter(window_size=60, max_requests=5) # 5 requests per minute for _ in range(10): print(limiter.allow_request()) # Will print True for the first 5 requests, then False time.sleep(0.1) # Wait a bit between requests time.sleep(60) # Wait for the window to reset print(limiter.allow_request()) # True ``` ## /implementations/python/rate_limiting/leaky_bucket.py ```py path="/implementations/python/rate_limiting/leaky_bucket.py" from collections import deque import time class LeakyBucket: def __init__(self, capacity, leak_rate): self.capacity = capacity # Maximum number of requests in the bucket self.leak_rate = leak_rate # Rate at which requests leak (requests/second) self.bucket = deque() # Queue to hold request timestamps self.last_leak = time.time() # Last time we leaked from the bucket def allow_request(self): now = time.time() # Simulate leaking from the bucket leak_time = now - self.last_leak leaked = int(leak_time * self.leak_rate) if leaked > 0: # Remove the leaked requests from the bucket for _ in range(min(leaked, len(self.bucket))): self.bucket.popleft() self.last_leak = now # Check if there's capacity and add the new request if len(self.bucket) < self.capacity: self.bucket.append(now) return True return False # Usage example limiter = LeakyBucket(capacity=5, leak_rate=1) # 5 requests, leak 1 per second for _ in range(10): print(limiter.allow_request()) # Will print True for the first 5 requests, then False time.sleep(0.1) # Wait a bit between requests time.sleep(1) # Wait for bucket to leak print(limiter.allow_request()) # True ``` ## /implementations/python/rate_limiting/sliding_window_counter.py ```py path="/implementations/python/rate_limiting/sliding_window_counter.py" import time class SlidingWindowCounter: def __init__(self, window_size, max_requests): self.window_size = window_size # Size of the sliding window in seconds self.max_requests = max_requests # Maximum number of requests per window self.current_window = time.time() // window_size self.request_count = 0 self.previous_count = 0 def allow_request(self): now = time.time() window = now // self.window_size # If we've moved to a new window, update the counts if window != self.current_window: self.previous_count = self.request_count self.request_count = 0 self.current_window = window # Calculate the weighted request count window_elapsed = (now % self.window_size) / self.window_size threshold = self.previous_count * (1 - window_elapsed) + self.request_count # Check if we're within the limit if threshold < self.max_requests: self.request_count += 1 return True return False # Usage example limiter = SlidingWindowCounter(window_size=60, max_requests=5) # 5 requests per minute for _ in range(10): print(limiter.allow_request()) # Will print True for the first 5 requests, then gradually become False time.sleep(0.1) # Wait a bit between requests time.sleep(30) # Wait for half the window to pass print(limiter.allow_request()) # Might be True or False depending on the exact timing ``` ## /implementations/python/rate_limiting/sliding_window_log.py ```py path="/implementations/python/rate_limiting/sliding_window_log.py" import time from collections import deque class SlidingWindowLog: def __init__(self, window_size, max_requests): self.window_size = window_size # Size of the sliding window in seconds self.max_requests = max_requests # Maximum number of requests per window self.request_log = deque() # Log to keep track of request timestamps def allow_request(self): now = time.time() # Remove timestamps that are outside the current window while self.request_log and now - self.request_log[0] >= self.window_size: self.request_log.popleft() # Check if we're still within the limit if len(self.request_log) < self.max_requests: self.request_log.append(now) return True return False # Usage example limiter = SlidingWindowLog(window_size=60, max_requests=5) # 5 requests per minute for _ in range(10): print(limiter.allow_request()) # Will print True for the first 5 requests, then False time.sleep(0.1) # Wait a bit between requests time.sleep(60) # Wait for the window to slide print(limiter.allow_request()) # True ``` ## /implementations/python/rate_limiting/token_bucket.py ```py path="/implementations/python/rate_limiting/token_bucket.py" import time class TokenBucket: def __init__(self, capacity, fill_rate): self.capacity = capacity # Maximum number of tokens the bucket can hold self.fill_rate = fill_rate # Rate at which tokens are added (tokens/second) self.tokens = capacity # Current token count, start with a full bucket self.last_time = time.time() # Last time we checked the token count def allow_request(self, tokens=1): now = time.time() # Calculate how many tokens have been added since the last check time_passed = now - self.last_time self.tokens = min(self.capacity, self.tokens + time_passed * self.fill_rate) self.last_time = now # Check if we have enough tokens for this request if self.tokens >= tokens: self.tokens -= tokens return True return False # Usage example limiter = TokenBucket(capacity=10, fill_rate=1) # 10 tokens, refill 1 token per second for _ in range(15): print(limiter.allow_request()) # Will print True for the first 10 requests, then False time.sleep(0.1) # Wait a bit between requests time.sleep(5) # Wait for bucket to refill print(limiter.allow_request()) # True ``` The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.