Repository: ashishps1/awesome-system-design-resources
Branch: main
Commit: 25724090f7dd
Files: 24
Total size: 76.9 KB
Directory structure:
gitextract_sclv_x77/
├── LICENSE
├── README.md
└── 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
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# Awesome System Design Resources
<p align="center">
<img src="diagrams/system-design-github.png" width="400" height="250">
</p>
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)
## ⚙️ Core Concepts
- [Scalability](https://algomaster.io/learn/system-design/scalability)
- [Availability](https://algomaster.io/learn/system-design/availability)
- [Reliability](https://algomaster.io/learn/system-design/reliability)
- [SPOF](https://algomaster.io/learn/system-design/single-point-of-failure-spof)
- [Latency vs Throughput vs Bandwidth](https://algomaster.io/learn/system-design/latency-vs-throughput)
- [Consistent Hashing](https://algomaster.io/learn/system-design/consistent-hashing)
- [CAP Theorem](https://algomaster.io/learn/system-design/cap-theorem)
- [Failover](https://www.druva.com/glossary/what-is-a-failover-definition-and-related-faqs)
- [Fault Tolerance](https://www.cockroachlabs.com/blog/what-is-fault-tolerance/)
## 🌐 Networking Fundamentals
- [OSI Model](https://algomaster.io/learn/system-design/osi)
- [IP Addresses](https://algomaster.io/learn/system-design/ip-address)
- [Domain Name System (DNS)](https://blog.algomaster.io/p/how-dns-actually-works)
- [Proxy vs Reverse Proxy](https://blog.algomaster.io/p/proxy-vs-reverse-proxy-explained)
- [HTTP/HTTPS](https://algomaster.io/learn/system-design/http-https)
- [TCP vs UDP](https://algomaster.io/learn/system-design/tcp-vs-udp)
- [Load Balancing](https://blog.algomaster.io/p/load-balancing-algorithms-explained-with-code)
- [Checksums](https://algomaster.io/learn/system-design/checksums)
## 🔌 API Fundamentals
- [APIs](https://algomaster.io/learn/system-design/what-is-an-api)
- [API Gateway](https://blog.algomaster.io/p/what-is-an-api-gateway)
- [REST vs GraphQL](https://blog.algomaster.io/p/rest-vs-graphql)
- [WebSockets](https://blog.algomaster.io/p/websockets)
- [Webhooks](https://algomaster.io/learn/system-design/webhooks)
- [Idempotency](https://algomaster.io/learn/system-design/idempotency)
- [Rate limiting](https://blog.algomaster.io/p/rate-limiting-algorithms-explained-with-code)
- [API Design](https://abdulrwahab.medium.com/api-architecture-best-practices-for-designing-rest-apis-bf907025f5f)
## 🗄️ Database Fundamentals
- [ACID Transactions](https://algomaster.io/learn/system-design/acid-transactions)
- [SQL vs NoSQL](https://algomaster.io/learn/system-design/sql-vs-nosql)
- [Database Indexes](https://algomaster.io/learn/system-design/indexing)
- [Database Sharding](https://algomaster.io/learn/system-design/sharding)
- [Data Replication](https://redis.com/blog/what-is-data-replication/)
- [Database Scaling](https://blog.algomaster.io/p/system-design-how-to-scale-a-database)
- [Databases Types](https://blog.algomaster.io/p/15-types-of-databases)
- [Bloom Filters](https://algomaster.io/learn/system-design/bloom-filters)
- [Database Architectures](https://www.mongodb.com/developer/products/mongodb/active-active-application-architectures/)
## ⚡ Caching Fundamentals
- [Caching 101](https://algomaster.io/learn/system-design/what-is-caching)
- [Caching Strategies](https://algomaster.io/learn/system-design/caching-strategies)
- [Cache Eviction Policies](https://blog.algomaster.io/p/7-cache-eviction-strategies)
- [Distributed Caching](https://blog.algomaster.io/p/distributed-caching)
- [Content Delivery Network (CDN)](https://algomaster.io/learn/system-design/content-delivery-network-cdn)
## 🔄 Asynchronous Communication
- [Pub/Sub](https://algomaster.io/learn/system-design/pub-sub)
- [Message Queues](https://algomaster.io/learn/system-design/message-queues)
- [Change Data Capture (CDC)](https://algomaster.io/learn/system-design/change-data-capture-cdc)
## 🧩 Distributed System and Microservices
- [HeartBeats](https://blog.algomaster.io/p/heartbeats-in-distributed-systems)
- [Service Discovery](https://blog.algomaster.io/p/service-discovery-in-distributed-systems)
- [Consensus Algorithms](https://medium.com/@sourabhatta1819/consensus-in-distributed-system-ac79f8ba2b8c)
- [Distributed Locking](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html)
- [Gossip Protocol](http://highscalability.com/blog/2023/7/16/gossip-protocol-explained.html)
- [Circuit Breaker](https://medium.com/geekculture/design-patterns-for-microservices-circuit-breaker-pattern-276249ffab33)
- [Disaster Recovery](https://cloud.google.com/learn/what-is-disaster-recovery)
- [Distributed Tracing](https://www.dynatrace.com/news/blog/what-is-distributed-tracing/)
## 🖇️ Architectural Patterns
- [Client-Server Architecture](https://algomaster.io/learn/system-design/client-server-architecture)
- [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/)
## ⚖️ System Design Tradeoffs
- [Top 15 Tradeoffs](https://blog.algomaster.io/p/system-design-top-15-trade-offs)
- [Vertical vs Horizontal Scaling](https://algomaster.io/learn/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/stateful-vs-stateless-architecture)
- [Strong vs Eventual Consistency](https://blog.algomaster.io/p/strong-vs-eventual-consistency)
- [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/)
## ✅ [How to Answer a System Design Interview Problem](https://algomaster.io/learn/system-design-interviews/answering-framework)
## 💻 System Design Interview Problems
### Easy
- [Design URL Shortener like TinyURL](https://algomaster.io/learn/system-design-interviews/design-url-shortener)
- [Design Autocomplete for Search Engines](https://algomaster.io/learn/system-design-interviews/design-instagram)
- [Design Load Balancer](https://algomaster.io/learn/system-design-interviews/design-load-balancer)
- [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://algomaster.io/learn/system-design-interviews/design-whatsapp)
- [Design Spotify](https://algomaster.io/learn/system-design-interviews/design-spotify)
- [Design Instagram](https://algomaster.io/learn/system-design-interviews/design-instagram)
- [Design Notification Service](https://algomaster.io/learn/system-design-interviews/design-notification-service)
- [Design Distributed Job Scheduler](https://blog.algomaster.io/p/design-a-distributed-job-scheduler)
- [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 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 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 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)
## 📇 Courses
- [System Design Fundamentals](https://algomaster.io/learn/system-design/course-introduction)
- [System Design Interviews](https://algomaster.io/learn/system-design-interviews/introduction)
## 📩 Newsletters
- [AlgoMaster Newsletter](https://blog.algomaster.io/)
## 📚 Books
- [Designing Data-Intensive Applications](https://www.amazon.in/dp/9352135245)
## 📺 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)
---
<p align="center">
<i>If you find this resource helpful, please give it a star ⭐️ and share it with others!</i>
</p>
================================================
FILE: 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<Long, String> ring; // Hash ring storing virtual nodes
private final Set<String> servers; // Set of physical servers
public ConsistentHashing(List<String> 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<Long, String> 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<String> 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"));
}
}
================================================
FILE: implementations/java/load_balancing_algorithms/IPHash.java
================================================
import java.util.List;
public class IPHash {
private List<String> servers;
public IPHash(List<String> 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<String> servers = List.of("Server1", "Server2", "Server3");
IPHash ipHash = new IPHash(servers);
List<String> 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));
}
}
}
================================================
FILE: implementations/java/load_balancing_algorithms/LeastConnections.java
================================================
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LeastConnections {
private Map<String, Integer> serverConnections;
public LeastConnections(List<String> 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<String> 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);
}
}
}
================================================
FILE: implementations/java/load_balancing_algorithms/LeastResponseTime.java
================================================
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class LeastResponseTime {
private List<String> servers;
private List<Double> responseTimes;
public LeastResponseTime(List<String> 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<String> 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");
}
}
}
================================================
FILE: implementations/java/load_balancing_algorithms/RoundRobin.java
================================================
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class RoundRobin {
private List<String> servers;
private AtomicInteger index;
public RoundRobin(List<String> 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<String> servers = List.of("Server1", "Server2", "Server3");
RoundRobin roundRobinLB = new RoundRobin(servers);
for (int i = 0; i < 6; i++) {
System.out.println(roundRobinLB.getNextServer());
}
}
}
================================================
FILE: implementations/java/load_balancing_algorithms/WeightedRoundRobin.java
================================================
import java.util.List;
public class WeightedRoundRobin {
private List<String> servers;
private List<Integer> weights;
private int currentIndex;
private int currentWeight;
public WeightedRoundRobin(List<String> servers, List<Integer> 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<String> servers = List.of("Server1", "Server2", "Server3");
List<Integer> weights = List.of(5, 1, 1);
WeightedRoundRobin weightedRoundRobinLB = new WeightedRoundRobin(servers, weights);
for (int i = 0; i < 7; i++) {
System.out.println(weightedRoundRobinLB.getNextServer());
}
}
}
================================================
FILE: 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
}
}
================================================
FILE: 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<Instant> 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;
}
}
================================================
FILE: 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
}
}
================================================
FILE: 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<Long> 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
}
}
================================================
FILE: 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;
}
}
================================================
FILE: 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
================================================
FILE: 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}")
================================================
FILE: 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)
================================================
FILE: 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")
================================================
FILE: 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}")
================================================
FILE: 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}")
================================================
FILE: 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
================================================
FILE: 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
================================================
FILE: 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
================================================
FILE: 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
================================================
FILE: 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
gitextract_sclv_x77/
├── LICENSE
├── README.md
└── 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
SYMBOL INDEX (87 symbols across 22 files)
FILE: implementations/java/consistent_hashing/ConsistentHashing.java
class ConsistentHashing (line 7) | public class ConsistentHashing {
method ConsistentHashing (line 12) | public ConsistentHashing(List<String> servers, int numReplicas) {
method hash (line 23) | private long hash(String key) {
method addServer (line 37) | public void addServer(String server) {
method removeServer (line 45) | public void removeServer(String server) {
method getServer (line 54) | public String getServer(String key) {
method main (line 69) | public static void main(String[] args) {
FILE: implementations/java/load_balancing_algorithms/IPHash.java
class IPHash (line 3) | public class IPHash {
method IPHash (line 6) | public IPHash(List<String> servers) {
method getNextServer (line 10) | public String getNextServer(String clientIp) {
method main (line 16) | public static void main(String[] args) {
FILE: implementations/java/load_balancing_algorithms/LeastConnections.java
class LeastConnections (line 5) | public class LeastConnections {
method LeastConnections (line 8) | public LeastConnections(List<String> servers) {
method getNextServer (line 15) | public String getNextServer() {
method releaseConnection (line 22) | public void releaseConnection(String server) {
method main (line 26) | public static void main(String[] args) {
FILE: implementations/java/load_balancing_algorithms/LeastResponseTime.java
class LeastResponseTime (line 5) | public class LeastResponseTime {
method LeastResponseTime (line 9) | public LeastResponseTime(List<String> servers) {
method getNextServer (line 16) | public String getNextServer() {
method updateResponseTime (line 28) | public void updateResponseTime(String server, double responseTime) {
method simulateResponseTime (line 33) | public static double simulateResponseTime(String server) {
method main (line 45) | public static void main(String[] args) {
FILE: implementations/java/load_balancing_algorithms/RoundRobin.java
class RoundRobin (line 4) | public class RoundRobin {
method RoundRobin (line 8) | public RoundRobin(List<String> servers) {
method getNextServer (line 13) | public String getNextServer() {
method main (line 18) | public static void main(String[] args) {
FILE: implementations/java/load_balancing_algorithms/WeightedRoundRobin.java
class WeightedRoundRobin (line 3) | public class WeightedRoundRobin {
method WeightedRoundRobin (line 9) | public WeightedRoundRobin(List<String> servers, List<Integer> weights) {
method getNextServer (line 16) | public String getNextServer() {
method getMaxWeight (line 31) | private int getMaxWeight() {
method main (line 35) | public static void main(String[] args) {
FILE: implementations/java/rate_limiting/FixedWindowCounter.java
class FixedWindowCounter (line 5) | public class FixedWindowCounter {
method FixedWindowCounter (line 11) | public FixedWindowCounter(long windowSizeInSeconds, long maxRequestsPe...
method allowRequest (line 18) | public synchronized boolean allowRequest() {
FILE: implementations/java/rate_limiting/LeakyBucket.java
class LeakyBucket (line 7) | public class LeakyBucket {
method LeakyBucket (line 13) | public LeakyBucket(long capacity, double leakRate) {
method allowRequest (line 20) | public synchronized boolean allowRequest() {
method leak (line 30) | private void leak() {
FILE: implementations/java/rate_limiting/SlidingWindowCounter.java
class SlidingWindowCounter (line 5) | public class SlidingWindowCounter {
method SlidingWindowCounter (line 12) | public SlidingWindowCounter(long windowSizeInSeconds, long maxRequests...
method allowRequest (line 20) | public synchronized boolean allowRequest() {
FILE: implementations/java/rate_limiting/SlidingWindowLog.java
class SlidingWindowLog (line 7) | public class SlidingWindowLog {
method SlidingWindowLog (line 12) | public SlidingWindowLog(long windowSizeInSeconds, long maxRequestsPerW...
method allowRequest (line 18) | public synchronized boolean allowRequest() {
FILE: implementations/java/rate_limiting/TokenBucket.java
class TokenBucket (line 5) | public class TokenBucket {
method TokenBucket (line 11) | public TokenBucket(long capacity, double fillRate) {
method allowRequest (line 18) | public synchronized boolean allowRequest(int tokens) {
method refill (line 29) | private void refill() {
FILE: implementations/python/consistent_hashing/consistent-hashing.py
class ConsistentHashing (line 4) | class ConsistentHashing:
method __init__ (line 5) | def __init__(self, servers, num_replicas=3):
method _hash (line 21) | def _hash(self, key):
method add_server (line 25) | def add_server(self, server):
method remove_server (line 38) | def remove_server(self, server):
method get_server (line 49) | def get_server(self, key):
FILE: implementations/python/load_balancing_algorithms/ip_hash.py
class IPHash (line 3) | class IPHash():
method __init__ (line 4) | def __init__(self, servers):
method get_next_server (line 7) | def get_next_server(self, client_ip):
FILE: implementations/python/load_balancing_algorithms/least_connections.py
class LeastConnections (line 3) | class LeastConnections:
method __init__ (line 4) | def __init__(self, servers):
method get_next_server (line 7) | def get_next_server(self):
method release_connection (line 17) | def release_connection(self, server):
FILE: implementations/python/load_balancing_algorithms/least_response_time.py
class LeastResponseTime (line 4) | class LeastResponseTime:
method __init__ (line 5) | def __init__(self, servers):
method get_next_server (line 9) | def get_next_server(self):
method update_response_time (line 14) | def update_response_time(self, server, response_time):
function simulate_response_time (line 19) | def simulate_response_time():
FILE: implementations/python/load_balancing_algorithms/round_robin.py.py
class RoundRobin (line 1) | class RoundRobin:
method __init__ (line 2) | def __init__(self, servers):
method get_next_server (line 6) | def get_next_server(self):
FILE: implementations/python/load_balancing_algorithms/weighted_round_robin.py
class WeightedRoundRobin (line 1) | class WeightedRoundRobin:
method __init__ (line 2) | def __init__(self, servers, weights):
method get_next_server (line 8) | def get_next_server(self):
FILE: implementations/python/rate_limiting/fixed_window_counter.py
class FixedWindowCounter (line 3) | class FixedWindowCounter:
method __init__ (line 4) | def __init__(self, window_size, max_requests):
method allow_request (line 10) | def allow_request(self):
FILE: implementations/python/rate_limiting/leaky_bucket.py
class LeakyBucket (line 4) | class LeakyBucket:
method __init__ (line 5) | def __init__(self, capacity, leak_rate):
method allow_request (line 11) | def allow_request(self):
FILE: implementations/python/rate_limiting/sliding_window_counter.py
class SlidingWindowCounter (line 3) | class SlidingWindowCounter:
method __init__ (line 4) | def __init__(self, window_size, max_requests):
method allow_request (line 11) | def allow_request(self):
FILE: implementations/python/rate_limiting/sliding_window_log.py
class SlidingWindowLog (line 4) | class SlidingWindowLog:
method __init__ (line 5) | def __init__(self, window_size, max_requests):
method allow_request (line 10) | def allow_request(self):
FILE: implementations/python/rate_limiting/token_bucket.py
class TokenBucket (line 3) | class TokenBucket:
method __init__ (line 4) | def __init__(self, capacity, fill_rate):
method allow_request (line 10) | def allow_request(self, tokens=1):
Condensed preview — 24 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (83K chars).
[
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 13398,
"preview": "# Awesome System Design Resources\n\n<p align=\"center\">\n <img src=\"diagrams/system-design-github.png\" width=\"400\" height="
},
{
"path": "implementations/java/consistent_hashing/ConsistentHashing.java",
"chars": 2995,
"preview": "package implementations.java.consistent_hashing;\n\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorit"
},
{
"path": "implementations/java/load_balancing_algorithms/IPHash.java",
"chars": 749,
"preview": "import java.util.List;\n\npublic class IPHash {\n private List<String> servers;\n\n public IPHash(List<String> servers)"
},
{
"path": "implementations/java/load_balancing_algorithms/LeastConnections.java",
"chars": 1128,
"preview": "import java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class LeastConnections {\n private Map<"
},
{
"path": "implementations/java/load_balancing_algorithms/LeastResponseTime.java",
"chars": 2007,
"preview": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\npublic class LeastResponseTime {\n privat"
},
{
"path": "implementations/java/load_balancing_algorithms/RoundRobin.java",
"chars": 747,
"preview": "import java.util.List;\nimport java.util.concurrent.atomic.AtomicInteger;\n\npublic class RoundRobin {\n private List<Str"
},
{
"path": "implementations/java/load_balancing_algorithms/WeightedRoundRobin.java",
"chars": 1355,
"preview": "import java.util.List;\n\npublic class WeightedRoundRobin {\n private List<String> servers;\n private List<Integer> we"
},
{
"path": "implementations/java/rate_limiting/FixedWindowCounter.java",
"chars": 1398,
"preview": "package implementations.java.rate_limiting;\n\nimport java.time.Instant;\n\npublic class FixedWindowCounter {\n private fi"
},
{
"path": "implementations/java/rate_limiting/LeakyBucket.java",
"chars": 1564,
"preview": "package implementations.java.rate_limiting;\n\nimport java.time.Instant;\nimport java.util.LinkedList;\nimport java.util.Que"
},
{
"path": "implementations/java/rate_limiting/SlidingWindowCounter.java",
"chars": 1840,
"preview": "package implementations.java.rate_limiting;\n\nimport java.time.Instant;\n\npublic class SlidingWindowCounter {\n private "
},
{
"path": "implementations/java/rate_limiting/SlidingWindowLog.java",
"chars": 1285,
"preview": "package implementations.java.rate_limiting;\n\nimport java.time.Instant;\nimport java.util.LinkedList;\nimport java.util.Que"
},
{
"path": "implementations/java/rate_limiting/TokenBucket.java",
"chars": 1446,
"preview": "package implementations.java.rate_limiting;\n\nimport java.time.Instant;\n\npublic class TokenBucket {\n private final lon"
},
{
"path": "implementations/python/consistent_hashing/consistent-hashing.py",
"chars": 3260,
"preview": "import hashlib\nimport bisect\n\nclass ConsistentHashing:\n def __init__(self, servers, num_replicas=3):\n \"\"\"\n "
},
{
"path": "implementations/python/load_balancing_algorithms/ip_hash.py",
"chars": 569,
"preview": "import hashlib\n\nclass IPHash():\n def __init__(self, servers):\n self.servers = servers\n\n def get_next_server"
},
{
"path": "implementations/python/load_balancing_algorithms/least_connections.py",
"chars": 1021,
"preview": "import random\n\nclass LeastConnections:\n def __init__(self, servers):\n self.servers = {server: 0 for server in "
},
{
"path": "implementations/python/load_balancing_algorithms/least_response_time.py",
"chars": 1073,
"preview": "import time\nimport random\n\nclass LeastResponseTime:\n def __init__(self, servers):\n self.servers = servers\n "
},
{
"path": "implementations/python/load_balancing_algorithms/round_robin.py.py",
"chars": 471,
"preview": "class RoundRobin:\n def __init__(self, servers):\n self.servers = servers\n self.current_index = -1\n\n d"
},
{
"path": "implementations/python/load_balancing_algorithms/weighted_round_robin.py",
"chars": 878,
"preview": "class WeightedRoundRobin:\n def __init__(self, servers, weights):\n self.servers = servers\n self.weights "
},
{
"path": "implementations/python/rate_limiting/fixed_window_counter.py",
"chars": 1175,
"preview": "import time\n\nclass FixedWindowCounter:\n def __init__(self, window_size, max_requests):\n self.window_size = win"
},
{
"path": "implementations/python/rate_limiting/leaky_bucket.py",
"chars": 1336,
"preview": "from collections import deque\nimport time\n\nclass LeakyBucket:\n def __init__(self, capacity, leak_rate):\n self."
},
{
"path": "implementations/python/rate_limiting/sliding_window_counter.py",
"chars": 1493,
"preview": "import time\n\nclass SlidingWindowCounter:\n def __init__(self, window_size, max_requests):\n self.window_size = w"
},
{
"path": "implementations/python/rate_limiting/sliding_window_log.py",
"chars": 1147,
"preview": "import time\nfrom collections import deque\n\nclass SlidingWindowLog:\n def __init__(self, window_size, max_requests):\n "
},
{
"path": "implementations/python/rate_limiting/token_bucket.py",
"chars": 1219,
"preview": "import time\n\nclass TokenBucket:\n def __init__(self, capacity, fill_rate):\n self.capacity = capacity # Maximum"
}
]
About this extraction
This page contains the full source code of the ashishps1/awesome-system-design-resources GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 24 files (76.9 KB), approximately 18.8k tokens, and a symbol index with 87 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.