Skip to content

Clarify support for forking process models #3307

Open

Description

@PeterJCLaw

https://opentelemetry-python.readthedocs.io/en/latest/examples/fork-process-model/README.html indicates that BatchSpanProcessor does not support forking process models, including those used by Gunicorn and uWSGI. However those docs (#1609) pre-date other changes which appear to have added support for forking process models, including:

which seem specifically targetted at resolving the described issues.

What is the current expected state of support for the various forking models?
Either way, updating the docs to clarify the actual situation would be appreciated.

Possibly related issues:

Activity

  1. aabmass commented on May 11, 2023

    @aabmass
    Member

    Thanks for opening this issue, I think it is an important topic.

    Afaik, things should be working for tracing at this point. Metrics are a little more complicated and #2837 is definitely still valid. It would be great if we could clean up old issues/documentation and would definitely appreciate help on this if you have the time @PeterJCLaw.

    @srikanthccv last worked on this, do you know if any of the linked bugs can be closed out now?

  2. srikanthccv commented on May 11, 2023

    @srikanthccv
    Member
  3. PeterJCLaw commented on May 11, 2023

    @PeterJCLaw
    Author

    Thanks for those additional details.

    • I think 4th linked issue can be closed; however, it's better to verify once before closing.

    What does verification look like here? Given the nature of this as a forking issue I'd kinda assumed the failure mode was race conditions and the like -- timing based and hard to reproduce/be sure if fixed just from testing. Is there a known reproduction of the failure mode or something we can do to check that it's working as intended?
    (Or is it a cased of code inspection?)

  4. srikanthccv commented on May 11, 2023

    @srikanthccv
    Member

    The verification can be pretty simple. If you run a simple gunicorn based application with multiple workers (Without following the special instructions mentioned in the docs), it should export the traces/metrics/logs. If they are not exported (to the collector, console etc.), then the issue still exists.

  5. PeterJCLaw commented on May 11, 2023

    @PeterJCLaw
    Author

    Hrm, ok. I'm currently running gunicorn with the default worker type and that does seem to work. My reading of gunicorns docs indicate that the master process doesn't actually load the application though -- only the workers do (after the fork happens), unless you use the --preload option (which I'm currently not doing).

    I'll see if I can find some time to validate the behaviours under gunicorn & uwssgi.

    Edit for clarity: my use of gunicorn without --preload works fine -- I get tracing reported even though I'm using BatchSpanProcessor.

  6. srikanthccv commented on May 12, 2023

    @srikanthccv
    Member

    I am confused now. Is it working or not working with gunicorn?

  7. PeterJCLaw commented on May 13, 2023

    @PeterJCLaw
    Author

    My current setup is using gunicorn without calling --preload and that seems to work.
    Not using --preload under gunicorn seems to be the default, though the open telemetry docs seem to imply that they're expecting the inverse -- that gunicorn will preload before forking.

  8. PeterJCLaw commented on May 13, 2023

    @PeterJCLaw
    Author

    I've just tested a toy application under gunicorn and uWSGI, using both their --preload and --lazy-apps modes (and not) respectively using https://gist.github.com/PeterJCLaw/5e6fd585d0c620496c82ca926ce50f67. All four configurations seem to work ok -- I get traces printed out to the console which seem reasonable.

    I'm not sure how to validate that the desired batching is happening, though I can see that the traces are often not printed until several requests later which suggests that it is working.

  9. srikanthccv commented on May 14, 2023

    @srikanthccv
    Member

    I've just tested a toy application under gunicorn and uWSGI, using both their --preload and --lazy-apps modes (and not) respectively using https://gist.github.com/PeterJCLaw/5e6fd585d0c620496c82ca926ce50f67. All four configurations seem to work ok -- I get traces printed out to the console which seem reasonable.

    Thank you, this confirms the above statement that traces and logs batch processors work all the time.

    I'm not sure how to validate that the desired batching is happening, though I can see that the traces are often not printed until several requests later which suggests that it is working

    They are emitted if the queue becomes full or batch timeout elapses. I think this is working fine.

  10. PeterJCLaw commented on Jun 6, 2023

    @PeterJCLaw
    Author

    Unfortunately while it looks like the BatchSpanProcessor does actually work fine, the PeriodicExportingMetricReader appears not to. I've not tested it under all the various configurations previously discussed, however I have observed it not working correctly in uWSGI's default mode (i.e: where it imports the WSGI app before forking). In that case the ticker thread only exists in the main process, presumably meaning that metrics are only collected from that main process. I'd guess this is due to PeriodicExportingMetricReader using the approach from #2242 rather then the enhanced approach introduced in #2277.

    Edit: using uWSGI's --lazy-apps to delay the import does get PeriodicExportingMetricReader running in all the worker processes.

  11. PeterJCLaw commented on Jun 6, 2023

    @PeterJCLaw
    Author

    Hrm, the uWSGI side of this may be somewhat resolvable by users. Ish. Via https://stackoverflow.com/a/72601192 and unbit/uwsgi#2388 it seems that uWSGI has some extra options which can be used to enable os.register_at_fork to work -- specifically --py-call-osafterfork. There's also --enable-threads which seems to be needed to enable workers to have threads. Unfortunately in local testing I'm seeing that using those two options together results in uWSGI not serving any requests (at all); while using just --py-call-osafterfork seems to lock up one of the two workers I'm running with. Not sure yet if this is a uWSGI issue generally (definitely feels like it could be) or something to do with threads. I doubt it's open-telemetry specific. Posting here as hopefully useful to others hitting this.

  12. SharifiFaranak commented on Jan 29, 2024

    @SharifiFaranak

    +1 to updating docs here since BatchSpanProcessor is working well with Gunicorn. It cost me more than a few hours trying to get the post_fork hook to work (which didn't end up working) when it wasn't necessary.

  13. alexmojaki commented on Oct 14, 2024

    @alexmojaki
    Contributor

    It seems that BatchSpanProcessor works fine, but not OTLPSpanExporter (with --preload). Given test.py containing:

    from flask import Flask
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
    from opentelemetry.instrumentation.flask import FlaskInstrumentor
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcessor, ConsoleSpanExporter
    
    # BatchSpanProcessor works fine
    # exporter = ConsoleSpanExporter()
    # span_processor = BatchSpanProcessor(exporter)
    
    # But OTLPSpanExporter does not
    exporter = OTLPSpanExporter()
    span_processor = SimpleSpanProcessor(exporter)
    
    tracer_provider = TracerProvider()
    tracer_provider.add_span_processor(span_processor)
    
    app = Flask(__name__)
    FlaskInstrumentor().instrument_app(app, tracer_provider=tracer_provider)
    
    
    @app.route('/')
    def hello():
        return 'Hello!'

    and running gunicorn --workers=2 --preload test:app, visiting http://127.0.0.1:8000 causes an error:

    objc[37636]: +[NSCharacterSet initialize] may have been in progress in another thread when fork() was called.
    objc[37636]: +[NSCharacterSet initialize] may have been in progress in another thread when fork() was called. We cannot safely call it or ignore it in the fork() child process. Crashing instead. Set a breakpoint on objc_initializeAfterForkError to debug.
    [2024-10-14 13:50:45 +0200] [37634] [ERROR] Worker (pid:37636) was sent SIGKILL! Perhaps out of memory?
    
  14. alexmojaki commented on Jan 8, 2025

    @alexmojaki
    Contributor

    Running this code:

    import warnings
    from multiprocessing import Process, set_start_method
    
    from opentelemetry.sdk.metrics.export import ConsoleMetricExporter, PeriodicExportingMetricReader
    
    warnings.simplefilter('always')
    set_start_method('fork')
    
    PeriodicExportingMetricReader(ConsoleMetricExporter())
    
    Process(target=lambda: None).start()

    causes a warning:

    /Users/alex/.pyenv/versions/3.12.6/lib/python3.12/multiprocessing/popen_fork.py:66: DeprecationWarning: This process (pid=5221) is multi-threaded, use of fork() may lead to deadlocks in the child.
      self.pid = os.fork()
    

    This is documented in https://docs.python.org/3/library/os.html#os.fork.

    I'd guess this is due to PeriodicExportingMetricReader using the approach from #2242

    Is it though? #2242 made BatchSpanProcessor create a fresh lock:

    def _at_fork_reinit(self):
    self.condition = threading.Condition(threading.Lock())
    self.queue.clear()
    # worker_thread is local to a process, only the thread that issued fork continues
    # to exist. A new worker thread must be started in child process.
    self.worker_thread = threading.Thread(
    name="OtelBatchSpanProcessor", target=self.worker, daemon=True
    )
    self.worker_thread.start()
    self._pid = os.getpid()

    PeriodicExportingMetricReader only starts a new thread, it doesn't create a fresh lock:

    def _at_fork_reinit(self):
    self._daemon_thread = Thread(
    name="OtelPeriodicExportingMetricReader",
    target=self._ticker,
    daemon=True,
    )
    self._daemon_thread.start()

    I don't understand the technical details of the problem with fork(). But the fact that the Python warning says "use of fork() may lead to deadlocks in the child" makes me think that not sharing locks is important. I understand that BatchSpanProcessor also triggers the warning, but at least I see signs of the problem being addressed there.

  15. srikanthccv commented on Jan 10, 2025

    @srikanthccv
    Member

    Wanted to chime in and share the context, as I spent relatively more time in this area than other maintainers

    PeriodicExportingMetricReader only starts a new thread, it doesn't create a fresh lock:

    Either we overlooked it, or there were no sync variables other than the worker thread at the time fork hook patch, and later, some locks were introduced but never cleaned up in the fork hook. We should fix this.

    I don't understand the technical details of the problem with fork(). But the fact that the Python warning says "use of fork() may lead to deadlocks in the child" makes me think that not sharing locks is important. I understand that BatchSpanProcessor also triggers the warning, but at least I see signs of the problem being addressed there.

    Correct, we do the same for BatchLogProcessor as well

    def _at_fork_reinit(self):
    self._condition = threading.Condition(threading.Lock())
    self._queue.clear()
    self._worker_thread = threading.Thread(
    name="OtelBatchLogRecordProcessor",
    target=self.worker,
    daemon=True,
    )
    self._worker_thread.start()
    self._pid = os.getpid()

    The following resource explains the issue in detail

    A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources.

    https://pubs.opengroup.org/onlinepubs/9699919799/functions/fork.html

    When fork() is called, only the calling thread is duplicated in the child process. Synchronization variables remain in the same state in the child as they were in the parent at the time fork() was called. Thus, for example, mutex locks may be held by threads that no longer exist in the child process, and any associated states may be inconsistent. The intention was that the parent process could have avoided this by explicit code that acquires and releases locks critical to the child via pthread_atfork(). In addition, any critical threads would have needed to be recreated and reinitialized to the proper state in the child (also via pthread_atfork()).

    https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_atfork.html

    So, to avoid the dead threads and inconsistent state, we are recreating all the sync variables in the child process. cpython standard lib modules also make use of the atfork handler to clean up the inconsistent state https://github.com/search?q=repo%3Apython%2Fcpython%20register_at_fork&type=code

    Although the changes from #2242 helped, they didn't fix the issue for users running uWSGI. Therefore, we introduced an additional workaround in #2277, using the PID to reset state. This approach solves the problem of logs and traces because they get pushed to the processor queue, allowing us to detect the child process via PID and then clean up. However, metrics are pulled (and exported without a queue), so PeriodicExportingMetricReader can’t clear its inconsistent state except via _at_fork_reinit

  16. alexmojaki commented on Jan 10, 2025

    @alexmojaki
    Contributor

    Could PeriodicExportingMetricReader check the PID before acquiring a lock?

  17. srikanthccv commented on Jan 11, 2025

    @srikanthccv
    Member

    No, as the worker thread that initiates the collection no longer exists in the child process

  18. rodda-kyusu commented on Mar 19, 2025

    @rodda-kyusu

    I'm a little confused as to the conclusion of this thread, is the following a fair summary?

    PeriodicExportingMetricReader is not compatible with a fork / cooperative multiprocessing environment, like the one used by gunicorn w/ gevent.

    I'm having a devil of a time getting PeriodicExportingMetricReader to work with gunicorn and gevent. Is there a working example to point to with this working? I think traces and logging works out of the box as indicated above in this thread.

  19. ZombieFoodDan commented on May 13, 2025

    @ZombieFoodDan

    While the batch exporters re-init themselves they don't re-init the underlying self._exporter (which in the case of e.g. the standard http OTLPLogExporter contains a long-lived requests.session(), which is unsafe to use post fork if it was used/in use pre-fork).

    psf/requests#4323

    Keeping a requests.session object across a fork seems to be unsafe thanks to the underlying use of urllib3's connection pool (specifically in the case where you've used it at least once pre-fork).

    Most likely OTLPLogExporter/OTLPSpanExporter/etc.. also need an _at_fork_reinit() style change to fix themselves post fork.

  20. drozdowsky commented on Feb 12, 2026

    @drozdowsky

    I just encountered similar issues when working with Celery.
    We have added the instrumentation also to the Main Celery Process (because it consumes some custom events), so when process forks the workers end up with broken instrumentation:

    [2026-02-12 10:45:47,755: ERROR/ForkPoolWorker-2] Failed to export metrics to otel-collector:4317, error code: StatusCode.DEADLINE_EXCEEDED
    

    I know it's probably not a priority but it would be great to have some way to instrument both the parent and the forks.
    In our production setting forked workers are being restarted (forked again) every X tasks so delaying the instrumentation in parent is not an option (I still have to confirm this since I am not sure how this celery forks happen).

  21. ocelotl commented on Jul 1, 2026

    @ocelotl
    Contributor

    More related issues: #4994 #4215 #4759

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

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions