i was reading alex xu, i did not get good idea about sliding window and sliding window counter. now after i watched your explanation it is crystal clear and with pros and cons. thank you for doing this!!
My implementation takes advantage of Redis expiration.. When a call comes in, I create a record and the increment the value. Consequent calls will increment the value until the quota is reached. If the quota is not reached by the time the record expires, consequential request will cause a creation of new record and restart the counter.. This way I dont need to check and compare dates at any point. Code is very simple. Albeit, I am not maintaining a perpetual quota, I am only preventing abuse, which is really the main gist of request throttling
@varshard03 жыл бұрын
This is the way I implemented for my org also. Simple and served its purpose well.
@shelendrasharma96803 жыл бұрын
how would you manage the concurrancy here in redis.
@bazzalseed2 жыл бұрын
@@shelendrasharma9680 redis is single thread.
@dhruveshkhandelwal81042 жыл бұрын
this is indirectly fixed window counter
@sid007ashish9 ай бұрын
This is fixed window counter only.
@praveenakarapu6 жыл бұрын
Narendra, very informative video, keep it up. About locking in case of distributed token bucket you can use following technique Optimistic locking or conditional put - many no sql databases support conditional put. This is how it works * Read current value, say 9 * You do a conditional put with value 10 only if current value is 9. * When 2 concurrent requests try to update the value to 10, only one of them will succeed and other will fail as current value for that request will be 10.
@prabudasv4 жыл бұрын
Narendra, your video are great resources for learning system design. Your explanation of concepts is crystal clear. Big thumbs up for you
@nikhilchopra92476 жыл бұрын
Good Stuff Naren! Even famous profs are not able to explain this kind of stuff so clearly.
@TechDummiesNarendraL6 жыл бұрын
Thanks
@logeshkumar83335 жыл бұрын
This channel is just hidden Gem!
@RandomShowerThoughts2 жыл бұрын
I think you're easily the best youtuber for system design content
@rabbanishahid3 жыл бұрын
Best explanation, almost searched everywhere for my scenario, but found this tutorial very very helpful, once again thanks man.
@farseenmk3 жыл бұрын
very underrated youtube channel for system design
@terigopula5 жыл бұрын
you have my respect Narendra.. great work! :)
@JoshKemmerer3 жыл бұрын
I love your voice brother. It makes it exciting to listen to what you have to say about this very interesting design topic.
@1qwertyuiop10003 жыл бұрын
I love your cap.. Looks like a trademark for you.. Thanks for all your videos..
@sbylk995 жыл бұрын
Great tutorial. Tricky part comes at 25:12:)
@valeriiryzhuk41265 жыл бұрын
One additional case, were sliding logs should be used: limit a bitrate of video/audio/internet signal. In such case you need to store a packet size with a timestamp
@princenarayana3 жыл бұрын
Sliding window can be optimized by setting the size of the queue to Max Requests allowed and try to remove the old entries only if max size is reached by comparing timestamp
@SanjayKumar-di5db4 жыл бұрын
You can solve this with the help of increment or decrement method on redis which works atomically on any key so there is no chance for data inconsistencies and no need to put any lock 😊
@himanshu1112844 жыл бұрын
2 services firing increment concurrently will still face the same problem, so i think it will not work without locking. Read + Write has to be an atomic transaction.
@SanjayKumar-di5db4 жыл бұрын
@@himanshu111284 in redis increment and decrement methods on id are atomic so no need for lock
@rajsekharmahapatro2 жыл бұрын
@@SanjayKumar-di5db First time i am learning something new by going through KZbin comments bro. Thanks for it man.
@xuanwang74002 жыл бұрын
"compare and set" kind of logic works perfectly without explicit locking in simple operation case. But in complex situation, the app server may need a few requests. e.g. read the data first, the do some processing, then write back. and then two servers can do the same thing with same data at same time, thus race condition.
@Awaarige4 жыл бұрын
Bro, You saved my months. Love from Pakistan
@ishansoni84944 жыл бұрын
Great work Narendra..! I am currently planning to switch jobs and your videos on system design are amazing...!!
@screen1896 жыл бұрын
Hi Narendra - You are doing a good job in your knowledge transfer. I suggest you cover these topics as well - a) Job Scheduler b) Internals of Zoo Keeper c) Dist.Sys concepts like 2PC, 3PC, Paxos d) DB Internals.
@TechDummiesNarendraL6 жыл бұрын
Added to TODO, Thanks
@screen1896 жыл бұрын
Thanks for your response. Looking forward for her videos!!@@TechDummiesNarendraL
@VirgiliuIonescu4 жыл бұрын
For the last example with concurrency. How about optimistic locking on the counter. Number of req has a version. If you try to update from 2 different RL, one of them will have the NoReq version smaller than the current one and will fail. The RL can retry or drop
@r3jk85 жыл бұрын
This video was a clear and concise explanation of these topics! Great job! You have a new subscriber.
@rajeshd73894 жыл бұрын
Narendra L !! This is just superb ... keep going.
@akhashramamurthy87744 жыл бұрын
Thank you Narendra. The incredible content archive that you are building is invaluable. Thank you.
@dbenbasa4 жыл бұрын
For token bucket - why do we need to update the timestamp (and not only the counter) when we are within the same minute, e.g. from 11:01:10 to 11:01:15? Why not just upata the timestamp when refilling the bucket, i.e. when we switched to a different minute, e.g.: from 11:01:10 to 11:02:07?
@alivesurvive4713 жыл бұрын
You only set the timestamp on the first connection within the period or if you using something like memcached you can set the instance with a ttl value.
@ajaypuri18376 жыл бұрын
Narendra L! You doing good job! I watched your couple of videos. Keep it up!
@vinodcs802 жыл бұрын
very comprehensive video. Great work. subscribed
@keatmin3 жыл бұрын
Thanks for the great tutorial, but I have a question as how would a rate limit service obtain lock of a record in separate db affect another rate limiter service obtain the count from different db within a node?
@ambujbaranwal93513 ай бұрын
00:04 Rate limiting is essential for managing API usage and protecting against misuse and attacks. 04:46 Rate-limiting algorithm for token management 09:30 The algorithm for managing tokens and requests can be memory efficient but may cause race conditions in a distributed environment. 13:57 Using sliding locks algorithm to calculate the rate in real time 18:28 Implement sliding-window counter for efficient memory usage 22:47 The solution optimizes memory usage by using counters instead of storing every request entry 27:11 Inconsistency in rate limiting leads to exceeding request limits 31:28 Syncing data between distributed systems can result in latency and race conditions.
@rahulsharma50303 жыл бұрын
@31:00 you have confused me here, if we use locks, region 1 will have lock in region 1 redis only. Still regions 2 call can read old data from region 2 redis and allow more requests. R1 should take lock of all regions DB theoretically if u say locking is one way to solve consistency?
@081sidd5 жыл бұрын
at 10:37 video time, you mentioned that race condition may occur because of multiple requests coming from the different or same server. As you said, we are using Redis for this solution. Redis commands are atomic in itself and while executing atomic commands there is no scope of any data races. Did I get something wrong here?
@gxbambu5 жыл бұрын
same question here!
@musheerahmed58155 жыл бұрын
Two request from the same user coming at the same time. Both get the same data one after the other. Both increment the count one after the other. The count ends up incremented only once.
@mukeshbansiwal5 жыл бұрын
@@musheerahmed5815 Use optimistic locking by adding version column to avoid lost update
@vivek98765 жыл бұрын
Because here two operation are required. 1) Get the current counter value 2) And If its less than threshold then increment the counter. For example current counter value is 9 and threshold is 10 and if two request comes at the same time and both request see current value as 9 and so both request allowed but in real case one of the request must fail. You either has to take Lock implementation on Redis or have to write atomic operation using WATCH/MULTI or write LUA script for your usecase.
@faizanfareed90764 жыл бұрын
Using redis lock or lua scripts increases latency to user request.
@dragonmohammad4 жыл бұрын
Distributed Systems, a necessary evil.. very nicely explained Narendra !!
@dev-skills6 жыл бұрын
Redis provides INCR and DECR commands which are atomic operations for increment and decrement of its Integer Data Type. Will this not take care of distributed access without any lock ?
@victoryang77345 жыл бұрын
I think his assumption is redis is seperate
@Priyam_Gupta3 жыл бұрын
Yes this will be taking care as they are atomic.
@abcdef-fo1tf Жыл бұрын
@@victoryang7734 what does separate redis mean. Is distributed redis not a shared cache?
@mszjuliak5 жыл бұрын
What's the difference between token bucket and fixed window? they seem so similar
@mumbaibusa4 жыл бұрын
The key and value stores are different for the two. In the case of the fixed counter, the key is defined by the Userid+minute whereas for token bucket the key is userid. For value the FC is just number of reqs, for token you track the time and the number of requests so the checking algorithm has more to do.
@preety2024 жыл бұрын
Burst problem at boundary seem to exist in token bucket as well right?
@romangavrilovich84534 жыл бұрын
@@preety202 yes
@grantl30324 жыл бұрын
seems they are about the same to be functionally, maybe a bit diff implement wise?
@paraschawla37574 жыл бұрын
token bucket is the number of tokens in a bucket, there is refill() happening in bucket after nth min/sec. Number of tokens represent number of request that can be served. with every new request, it keeps going down...but tokens keep increasing based on ratelimit as well. Fixed window counter is having User+TimeStamp as key and count as value for particular window and then start again.
@amitchaudhary61994 жыл бұрын
Great work Narendra👍👍
@molugueshwar15 жыл бұрын
Hi Narendra, In token bucket scenario above, I would like to add one point that in order to reset the requests count after one minute to 5 again, we have to store the time(start time) of the first request so that we can check the difference of one minute to reset the count
@nikhilneela5 жыл бұрын
Yes, I agree. If you simply reset the tokens to 5 when the minute changes, it would allow more than 5 requests/minute. Storing the start time and always comparing it with the current request time and if the delta is equal to or more than a minute, only then we can reset the tokens. @Eshwar, is this what you meant ?
@molugueshwar15 жыл бұрын
@@nikhilneela yes Nikhil. That's right
@gulati95 жыл бұрын
At 19:18 How can we serve 11 requests , when the limit is set to 10?
@nitinkulkarni79424 жыл бұрын
Exactly. I dont think it will happen
@ShivamSingh-jw8ey4 жыл бұрын
04:15 Rate Limting Algorithms 25:11 Race Conditions in distributed systems
@PankajKumar-mv8pd4 жыл бұрын
One of best explanation, thanks man :)
@DeepakMishra1175 жыл бұрын
At 17:50 and 22:56 do we need to sort the array? Won't the array be already sorted, as the requests are only appending the time at the end of the list?
@mmshaban20025 жыл бұрын
Same question I had in mind
@abcdef-fo1tf Жыл бұрын
Why do you say there's issues of race condition for token bucket but not for later counter methods? What if two requests come in at the same time and they both try to increment requests served?
@cbest36783 жыл бұрын
isnt the token bucket and fixed window has the same problem of boundary request problem... ? since even in token bucket you can request more token in end of the first request window and request more token to the second of the window.?
@helishah67193 жыл бұрын
For the Local Memory solution that you provided, how is it different from the solution that you explained just before (where the rate limiter is connected directly to the Redis)?
@amanshivhare55924 жыл бұрын
So Ideally, Token Bucket can have more request in particular time. Like if 5 request were made on 11:55:00 and the very next minute 11:56:00 5 more request are made, so total 10 request can be made in a minute. (or size of a bucket)? Right?
@IC-kf4mz4 жыл бұрын
Yes. If it's implemented as explained you are right.
@lolnikal685110 ай бұрын
20:36 Sliding Window counter The rate limit is 10R/M While in explanation , he considered 10R/S so please don't get confuse and think he is wrong
@shrimpo64162 жыл бұрын
Perfect! I wish I can give you 1,000,000 likes!
@IC-kf4mz4 жыл бұрын
Token Bucket and Fixed Window counter, what's the difference?
@uditagrawal66033 жыл бұрын
Yes this explanation for token bucket doesn't seem correct as in token bucket tokens are added at a particular rate in a particular window time , also there might be chances of going over rate limit in certain scenarios.
@PABJEEGamer3 жыл бұрын
With token bucket algorithm we have control over cost of each operation(we can associate how many tokens an operation costs), where as in fixed window we dont, since we increase the counter by 1 each time
@abcdef-fo1tf Жыл бұрын
@@uditagrawal6603 why can't we have a set and compare operation on the counter, or just a restriction that it can't go over a certain amount, and have requests try to increment number by 1 and reject them if it can't?
@karthikrangaraju94214 жыл бұрын
The inconsistency problem is basically a common DB problem called "lost update" due to two threads reading committed data concurrently and performing writes without any locks. Solution is to introduce locking to enforce ordering. Or enforce ordering by sticky session at a much higher level
@bhaskargurram944 жыл бұрын
Thanks for the nice explanation. One question - What is the difference between fixed window counter and token bucket? Are they not doing the same?
@paraschawla37574 жыл бұрын
token bucket is the number of tokens in a bucket, there is refill() happening in bucket after nth min/sec. Number of tokens represent number of request that can be served. with every new request, it keeps going down...but tokens keep increasing based on ratelimit as well. Fixed window counter is having User+TimeStamp as key and count as value for particular window and then start again. Essence of both alogos are very different.
@curiousbhartiya84104 жыл бұрын
@@paraschawla3757 But the underlying problem of both algorithms is the same is what the original comment meant. That they both might end up serving twice the amount of the desired RPM.
@PABJEEGamer3 жыл бұрын
With token bucket algorithm we have control over cost of each operation(we can associate how many tokens an operation costs), where as in fixed window we dont, since we increase the counter by 1 each time
@krishankantsharma36554 жыл бұрын
Sir, for amazon any particular series of questions you want to suggest.
@karthikeyaacharya57003 жыл бұрын
why not use cache expiry to set rate limit? If the rate limit is set at 10 rpm, For a user, maintain a key in redis, set the cache expiry to 1 minute. Fetch the user key from redis for every API request, If the key is present, check if the count has exceeded. If yes, block the current request. If the count is under the rate limit, update the count for user. The cache will expire after a minute. Is there any problem with this approach?
@Ghost_18232 жыл бұрын
Your content is good. But please try to change your voice modulation. It really helps for long videos.
@sethuramanramaiah11322 жыл бұрын
Don't the fixed window counter also run into concurrency issue like the first scenario ?
@sivamarun2 жыл бұрын
So if no two request arrive at the same time, then sliding window counter will have the same issues as the sliding window algorithm in terms of memory
@utkarshchugh8686 Жыл бұрын
In sliding window logs, how are we able to serve 11 (requests) in last minute, if we're checking the rate in real time. Ideally it shouldn't allow for more than 10.
@saip71374 жыл бұрын
You have a new subscriber. Thanks for making this video.
@dataguy70134 жыл бұрын
@Naren, even with local memory, you can have inconsistency. It just is a bit faster. Do I have that right?
@Priyam_Gupta3 жыл бұрын
yes it won't work. if we are even talking about updating it all the time its better to rely on redis cluster to do the copy then our application server.
@raghugrinus47793 жыл бұрын
Can you please let us know the books which you have read to prepare for the video?
@pratyushprateek25032 жыл бұрын
In case of token bucket algorithm, isn't Redis thread safe or can't we enforce synchronization using locks if requests from multiple application servers are meant to be served concurrently?
@rahulsharma50304 жыл бұрын
1. The tocken bucket discussed at start will has same problem as fixed window?Like if in a minute at last second 10 request comes and in 1sec of next window,10 more comes,then tocken bucket also will have 20 active request but allowed is 10.Am i correct? 2. In case of sticky session solution, there is still possibility of inconsistency. Consider user1 sends 3 request in parallel and our service can accept parallel requests,then they can read same counter value and the issue persists.And if the same user issues some hundreds of request and it is allowed 100 limit then if all of them read redis at same time then all will get same data.So it is not the case, that there will be 2-3 extra request, i think in worst case the extra requests will be max allowed concurrent connections by the server.Please correct me if i missed anything
@harinale44834 ай бұрын
Hi Narendra, Relaxing Rate Limit and Local Memory + sync service is almost similar because in both the solution we might serve couple of extra request. what is your thought on my understanding?
@sivakumar-wr1hn2 жыл бұрын
in token bucket algorithm, what happens if requests are came at 55th second of previous minute and 5th second of current minute?
@akshaytelang45325 жыл бұрын
can't we use Zookeeper for synchronization to manage requests along multiple regions
@designpathy3 жыл бұрын
If we are using an API Gateway for all the user requests, and redis updates are atomic, still race condition can happen ?
@rushio86732 ай бұрын
the video was good, but i think token bucket wasn't explained clearly, we took example of 5 tokens per minute, but do we update the last request time everytime after receiving the request ? or we just keep the first request time so that we know whether 1 minute is elapsed after the first request, or since which second we started making a request that started getting deducted from the max limit ? for example what if 4 requests were made in the later half of the minute and 4 more requests were made in the first half of the next minute ? in that case we made 8 requests exceeding the threshold limit of 5, no clear explanation threre
@Sudarshansridhar4 жыл бұрын
can we have sync service + memory between RL and Redis/Casandra ? So all RLs will go via sync service to get quick response. Sync service is responsible to write to Redis/Casandra. If sync service is not available, RL will make direct call to Redis/Casandra. Not sure how optimal this change is .
@michael47993 жыл бұрын
For the situation of distributed race limit, even though one user send two requests at the same time in one server, it dosen't mean that the actual two processing threads will deal them serially, so the inconsistency problem seems still exist. I think to address this problem we can make the read and update operation as atomic with redis+Lua.
@prajwal96103 жыл бұрын
Redis does this by having a lock which is already suggested in the video
@rekhakalasare4910 Жыл бұрын
@@prajwal9610 yea but in case of local memory suppose single user two request going to 2 regions and regions local cache first read from db and then update in cache and db. Then also there is inconsistency as both req operating parellely
@shreysom2060 Жыл бұрын
Can't we use a sorted Redis set to avoid the concurrency issue?
@RandomShowerThoughts Жыл бұрын
31:00 and you can't even lock across the nodes. If you are sharding then maybe, but as soon as you introduce replication, I don't think it'll just work like that
@resetengineering2 жыл бұрын
Why are you using two caches? Your sync issues are solved by keeping one single cache. Then, coming to race conditions, redis automatically acquires a lock on the transaction since it is atomic and therefore, the other request(second) should get an updated value. For SPOF on one cache, we can keep a master slave nodes for redis
@shrikantkhadilkar40192 жыл бұрын
Hello Narendra, Fixed window counter looks the same as token bucket for me - only the concept is different but the effect will be the same, right?
@ersinerdem72853 жыл бұрын
so, we are building a web application for example. Where do we put this rate limiter? As an aspect in java, as a cross cutting concern? Or as a server like load balancer in front of the application server?
@vishnusannidi78303 жыл бұрын
Generally, rate limiters, authorization are offloaded to Load balancer/API GW.
@rangak75026 жыл бұрын
Awesome work sir.. 👍🏼
@thejaswiniuttarkar6204 жыл бұрын
the threshold is calculated per second, for example AWS API gateway 5000 req/sec .. we can just declare an Array Queue or Array stack and start pushing elements in to it and keep flushing it every second ... + or - 10/20 request would not matter .. if the stack/Queue fills up it would throw an error and that error could be propagated to the user !!
@mukulchakravarty87886 жыл бұрын
Hi is it possible to lock a key across replicas ? They are essentially copies of each other right ?
@153deep5 жыл бұрын
Consider this scenario for token bucket: We can only serve 5 request/5 min. One request (10.05), Two request(10.06), Two request(10.07) we have served all the 5 requests so at 10.07 we will have 0. Now when we get new request at 10.11 it should be the valid request because request at 10.05 & 10.06 should be removed but as per token bucket it won't be served because 10.07 is set to 0 & will be reset at 10.12
@vaidyanathanpk92215 жыл бұрын
Not really. Read about the token bucket algorithm. Before serving the operation at 10.12, it'll try to figure out the time elapsed so far ( 10.12 - 10:07 ) Then it'll figure out the number of tokens to add for this time elapsed ( For 5 minutes, we need to add 5 tokens ) So before doing the serving calculation, these addition of tokens will be done and then when you do the calculation, you should be able to serve these requests. The key point is maintaining something called as lastUpdateTime in the bucket.
@saurabhchako89 Жыл бұрын
Great video. Well explained.
@feitongyin32915 жыл бұрын
Question about using locks. In example where two requests come in, RL1 gets the lock first, and then "locks" the key. How does it lock the key though such that it somehow impacts RL2? I'd imagine it only has access to the db in its own region (the one on the right on your drawing), so how does it lock the key such that when RL2 access the db in its own region (the one on left), that it knows to wait for the lock to be released? Thanks for the video as always.
@krupananda53502 жыл бұрын
What happens if the rate limiter not working. Does it become a single point of failure?. How do we make sure it wont affect system performance?
@JitendraSarswat4 жыл бұрын
There is one con to all your videos. If you skip 10 sec of this video, you are doomed :-P Exceptional work, Narendra.
@nishathussain36724 жыл бұрын
I love your videos. Thank you for making such detailed videos which explain the concepts so clearly. :)
@anuraggupta68905 жыл бұрын
Narendra from where do you get such a great understanding of system
@rationalthinker3223 Жыл бұрын
Outstanding Explanation
@knimr34 жыл бұрын
Hi Naren, what's the essential differences between sliding window log and leaky bucket. They look like pretty much the same in functionality.
@adityagoel123able3 жыл бұрын
Awesome Narendra..
@OmarGuntaue5 жыл бұрын
Is it ok that the LB is before the RL? Shouldn't be the other way around?
@ashutoshbang58363 жыл бұрын
Great video, keep up the good work :)
@reaganrosario5 жыл бұрын
Why cant we use the distributed counter method that you had explained in some other video? Like having zookeeper manager the counters?
@rbsrafa2 жыл бұрын
Great video, congrats!!
@poojachauhan15094 жыл бұрын
Great work, Searching for System design like leetcode or Hackerank...
@aswinraghuraman78422 жыл бұрын
Is it possible to rate limit at the dns level? That way even if it’s distributed it will be single entry to all requests
@sunny8nits5 жыл бұрын
In case of using locks in distributed system, If RL1 gets lock on redis/Casandra DB instance 1, How will it prevent RL2 to have lock on redis instance two. Since the database is distributed too, each wil have their own lock. Wouldn't RL2 can be able to access Redis instance 2 even while RL1 is having lock on redis instance 1
@mritunjayyadav37884 жыл бұрын
Hi Narendra great work I loved your content but i have one question . why not keep only one Redis DB instance instead of two in that case we dont have to sync them ? or is there any significance of having diff instances of Redis (per LB , RL , App instances) .
@anirbanghosh11762 жыл бұрын
@mritunjay yadav - in ditributed system you cannot have single point of failure
@namanmishra08 Жыл бұрын
That's because the entire point of having multiple regions is to have fault tolerance. For a single region, we can have a primary-secondary model with asynchronous replication between them but for a multi-region setup, each component should have a replica. One approach to solve this is to use distributed locks that Redis provides.
@cantwaittowatch5 жыл бұрын
Well explained Narendra
@abcd122724 жыл бұрын
Could there be race conditions for the window method too?
@ambermani16674 жыл бұрын
32:06 how do we achieve lock for a user in both cache at same time?
@OmprakashYadav-nq8uj4 жыл бұрын
replica cache is used if there is some failure in 1st cache. So l think lock will be on one key itself.
@DeepakMishra1175 жыл бұрын
Is there any way to use sticky session for a user on the seconds level, so that we can use sliding window counter and the nodes can sync themselves over a minute?
@CM2SFL5 жыл бұрын
How can you put a lock in a RL and the other RL cannot access the same key? Are you talking about the distributed lock?
@prasukjain8488 Жыл бұрын
Why he is looking like varun singla sir from Gate smashers , btw nice lecture