Debian Codegraph @

docs/getting-started/backends-and-brokers/redis.rst

raw
1 .. _broker-redis:
2
3 =============
4 Using Redis
5 =============
6
7 .. _broker-redis-installation:
8
9 Installation
10 ============
11
12 For the Redis support you have to install additional dependencies.
13 You can install both Celery and these dependencies in one go using
14 the ``celery[redis]`` :ref:`bundle <bundles>`:
15
16 .. code-block:: console
17
18 $ pip install -U "celery[redis]"
19
20 .. _broker-redis-configuration:
21
22 Configuration
23 =============
24
25 Configuration is easy, just configure the location of
26 your Redis database:
27
28 .. code-block:: python
29
30 app.conf.broker_url = 'redis://localhost:6379/0'
31
32 Where the URL is in the format of:
33
34 .. code-block:: text
35
36 redis://:password@hostname:port/db_number
37
38 all fields after the scheme are optional, and will default to ``localhost``
39 on port 6379, using database 0.
40
41 If redis credential provider should be used, the URL needs to be in the following format:
42
43 .. code-block:: text
44
45 redis://@hostname:port/db_number?credential_provider=mymodule.myfile.myclass
46
47
48 If a Unix socket connection should be used, the URL needs to be in the format:
49
50 .. code-block:: text
51
52 redis+socket:///path/to/redis.sock
53
54 Specifying a different database number when using a Unix socket is possible
55 by adding the ``virtual_host`` parameter to the URL:
56
57 .. code-block:: text
58
59 redis+socket:///path/to/redis.sock?virtual_host=db_number
60
61 It is also easy to connect directly to a list of Redis Sentinel:
62
63 .. code-block:: python
64
65 app.conf.broker_url = 'sentinel://localhost:26379;sentinel://localhost:26380;sentinel://localhost:26381'
66 app.conf.broker_transport_options = { 'master_name': "cluster1" }
67
68 Additional options can be passed to the Sentinel client using ``sentinel_kwargs``:
69
70 .. code-block:: python
71
72 app.conf.broker_transport_options = { 'sentinel_kwargs': { 'password': "password" } }
73
74 .. _redis-visibility_timeout:
75
76 Visibility Timeout
77 ------------------
78
79 The visibility timeout defines the number of seconds to wait
80 for the worker to acknowledge the task before the message is redelivered
81 to another worker. Be sure to see :ref:`redis-caveats` below.
82
83 This option is set via the :setting:`broker_transport_options` setting:
84
85 .. code-block:: python
86
87 app.conf.broker_transport_options = {'visibility_timeout': 3600} # 1 hour.
88
89 The default visibility timeout for Redis is 1 hour.
90
91 .. _redis-results-configuration:
92
93 Results
94 -------
95
96 If you also want to store the state and return values of tasks in Redis,
97 you should configure these settings::
98
99 app.conf.result_backend = 'redis://localhost:6379/0'
100
101 For a complete list of options supported by the Redis result backend, see
102 :ref:`conf-redis-result-backend`.
103
104 If you are using Sentinel, you should specify the master_name using the :setting:`result_backend_transport_options` setting:
105
106 .. code-block:: python
107
108 app.conf.result_backend_transport_options = {'master_name': "mymaster"}
109
110 .. _redis-result-backend-global-keyprefix:
111
112 Global keyprefix
113 ^^^^^^^^^^^^^^^^
114
115 The global key prefix will be prepended to all keys used for the result backend,
116 which can be useful when a redis database is shared by different users.
117 By default, no prefix is prepended.
118
119 To configure the global keyprefix for the Redis result backend, use the ``global_keyprefix`` key under :setting:`result_backend_transport_options`:
120
121
122 .. code-block:: python
123
124 app.conf.result_backend_transport_options = {
125 'global_keyprefix': 'my_prefix_'
126 }
127
128 .. _redis-result-backend-timeout:
129
130 Connection timeouts
131 ^^^^^^^^^^^^^^^^^^^
132
133 To configure the connection timeouts for the Redis result backend, use the ``retry_policy`` key under :setting:`result_backend_transport_options`:
134
135
136 .. code-block:: python
137
138 app.conf.result_backend_transport_options = {
139 'retry_policy': {
140 'timeout': 5.0
141 }
142 }
143
144 See :func:`~kombu.utils.functional.retry_over_time` for the possible retry policy options.
145
146 .. _redis-serverless:
147
148 Serverless
149 ==========
150
151 Celery supports utilizing a remote serverless Redis, which can significantly
152 reduce the operational overhead and cost, making it a favorable choice in
153 microservice architectures or environments where minimizing operational
154 expenses is crucial. Serverless Redis provides the necessary functionalities
155 without the need for manual setup, configuration, and management, thus
156 aligning well with the principles of automation and scalability that Celery promotes.
157
158 Upstash
159 -------
160
161 `Upstash <http://upstash.com/?code=celery>`_ offers a serverless Redis database service,
162 providing a seamless solution for Celery users looking to leverage
163 serverless architectures. Upstash's serverless Redis service is designed
164 with an eventual consistency model and durable storage, facilitated
165 through a multi-tier storage architecture.
166
167 Integration with Celery is straightforward as demonstrated
168 in an `example provided by Upstash <https://github.com/upstash/examples/tree/main/examples/using-celery>`_.
169
170 Dragonfly
171 ---------
172 `Dragonfly <https://www.dragonflydb.io/>`_ is a drop-in Redis replacement that cuts costs and boosts performance.
173 Designed to fully utilize the power of modern cloud hardware and deliver on the data demands of modern applications,
174 Dragonfly frees developers from the limits of traditional in-memory data stores.
175
176 .. _redis-caveats:
177
178 Caveats
179 =======
180
181 Visibility timeout
182 ------------------
183
184 If a task isn't acknowledged within the :ref:`redis-visibility_timeout`
185 the task will be redelivered to another worker and executed.
186
187 This causes problems with ETA/countdown/retry tasks where the
188 time to execute exceeds the visibility timeout; in fact if that
189 happens it will be executed again, and again in a loop.
190
191 To remediate that, you can increase the visibility timeout to match
192 the time of the longest ETA you're planning to use. However, this is not
193 recommended as it may have negative impact on the reliability.
194 Celery will redeliver messages at worker shutdown,
195 so having a long visibility timeout will only delay the redelivery
196 of 'lost' tasks in the event of a power failure or forcefully terminated
197 workers.
198
199 Broker is not a database, so if you are in need of scheduling tasks for
200 a more distant future, database-backed periodic task might be a better choice.
201 Periodic tasks won't be affected by the visibility timeout,
202 as this is a concept separate from ETA/countdown.
203
204 You can increase this timeout by configuring all of the following options
205 with the same name (required to set all of them):
206
207 .. code-block:: python
208
209 app.conf.broker_transport_options = {'visibility_timeout': 43200}
210 app.conf.result_backend_transport_options = {'visibility_timeout': 43200}
211 app.conf.visibility_timeout = 43200
212
213 The value must be an int describing the number of seconds.
214
215 Note: If multiple applications are sharing the same Broker, with different settings, the _shortest_ value will be used.
216 This include if the value is not set, and the default is sent
217
218 Soft Shutdown
219 -------------
220
221 During :ref:`shutdown <worker-stopping>`, the worker will attempt to re-queue any unacknowledged messages
222 with :setting:`task_acks_late` enabled. However, if the worker is terminated forcefully
223 (:ref:`cold shutdown <worker-cold-shutdown>`), the worker might not be able to re-queue the tasks on time,
224 and they will not be consumed again until the :ref:`redis-visibility_timeout` has passed. This creates a
225 problem when the :ref:`redis-visibility_timeout` is very high and a worker needs to shut down just after it has
226 received a task. If the task is not re-queued in such case, it will need to wait for the long visibility timeout
227 to pass before it can be consumed again, leading to potentially very long delays in tasks execution.
228
229 The :ref:`soft shutdown <worker-soft-shutdown>` introduces a time-limited warm shutdown phase just before
230 the :ref:`cold shutdown <worker-cold-shutdown>`. This time window significantly increases the chances of
231 re-queuing the tasks during shutdown which mitigates the problem of long visibility timeouts.
232
233 To enable the :ref:`soft shutdown <worker-soft-shutdown>`, set the :setting:`worker_soft_shutdown_timeout` to a value
234 greater than 0. The value must be an float describing the number of seconds. During this time, the worker will
235 continue to process the running tasks until the timeout expires, after which the :ref:`cold shutdown <worker-cold-shutdown>`
236 will be initiated automatically to terminate the worker gracefully.
237
238 If the :ref:`REMAP_SIGTERM <worker-REMAP_SIGTERM>` is configured to SIGQUIT in the environment variables, and
239 the :setting:`worker_soft_shutdown_timeout` is set, the worker will initiate the :ref:`soft shutdown <worker-soft-shutdown>`
240 when it receives the :sig:`TERM` signal (*and* the :sig:`QUIT` signal).
241
242 Key eviction
243 ------------
244
245 Redis may evict keys from the database in some situations
246
247 If you experience an error like:
248
249 .. code-block:: text
250
251 InconsistencyError: Probably the key ('_kombu.binding.celery') has been
252 removed from the Redis database.
253
254 then you may want to configure the :command:`redis-server` to not evict keys
255 by setting in the redis configuration file:
256
257 - the ``maxmemory`` option
258 - the ``maxmemory-policy`` option to ``noeviction`` or ``allkeys-lru``
259
260 See Redis server documentation about Eviction Policies for details:
261
262 https://redis.io/topics/lru-cache
263
264 .. _redis-group-result-ordering:
265
266 Group result ordering
267 ---------------------
268
269 Versions of Celery up to and including 4.4.6 used an unsorted list to store
270 result objects for groups in the Redis backend. This can cause those results to
271 be returned in a different order to their associated tasks in the original
272 group instantiation. Celery 4.4.7 introduced an opt-in behaviour which fixes
273 this issue and ensures that group results are returned in the same order the
274 tasks were defined, matching the behaviour of other backends. In Celery 5.0
275 this behaviour was changed to be opt-out. The behaviour is controlled by the
276 `result_chord_ordered` configuration option which may be set like so:
277
278 .. code-block:: python
279
280 # Specifying this for workers running Celery 4.4.6 or earlier has no effect
281 app.conf.result_backend_transport_options = {
282 'result_chord_ordered': True # or False
283 }
284
285 This is an incompatible change in the runtime behaviour of workers sharing the
286 same Redis backend for result storage, so all workers must follow either the
287 new or old behaviour to avoid breakage. For clusters with some workers running
288 Celery 4.4.6 or earlier, this means that workers running 4.4.7 need no special
289 configuration and workers running 5.0 or later must have `result_chord_ordered`
290 set to `False`. For clusters with no workers running 4.4.6 or earlier but some
291 workers running 4.4.7, it is recommended that `result_chord_ordered` be set to
292 `True` for all workers to ease future migration. Migration between behaviours
293 will disrupt results currently held in the Redis backend and cause breakage if
294 downstream tasks are run by migrated workers - plan accordingly.