<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Hiresh Trivedi on Medium]]></title>
        <description><![CDATA[Stories by Hiresh Trivedi on Medium]]></description>
        <link>https://medium.com/@hiresh.at?source=rss-23e3a2b0c3f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xM8KBSOTpkgLOgBB0-Sv3g.jpeg</url>
            <title>Stories by Hiresh Trivedi on Medium</title>
            <link>https://medium.com/@hiresh.at?source=rss-23e3a2b0c3f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:17:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hiresh.at/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Designing a Distributed Rate Limiter — Deep Dive]]></title>
            <link>https://medium.com/wineofbits/designing-a-distributed-rate-limiter-deep-dive-76d7e8d8452d?source=rss-23e3a2b0c3f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/76d7e8d8452d</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[system-design-project]]></category>
            <dc:creator><![CDATA[Hiresh Trivedi]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 15:55:15 GMT</pubDate>
            <atom:updated>2021-08-04T15:55:15.714Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a Distributed Rate Limiter — Deep Dive</h3><h3>Pre-requisite</h3><p>This article follows <a href="https://medium.com/@hiresh.at/designing-a-distributed-rate-limiter-introduction-731afd345a66">Designing a distributed rate limiter — Introduction</a>. The beginning might seem abrupt if the first article is skipped.</p><p>We now have the motivation to implement a rate limiter, discussed many questions that might arise before implementing rate limiters, and had a look at real-world examples where rate limiters saved the day and examples of existing services using rate limiters. We can now have a deep dive into implementation details.</p><h4>Where to place rate limiter in your architecture?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQXK30B3gxgYAQL-KVTy5A.png" /><figcaption>Image courtesy : Microsoft cloud architecture guide</figcaption></figure><p>We can place it in API Gateway, as an external service, or inside your application server. Mostly a matured architecture would be using an API gateway for authentication, IP whitelisting, SSL termination, etc. If we have sufficient control on API gateway we can have our rate limiter inside API Gateway and have a fallback mechanism because they can fail too (<a href="https://searchunifiedcommunications.techtarget.com/news/252495267/Massive-Slack-outage-caused-by-AWS-gateway-failure"><em>Slack outage because of AWS gateway failure</em></a>).</p><p>If we do not want to commit forever to API gateway and decouple rate limiter service we can place it as an external service after API gateway.</p><p>It is important to address the urge to place rate limiter in application container using <a href="https://medium.com/nerd-for-tech/microservice-design-pattern-sidecar-sidekick-pattern-dbcea9bed783">sidecar pattern</a>, arguing that if a threshold is violated we do not proceed with sending requests to the database, cache, or other services, thereby effectively getting rid of invalid requests in less time and not overworking application server, but this defies the core principle of keeping application servers alienated from such requests, to begin with, and thereby allowing more <em>valid</em> user requests to reach our application servers.</p><p>Based on tech stack, control on API gateway, and infrastructure we can decide placing rate limiter at the appropriate level, however, it will be tough to find substantial cons for having a separate service of rate limiter after API gateway.</p><h4>Algorithms to implement rate limiting logic</h4><p>We have various options to select the underlying algorithm, some of them are</p><ul><li>Token bucket algorithm</li><li>Leaky bucket algorithm</li><li>Sliding window counter</li><li>Fixed window counter</li></ul><p>Token bucket algorithm is arguably the most widely used algorithm, we will discuss about Token Buckets here, exclusion of other algorithms here is intentional to keep article brief.</p><h4>Token Bucket Algorithm</h4><p>Identifiers can be user, IP, API path, or any other entity we wish to track request count for.</p><p>we specify 2 parameters :</p><ol><li>Bucket size (maximum number of requests allowed for an identifier)</li><li>Refill rate (refill the bucket with bucket size at every X seconds)</li></ol><p>At each incoming request we check the remaining number of tokens of the identifier, if the remaining number of tokens is above the permitted threshold in the rule, we allow the request else we drop it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*heqi5WacHpyT8fKdvyDmrQ.jpeg" /></figure><p>Finally we schedule a timer that refills the bucket with specified tokens after a constant time interval.</p><h4>Where are the rules to limit requests stored?</h4><p>We will need a specification for threshold of requests allowed for each identifier that gives information like</p><ol><li>How many times a user is allowed to access a premium content for free?</li><li>How many tweets per second a user can tweet?</li></ol><p>There are existing rate limiters which store such configuration in files, we can also have a in-memory cache storing these rules given that these rules wont change frequently.</p><h4>How are the availed request counters for each identifiers stored?</h4><p>We will need to store available tokens for each identifier and update the number of tokens on each identifier request so that when it hits its limit we can identify the same. This seems to be an important decision.</p><p>Using a database might not be the best decision here because of the disk reads, storing the counters in a persistent cache like Redis with inbuilt features like <em>INCR </em>and<em> EXPIRE </em>can substantially reduce latency.</p><h4>How does a client know it is being throttled?</h4><p>Clients can also handle rates at which they send requests if informed about limits. Certain HTTP response headers can be used to achieve this :</p><ol><li><em>X-Ratelimit-Remaining</em>: remaining number of allowed requests in the window</li><li><em>X-Ratelimit-Limit</em>: number of calls client can make in time window</li><li><em>X-Ratelimit-Retry-After</em>: number of seconds to wait</li></ol><p>and others that can help client react accordingly.</p><p>We can now visualize our design as pictured below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bcdcls-gRI3jKBy8HdtJbQ.jpeg" /></figure><h4>Rate limiter in distributed environment</h4><p>Now that we have the design represented in a way that we can scale it further, we need to anticipate any problems that we could face in distributed environment.</p><h4>Synchronization problem or consistency issues</h4><p>Consistency of data might not be maintained if second request of the user comes before the first update is propagated to all the nodes.</p><p>To demonstrate the problem, consider the following events in order</p><p>0. Rule for user — maximum 4 requests allowed per second.</p><ol><li>‘User 1’ sends request to Rate limiter server “A”</li><li>Server “A” updates the counter in <strong>its</strong> Redis cache node, number of tokens is now 3 (was previously 4).</li><li>The same ‘User 1’ again sends request but to server “B” whose Redis cache instance does not have the updated count for this user (user 1), makes the counter 3 (should be 2).</li></ol><p>One solution is to use sticky sessions, the user sends the requests to the same server, but this is not fault-tolerant, and adding or removing servers will cause issues, it is mostly recommended to go for stateless web-tier.</p><p>We can use locks and use gossip protocol to propagate the change to other servers so that when the next request comes every node has updated data, this will increase the inter-service communication and thereby increase latency.</p><p>We can instead have a centralized Redis store and have all the rate limiter servers reach out to the same centralized store, but this does not scale well. Our rate limiter nodes can overwhelm the centralized Redis store.</p><p>As we see, with these approaches we either compensate consistency for low-latency or its inverse.</p><p>We can shard the Redis store based on the identifier and route the requests to the Redis store that has the details for this identifier. This will solve the issue of consistency since requests of a particular identifier will reach only the concerned Redis store and low latency is achieved because there are multiple rate limiter servers. What if a shard fails? We might lose the data for a set of the identifiers, hence we maintain replicas, this is will give us a good balance of low-latency, fault tolerance, and consistency (eventual consistency).</p><p>For possible race conditions please refer to an interesting solution — <a href="https://engineering.classdojo.com/blog/2015/02/06/rolling-rate-limiter/">Better rate limiting with Redis sorted sets</a></p><p>We should now have a decent idea on features, implementation details and high level design of rate limiters and we are now equipped with the basic concepts that can help us find answers if any further curiosity on the topic arises.</p><p>I wish medium had a feature where all the embedded links could be listed at one place in the article, there are some interesting links added in both of my articles, consider this as a reminder to visit them if they were overlooked earlier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76d7e8d8452d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wineofbits/designing-a-distributed-rate-limiter-deep-dive-76d7e8d8452d">Designing a Distributed Rate Limiter — Deep Dive</a> was originally published in <a href="https://medium.com/wineofbits">wineofbits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Distributed Rate Limiter — Part 1]]></title>
            <link>https://medium.com/wineofbits/designing-a-distributed-rate-limiter-introduction-731afd345a66?source=rss-23e3a2b0c3f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/731afd345a66</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[system-design-project]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[Hiresh Trivedi]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 15:54:08 GMT</pubDate>
            <atom:updated>2021-08-05T06:41:27.599Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing a Distributed Rate Limiter — Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*pgJ3Lbla7d_mj25Ve-bs1Q.jpeg" /><figcaption>Neo from matrix limiting bullets</figcaption></figure><h4>What is Rate Limiter?</h4><p>Imagine you have deployed a public API and the users are crazy about the product, it could be</p><ol><li>URL shortening</li><li>Getting the nearest pizza store from the user’s location</li><li>Getting the statistical analysis of a stock</li></ol><p>But you do not have …</p><p>A middleware that can control the rate of the traffic that is being sent to your web servers based on flexible rules. If the specified threshold is violated, it drops or enqueues the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*smqvRy2wWXtZnXeidHE5oQ.png" /><figcaption>Image credit : <a href="https://www.tibco.com/sites/tibco/files/media_entity/2021-04/rate-limiting-diagram.svg">https://www.tibco.com/sites/tibco/files/media_entity/2021-04/rate-limiting-diagram.svg</a></figcaption></figure><p>This rules out malicious requests that can overwork your servers and enable you to distinguish organic requests from automated ones by identifying users’ accounts or IPs that are violating specifications for your API rate limits.</p><h4>Why designing a Rate Limiter is interesting?</h4><p>It is interesting mainly for its span of problems across breadth and depth that it solves while also preventing a DDoS attack. Rate limiters can be used,</p><ol><li>For the client applications of your trading system: allow each client app to only send 5 orders per second</li><li>Throttle number of rewards on payment platform per user per month, or/and a global limit on rewards per user</li><li>For platforms like Medium: allow non-premium users to access only 3 premium stories per month</li><li>Early Fraud detection if possible can be dropped from middleware before reaching the web servers</li></ol><p>As it appears, it needs to handle cases of persisting states of available access counters for months and needs to handle data-intensive bursts of requests with low latency.</p><p>There also can be cases where access restrictions are ‘soft’, eventually serve requests but do not send requests to web servers right away if rules are violated (throttle), adding requests to a queue will also open gates for a back-pressure scenario where your queue is overwhelmed.</p><p>We talk about server-side rate limiters here, but clients can also have rate limiters in place before sending out requests to servers.</p><p>It is also good to know that OWASP security top 10 has a lack of rate limiter at number 4. It’s very pleasing to have a solution that not only secures your service but also improves performance and user experience.</p><h4>Why not just look up docs and use an existing popular rate limiter?</h4><p>Given that the problems rate limiters solve are faced in almost every large-scale distributed system, there are a lot of rate limiters that can do the job.</p><ul><li><a href="https://www.socialmediatoday.com/news/twitter-says-its-smyte-acquisition-has-helped-it-significantly-reduce-crypt/557524/">Smyte (acquired by Twitter) reduced the crypto-scams</a> on Twitter to 5000 per day from 1 million per day by limiting the scam tweets. <a href="https://github.com/smyte/ratelimit">Its Rate limiter</a> is not the core application here but it is crucial for achieving this.</li><li><a href="https://www.youtube.com/watch?v=rZ8mhTMDoCU">Dealing with 30 Million requests</a> using Rate limiting features of <a href="https://github.blog/2021-04-05-how-we-scaled-github-api-sharded-replicated-rate-limiter-redis/">Redis</a></li><li><a href="https://eng.lyft.com/announcing-ratelimit-c2e8f3182555">Lyft had open-sourced its Rate limiter</a> back in 2017.</li></ul><p><a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html">Amazon uses Token Bucket Algorithm</a> to limit requests, so does Stripe. Some say <a href="https://medium.com/@animirr/fixed-window-rate-limiter-is-slightly-better-than-token-bucket-here-is-why-bc769c0bdd9">a fixed window algorithm is better</a>.</p><p>And many more solutions, that can get you going in no time, however, it is very crucial to understand basic working mechanisms and know challenges to anticipate for each of them, with more choices comes the problem of choosing the most suitable choice.</p><p>Hence the scope of this series is to give a detailed account of the design of Rate limiting systems, algorithms used to achieve rate limiting, and CAP challenges in a distributed system.</p><h4>Why not just use server configuration parameters to limit requests?</h4><p>Parameters like max connection and max thread count can tune requests but our requirement simply is a bit customized, these parameters have no knowledge about the user interaction with application logic, imagine if few clients cover the max number of requests threshold, other users will have to simply wait even when existing requests are not justified.</p><p>Load balancers will also distribute requests in round-robin or based on current server load and be agnostic about the application logic on throttling and latency potential of the request.</p><h4>Should we not auto-scale our infrastructure to accommodate all the requests?</h4><p>Apart from the charges that auto-scaling will incur, it is not an instant process, it will still be a possible outage situation while the nodes are added, registered in service discovery and consensus is established on leader, the request rate will have to be insane for this scenario, which typically is… for a worldwide popular service. Snippet from a slack outage report might help.</p><blockquote>The large number of broken instances caused us to hit our pre-configured autoscaling-group size limits, which determine the maximum number of instances in our web tier.</blockquote><blockquote>we couldn’t provision new dashboard service instances because provision-service was overloaded.</blockquote><p>Rate limiters can also control the rate of low priority requests of API and high priority requests, allowing you to drop low priority requests if there are some internal issues and serve high priority requests.</p><h4>Sounds like the rate limiter will be a performance bottleneck since it will check every incoming request, who will limit the requests to the rate limiter?</h4><ul><li>Rate limiter will be deployed in a distributed system, we have multiple nodes of rate limiters receiving requests from load balancer (<a href="https://stackoverflow.com/questions/55201050/what-can-we-do-when-load-balancer-becomes-the-bottleneck">Load Balancer is not a bottleneck because of DNS Load Balancing</a>)</li><li>The number of rate limiter nodes will not be as high as application server nodes as the rate limiter’s capacity to handle requests is substantially higher as it’s not a high latency operation as we will see in our next article.</li></ul><p>The preface, as lengthy as it is, serves the purpose of clarity on deciding when to use a rate limiter and the scenarios that it serves best. We do not want to document, build and test a middleware when we are better off without it or find out that we could have done better. We can now happily proceed to discuss details. <a href="https://medium.com/@hiresh.at/designing-a-distributed-rate-limiter-deep-dive-76d7e8d8452d">Designing a rate limiter — Deep Dive</a></p><p><a href="https://medium.com/wineofbits/designing-a-distributed-rate-limiter-deep-dive-76d7e8d8452d">Designing a Distributed Rate Limiter — Deep Dive</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=731afd345a66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wineofbits/designing-a-distributed-rate-limiter-introduction-731afd345a66">Designing a Distributed Rate Limiter — Part 1</a> was originally published in <a href="https://medium.com/wineofbits">wineofbits</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>