Skip to main content

RateLimitingFilter

https://travis-ci.org/wkeeling/ratelimitingfilter.svg?branch=master https://codecov.io/gh/wkeeling/ratelimitingfilter/branch/master/graph/badge.svg https://img.shields.io/badge/python-2.7%2C%203.4%2C%203.5%2C%203.6%2C%203.7%2C%203.8%2C%203.9-blue.svg https://img.shields.io/pypi/v/ratelimitingfilter.svg https://img.shields.io/pypi/l/ratelimitingfilter.svg

The RateLimitingFilter is a filter for the Python logging system that allows you to restrict the rate at which messages can pass through your logging handlers.

The filter can be useful if you’re using a handler such as Python’s logging.handlers.SMTPHandler to send error notification emails. Error notification emails provide a useful means of keeping an eye on the health of a running system, but these emails have the potential to overload a mailbox if they start arriving in quick succession due to some kind of critical failure.

The RateLimitingFilter can help prevent mailbox overload by throttling messages based on a configurable rate, whilst allowing for periodic bursts of messages which can be a useful indicator that something somewhere has broken.

Compatibility

  • Python 2.7, 3.4+

Installing

$ pip install ratelimitingfilter

or

$ git clone https://github.com/wkeeling/ratelimitingfilter.git
$ cd ratelimitingfilter
$ python setup.py install

Usage

You can rate-limit a logging handler simply by creating a new instance of the RateLimitingFilter and adding it to the handler:

from ratelimitingfilter import RateLimitingFilter

...

ratelimit = RateLimitingFilter()
handler.addFilter(ratelimit)

Creating an instance of the RateLimitingFilter without any arguments like in the example above will restrict the flow of messages to 1 every 30 seconds.

You can customize the flow rate by supplying your own values for the rate, per and burst attributes. For example, to allow a rate of 1 message every 2 minutes with a periodic burst of up to 5 messages:

ratelimit = RateLimitingFilter(rate=1, per=120, burst=5)
handler.addFilter(ratelimit)

SMTPHandler Example

A typical use case may be to throttle error notification emails sent by the logging.handlers.SMTPHandler.

Here’s an example of how you might set that up:

import logging.handlers
import time

from ratelimitingfilter import RateLimitingFilter

logger = logging.getLogger('throttled_smtp_example')

# Create an SMTPHandler
smtp = logging.handlers.SMTPHandler(
    mailhost='smtp.example.com',
    fromaddr='from@example.com',
    toaddrs='to@example.com',
    subject='An error has occurred'
)
smtp.setLevel(logging.ERROR)

# Create a formatter and set it on the handler
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
smtp.setFormatter(formatter)

# Create an instance of the RateLimitingFilter, and add it to the handler
ratelimit = RateLimitingFilter()
smtp.addFilter(ratelimit)

# Add the handler to the logger
logger.addHandler(smtp)

# Logged errors will now be restricted to 1 every 30 seconds
while True:
    logger.error('An error message')
    time.sleep(2)

Advanced Usage

It is possible to pass some additional configuration options to the RateLimitingFilter initializer for further control over message throttling.

Perhaps you want to selectively throttle particular error messages whilst allowing other messages to pass through freely. This might be the case if there is part of the application which you know can generate large volumes of errors, whilst the rest of the application is unlikely to.

One way to achieve this might be to use separate loggers, one configured with rate limiting, one without, for the different parts of the application. Alternatively, you can use a single logger and configure the RateLimitingFilter to match only those messages that you want to throttle.

Applying selective rate limiting allows for constant visbility of lower volume errors whilst keeping the higher volume errors in check.

The RateLimitingFilter supports two ways to selectively throttle messages:

Substring based message throttling

You can pass a list of substrings to the RateLimitingFilter which it will use to match messages to apply to.

config = {'match': ['some error', 'a different error']}

ratelimit = RateLimitingFilter(rate=1, per=60, burst=1, **config)
smtp.addFilter(ratelimit)

# Can be rate limited
logger.error('some error occurred')

# Can be rate limited
logger.error('a different error occurred')

# Will not be rate limited
logger.error('something completely different happened')

Automatic message throttling

This is an experimental feature.

You can let the RateLimitingFilter automatically throttle messages by setting the match option to auto.

config = {'match': 'auto'}
ratelimit = RateLimitingFilter(rate=1, per=60, burst=1, **config)

The filter will then attempt to identify messages based on their content in order to figure out whether to throttle them or not. It will tolerate slight differences in content when identifying messages. So for example, if error messages are being rapidly logged that are the same apart from a timestamp, or perhaps an incrementing id, then these messages will be treated as the same as far as rate limiting is concerned.

License

MIT

Contributing

Feedback and improvements are more than welcome. Please submit a pull request!

https://github.com/wkeeling/ratelimitingfilter

Metadata

Release files for ratelimitingfilter 1.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ratelimitingfilter 1.5
File Size Uploaded
ratelimitingfilter-1.5.tar.gz 6.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for ratelimitingfilter 1.5
File Interpreter ABI Platform
ratelimitingfilter-1.5-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 13.2 kB

Release files / ratelimitingfilter-1.5.tar.gz

Download URL ratelimitingfilter-1.5.tar.gz
Size 6.2 kB
Tags Source
SHA-256 checksum
How to use checksums
1b05934c6de6789c903115542f7f7b9280d12521de3cb3fd66d773c5a12adf15
BLAKE2b-256 checksum
How to use checksums
ccc5c5c8dfb0853ff099ff587b18c931b275f1c2f69ba152b1d01bee796f6dec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.5.0 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.5

Release files / ratelimitingfilter-1.5-py2.py3-none-any.whl

Download URL ratelimitingfilter-1.5-py2.py3-none-any.whl
Size 7.0 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
8be579efdbdb49dee755477a9d9c19994ad246a37438a5e2d06d53b4ea4c2c19
BLAKE2b-256 checksum
How to use checksums
03b6abdc53b97ac051b458b025c7ea66a2aaa686484f596cae6c387a1d6bc63b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.5.0 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.5

Release history Release notifications | RSS feed

This release

1.5 This release

2 release files

1.4

2 release files

1.2

2 release files

1.1

2 release files

1.0

2 release files

0.7

2 release files

0.6

1 release file

0.5

1 release file

0.4

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page