Skip to content

Memory leak from writing in a loop to a broken rabbitmq heartbeat connection #5047

Closed

Description

@mgeens

Checklist

Verified in both the released 4.2.1 and the master (which is reported as 4.2.0).

  • I have included the output of celery -A proj report in the issue.
    (if you are not able to do this, then at least specify the Celery
    version affected).
software -> celery:4.2.1 (windowlicker) kombu:4.2.1 py:3.6.5
            billiard:3.5.0.4 py-amqp:2.3.2
platform -> system:Linux arch:64bit, ELF imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:pyamqp results:disabled

broker_url: 'amqp://guest:********@172.17.0.1:5672//'
  • I have verified that the issue exists against the master branch of Celery.

Version: https://github.com/celery/celery/tree/ed17e12b14051bac51b84593cf7c8cf21c77e010

software -> celery:4.2.0 (windowlicker) kombu:4.2.1 py:3.6.5
            billiard:3.5.0.4 py-amqp:2.3.2
platform -> system:Linux arch:64bit, ELF imp:CPython
loader   -> celery.loaders.app.AppLoader
settings -> transport:pyamqp results:disabled
broker_url: 'amqp://guest:********@172.17.0.1:5672//'

Description

The celery workers of several different applications I work on would sporadically start leaking memory in a continuous fashion, until the machine ran out of memory. We initially tried to work around that by making use of the flag that automatically restart the workers after a certain number of tasks was completed. However, the leak turned out to be in the main worker process that manages workers, so this did not help.

I've found 3 issues that together cause this to happen. One of them clearly seems to be a celery/kombu issue, which is what this report is about. For the other two it's not clear yet but I'll include them for context and reproducibility.

The first issue is that a high CPU (or maybe IO) load can cause Celery workers to lose connections. There's been mention of this in #3377 and #3932 . I've been able to reproduce that by using the stress tool with cpu and io flags enabled. I see celery worker connection resets and missed heartbeats appearing in the logs when I do that. In particular I see the connection resets in the worker log for application A when restarting the worker for application B, while under that load. While I saw similar log messages right before memory leaking started to happen, the leaking didn't happen consistently. I believe this is because the connections that are killed are somewhat random, and some of them can recover from that while others don't.

The second issue, for which the reproduction steps are listed below, is that if the celery worker main process' connection used for sending heartbeats to the rabbitmq broker is broken, it will stay broken. In an strace you can see it repeatedly getting SIGPIPE / broken pipe errors. The process keeps 1-2 other connections open to the broker, one of them consistently (I think for receiving the status of other workers and maybe incoming jobs) another intermittent. If I kill the consistent one, another one is immediately recreated. I've also tried swapping out rabbitmq for redis as the broker. When the same connections are killed in that case, they are also recreated right after. I've only found the rabbitmq connection that sends heartbeats to be affected. If the --without-heartbeat flag is used, the connection is still opened, but there's no longer a heartbeat being sent over it. #3921, #3773, #3377 and #3932 appear to be related.

The third issue is that when the repeated writing attempts to the broken connection happen, the main worker process starts leaking memory. I'm not sure yet if this is at the Python object level or something lower.

Potential workarounds appear to be to use a different broker or the --without-heartbeat flag (although I'm not sure if the connection that still gets opened in that case is also used for other things).

Steps to reproduce

Assuming a Ubuntu 18.04 system, you'll need to have the strace and dsniff (for tcpkill) packages installed.

  1. Create a simple tasks.py that uses rabbitmq as the broker. Set the appropriate credentials for your broker. Make sure the ip address used is an external interface, not 127.0.0.1, because we want an internet socket to be used, not a unix one.
from celery import Celery

app = Celery('tasks', broker='pyamqp://guest:[email protected]//')


@app.task
def add(x, y):
    return x + y
  1. Run python -m celery worker -A tasks

  2. Run sudo ss -a -p | grep amq. Assuming your celery test worker is the only thing connected to rabbitmq, you should see something like:

tcp              ESTAB                  0                   0                                                                                        172.17.0.1:57522                                               172.17.0.1:amqp              users:(("python",pid=6051,fd=46))                                              
tcp              ESTAB                  0                   0                                                                                        172.17.0.1:57518                                               172.17.0.1:amqp              users:(("python",pid=6051,fd=44))                                              
tcp              ESTAB                  0                   0                                                                                        172.17.0.1:57520                                               172.17.0.1:amqp              users:(("python",pid=6051,fd=45))                                              
tcp              LISTEN                 0                   128                                                                                               *:amqp                                                         *:*                 users:(("beam.smp",pid=1741,fd=56))                                            
tcp              ESTAB                  0                   0                                                                               [::ffff:172.17.0.1]:amqp                                     [::ffff:192.168.1.59]:57518             users:(("beam.smp",pid=1741,fd=14))                                            
tcp              ESTAB                  0                   0                                                                               [::ffff:172.17.0.1]:amqp                                     [::ffff:192.168.1.59]:57520             users:(("beam.smp",pid=1741,fd=15))                                            
tcp              ESTAB                  0                   0                                                                               [::ffff:172.17.0.1]:amqp                                     [::ffff:192.168.1.59]:57522             users:(("beam.smp",pid=1741,fd=16))               

Your worker will be the python process. If you have more processes running you'll need to narrow it down to the pid of the main worker process using ps aux or similar. There will be 2-3 file descriptors that the process has open towards rabbitmq, which increase linearly from some starting value. We're interested in the second one, fd=45 in this example. I'll refer to the pid of the main worker process as $PID in subsequent commands. Also make note of the port associated with that file descriptor, 57520 in this example. I'll refer to it as $PORT subsequently.

  1. Run sudo strace -tt -f -s 1000 -p $PID -e trace=sendto. You'll see celery sending heartbeat messages to the mentioned second file descriptor (45 in this example).
10:40:20.011043 sendto(45, "\1\0\1\0\0\0!\0<\0(\0\0\10celeryev\20worker.heartbeat\0\316\2\0\1\0\0\0H\0<\0\0\0\0\0\0\0\0\1\20\370\0\20application/json\5utf-8\0\0\0\35\10hostnameS\0\0\0\17celery@amaranth\1\0\316\3\0\1\0\0\1\20{\"hostname\": \"celery@amaranth\", \"utcoffset\": -2, \"pid\": 6051, \"clock\": 481, \"freq\": 2.0, \"active\": 0, \"processed\": 0, \"loadavg\": [0.56, 0.68, 0.61], \"sw_ident\": \"py-celery\", \"sw_ver\": \"4.2.1\", \"sw_sys\": \"Linux\", \"timestamp\": 1536741620.0103393, \"type\": \"worker-heartbeat\"}\316", 401, 0, NULL, 0) = 401
  1. Now we're going to use tcpkill to simulate the issue where celery workers can lose connections under high load. Run sudo tcpkill -i lo host 172.17.0.1 and port $PORT, substituting the network interface passed to -i and the ip address with the ones you're using. tcpkill will run continuously, but you can close it after it's printed its initial output. You can verify with ss that the connection is gone.

  2. Run sudo strace -tt -f -s 1000 -p $PID -e trace=sendto again. There will be repeated SIGPIPE errors.

11:14:53.978952 sendto(45, "\1\0\1\0\0\0!\0<\0(\0\0\10celeryev\20worker.heartbeat\0\316\2\0\1\0\0\0H\0<\0\0\0\0\0\0\0\0\1\17\370\0\20application/json\5utf-8\0\0\0\35\10hostnameS\0\0\0\17celery@amaranth\1\0\316\3\0\1\0\0\1\17{\"hostname\": \"celery@amaranth\", \"utcoffset\": -2, \"pid\": 6051, \"clock\": 2476, \"freq\": 2.0, \"active\": 0, \"processed\": 0, \"loadavg\": [0.79, 0.7, 0.73], \"sw_ident\": \"py-celery\", \"sw_ver\": \"4.2.1\", \"sw_sys\": \"Linux\", \"timestamp\": 1536743693.978148, \"type\": \"worker-heartbeat\"}\316", 400, 0, NULL, 0) = -1 EPIPE (Broken pipe)
11:14:53.979275 --- SIGPIPE {si_signo=SIGPIPE, si_code=SI_USER, si_pid=6051, si_uid=1000} ---
  1. Monitor the resident memory size of the main worker process over a longer time period, say half an hour. For example using pidstat -r -p $PID 1. In my case the memory size increases and keeps increasing by about 20 megabytes per hour.

Expected behavior

  1. The connection reappears after killing it
  2. There are no SIGPIPE errors
  3. Ideally no leaking, but that might not be because of Celery

Example log message when issue 1 (losing connections under load) happens.

This is the log from the worker for app1. app2 is a different application that has its own workers.

[2018-08-30 09:19:02,621: INFO/MainProcess] [2018-08-30 09:19:02Z] missed heartbeat from app2@worker-1
[2018-08-30 09:19:08,588: INFO/MainProcess] [2018-08-30 09:19:08Z] sync with app2@worker-2
[2018-08-30 09:19:08,589: ERROR/MainProcess] [2018-08-30 09:19:08Z] Control command error: ConnectionResetError(104, 'Connection reset by peer')
[2018-08-30 09:19:10,349: INFO/MainProcess] [2018-08-30 09:19:10Z] sync with app2@worker-1

Activity

  1. mgeens commented on Sep 12, 2018

    @mgeens
    ContributorAuthor

    I was able to reproduce the connection loss under load issue on my local machine using the above example. This is using the master branch at https://github.com/celery/celery/tree/ed17e12b14051bac51b84593cf7c8cf21c77e010

    1. Make a copy of tasks.py and rename it as tasks2.py, do the same with the 'tasks' string inside it, as well as the add function for good measure:
    from celery import Celery                                           
                                                                        
    app = Celery('tasks2', broker='pyamqp://guest:[email protected]//')
                                                                        
                                                                        
    @app.task                                                           
    def add2(x, y):                                                     
        return x + y                                                    
    
    1. Start two celery workers running each of the two tasks, preferably in two side-by-side terminals:
      python -m celery worker -A tasks --loglevel=debug -n tasks@%h
      python -m celery worker -A tasks2 --loglevel=debug -n tasks2@%h

    2. In another terminal run stress and max out your cores, I used stress --cpu 8 --io 8. It seems it can sometimes also reproduce without this step, but it seems to happen less frequently. Maybe a red herring. Update 2: indeed a red herring, you just need to wait until the heartbeat timeouts in step 4 happen.

    3. Wait 5 minutes. Update: you can also watch the rabbitmq log with tail -f. After a few minutes, it will report closing two AMQP connections due to a heartbeat timeout. See the log below. After that happens, proceed to the next step.

    4. Close the first worker with ctrl-c. The second worker will note its departure tasks@amaranth left.

    5. Start the first worker again.

    6. The second worker will show a connection reset error:

    [2018-09-12 15:40:29,667: DEBUG/MainProcess] tasks@amaranth left
    [2018-09-12 15:40:36,266: DEBUG/MainProcess] tasks@amaranth joined the party
    [2018-09-12 15:40:36,327: DEBUG/MainProcess] pidbox received method hello(from_node='tasks@ama
    ranth', revoked={}) [reply_to:{'exchange': 'reply.celery.pidbox', 'routing_key': '4c5426c9-c12
    5-3e77-9ab4-d192e8d5daad'} ticket:2ca161a9-10b0-4304-a67e-4c5bfbbcff1a]
    [2018-09-12 15:40:36,327: INFO/MainProcess] sync with tasks@amaranth
    [2018-09-12 15:40:36,328: ERROR/MainProcess] Control command error: ConnectionResetError(104, 
    'Connection reset by peer')
    Traceback (most recent call last):
      File "/home/rgeens/Development/celery/celery/worker/pidbox.py", line 46, in on_message
        self.node.handle_message(body, message)
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/pidbox
    .py", line 129, in handle_message
        return self.dispatch(**body)
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/pidbox
    .py", line 112, in dispatch
        ticket=ticket)
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/pidbox
    .py", line 135, in reply
        serializer=self.mailbox.serializer)
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/pidbox
    .py", line 265, in _publish_reply
        **opts
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/messag
    ing.py", line 181, in publish
        exchange_name, declare,
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/messag
    ing.py", line 194, in _publish
        [maybe_declare(entity) for entity in declare]
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/messag
    ing.py", line 194, in <listcomp>
        [maybe_declare(entity) for entity in declare]
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/messag
    ing.py", line 102, in maybe_declare
        return maybe_declare(entity, self.channel, retry, **retry_policy)
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/common
    .py", line 129, in maybe_declare
        return _maybe_declare(entity, declared, ident, channel, orig)
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/common
    .py", line 135, in _maybe_declare
        entity.declare(channel=channel)
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/kombu/entity
    .py", line 185, in declare
        nowait=nowait, passive=passive,
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/amqp/channel
    .py", line 614, in exchange_declare
        wait=None if nowait else spec.Exchange.DeclareOk,
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/amqp/abstrac
    t_channel.py", line 50, in send_method
        conn.frame_writer(1, self.channel_id, sig, args, content) 
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/amqp/method_
    framing.py", line 166, in write_frame                                                         
        write(view[:offset])                                                                      
      File "/home/rgeens/PycharmProjects/celery-leak/venv/lib/python3.6/site-packages/amqp/transpo
    rt.py", line 275, in write                                                                    
        self._write(s)                                                                            
    ConnectionResetError: [Errno 104] Connection reset by peer                                    
    [2018-09-12 15:40:36,335: DEBUG/MainProcess] Closed channel #2                                
    [2018-09-12 15:40:36,336: DEBUG/MainProcess] using channel_id: 2                              
    [2018-09-12 15:40:36,337: DEBUG/MainProcess] Channel open                                     
    [2018-09-12 15:40:45,771: DEBUG/MainProcess] heartbeat_tick : for connection 0a1ccf9d8d324d86b
    8940e4a520cb97e                                                                               
    [2018-09-12 15:40:45,771: DEBUG/MainProcess] heartbeat_tick : Prev sent/recv: 31/991, now - 38
    /1054, monotonic - 109608.816287304, last_heartbeat_sent - 109608.81628547, heartbeat int. - 6
    0 for connection 0a1ccf9d8d324d86b8940e4a520cb97e                                             
    

    This method has been fairly consistent for me, but it seems some chance is still involved.

    Rabbitmq log:

    =INFO REPORT==== 12-Sep-2018::15:35:04 ===                                           [278/5994]
    accepting AMQP connection <0.5486.0> (192.168.1.59:52786 -> 172.17.0.1:5672)                   
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:35:04 ===                                                     
    connection <0.5486.0> (192.168.1.59:52786 -> 172.17.0.1:5672): user 'guest' authenticated and 
    granted access to vhost '/'                                                                    
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:35:04 ===                                                     
    accepting AMQP connection <0.5506.0> (192.168.1.59:52788 -> 172.17.0.1:5672)                   
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:35:04 ===                                                     
    connection <0.5506.0> (192.168.1.59:52788 -> 172.17.0.1:5672): user 'guest' authenticated and 
    granted access to vhost '/'                                                                    
                                                                                                   
    =ERROR REPORT==== 12-Sep-2018::15:38:02 ===                                                    
    closing AMQP connection <0.5447.0> (192.168.1.59:52778 -> 172.17.0.1:5672):                    
    missed heartbeats from client, timeout: 60s                                                    
                                                                                                   
    =ERROR REPORT==== 12-Sep-2018::15:38:04 ===                                                    
    closing AMQP connection <0.5506.0> (192.168.1.59:52788 -> 172.17.0.1:5672):                    
    missed heartbeats from client, timeout: 60s                                                    
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:30 ===                                                     
    closing AMQP connection <0.5427.0> (192.168.1.59:52776 -> 172.17.0.1:5672, vhost: '/', user: 'n
    obody')                                                                                        
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:30 ===                                                     
    closing AMQP connection <0.5420.0> (192.168.1.59:52774 -> 172.17.0.1:5672, vhost: '/', user: 'n
    obody')                                                                                        
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:36 ===                                                     
    accepting AMQP connection <0.5569.0> (192.168.1.59:53228 -> 172.17.0.1:5672)                   
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:36 ===                                                     
    connection <0.5569.0> (192.168.1.59:53228 -> 172.17.0.1:5672): user 'guest' authenticated and 
    granted access to vhost '/'                                                                    
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:36 ===                                                     
    accepting AMQP connection <0.5576.0> (192.168.1.59:53230 -> 172.17.0.1:5672)                   
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:36 ===                                                     
    connection <0.5576.0> (192.168.1.59:53230 -> 172.17.0.1:5672): user 'guest' authenticated and 
    granted access to vhost '/'                                                                    
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:36 ===                                                     
    accepting AMQP connection <0.5596.0> (192.168.1.59:53232 -> 172.17.0.1:5672)                   
                                                                                                   
    =INFO REPORT==== 12-Sep-2018::15:40:36 ===                                                     
    connection <0.5596.0> (192.168.1.59:53232 -> 172.17.0.1:5672): user 'guest' authenticated and 
    granted access to vhost '/'                                                                    
    
  2. auvipy commented on Sep 12, 2018

    @auvipy
    Member

    thanks for the detailed report. do you have any fix in mind? or any suggestions?

  3. mgeens commented on Sep 13, 2018

    @mgeens
    ContributorAuthor

    I haven't looked into a fix yet. At work they're switching to a redis broker which would seem to avoid the whole issue, so I probably can't justify spending more time on it there. However, I'm still interested in finding the root causes for these issues and fixing them, so I intend to spend some of my spare time on it.

  4. auvipy commented on Sep 13, 2018

    @auvipy
    Member

    I have tagged this for django con us sprint 2018

  5. mgeens commented on Sep 22, 2018

    @mgeens
    ContributorAuthor

    I found the cause of the broken pipe error and leak and made a fix. More details in the pull request.

  6. mgeens commented on Oct 28, 2018

    @mgeens
    ContributorAuthor

    I had a look at the AMQP network traffic when doing #5047 (comment). When the two tasks are running, rabbitmq sends 4 AMQP heartbeat messages to the workers every 60 seconds (2 for each worker). This seems to make sense given that they each have 2 connections open to rabbitmq. However, each worker only sends back 1 heartbeat in response. After about 3 minutes 2 closing AMQP connection <snip> missed heartbeats from client, timeout: 60s messages appear in the rabbitmq server log. In the network traffic, rabbitmq only sends 2 AMQP heartbeat messages from this point on, which receive 2 replies.

    In other words, it looks like 1 of the connections on each worker isn't responding to rabbitmq's heartbeat, and rabbitmq ends up terminating the connection in response eventually.

    It should be noted that this is using the amq library. When I switched to librabbitmq (updating the broker urls to start with librabbitmq://), I noticed there were no AMQP heartbeats in the network traffic. The issue also didn't reproduce anymore.

    So I suspect the connection loss issue either has to do with how Celery is currently using the amq library or something in amq itself going wrong. It also suggests that using librabbitmq instead of amq could be a workaround for people having these connection loss issues.

    Packet dumps from doing #5047 (comment) with both amq and librabbitmq: celery-rabbitmq-pcap.zip . The amq one has everything except heartbeats filtered out, the librabbitmq one has all amqp communication.

  7. added this to the v4.3 milestone on Nov 22, 2018
  8. kosmos342 commented on Dec 28, 2018

    @kosmos342
    Contributor

    Why this issue was closed? I though that py-amqp is recommended celery/librabbitmq#118 (comment)

  9. iwinux commented on Mar 21, 2019

    @iwinux

    This might not be completely related to RabbitMQ. I was trying out the experimental Redis Cluster transport, and encountered serious memory leak as well. My observations:

    1. memory leak stops when --without-heartbeat is specified.
    2. it seems that Celery is creating a lot of Channel instances somewhere (confirmed by printing logs in Channel constructor)
  10. mgeens commented on Mar 21, 2019

    @mgeens
    ContributorAuthor

    Yes, the memory leak wasn't tied to rabbitmq as such, it was because of the heartbeat connection in Celery leaking if it died, which is why disabling it helps. A fix for that should be in 4.3.

    The reason the connection failed in the first place does have something to do with rabbitmq, and I'm not aware of that having been resolved yet.

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