| 1 |
.. _broker-sqs: |
| 2 |
|
| 3 |
================== |
| 4 |
Using Amazon SQS |
| 5 |
================== |
| 6 |
|
| 7 |
.. _broker-sqs-installation: |
| 8 |
|
| 9 |
Installation |
| 10 |
============ |
| 11 |
|
| 12 |
For the Amazon SQS support you have to install additional dependencies. |
| 13 |
You can install both Celery and these dependencies in one go using |
| 14 |
the ``celery[sqs]`` :ref:`bundle <bundles>`: |
| 15 |
|
| 16 |
.. code-block:: console |
| 17 |
|
| 18 |
$ pip install "celery[sqs]" |
| 19 |
|
| 20 |
.. _broker-sqs-configuration: |
| 21 |
|
| 22 |
Configuration |
| 23 |
============= |
| 24 |
|
| 25 |
You have to specify SQS in the broker URL:: |
| 26 |
|
| 27 |
broker_url = 'sqs://ABCDEFGHIJKLMNOPQRST:ZYXK7NiynGlTogH8Nj+P9nlE73sq3@' |
| 28 |
|
| 29 |
where the URL format is: |
| 30 |
|
| 31 |
.. code-block:: text |
| 32 |
|
| 33 |
sqs://aws_access_key_id:aws_secret_access_key@ |
| 34 |
|
| 35 |
Please note that you must remember to include the ``@`` sign at the end and |
| 36 |
encode the password so it can always be parsed correctly. For example: |
| 37 |
|
| 38 |
.. code-block:: python |
| 39 |
|
| 40 |
from kombu.utils.url import safequote |
| 41 |
|
| 42 |
aws_access_key = safequote("ABCDEFGHIJKLMNOPQRST") |
| 43 |
aws_secret_key = safequote("ZYXK7NiynG/TogH8Nj+P9nlE73sq3") |
| 44 |
|
| 45 |
broker_url = "sqs://{aws_access_key}:{aws_secret_key}@".format( |
| 46 |
aws_access_key=aws_access_key, aws_secret_key=aws_secret_key, |
| 47 |
) |
| 48 |
|
| 49 |
.. warning:: |
| 50 |
|
| 51 |
Don't use this setup option with django's ``debug=True``. |
| 52 |
It may lead to security issues within deployed django apps. |
| 53 |
|
| 54 |
In debug mode django shows environment variables and the SQS URL |
| 55 |
may be exposed to the internet including your AWS access and secret keys. |
| 56 |
Please turn off debug mode on your deployed django application or |
| 57 |
consider a setup option described below. |
| 58 |
|
| 59 |
|
| 60 |
The login credentials can also be set using the environment variables |
| 61 |
:envvar:`AWS_ACCESS_KEY_ID` and :envvar:`AWS_SECRET_ACCESS_KEY`, |
| 62 |
in that case the broker URL may only be ``sqs://``. |
| 63 |
|
| 64 |
If you are using IAM roles on instances, you can set the BROKER_URL to: |
| 65 |
``sqs://`` and kombu will attempt to retrieve access tokens from the instance |
| 66 |
metadata. |
| 67 |
|
| 68 |
Options |
| 69 |
======= |
| 70 |
|
| 71 |
Region |
| 72 |
------ |
| 73 |
|
| 74 |
The default region is ``us-east-1`` but you can select another region |
| 75 |
by configuring the :setting:`broker_transport_options` setting:: |
| 76 |
|
| 77 |
broker_transport_options = {'region': 'eu-west-1'} |
| 78 |
|
| 79 |
.. seealso:: |
| 80 |
|
| 81 |
An overview of Amazon Web Services regions can be found here: |
| 82 |
|
| 83 |
http://aws.amazon.com/about-aws/globalinfrastructure/ |
| 84 |
|
| 85 |
.. _sqs-visibility-timeout: |
| 86 |
|
| 87 |
Visibility Timeout |
| 88 |
------------------ |
| 89 |
|
| 90 |
The visibility timeout defines the number of seconds to wait |
| 91 |
for the worker to acknowledge the task before the message is redelivered |
| 92 |
to another worker. Also see caveats below. |
| 93 |
|
| 94 |
This option is set via the :setting:`broker_transport_options` setting:: |
| 95 |
|
| 96 |
broker_transport_options = {'visibility_timeout': 3600} # 1 hour. |
| 97 |
|
| 98 |
The default visibility timeout is 30 minutes. |
| 99 |
|
| 100 |
This option is used when creating the SQS queue and has no effect if |
| 101 |
using :ref:`predefined queues <predefined-queues>`. |
| 102 |
|
| 103 |
Polling Interval |
| 104 |
---------------- |
| 105 |
|
| 106 |
The polling interval decides the number of seconds to sleep between |
| 107 |
unsuccessful polls. This value can be either an int or a float. |
| 108 |
By default the value is *one second*: this means the worker will |
| 109 |
sleep for one second when there's no more messages to read. |
| 110 |
|
| 111 |
You must note that **more frequent polling is also more expensive, so increasing |
| 112 |
the polling interval can save you money**. |
| 113 |
|
| 114 |
The polling interval can be set via the :setting:`broker_transport_options` |
| 115 |
setting:: |
| 116 |
|
| 117 |
broker_transport_options = {'polling_interval': 0.3} |
| 118 |
|
| 119 |
Very frequent polling intervals can cause *busy loops*, resulting in the |
| 120 |
worker using a lot of CPU time. If you need sub-millisecond precision you |
| 121 |
should consider using another transport, like `RabbitMQ <broker-amqp>`, |
| 122 |
or `Redis <broker-redis>`. |
| 123 |
|
| 124 |
Long Polling |
| 125 |
------------ |
| 126 |
|
| 127 |
`SQS Long Polling`_ is enabled by default and the ``WaitTimeSeconds`` parameter |
| 128 |
of `ReceiveMessage`_ operation is set to 10 seconds. |
| 129 |
|
| 130 |
The value of ``WaitTimeSeconds`` parameter can be set via the |
| 131 |
:setting:`broker_transport_options` setting:: |
| 132 |
|
| 133 |
broker_transport_options = {'wait_time_seconds': 15} |
| 134 |
|
| 135 |
Valid values are 0 to 20. Note that newly created queues themselves (also if |
| 136 |
created by Celery) will have the default value of 0 set for the "Receive Message |
| 137 |
Wait Time" queue property. |
| 138 |
|
| 139 |
.. _`SQS Long Polling`: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html |
| 140 |
.. _`ReceiveMessage`: https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html |
| 141 |
|
| 142 |
Queue Prefix |
| 143 |
------------ |
| 144 |
|
| 145 |
By default Celery won't assign any prefix to the queue names, |
| 146 |
If you have other services using SQS you can configure it do so |
| 147 |
using the :setting:`broker_transport_options` setting:: |
| 148 |
|
| 149 |
broker_transport_options = {'queue_name_prefix': 'celery-'} |
| 150 |
|
| 151 |
.. _predefined-queues: |
| 152 |
|
| 153 |
Predefined Queues |
| 154 |
----------------- |
| 155 |
|
| 156 |
If you want Celery to use a set of predefined queues in AWS, and to |
| 157 |
never attempt to list SQS queues, nor attempt to create or delete them, |
| 158 |
pass a map of queue names to URLs using the :setting:`predefined_queues` |
| 159 |
setting:: |
| 160 |
|
| 161 |
broker_transport_options = { |
| 162 |
'predefined_queues': { |
| 163 |
'my-q': { |
| 164 |
'url': 'https://ap-southeast-2.queue.amazonaws.com/123456/my-q', |
| 165 |
'access_key_id': 'xxx', |
| 166 |
'secret_access_key': 'xxx', |
| 167 |
} |
| 168 |
} |
| 169 |
} |
| 170 |
|
| 171 |
.. warning:: |
| 172 |
|
| 173 |
**Important:** When using ``predefined_queues``, do NOT use URL-encoded |
| 174 |
credentials (``safequote``) for the ``access_key_id`` and ``secret_access_key`` |
| 175 |
values. URL encoding should only be applied to credentials in the broker URL. |
| 176 |
|
| 177 |
Using URL-encoded credentials in ``predefined_queues`` will cause signature |
| 178 |
mismatch errors like: "The request signature we calculated does not match |
| 179 |
the signature you provided." |
| 180 |
|
| 181 |
**Correct example combining broker URL and predefined queues:** |
| 182 |
|
| 183 |
.. code-block:: python |
| 184 |
|
| 185 |
import os |
| 186 |
from kombu.utils.url import safequote |
| 187 |
from celery import Celery |
| 188 |
|
| 189 |
# Raw credentials from environment |
| 190 |
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") |
| 191 |
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") |
| 192 |
|
| 193 |
# URL-encode ONLY for broker URL |
| 194 |
aws_access_key_encoded = safequote(AWS_ACCESS_KEY_ID) |
| 195 |
aws_secret_key_encoded = safequote(AWS_SECRET_ACCESS_KEY) |
| 196 |
|
| 197 |
# Use encoded credentials in broker URL |
| 198 |
broker_url = f"sqs://{aws_access_key_encoded}:{aws_secret_key_encoded}@" |
| 199 |
|
| 200 |
celery_app = Celery("tasks", broker=broker_url) |
| 201 |
celery_app.conf.broker_transport_options = { |
| 202 |
"region": "us-east-1", |
| 203 |
"predefined_queues": { |
| 204 |
"my-queue": { |
| 205 |
"url": "https://sqs.us-east-1.amazonaws.com/123456/my-queue", |
| 206 |
# Use RAW credentials here (NOT encoded) |
| 207 |
"access_key_id": AWS_ACCESS_KEY_ID, |
| 208 |
"secret_access_key": AWS_SECRET_ACCESS_KEY, |
| 209 |
}, |
| 210 |
}, |
| 211 |
} |
| 212 |
|
| 213 |
When using this option, the visibility timeout should be set in the SQS queue |
| 214 |
(in AWS) rather than via the :ref:`visibility timeout <sqs-visibility-timeout>` |
| 215 |
option. |
| 216 |
|
| 217 |
Back-off policy |
| 218 |
------------------------ |
| 219 |
Back-off policy is using SQS visibility timeout mechanism altering the time difference between task retries. |
| 220 |
The mechanism changes message specific ``visibility timeout`` from queue ``Default visibility timeout`` to policy configured timeout. |
| 221 |
The number of retries is managed by SQS (specifically by the ``ApproximateReceiveCount`` message attribute) and no further action is required by the user. |
| 222 |
|
| 223 |
Configuring the queues and backoff policy:: |
| 224 |
|
| 225 |
broker_transport_options = { |
| 226 |
'predefined_queues': { |
| 227 |
'my-q': { |
| 228 |
'url': 'https://ap-southeast-2.queue.amazonaws.com/123456/my-q', |
| 229 |
'access_key_id': 'xxx', |
| 230 |
'secret_access_key': 'xxx', |
| 231 |
'backoff_policy': {1: 10, 2: 20, 3: 40, 4: 80, 5: 320, 6: 640}, |
| 232 |
'backoff_tasks': ['svc.tasks.tasks.task1'] |
| 233 |
} |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
|
| 238 |
``backoff_policy`` dictionary where key is number of retries, and value is delay seconds between retries (i.e |
| 239 |
SQS visibility timeout) |
| 240 |
``backoff_tasks`` list of task names to apply the above policy |
| 241 |
|
| 242 |
The above policy: |
| 243 |
|
| 244 |
+-----------------------------------------+--------------------------------------------+ |
| 245 |
| **Attempt** | **Delay** | |
| 246 |
+-----------------------------------------+--------------------------------------------+ |
| 247 |
| ``2nd attempt`` | 20 seconds | |
| 248 |
+-----------------------------------------+--------------------------------------------+ |
| 249 |
| ``3rd attempt`` | 40 seconds | |
| 250 |
+-----------------------------------------+--------------------------------------------+ |
| 251 |
| ``4th attempt`` | 80 seconds | |
| 252 |
+-----------------------------------------+--------------------------------------------+ |
| 253 |
| ``5th attempt`` | 320 seconds | |
| 254 |
+-----------------------------------------+--------------------------------------------+ |
| 255 |
| ``6th attempt`` | 640 seconds | |
| 256 |
+-----------------------------------------+--------------------------------------------+ |
| 257 |
|
| 258 |
|
| 259 |
STS token authentication |
| 260 |
---------------------------- |
| 261 |
|
| 262 |
https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html |
| 263 |
|
| 264 |
AWS STS authentication is supported by using the ``sts_role_arn`` and ``sts_token_timeout`` broker transport options. ``sts_role_arn`` is the assumed IAM role ARN we use to authorize our access to SQS. |
| 265 |
``sts_token_timeout`` is the token timeout, defaults (and minimum) to 900 seconds. After the mentioned period, a new token will be created:: |
| 266 |
|
| 267 |
broker_transport_options = { |
| 268 |
'predefined_queues': { |
| 269 |
'my-q': { |
| 270 |
'url': 'https://ap-southeast-2.queue.amazonaws.com/123456/my-q', |
| 271 |
'access_key_id': 'xxx', |
| 272 |
'secret_access_key': 'xxx', |
| 273 |
'backoff_policy': {1: 10, 2: 20, 3: 40, 4: 80, 5: 320, 6: 640}, |
| 274 |
'backoff_tasks': ['svc.tasks.tasks.task1'] |
| 275 |
} |
| 276 |
}, |
| 277 |
'sts_role_arn': 'arn:aws:iam::<xxx>:role/STSTest', # optional |
| 278 |
'sts_token_timeout': 900 # optional |
| 279 |
} |
| 280 |
|
| 281 |
|
| 282 |
.. _sqs-caveats: |
| 283 |
|
| 284 |
Caveats |
| 285 |
======= |
| 286 |
|
| 287 |
- If a task isn't acknowledged within the ``visibility_timeout``, |
| 288 |
the task will be redelivered to another worker and executed. |
| 289 |
|
| 290 |
This causes problems with ETA/countdown/retry tasks where the |
| 291 |
time to execute exceeds the visibility timeout; in fact if that |
| 292 |
happens it will be executed again, and again in a loop. |
| 293 |
|
| 294 |
So you have to increase the visibility timeout to match |
| 295 |
the time of the longest ETA you're planning to use. |
| 296 |
|
| 297 |
Note that Celery will redeliver messages at worker shutdown, |
| 298 |
so having a long visibility timeout will only delay the redelivery |
| 299 |
of 'lost' tasks in the event of a power failure or forcefully terminated |
| 300 |
workers. |
| 301 |
|
| 302 |
Periodic tasks won't be affected by the visibility timeout, |
| 303 |
as it is a concept separate from ETA/countdown. |
| 304 |
|
| 305 |
The maximum visibility timeout supported by AWS as of this writing |
| 306 |
is 12 hours (43200 seconds):: |
| 307 |
|
| 308 |
broker_transport_options = {'visibility_timeout': 43200} |
| 309 |
|
| 310 |
- SQS doesn't yet support worker remote control commands. |
| 311 |
|
| 312 |
- SQS doesn't yet support events, and so cannot be used with |
| 313 |
:program:`celery events`, :program:`celerymon`, or the Django Admin |
| 314 |
monitor. |
| 315 |
|
| 316 |
- With FIFO queues it might be necessary to set additional message properties such as ``MessageGroupId`` and ``MessageDeduplicationId`` when publishing a message. |
| 317 |
|
| 318 |
Message properties can be passed as keyword arguments to :meth:`~celery.app.task.Task.apply_async`: |
| 319 |
|
| 320 |
.. code-block:: python |
| 321 |
|
| 322 |
message_properties = { |
| 323 |
'MessageGroupId': '<YourMessageGroupId>', |
| 324 |
'MessageDeduplicationId': '<YourMessageDeduplicationId>' |
| 325 |
} |
| 326 |
task.apply_async(**message_properties) |
| 327 |
|
| 328 |
- During :ref:`shutdown <worker-stopping>`, the worker will attempt to re-queue any unacknowledged messages |
| 329 |
with :setting:`task_acks_late` enabled. However, if the worker is terminated forcefully |
| 330 |
(:ref:`cold shutdown <worker-cold-shutdown>`), the worker might not be able to re-queue the tasks on time, |
| 331 |
and they will not be consumed again until the :ref:`sqs-visibility-timeout` has passed. This creates a |
| 332 |
problem when the :ref:`sqs-visibility-timeout` is very high and a worker needs to shut down just after it has |
| 333 |
received a task. If the task is not re-queued in such case, it will need to wait for the long visibility timeout |
| 334 |
to pass before it can be consumed again, leading to potentially very long delays in tasks execution. |
| 335 |
|
| 336 |
The :ref:`soft shutdown <worker-soft-shutdown>` introduces a time-limited warm shutdown phase just before |
| 337 |
the :ref:`cold shutdown <worker-cold-shutdown>`. This time window significantly increases the chances of |
| 338 |
re-queuing the tasks during shutdown which mitigates the problem of long visibility timeouts. |
| 339 |
|
| 340 |
To enable the :ref:`soft shutdown <worker-soft-shutdown>`, set the :setting:`worker_soft_shutdown_timeout` to a value |
| 341 |
greater than 0. The value must be an float describing the number of seconds. During this time, the worker will |
| 342 |
continue to process the running tasks until the timeout expires, after which the :ref:`cold shutdown <worker-cold-shutdown>` |
| 343 |
will be initiated automatically to terminate the worker gracefully. |
| 344 |
|
| 345 |
If the :ref:`REMAP_SIGTERM <worker-REMAP_SIGTERM>` is configured to SIGQUIT in the environment variables, and |
| 346 |
the :setting:`worker_soft_shutdown_timeout` is set, the worker will initiate the :ref:`soft shutdown <worker-soft-shutdown>` |
| 347 |
when it receives the :sig:`TERM` signal (*and* the :sig:`QUIT` signal). |
| 348 |
|
| 349 |
|
| 350 |
.. _sqs-results-configuration: |
| 351 |
|
| 352 |
Results |
| 353 |
------- |
| 354 |
|
| 355 |
Multiple products in the Amazon Web Services family could be a good candidate |
| 356 |
to store or publish results with, but there's no such result backend included |
| 357 |
at this point. |
| 358 |
|
| 359 |
.. warning:: |
| 360 |
|
| 361 |
Don't use the ``amqp`` result backend with SQS. |
| 362 |
|
| 363 |
It will create one queue for every task, and the queues will |
| 364 |
not be collected. This could cost you money that would be better |
| 365 |
spent contributing an AWS result store backend back to Celery :) |