Skip to content

Use redis as a storage for throttling statistic #330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

andrejromanov
Copy link
Collaborator

No description provided.

@@ -61,6 +62,8 @@ pytz = ">=2020.5"

[tool.poetry.group.dev.dependencies]
setuptools = "^71.1.0"
testcontainers = "^4.10.0"
redis = "^6.2.0"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already specified in non-dev deps

from .throttling import throttling
from .urls import register_url_regexp


def setup():
def setup(redis_throttling_configuration: RedisThrottlingConfiguration):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to extract this to a separate function to make it optional.


def allow_request(self, request: django.http.HttpRequest) -> bool:
ident = _get_ident(request)
key = _get_cache_key(self._throttling.scope, ident)

history = default_cache.get(key, [])
now = time.time()
with self._storage.lock(key, timeout_sec=2):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to avoid locks and rely on Redis atomic operations, something like:

pipe = redis.pipeline()
pipe.zadd(key, {str(now): now})
pipe.zremrangebyscore(key, 0, now - self._throttling.duration)
pipe.zcard(key)
pipe.expire(key, self._throttling.duration)
_, _, count, _ = pipe.execute()

return count <= limit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants