celery-heimdall


Namecelery-heimdall JSON
Version 1.0.1 PyPI version JSON
download
home_pagehttps://github.com/tktech/celery-heimdall
SummaryHelpful celery extensions.
upload_time2024-05-31 17:27:54
maintainerNone
docs_urlNone
authorTyler Kennedy
requires_python<4.0,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # celery-heimdall

[![codecov](https://codecov.io/gh/TkTech/celery-heimdall/branch/main/graph/badge.svg?token=1A2CVHQ25Q)](https://codecov.io/gh/TkTech/celery-heimdall)
![GitHub](https://img.shields.io/github/license/tktech/celery-heimdall)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/celery-heimdall)

Celery Heimdall is a set of common utilities useful for the Celery background
worker framework, built on top of Redis. It's not trying to handle every use
case, but to be an easy, modern, and maintainable drop-in solution for 90% of
projects.

## Features

- Globally unique tasks, allowing only 1 copy of a task to execute at a time, or
  within a time period (ex: "Don't allow queuing until an hour has passed")
- Global rate limiting. Celery has built-in rate limiting, but it's a rate limit
  _per worker_, making it unsuitable for purposes such as limiting requests to
  an API.

## Installation

`pip install celery-heimdall`

## Usage

### Unique Tasks

Imagine you have a task that starts when a user presses a button. This task
takes a long time and a lot of resources to generate a report. You don't want
the user to press the button 10 times and start 10 tasks. In this case, you
want what Heimdall calls a unique task:

```python
from celery import shared_task
from celery_heimdall import HeimdallTask

@shared_task(base=HeimdallTask, heimdall={'unique': True})
def generate_report(customer_id):
    pass
```

All we've done here is change the base Task class that Celery will use to run
the task, and passed in some options for Heimdall to use. This task is now
unique - for the given arguments, only 1 will ever run at the same time.

#### Expiry

What happens if our task dies, or something goes wrong? We might end up in a
situation where our lock never gets cleared, called [deadlock][]. To work around
this, we add a maximum time before the task is allowed to be queued again:


```python
from celery import shared_task
from celery_heimdall import HeimdallTask

@shared_task(
  base=HeimdallTask,
  heimdall={
    'unique': True,
    'unique_timeout': 60 * 60
  }
)
def generate_report(customer_id):
  pass
```

Now, `generate_report` will be allowed to run again in an hour even if the
task got stuck, the worker ran out of memory, the machine burst into flames,
etc...

#### Custom Keys

By default, a hash of the task name and its arguments is used as the lock key.
But this often might not be what you want. What if you only want one report at
a time, even for different customers? Ex:

```python
from celery import shared_task
from celery_heimdall import HeimdallTask

@shared_task(
  base=HeimdallTask,
  heimdall={
    'unique': True,
    'key': lambda args, kwargs: 'generate_report'
  }
)
def generate_report(customer_id):
  pass
```
By specifying our own key function, we can completely customize how we determine
if a task is unique.

#### The Existing Task

By default, if you try to queue up a unique task that is already running,
Heimdall will return the existing task's `AsyncResult`. This lets you write
simple code that doesn't need to care if a task is unique or not. Imagine a
simple API endpoint that starts a report when it's hit, but we only want it
to run one at a time. The below is all you need:

```python
import time
from celery import shared_task
from celery_heimdall import HeimdallTask

@shared_task(base=HeimdallTask, heimdall={'unique': True})
def generate_report(customer_id):
  time.sleep(10)

def my_api_call(customer_id: int):
  return {
    'status': 'RUNNING',
    'task_id': generate_report.delay(customer_id).id
  }
```

Everytime `my_api_call` is called with the same `customer_id`, the same
`task_id` will be returned by `generate_report.delay()` until the original task
has completed.

Sometimes you'll want to catch that the task was already running when you tried
to queue it again. We can tell Heimdall to raise an exception in this case:

```python
import time
from celery import shared_task
from celery_heimdall import HeimdallTask, AlreadyQueuedError


@shared_task(
  base=HeimdallTask,
  heimdall={
    'unique': True,
    'unique_raises': True
  }
)
def generate_report(customer_id):
  time.sleep(10)


def my_api_call(customer_id: int):
  try:
    task = generate_report.delay(customer_id)
    return {'status': 'STARTED', 'task_id': task.id}
  except AlreadyQueuedError as exc:
    return {'status': 'ALREADY_RUNNING', 'task_id': exc.likely_culprit}
```

By setting `unique_raises` to `True` when we define our task, an
`AlreadyQueuedError` will be raised when you try to queue up a unique task
twice. The `AlreadyQueuedError` has two properties:

- `likely_culprit`, which contains the task ID of the already-running task,
- `expires_in`, which is the time remaining (in seconds) before the 
  already-running task is considered to be expired.

#### Unique Interval Task

What if we want the task to only run once in an hour, even if it's finished?
In those cases, we want it to run, but not clear the lock when it's finished:

```python
from celery import shared_task
from celery_heimdall import HeimdallTask

@shared_task(
  base=HeimdallTask,
  heimdall={
    'unique': True,
    'unique_timeout': 60 * 60,
    'unique_wait_for_expiry': True
  }
)
def generate_report(customer_id):
  pass
```

By setting `unique_wait_for_expiry` to `True`, the task will finish, and won't
allow another `generate_report()` to be queued until `unique_timeout` has
passed.

### Rate Limiting

Celery offers rate limiting out of the box. However, this rate limiting applies
on a per-worker basis. There's no reliable way to rate limit a task across all
your workers. Heimdall makes this easy:

```python
from celery import shared_task
from celery_heimdall import HeimdallTask, RateLimit

@shared_task(
  base=HeimdallTask,
  heimdall={
    'rate_limit': RateLimit((2, 60))
  }
)
def download_report_from_amazon(customer_id):
  pass
```

This says "every 60 seconds, only allow this task to run 2 times". If a task
can't be run because it would violate the rate limit, it'll be rescheduled.

It's important to note this does not guarantee that your task will run _exactly_
twice a second, just that it won't run _more_ than twice a second. Tasks are
rescheduled with a random jitter to prevent the [thundering herd][] problem.


#### Dynamic Rate Limiting

Just like you can dynamically provide a key for a task, you can also
dynamically provide a rate limit based off that key.


```python
from celery import shared_task
from celery_heimdall import HeimdallTask, RateLimit


@shared_task(
  base=HeimdallTask,
  heimdall={
    # Provide a lower rate limit for the customer with the ID 10, for everyone
    # else provide a higher rate limit.
    'rate_limit': RateLimit(lambda args: (1, 30) if args[0] == 10 else (2, 30)),
    'key': lambda args, kwargs: f'customer_{args[0]}'
  }
)
def download_report_from_amazon(customer_id):
  pass
```


## Inspirations

These are more mature projects which inspired this library, and which may
support older versions of Celery & Python then this project.

- [celery_once][], which is unfortunately abandoned and the reason this project
  exists.
- [celery_singleton][]
- [This snippet][snip] by Vigrond, and subsequent improvements by various
  contributors.


[celery_once]: https://github.com/cameronmaske/celery-once
[celery_singleton]: https://github.com/steinitzu/celery-singleton
[deadlock]: https://en.wikipedia.org/wiki/Deadlock
[thundering herd]: https://en.wikipedia.org/wiki/Thundering_herd_problem
[snip]: https://gist.github.com/Vigrond/2bbea9be6413415e5479998e79a1b11a
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/tktech/celery-heimdall",
    "name": "celery-heimdall",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Tyler Kennedy",
    "author_email": "tk@tkte.ch",
    "download_url": "https://files.pythonhosted.org/packages/86/e7/162c446d346ad8282581e77238f0a139771811aef67600425fa47ce6d5c0/celery_heimdall-1.0.1.tar.gz",
    "platform": null,
    "description": "# celery-heimdall\n\n[![codecov](https://codecov.io/gh/TkTech/celery-heimdall/branch/main/graph/badge.svg?token=1A2CVHQ25Q)](https://codecov.io/gh/TkTech/celery-heimdall)\n![GitHub](https://img.shields.io/github/license/tktech/celery-heimdall)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/celery-heimdall)\n\nCelery Heimdall is a set of common utilities useful for the Celery background\nworker framework, built on top of Redis. It's not trying to handle every use\ncase, but to be an easy, modern, and maintainable drop-in solution for 90% of\nprojects.\n\n## Features\n\n- Globally unique tasks, allowing only 1 copy of a task to execute at a time, or\n  within a time period (ex: \"Don't allow queuing until an hour has passed\")\n- Global rate limiting. Celery has built-in rate limiting, but it's a rate limit\n  _per worker_, making it unsuitable for purposes such as limiting requests to\n  an API.\n\n## Installation\n\n`pip install celery-heimdall`\n\n## Usage\n\n### Unique Tasks\n\nImagine you have a task that starts when a user presses a button. This task\ntakes a long time and a lot of resources to generate a report. You don't want\nthe user to press the button 10 times and start 10 tasks. In this case, you\nwant what Heimdall calls a unique task:\n\n```python\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask\n\n@shared_task(base=HeimdallTask, heimdall={'unique': True})\ndef generate_report(customer_id):\n    pass\n```\n\nAll we've done here is change the base Task class that Celery will use to run\nthe task, and passed in some options for Heimdall to use. This task is now\nunique - for the given arguments, only 1 will ever run at the same time.\n\n#### Expiry\n\nWhat happens if our task dies, or something goes wrong? We might end up in a\nsituation where our lock never gets cleared, called [deadlock][]. To work around\nthis, we add a maximum time before the task is allowed to be queued again:\n\n\n```python\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask\n\n@shared_task(\n  base=HeimdallTask,\n  heimdall={\n    'unique': True,\n    'unique_timeout': 60 * 60\n  }\n)\ndef generate_report(customer_id):\n  pass\n```\n\nNow, `generate_report` will be allowed to run again in an hour even if the\ntask got stuck, the worker ran out of memory, the machine burst into flames,\netc...\n\n#### Custom Keys\n\nBy default, a hash of the task name and its arguments is used as the lock key.\nBut this often might not be what you want. What if you only want one report at\na time, even for different customers? Ex:\n\n```python\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask\n\n@shared_task(\n  base=HeimdallTask,\n  heimdall={\n    'unique': True,\n    'key': lambda args, kwargs: 'generate_report'\n  }\n)\ndef generate_report(customer_id):\n  pass\n```\nBy specifying our own key function, we can completely customize how we determine\nif a task is unique.\n\n#### The Existing Task\n\nBy default, if you try to queue up a unique task that is already running,\nHeimdall will return the existing task's `AsyncResult`. This lets you write\nsimple code that doesn't need to care if a task is unique or not. Imagine a\nsimple API endpoint that starts a report when it's hit, but we only want it\nto run one at a time. The below is all you need:\n\n```python\nimport time\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask\n\n@shared_task(base=HeimdallTask, heimdall={'unique': True})\ndef generate_report(customer_id):\n  time.sleep(10)\n\ndef my_api_call(customer_id: int):\n  return {\n    'status': 'RUNNING',\n    'task_id': generate_report.delay(customer_id).id\n  }\n```\n\nEverytime `my_api_call` is called with the same `customer_id`, the same\n`task_id` will be returned by `generate_report.delay()` until the original task\nhas completed.\n\nSometimes you'll want to catch that the task was already running when you tried\nto queue it again. We can tell Heimdall to raise an exception in this case:\n\n```python\nimport time\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask, AlreadyQueuedError\n\n\n@shared_task(\n  base=HeimdallTask,\n  heimdall={\n    'unique': True,\n    'unique_raises': True\n  }\n)\ndef generate_report(customer_id):\n  time.sleep(10)\n\n\ndef my_api_call(customer_id: int):\n  try:\n    task = generate_report.delay(customer_id)\n    return {'status': 'STARTED', 'task_id': task.id}\n  except AlreadyQueuedError as exc:\n    return {'status': 'ALREADY_RUNNING', 'task_id': exc.likely_culprit}\n```\n\nBy setting `unique_raises` to `True` when we define our task, an\n`AlreadyQueuedError` will be raised when you try to queue up a unique task\ntwice. The `AlreadyQueuedError` has two properties:\n\n- `likely_culprit`, which contains the task ID of the already-running task,\n- `expires_in`, which is the time remaining (in seconds) before the \n  already-running task is considered to be expired.\n\n#### Unique Interval Task\n\nWhat if we want the task to only run once in an hour, even if it's finished?\nIn those cases, we want it to run, but not clear the lock when it's finished:\n\n```python\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask\n\n@shared_task(\n  base=HeimdallTask,\n  heimdall={\n    'unique': True,\n    'unique_timeout': 60 * 60,\n    'unique_wait_for_expiry': True\n  }\n)\ndef generate_report(customer_id):\n  pass\n```\n\nBy setting `unique_wait_for_expiry` to `True`, the task will finish, and won't\nallow another `generate_report()` to be queued until `unique_timeout` has\npassed.\n\n### Rate Limiting\n\nCelery offers rate limiting out of the box. However, this rate limiting applies\non a per-worker basis. There's no reliable way to rate limit a task across all\nyour workers. Heimdall makes this easy:\n\n```python\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask, RateLimit\n\n@shared_task(\n  base=HeimdallTask,\n  heimdall={\n    'rate_limit': RateLimit((2, 60))\n  }\n)\ndef download_report_from_amazon(customer_id):\n  pass\n```\n\nThis says \"every 60 seconds, only allow this task to run 2 times\". If a task\ncan't be run because it would violate the rate limit, it'll be rescheduled.\n\nIt's important to note this does not guarantee that your task will run _exactly_\ntwice a second, just that it won't run _more_ than twice a second. Tasks are\nrescheduled with a random jitter to prevent the [thundering herd][] problem.\n\n\n#### Dynamic Rate Limiting\n\nJust like you can dynamically provide a key for a task, you can also\ndynamically provide a rate limit based off that key.\n\n\n```python\nfrom celery import shared_task\nfrom celery_heimdall import HeimdallTask, RateLimit\n\n\n@shared_task(\n  base=HeimdallTask,\n  heimdall={\n    # Provide a lower rate limit for the customer with the ID 10, for everyone\n    # else provide a higher rate limit.\n    'rate_limit': RateLimit(lambda args: (1, 30) if args[0] == 10 else (2, 30)),\n    'key': lambda args, kwargs: f'customer_{args[0]}'\n  }\n)\ndef download_report_from_amazon(customer_id):\n  pass\n```\n\n\n## Inspirations\n\nThese are more mature projects which inspired this library, and which may\nsupport older versions of Celery & Python then this project.\n\n- [celery_once][], which is unfortunately abandoned and the reason this project\n  exists.\n- [celery_singleton][]\n- [This snippet][snip] by Vigrond, and subsequent improvements by various\n  contributors.\n\n\n[celery_once]: https://github.com/cameronmaske/celery-once\n[celery_singleton]: https://github.com/steinitzu/celery-singleton\n[deadlock]: https://en.wikipedia.org/wiki/Deadlock\n[thundering herd]: https://en.wikipedia.org/wiki/Thundering_herd_problem\n[snip]: https://gist.github.com/Vigrond/2bbea9be6413415e5479998e79a1b11a",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Helpful celery extensions.",
    "version": "1.0.1",
    "project_urls": {
        "Homepage": "https://github.com/tktech/celery-heimdall",
        "Repository": "https://github.com/tktech/celery-heimdall"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1752e264911b21804b3dada053aa8babb04c1fd1bbef50ae90cc1340adf67b69",
                "md5": "4cb37cf681201c38f3f7ed121e8c37a0",
                "sha256": "f7327f39bbd0242ca45d00c56b8c9021863a44f7a392b5b7e91e09931c13ce85"
            },
            "downloads": -1,
            "filename": "celery_heimdall-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4cb37cf681201c38f3f7ed121e8c37a0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 14730,
            "upload_time": "2024-05-31T17:27:53",
            "upload_time_iso_8601": "2024-05-31T17:27:53.616585Z",
            "url": "https://files.pythonhosted.org/packages/17/52/e264911b21804b3dada053aa8babb04c1fd1bbef50ae90cc1340adf67b69/celery_heimdall-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "86e7162c446d346ad8282581e77238f0a139771811aef67600425fa47ce6d5c0",
                "md5": "c7543d65b278a10f1d0714b764e8f059",
                "sha256": "ab95c44e156b11fb3e0d58d50d1d69af17840e86ccfbaf5dd883c46408040bc7"
            },
            "downloads": -1,
            "filename": "celery_heimdall-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "c7543d65b278a10f1d0714b764e8f059",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 14029,
            "upload_time": "2024-05-31T17:27:54",
            "upload_time_iso_8601": "2024-05-31T17:27:54.611220Z",
            "url": "https://files.pythonhosted.org/packages/86/e7/162c446d346ad8282581e77238f0a139771811aef67600425fa47ce6d5c0/celery_heimdall-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-31 17:27:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "tktech",
    "github_project": "celery-heimdall",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "celery-heimdall"
}
        
Elapsed time: 1.08755s