celery-keepalive 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ from celery_keepalive.bootstep import KeepaliveStep
2
+ from celery_keepalive.channels import VersionChannel
3
+ from celery_keepalive.settings import DEFAULT_PROTECTION_MINUTES
4
+
5
+ __all__ = ["DEFAULT_PROTECTION_MINUTES", "KeepaliveStep", "VersionChannel"]
@@ -0,0 +1,87 @@
1
+ """The ECS agent in each task, which protects the task from scale-in."""
2
+
3
+ import json
4
+ import urllib.request
5
+
6
+ from pydantic import BaseModel
7
+ from pydantic import ConfigDict
8
+ from pydantic import ValidationError
9
+ from pydantic.alias_generators import to_pascal
10
+
11
+ # How long a call to the agent may take before it is given up on, so an agent
12
+ # that never answers can't hold up a job.
13
+ AGENT_TIMEOUT_SECONDS = 2
14
+
15
+
16
+ class EcsAgent:
17
+ """Asks the task's ECS agent to protect the task."""
18
+
19
+ def __init__(self, agent_uri: str, protection_minutes: int) -> None:
20
+ self._protection_url = f"{agent_uri}/task-protection/v1/state"
21
+ self._protection_minutes = protection_minutes
22
+
23
+ def protect(self) -> None:
24
+ """Protects the task for the next protection_minutes, or raises
25
+ ProtectionFailed."""
26
+ body = {
27
+ "ProtectionEnabled": True,
28
+ "ExpiresInMinutes": self._protection_minutes,
29
+ }
30
+ request = urllib.request.Request(
31
+ self._protection_url,
32
+ data=json.dumps(body).encode(),
33
+ headers={"Content-Type": "application/json"},
34
+ method="PUT",
35
+ )
36
+
37
+ try:
38
+ with urllib.request.urlopen(
39
+ request,
40
+ timeout=AGENT_TIMEOUT_SECONDS,
41
+ ) as response:
42
+ reply_json = response.read()
43
+ except OSError as error:
44
+ raise ProtectionFailed(str(error)) from error
45
+
46
+ try:
47
+ reply = ProtectionReply.model_validate_json(reply_json)
48
+ except ValidationError as error:
49
+ raise ProtectionFailed("the agent's reply was not understood") from error
50
+ reply.raise_for_reported_problem()
51
+
52
+
53
+ class ProtectionFailed(Exception):
54
+ """The task is not protected: the agent couldn't be reached, or answered
55
+ but not to say the task is protected."""
56
+
57
+
58
+ class AgentFailure(BaseModel):
59
+ """ECS refused to protect the task, as the agent reports it."""
60
+
61
+ model_config = ConfigDict(alias_generator=to_pascal)
62
+
63
+ reason: str
64
+ detail: str
65
+
66
+
67
+ class AgentError(BaseModel):
68
+ """The agent couldn't ask ECS to protect the task, as it reports it."""
69
+
70
+ model_config = ConfigDict(alias_generator=to_pascal)
71
+
72
+ code: str
73
+ message: str
74
+
75
+
76
+ class ProtectionReply(BaseModel):
77
+ """The agent's reply to a request to protect the task."""
78
+
79
+ failure: AgentFailure | None = None
80
+ error: AgentError | None = None
81
+
82
+ def raise_for_reported_problem(self) -> None:
83
+ """The agent reports a problem as a "failure" or an "error"."""
84
+ if self.failure is not None:
85
+ raise ProtectionFailed(f"{self.failure.reason}: {self.failure.detail}")
86
+ if self.error is not None:
87
+ raise ProtectionFailed(f"{self.error.code}: {self.error.message}")
@@ -0,0 +1,83 @@
1
+ import logging
2
+ import os
3
+ from typing import Protocol
4
+
5
+ from celery import Celery
6
+ from celery import bootsteps
7
+ from celery.signals import task_postrun
8
+ from celery.signals import task_prerun
9
+
10
+ from celery_keepalive.agent import EcsAgent
11
+ from celery_keepalive.draining import Consumer
12
+ from celery_keepalive.draining import Draining
13
+ from celery_keepalive.renewals import JobRenewals
14
+ from celery_keepalive.settings import settings
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class Worker(Protocol):
20
+ """The worker Celery builds the step with. The step reads its app config,
21
+ and drains its consumer."""
22
+
23
+ @property
24
+ def app(self) -> Celery: ...
25
+
26
+ @property
27
+ def consumer(self) -> Consumer: ...
28
+
29
+
30
+ class KeepaliveStep(bootsteps.StartStopStep):
31
+ """Keeps ECS from stopping the worker's task while it is running a job."""
32
+
33
+ def __init__(self, worker: Worker, **kwargs: object) -> None:
34
+ configured = settings(worker.app)
35
+ # Draining, once the worker has a version to drain by.
36
+ self._draining: Draining | None = None
37
+ protection_minutes = configured.keepalive_protection_minutes
38
+ check_interval_seconds = configured.keepalive_check_interval
39
+
40
+ agent_uri = os.environ.get("ECS_AGENT_URI")
41
+ if agent_uri is None:
42
+ logger.info("celery-keepalive disabled: ECS_AGENT_URI is not set")
43
+ return
44
+
45
+ version = configured.keepalive_version()
46
+ logger.info(
47
+ "celery-keepalive enabled: protecting for %d minutes, renewing "
48
+ "every %g seconds, %s",
49
+ protection_minutes,
50
+ check_interval_seconds,
51
+ "with no version" if version is None else f"as version {version}",
52
+ )
53
+
54
+ self._renewals = JobRenewals(
55
+ EcsAgent(agent_uri, protection_minutes),
56
+ protection_minutes,
57
+ check_interval_seconds,
58
+ )
59
+ task_prerun.connect(self._start_protecting)
60
+ task_postrun.connect(self._stop_protecting)
61
+
62
+ if version is None:
63
+ return
64
+ self._draining = Draining(
65
+ version,
66
+ configured.keepalive_version_channel(worker.app),
67
+ worker,
68
+ )
69
+ self._draining.start()
70
+
71
+ def stop(self, worker: Worker) -> None:
72
+ """Takes on no new jobs once the worker stops, and stops hearing
73
+ versions. Jobs still running, as in a warm shutdown, keep renewing
74
+ until they finish."""
75
+ task_prerun.disconnect(self._start_protecting)
76
+ if self._draining is not None:
77
+ self._draining.stop()
78
+
79
+ def _start_protecting(self, task_id: str, **kwargs: object) -> None:
80
+ self._renewals.start(task_id)
81
+
82
+ def _stop_protecting(self, task_id: str, **kwargs: object) -> None:
83
+ self._renewals.finish(task_id)
@@ -0,0 +1,88 @@
1
+ """Channels workers announce their versions to each other through, for
2
+ keepalive_version_channel."""
3
+
4
+ from collections.abc import Callable
5
+ from typing import Protocol
6
+
7
+ from celery import Celery
8
+ from celery.utils.dispatch import Signal
9
+ from celery.worker.control import control_command
10
+
11
+ # The remote control command a worker broadcasts to announce its version.
12
+ VERSION_ANNOUNCED = "keepalive_version_announced"
13
+
14
+ # Sent, with the app as sender, when a worker hears another announce its
15
+ # version over remote control.
16
+ version_heard = Signal(name="keepalive_version_heard")
17
+
18
+
19
+ class VersionChannel(Protocol):
20
+ """What workers announce their versions to each other through. Built
21
+ with the worker's Celery app, once per worker, as it starts."""
22
+
23
+ def announce(self, version: str) -> None:
24
+ """Tell the other workers this worker's version."""
25
+
26
+ def listen(self, on_version: Callable[[str], None]) -> None:
27
+ """Call on_version with every version heard from now on."""
28
+
29
+ def close(self) -> None:
30
+ """Stop listening: the worker is stopping."""
31
+
32
+
33
+ class RemoteControlChannel(VersionChannel):
34
+ """Announces and hears versions over the broker, with Celery's remote
35
+ control."""
36
+
37
+ def __init__(self, app: Celery) -> None:
38
+ self._app = app
39
+ # The signal receivers listen connected, for close to disconnect.
40
+ self._receivers: list[Callable[..., None]] = []
41
+
42
+ def announce(self, version: str) -> None:
43
+ """Tells every worker on the broker this worker's version."""
44
+ self._app.control.broadcast(
45
+ VERSION_ANNOUNCED,
46
+ arguments={"version": version},
47
+ )
48
+
49
+ def listen(self, on_version: Callable[[str], None]) -> None:
50
+ """Calls on_version with every version this worker hears."""
51
+
52
+ def receive(sender: Celery, version: str, **kwargs: object) -> None:
53
+ on_version(version)
54
+
55
+ # Held strongly, since nothing else keeps receive alive.
56
+ version_heard.connect(receive, sender=self._app, weak=False)
57
+ self._receivers.append(receive)
58
+
59
+ def close(self) -> None:
60
+ """Stops hearing versions: the worker is stopping."""
61
+ for receive in self._receivers:
62
+ version_heard.disconnect(receive, sender=self._app)
63
+ self._receivers.clear()
64
+
65
+
66
+ class ControlConsumer(Protocol):
67
+ """The worker's consumer, as a remote control command sees it."""
68
+
69
+ @property
70
+ def app(self) -> Celery: ...
71
+
72
+
73
+ class ControlState(Protocol):
74
+ """What Celery passes a remote control command about the worker."""
75
+
76
+ @property
77
+ def consumer(self) -> ControlConsumer: ...
78
+
79
+
80
+ @control_command(name=VERSION_ANNOUNCED)
81
+ def version_announced(
82
+ state: ControlState,
83
+ version: str,
84
+ **kwargs: object,
85
+ ) -> dict[str, str]:
86
+ """Passes a version another worker announced to this worker's listeners."""
87
+ version_heard.send(sender=state.consumer.app, version=version)
88
+ return {"ok": f"heard version {version}"}
@@ -0,0 +1,84 @@
1
+ """Stopping old workers taking new jobs once a newer version has started."""
2
+
3
+ import logging
4
+ from collections.abc import Callable
5
+ from collections.abc import Sequence
6
+ from typing import Protocol
7
+
8
+ import kombu
9
+ from celery import Celery
10
+
11
+ from celery_keepalive.channels import VersionChannel
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class TaskConsumer(Protocol):
17
+ """The consumer's kombu consumer; draining reads the queues it takes
18
+ jobs from."""
19
+
20
+ @property
21
+ def queues(self) -> Sequence[kombu.Queue]: ...
22
+
23
+
24
+ class Consumer(Protocol):
25
+ """The worker's consumer, which takes jobs from the broker."""
26
+
27
+ @property
28
+ def app(self) -> Celery: ...
29
+
30
+ @property
31
+ def task_consumer(self) -> TaskConsumer: ...
32
+
33
+ def call_soon(self, callback: Callable[..., object], *args: object) -> object: ...
34
+
35
+ def cancel_task_queue(self, queue: str) -> None: ...
36
+
37
+
38
+ class ConsumingWorker(Protocol):
39
+ """A worker, whose consumer draining stops."""
40
+
41
+ @property
42
+ def consumer(self) -> Consumer: ...
43
+
44
+
45
+ class Draining:
46
+ """Announces the worker's version, and stops the worker taking new jobs
47
+ when it hears another."""
48
+
49
+ def __init__(
50
+ self,
51
+ version: str,
52
+ channel: VersionChannel,
53
+ worker: ConsumingWorker,
54
+ ) -> None:
55
+ self._version = version
56
+ self._channel = channel
57
+ self._worker = worker
58
+
59
+ def start(self) -> None:
60
+ """Tells the other workers this worker's version, and listens for
61
+ theirs."""
62
+ self._channel.announce(self._version)
63
+ self._channel.listen(self._on_version)
64
+
65
+ def stop(self) -> None:
66
+ """Stops listening: the worker is stopping."""
67
+ self._channel.close()
68
+
69
+ def _on_version(self, heard_version: str) -> None:
70
+ if heard_version == self._version:
71
+ return
72
+ logger.info(
73
+ "celery-keepalive draining: heard version %s, and this worker is "
74
+ "version %s, so it takes no new jobs",
75
+ heard_version,
76
+ self._version,
77
+ )
78
+ stop_taking_jobs(self._worker.consumer)
79
+
80
+
81
+ def stop_taking_jobs(consumer: Consumer) -> None:
82
+ """Stops the consumer taking jobs from any of its queues."""
83
+ for queue in consumer.task_consumer.queues:
84
+ consumer.call_soon(consumer.cancel_task_queue, queue.name)
File without changes
@@ -0,0 +1,79 @@
1
+ """Keeping the task protected for as long as each job runs."""
2
+
3
+ import logging
4
+ import threading
5
+ from typing import Protocol
6
+
7
+ from celery_keepalive.agent import ProtectionFailed
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class Protector(Protocol):
13
+ """Protects the task for the protection period, or raises
14
+ ProtectionFailed."""
15
+
16
+ def protect(self) -> None: ...
17
+
18
+
19
+ class JobRenewals:
20
+ """Protects the task as each job starts, then renews the protection every
21
+ check interval, on a thread of the job's own, until the job finishes."""
22
+
23
+ def __init__(
24
+ self,
25
+ protector: Protector,
26
+ protection_minutes: int,
27
+ check_interval_seconds: float,
28
+ ) -> None:
29
+ self._protector = protector
30
+ self._protection_minutes = protection_minutes
31
+ self._check_interval_seconds = check_interval_seconds
32
+ # Each running job's "finished" flag, by the task id Celery gives it.
33
+ self._jobs_finished: dict[str, threading.Event] = {}
34
+
35
+ def start(self, task_id: str) -> None:
36
+ """Protects the task for the job, and keeps renewing until it
37
+ finishes."""
38
+ self._protect(task_id)
39
+
40
+ job_finished = threading.Event()
41
+ self._jobs_finished[task_id] = job_finished
42
+ threading.Thread(
43
+ target=self._renew_until,
44
+ args=(task_id, job_finished),
45
+ daemon=True,
46
+ ).start()
47
+
48
+ def finish(self, task_id: str) -> None:
49
+ """Stops renewing for the job. Its protection then runs out on its
50
+ own."""
51
+ self._jobs_finished.pop(task_id).set()
52
+ logger.debug(
53
+ "celery-keepalive stopped renewing for job %s: the task's protection "
54
+ "runs out within %d minutes, unless another job renews it",
55
+ task_id,
56
+ self._protection_minutes,
57
+ )
58
+
59
+ def _renew_until(self, task_id: str, job_finished: threading.Event) -> None:
60
+ while not job_finished.wait(self._check_interval_seconds):
61
+ self._protect(task_id)
62
+
63
+ def _protect(self, task_id: str) -> None:
64
+ """If protecting fails, the job runs regardless and the next check
65
+ tries again."""
66
+ try:
67
+ self._protector.protect()
68
+ except ProtectionFailed as error:
69
+ logger.warning(
70
+ "celery-keepalive could not protect the task for job %s: %s",
71
+ task_id,
72
+ error,
73
+ )
74
+ return
75
+ logger.debug(
76
+ "celery-keepalive protected the task for %d minutes, for job %s",
77
+ self._protection_minutes,
78
+ task_id,
79
+ )
@@ -0,0 +1,73 @@
1
+ """celery-keepalive's settings, read from the Celery config and checked."""
2
+
3
+ from collections.abc import Callable
4
+ from typing import Self
5
+
6
+ from celery import Celery
7
+ from celery.exceptions import ImproperlyConfigured
8
+ from pydantic import BaseModel
9
+ from pydantic import ConfigDict
10
+ from pydantic import Field
11
+ from pydantic import ImportString
12
+ from pydantic import ValidationError
13
+ from pydantic import model_validator
14
+
15
+ from celery_keepalive.channels import RemoteControlChannel
16
+ from celery_keepalive.channels import VersionChannel
17
+ from celery_keepalive.versions import from_git_commit
18
+
19
+ DEFAULT_PROTECTION_MINUTES = 2
20
+
21
+ # The protection periods ECS accepts, in whole minutes: up to 48 hours.
22
+ MIN_PROTECTION_MINUTES = 1
23
+ MAX_PROTECTION_MINUTES = 2880
24
+
25
+ DEFAULT_CHECK_INTERVAL_SECONDS = 30
26
+
27
+
28
+ class Settings(BaseModel):
29
+ """The keepalive_ settings, each within the limits it must keep to."""
30
+
31
+ model_config = ConfigDict(frozen=True, validate_default=True)
32
+
33
+ keepalive_protection_minutes: int = Field(
34
+ default=DEFAULT_PROTECTION_MINUTES,
35
+ strict=True,
36
+ ge=MIN_PROTECTION_MINUTES,
37
+ le=MAX_PROTECTION_MINUTES,
38
+ )
39
+
40
+ keepalive_check_interval: float = Field(
41
+ default=DEFAULT_CHECK_INTERVAL_SECONDS,
42
+ gt=0,
43
+ )
44
+
45
+ keepalive_version: ImportString[Callable[[], str | None]] = Field(
46
+ default=from_git_commit,
47
+ )
48
+
49
+ keepalive_version_channel: ImportString[Callable[[Celery], VersionChannel]] = Field(
50
+ default=RemoteControlChannel,
51
+ )
52
+
53
+ @model_validator(mode="after")
54
+ def check_interval_renews_before_protection_runs_out(self) -> Self:
55
+ protection_seconds = self.keepalive_protection_minutes * 60
56
+ if self.keepalive_check_interval >= protection_seconds:
57
+ raise ValueError(
58
+ "keepalive_check_interval must be less than the protection "
59
+ f"period ({protection_seconds} seconds)",
60
+ )
61
+ return self
62
+
63
+
64
+ def settings(app: Celery) -> Settings:
65
+ """The app's keepalive_ settings, or ImproperlyConfigured naming the
66
+ one that is wrong."""
67
+ configured = {
68
+ name: app.conf[name] for name in Settings.model_fields if name in app.conf
69
+ }
70
+ try:
71
+ return Settings.model_validate(configured)
72
+ except ValidationError as error:
73
+ raise ImproperlyConfigured(str(error)) from error
@@ -0,0 +1,8 @@
1
+ """Functions that work out a worker's version, for keepalive_version."""
2
+
3
+ import os
4
+
5
+
6
+ def from_git_commit() -> str | None:
7
+ """The GIT_COMMIT environment variable, if it is set."""
8
+ return os.environ.get("GIT_COMMIT")
@@ -0,0 +1,227 @@
1
+ Metadata-Version: 2.4
2
+ Name: celery-keepalive
3
+ Version: 0.1.0
4
+ Summary: Keeps ECS from stopping a Celery worker while it is running a job.
5
+ Keywords: celery,ecs,aws,scale-in,task-protection,deployment
6
+ Author: Kevin Carrogan
7
+ Author-email: Kevin Carrogan <kevin@carrogan.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: Celery
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: System :: Distributed Computing
19
+ Classifier: Typing :: Typed
20
+ Requires-Dist: celery>=5.7.0
21
+ Requires-Dist: pydantic>=2.14.4
22
+ Requires-Python: >=3.12
23
+ Project-URL: Homepage, https://github.com/kevincarrogan/celery-keepalive
24
+ Project-URL: Changelog, https://github.com/kevincarrogan/celery-keepalive/blob/main/CHANGELOG.md
25
+ Project-URL: Issues, https://github.com/kevincarrogan/celery-keepalive/issues
26
+ Description-Content-Type: text/markdown
27
+
28
+ # celery-keepalive
29
+
30
+ Keeps ECS from stopping a Celery worker while it is running a job.
31
+
32
+ ## Background
33
+
34
+ If you run Celery workers as an ECS service, ECS stops them when it scales in
35
+ or replaces tasks during a deployment, whether or not they have work in
36
+ flight.
37
+ SIGTERM starts Celery's warm shutdown, but ECS sends SIGKILL after the stop
38
+ timeout (at most 120 seconds on Fargate), so long-running jobs are killed.
39
+
40
+ celery-keepalive uses ECS [task scale-in protection][protection] to stop that:
41
+
42
+ - **Scale-in:** while a worker is running a job, ECS won't pick its task to
43
+ stop. Shortly after the worker goes idle, ECS can stop it as normal.
44
+ - **Deployments:** workers on the old version stop taking new jobs, finish the
45
+ ones they have, and are then replaced.
46
+ - **Failure:** if a worker dies, or a job hangs past its
47
+ [time limit](#recommended-celery-settings), the protection runs out on its
48
+ own, so a broken worker never blocks scaling or deployments for long.
49
+
50
+ [docs/design.md](https://github.com/kevincarrogan/celery-keepalive/blob/main/docs/design.md) explains how it works, and
51
+ [how to debug it](https://github.com/kevincarrogan/celery-keepalive/blob/main/docs/design.md#debugging).
52
+
53
+ It is in early development, so its settings and interfaces may still change
54
+ before 1.0.
55
+
56
+ [protection]: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-scale-in-protection.html
57
+
58
+ ## Install
59
+
60
+ ```sh
61
+ uv add celery-keepalive
62
+ ```
63
+
64
+ ### Requirements
65
+
66
+ - Python 3.12 or later
67
+ - Celery workers running as ECS tasks, on Fargate or EC2
68
+ - A task IAM role that allows `ecs:UpdateTaskProtection`
69
+ - For [draining during deployments](#deployments) with the default channel, a
70
+ broker that supports Celery's remote control, such as Redis or RabbitMQ.
71
+ Amazon SQS doesn't, but you can [use another channel](#using-another-channel).
72
+
73
+ ## Usage
74
+
75
+ Add the bootstep where you create your Celery app. In a Django project that is
76
+ usually `proj/celery.py`:
77
+
78
+ ```python
79
+ from celery import Celery
80
+ from celery_keepalive import KeepaliveStep
81
+
82
+ app = Celery("myapp")
83
+ app.steps["worker"].add(KeepaliveStep)
84
+ ```
85
+
86
+ With the default [configuration](#configuration), each job protects its ECS
87
+ task for the next 2 minutes as soon as it starts, and renews that every 30
88
+ seconds until it finishes. Nothing removes protection: within 2 minutes of
89
+ the last job finishing it runs out, and ECS can stop the task as normal.
90
+
91
+ This also works when a worker runs several jobs at once, or one ECS task runs
92
+ several workers: the task stays protected while any job is running.
93
+
94
+ If the ECS agent fails or doesn't answer within a couple of seconds, the job
95
+ runs regardless. The bootstep logs a warning and tries again at the next
96
+ renewal.
97
+
98
+ Outside ECS, such as in local development, the bootstep logs once that it is
99
+ disabled and does nothing else. It tells the two apart by whether ECS has set
100
+ `ECS_AGENT_URI`.
101
+
102
+ ### Deployments
103
+
104
+ When a worker starts, it tells the other workers its version over your Celery
105
+ broker. A worker that hears a different version stops taking new jobs and
106
+ finishes the ones it has. Its protection then runs out, and ECS replaces it.
107
+ Whichever version started most recently wins, so a rollback works the same
108
+ way.
109
+
110
+ A worker's version comes from the `GIT_COMMIT` environment variable by
111
+ default. A worker with no version neither announces itself nor drains.
112
+
113
+ To work the version out another way, such as from a file baked into the
114
+ image, write a function that returns it, or `None` for no version, and give
115
+ its dotted path in `keepalive_version`:
116
+
117
+ ```python
118
+ def release_from_image() -> str | None:
119
+ """Called once per worker, as it starts."""
120
+ ```
121
+
122
+ ```python
123
+ app.conf.keepalive_version = "myproject.versions.release_from_image"
124
+ ```
125
+
126
+ One catch: if a release's new workers start, announce themselves and then
127
+ crash, the old workers have already stopped taking jobs. Jobs wait on the
128
+ queue, and nothing is lost, until ECS rolls the deployment back or you deploy
129
+ again.
130
+
131
+ #### Using another channel
132
+
133
+ Workers announce and hear versions through a channel class. The default,
134
+ `celery_keepalive.channels.RemoteControlChannel`, uses Celery's remote
135
+ control. To use something else, such as a record in SSM Parameter Store that
136
+ workers poll, write a class with these methods and give its dotted path in
137
+ `keepalive_version_channel`. Subclassing `VersionChannel` lets your type
138
+ checker hold it to the contract:
139
+
140
+ ```python
141
+ from collections.abc import Callable
142
+
143
+ from celery import Celery
144
+ from celery_keepalive import VersionChannel
145
+
146
+
147
+ class MyVersionChannel(VersionChannel):
148
+ def __init__(self, app: Celery) -> None:
149
+ """Called once per worker, as it starts."""
150
+
151
+ def announce(self, version: str) -> None:
152
+ """Tell the other workers this worker's version."""
153
+
154
+ def listen(self, on_version: Callable[[str], None]) -> None:
155
+ """Call on_version with every version heard from now on."""
156
+
157
+ def close(self) -> None:
158
+ """Stop listening: the worker is stopping."""
159
+ ```
160
+
161
+ ```python
162
+ app.conf.keepalive_version_channel = "myproject.channels.MyVersionChannel"
163
+ ```
164
+
165
+ The channel only carries versions. celery-keepalive decides whether a version
166
+ it hears means this worker should drain, and stops it taking new jobs.
167
+
168
+ ## Configuration
169
+
170
+ Settings go in your Celery config, alongside the rest:
171
+
172
+ ```python
173
+ app.conf.keepalive_check_interval = 30 # seconds
174
+ app.conf.keepalive_protection_minutes = 2
175
+ ```
176
+
177
+ | Setting | Default | What it does |
178
+ | ------------------------------ | ------------------------------------------------ | ----------------------------------------------------------------------------- |
179
+ | `keepalive_check_interval` | `30` | Seconds between renewals of a running job's protection. |
180
+ | `keepalive_protection_minutes` | `2` | How long each protection lasts, and so how long an idle task stays protected. |
181
+ | `keepalive_version` | `celery_keepalive.versions.from_git_commit` | The function that returns the worker's version, which it announces on start. |
182
+ | `keepalive_version_channel` | `celery_keepalive.channels.RemoteControlChannel` | The class workers announce and hear versions through. |
183
+
184
+ `keepalive_protection_minutes` must be a whole number from 1 to 2880 (48
185
+ hours), which are ECS's limits, and `keepalive_check_interval` must be shorter
186
+ than it. A worker with a setting outside these limits refuses to start, with
187
+ an error naming the setting. It checks them outside ECS too, so a bad value
188
+ shows up in local development before it reaches a deployment.
189
+
190
+ ## Recommended Celery settings
191
+
192
+ These aren't required, but they make the most of celery-keepalive:
193
+
194
+ ```python
195
+ app.conf.task_acks_late = True
196
+ app.conf.worker_prefetch_multiplier = 1
197
+ app.conf.task_time_limit = 60 * 60 # seconds; longer than your longest job
198
+ ```
199
+
200
+ - **`task_acks_late`:** a job is acknowledged when it finishes, not when it
201
+ starts. If a worker is killed anyway, for example a hung worker whose
202
+ protection ran out, the job goes back on the queue instead of being lost.
203
+ The trade-off is that a job can run twice, so your tasks need to be safe to
204
+ repeat.
205
+ - **`worker_prefetch_multiplier = 1`:** a busy worker doesn't hold on to jobs
206
+ it hasn't started, so other workers can run them, and a worker that is
207
+ draining for a deployment has less to finish.
208
+ - **`task_time_limit`:** Celery kills a job that runs longer than this. A job
209
+ keeps its task protected for as long as it runs, so without a time limit a
210
+ job that hangs keeps its task protected forever. Set it longer than your
211
+ longest job.
212
+
213
+ ## Contributing
214
+
215
+ Issues and pull requests are welcome. To set up and run the checks:
216
+
217
+ ```sh
218
+ just setup
219
+ just check
220
+ ```
221
+
222
+ `just check` includes the end-to-end tests, which run a Docker Compose stack,
223
+ so it needs Docker running. `just test` runs only the unit tests, without it.
224
+
225
+ ## License
226
+
227
+ [MIT](https://github.com/kevincarrogan/celery-keepalive/blob/main/LICENSE)
@@ -0,0 +1,13 @@
1
+ celery_keepalive/__init__.py,sha256=pDE8GR1_NZh3H5BYWN_s67ItZfclJ7tQYLckqZNMOCQ,247
2
+ celery_keepalive/agent.py,sha256=XKB1N6Uj5Z9hKLO60YQROoZQPhxACZd2CDOTrPAL0oY,2772
3
+ celery_keepalive/bootstep.py,sha256=Vtz5MTNDrP-b-GBwx5K6lxsC5earZ7NGHxERmgfx--o,2783
4
+ celery_keepalive/channels.py,sha256=9onCFYDIhiPVBtOc9tI-ihNimseZrhWLTr2R6SsTwIU,2957
5
+ celery_keepalive/draining.py,sha256=tVrzB4EWUS41XN2VDx9Ox8v_Hjs6_4CjHCeNZTUK3mY,2307
6
+ celery_keepalive/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ celery_keepalive/renewals.py,sha256=xbHDtTORO5sluOVsHkHb6TA0yWAhwJ5vf6QBATEXh3k,2601
8
+ celery_keepalive/settings.py,sha256=ZcTBZ3f1K5r1D2rbpAQP43Ggsvkoo2UtdvxBbKLFMM8,2341
9
+ celery_keepalive/versions.py,sha256=9kJYw6RzdfQ_0nQ5TjxrHuzalgRN0mKNpbuP_aCyGsQ,224
10
+ celery_keepalive-0.1.0.dist-info/licenses/LICENSE,sha256=KjfGZG8ldTkM43Or5Y7Uo6lvU2Oq6Hh3_nPTaJHqbtI,1071
11
+ celery_keepalive-0.1.0.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
12
+ celery_keepalive-0.1.0.dist-info/METADATA,sha256=x3ixl4i0pZzy1Aw3bLV22m3AeZqs6BdxqJHlVr0fSig,9271
13
+ celery_keepalive-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.12
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Carrogan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.