Skip to content

The pubsub of redis is not thread safe, cause race condition error. #4670

Closed

Description

@ideascf

Envrionment

  • redis: 2.10.6
  • celery: 4.0.2
  • gevent: 1.0.2/1.2.1

problem

I'm using celery for run massive task, with CELERY_RESULT_BACKEND was enabled. The launch command is celery -A server worker -P gevent -l info -E. It work fine, but sometime got AssertionError.

The stacktrace:

  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/celery/app/task.py", line 412, in delay
    return self.apply_async(args, kwargs)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/celery/app/task.py", line 535, in apply_async
    **options
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/celery/app/base.py", line 736, in send_task
    self.backend.on_task_call(P, task_id)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/celery/backends/redis.py", line 180, in on_task_call
    self.result_consumer.consume_from(task_id)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/celery/backends/redis.py", line 76, in consume_from
    self._consume_from(task_id)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/celery/backends/redis.py", line 82, in _consume_from
    self._pubsub.subscribe(key)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/client.py", line 2482, in subscribe
    ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/client.py", line 2404, in execute_command
    self._execute(connection, connection.send_command, *args)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/client.py", line 2408, in _execute
    return command(*args)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/connection.py", line 610, in send_command
    self.send_packed_command(self.pack_command(*args))
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/connection.py", line 585, in send_packed_command
    self.connect()
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/connection.py", line 502, in connect
    callback(self)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/client.py", line 2376, in on_connect
    self.subscribe(**channels)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/client.py", line 2482, in subscribe
    ret_val = self.execute_command('SUBSCRIBE', *iterkeys(new_channels))
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/client.py", line 2404, in execute_command
    self._execute(connection, connection.send_command, *args)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/client.py", line 2408, in _execute
    return command(*args)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/connection.py", line 610, in send_command
    self.send_packed_command(self.pack_command(*args))
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/redis/connection.py", line 590, in send_packed_command
    self._sock.sendall(item)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/gevent/socket.py", line 466, in sendall
    data_sent += self.send(_get_memory(data, data_sent), flags, timeout=timeleft)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/gevent/socket.py", line 443, in send
    self._wait(self._write_event)
  File "/home/qfpay/agency_statistics/python/lib/python2.7/site-packages/gevent/socket.py", line 294, in _wait
    assert watcher.callback is None, 'This socket is already used by another greenlet: %r' % (watcher.callback, )
AssertionError: This socket is already used by another greenlet: <bound method Waiter.switch of <gevent.hub.Waiter object at 0x34dda50>>

Checklist

Steps to reproduce

Oh no, it't not easy to reproduce. you may encounter one for run tens of thousands of task.

Expected behavior

No Exception.

Actual behavior

raise AssertionError.

Activity

  1. georgepsarakis commented on Apr 19, 2018

    @georgepsarakis
    Contributor

    @ideascf can you please check if by any chance #4666 fixes this issue?

  2. Funnyang commented on May 3, 2018

    @Funnyang

    Yes, the same thing happened to me. I got message of other tasks when I use get() and on_message. I want to implement the web log, I must write it by myself now

  3. georgepsarakis commented on Jun 18, 2018

    @georgepsarakis
    Contributor

    @Funnyang @ideascf the latest release includes #4666 which might be fixing this issue. It would be great if you could try with the latest Celery version and share your feedback. Thanks!

  4. monsterxx03 commented on Jun 19, 2018

    @monsterxx03

    I think this problem still not fixed @georgepsarakis .

    Tested with :

    • python2.7.12
    • gevent 1.3.3
    • celery 4.2.0
    • redis py 2.10.5

    I tried with above packages on my prod env, came to similar problem, all happened during subscribe when apply_async, mainly caused by socket used by another greenlet

    A simple script to reproduce:

    import gevent
    import gevent.monkey
    gevent.monkey.patch_all()
    
    from celery import Celery
    
    app = Celery()
    app.conf.update(
        BROKER_URL='redis://localhost:6379/1',
        CELERY_RESULT_BACKEND='redis://localhost:6379/1'
    )
    
    @app.task
    def wrap():
        pass
    
    def run():
        gs = []
        for i in range(1000):
            gs.append(gevent.spawn(wrap.delay))
    
        gevent.joinall(gs)
    
    run()
    

    This script will not report error, but if you do redis-cli -p 6379 -n 1 monitor | grep -i subscribe on another shell when running , you will see SUBSCRIBE command with multi channel at very early start:

     "SUBSCRIBE" "celery-task-meta-9f1a6d9d-1d0b-4492-a605-e28390e8bb48" "celery-task-meta-11d2240e-2b39-4082-aad5-327b418287d1" "celery-task-meta-1ea6c92b-f097-46db-afdd-8b6c14a42be4"
    

    The root case is once gevent patched, redis client socket will by async, pubsub obj's on_connect callback will be called multi times: https://github.com/andymccurdy/redis-py/blob/master/redis/client.py#L2369

    I try to do a pre-ping in redis backend's init func (https://github.com/celery/celery/blob/master/celery/backends/redis.py#L204) to ensure connection is established before any task:

             self.result_consumer._pubsub = self.result_consumer.backend.client.pubsub(
                  ignore_subscribe_messages=True
              )
              self.result_consumer._pubsub.execute_command('ping')
    

    subscribe multi channels problem disappeared, but I'm not sure it's right way. (Also I didn't test it in my prod env).

  5. added this to the v4.3 milestone on Jun 23, 2018
  6. removed this from the v4.3 milestone on Nov 17, 2018
  7. added this to the 4.5 milestone on Jul 6, 2019
  8. self-assigned this
    on Jul 10, 2019
  9. removed their assignment
    on Feb 17, 2021
  10. auvipy commented on Feb 17, 2021

    @auvipy
    Member

    #6416 could fix this issue, @vinayinvicible can you verify this, please?

  11. modified the milestones: 4.5, 5.3 on Feb 17, 2021
  12. modified the milestones: 5.3, Future on Feb 19, 2023
  13. obaltian commented on Sep 30, 2025

    @obaltian

    Can confirm this still happens on our prod environment on celery==5.5.3 with redis==5.2.1, but during some cleanup.
    Maybe its a side-effect of a fix since it fails on UNSUBSCRIBE which was added as a fix.

    Traceback (most recent call last):
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/celery/result.py", line 417, in __del__
        self.backend.remove_pending_result(self)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/celery/backends/asynchronous.py", line 208, in remove_pending_result
        self.on_result_fulfilled(result)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/celery/backends/asynchronous.py", line 216, in on_result_fulfilled
        self.result_consumer.cancel_for(result.id)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/celery/backends/redis.py", line 184, in cancel_for
        self._pubsub.unsubscribe(key)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/redis/client.py", line 982, in unsubscribe
        return self.execute_command("UNSUBSCRIBE", *args)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/redis/client.py", line 798, in execute_command
        self._execute(connection, connection.send_command, *args, **kwargs)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/redis/client.py", line 841, in _execute
        return conn.retry.call_with_retry(
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/redis/retry.py", line 62, in call_with_retry
        return do()
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/redis/client.py", line 842, in <lambda>
        lambda: command(*args, **kwargs),
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/redis/connection.py", line 556, in send_command
        self.send_packed_command(
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/redis/connection.py", line 534, in send_packed_command
        self._sock.sendall(item)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/gevent/_socketcommon.py", line 698, in sendall
        return _sendall(self, data_memory, flags)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/gevent/_socketcommon.py", line 387, in _sendall
        timeleft = __send_chunk(socket, chunk, flags, timeleft, end)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/gevent/_socketcommon.py", line 327, in __send_chunk
        data_sent += socket.send(chunk, flags, timeout=timeleft)
      File "/home/appuser/app/.venv/lib/python3.13/site-packages/gevent/_socketcommon.py", line 726, in send
        self._wait(self._write_event)
      File "src/gevent/_hub_primitives.py", line 317, in gevent._gevent_c_hub_primitives.wait_on_socket
      File "src/gevent/_hub_primitives.py", line 322, in gevent._gevent_c_hub_primitives.wait_on_socket
      File "src/gevent/_hub_primitives.py", line 297, in gevent._gevent_c_hub_primitives._primitive_wait
    <...>
    Exception ignored in: <function AsyncResult.__del__ at 0x794dcdb311c0>
    <...>
    gevent.exceptions.ConcurrentObjectUseError: This socket is already used by another greenlet: <bound method Waiter.switch of <gevent._gevent_c_waiter.Waiter object at 0x794d267733d0>>

    PS I already checked this advice to set CELERY_RESULT_BACKEND_THREAD_SAFE = True and it's set.

  14. modified the milestones: Future, 5.7.x, 5.7.0 on Sep 19, 2026
  15. auvipy commented on Sep 21, 2026

    @auvipy
    Member

    merged a newly proposed fix for this. please report if that do not fix the problem fully or introduce any new regression in upcoming v5.7 release

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions