coveooss / spillway

A simple, distributed and flexible rate limiter
MIT License
34 stars 12 forks source link

Add new API for threadsafe tryCall. #48

Closed PrasadPereraCoveo closed 4 years ago

PrasadPereraCoveo commented 4 years ago

This PR contains not a fix but more of a new API that provides same functionality of tryCall with thread safety.

The existing tryCall seems to be not thread safe and can run into race conditions and the limit counter may end up giving unpredictable results. This can be tested with the test method in TryUpdateAndVerifyLimitTest:: tryUpdateAndVerifyLimitMultiThread. The existing issue of the API is that we read the counter value from underling storage and verify if the counter has exceeded the limit and then update the counter later. This is not thread safe as many threads will do the same comparison locally in different times after reading the value.

The solution is to do a setAndGet one time operation of the counter(s) at the storage level. This provides the thread safety as now the storage is responsible of the atomicity of the operation. In Redis storage, this is done using https://redis.io/commands/eval that provides atomicity of multi-operations in elements.

One main difference compared to tryCall in this API is that the final counter value will rather be limit + cost than limit (in general use, limit + 1)

Pros of the new API:

PrasadPereraCoveo commented 4 years ago

@Sytten @putgeminmouth @

Sytten commented 4 years ago

I will do a review over the weekend

dreisch-coveo commented 4 years ago

@MCoulombe727 @dlafreniere Can you please assist in the review and/or recommend others?

PrasadPereraCoveo commented 4 years ago

@MiloszKul

PrasadPereraCoveo commented 4 years ago

Hey @Sytten, I agree that it has a lot of duplicated code and duplicated tests etc. We didn't want to break anything for existing API so that's why ended up adding a new one. I will point to the specific parts of the code that really points to where the fix is done :)

The rest is just the new API code and duplicate tests. We wanted to fix this as a part of our findings while integrating of the Spillway library in one of our services.

PrasadPereraCoveo commented 4 years ago

👋 @Sytten @putgeminmouth @MCoulombe727 @dlafreniere @dreisch-coveo I would like to get some views on this. Currently, I'm looking to add some simple sliding window concepts to this library. And it would be great if this get merged before that. Thx :)

Sytten commented 4 years ago

I really don't have the time to work on this until end of next week sorry.