Skip to content

Support forkserver as a worker_pool_start_method #11096

Open

Description

@tzifudzi

Checklist

  • I have checked the issues list
    for similar or identical feature requests.
  • I have checked the pull requests list
    for existing proposed implementations of this feature.
  • I have checked the commit log
    to find out if the same feature was already implemented in the
    main branch.
  • I have included all related issues and possible duplicate issues
    in this issue (If there are none, check this box anyway).

Related Issues and Possible Duplicates

Related Issues

Possible Duplicates

  • None found

Brief Summary

This enhancement adds forkserver as an opt-in start method for Celery’s prefork pool, alongside fork and spawn.

fork offers fast startup and memory sharing but has the risk of inheriting fork-unsafe state. spawn provides cleaner initialization at the cost of higher startup latency and memory overhead. Users must therefore choose one approach and accept its trade-offs.

forkserver keeps the benefits of fork while making it safer:

  1. Like fork, workers start quickly and share memory, because they are copied from a fork server that has already preloaded the application.
  2. Unlike fork, workers are copied from that server rather than the running parent, so they never inherit what the parent or its libraries set up later, such as gRPC clients, which gRPC Python "doesn't support" across fork() (see grpc/grpc#31885 and Allow celery to spawn rather than fork #6036).

Further motivation for adding Celery forkserver support is that Python 3.14 made forkserver the default start method on Linux, reinforcing the case for making it a supported option in Celery.

Design

Proposed UI/UX

Users can select forkserver through worker_pool_start_method or the existing --pool-start-method CLI option. No new hooks are proposed. The existing worker_process_init hook can be used to defer resource setup until after forking, and worker_process_shutdown for best-effort cleanup.

A new optional setting lets users list modules to load into the fork server before it creates workers. An empty list means no application preloading.

Configuration setting CLI option Default Example Constraints
worker_forkserver_preload --forkserver-preload [] ['myapp.preload'] Only valid with forkserver.

Architectural Considerations

Proposed billiard changes

  • Billiard already provides forkserver. The proposal is to extend billiard to enable Celery support.
  • File descriptor handling
    • For forkserver to work reliably, the Celery parent worker needs to know the correct file descriptor numbers to acknowledge tasks and mark the right worker as available. Under forkserver today, they can differ between parent and child, as was observed in prefork is not safe anymore #10339, "With forkserver they get renumbered, and I can reproduce the breakage there".
    • They differ because fd numbers are per process, and under forkserver the child receives the pipe over a Unix socket rather than inheriting it, so the kernel assigns it the child's lowest free number, which can differ from the parent's.
    • The proposal is for billiard to preserve identifiers that Celery can recognize on the parent side.
  • Fork server recovery
    • Billiard currently does not detect or replace a dead server. Once it dies, attempts to create replacement workers fail, because nothing is listening on the dead server's socket.
    • The proposal is for billiard to detect server death and restart the server.

Keeping existing users unaffected

  • Current fork and spawn behavior will be preserved to reduce disruption.
  • The new mode is proposed as opt-in, with no change to existing multiprocessing defaults.

Unsupported platforms

  • Support will only be added for Linux and macOS. Windows will be left unsupported since it only supports spawn as of today.

Proposed Behavior

Matching worker identifiers in parent and child

  • Today, the child works out its worker identifiers from its own file descriptor table, which under forkserver gives different numbers from the parent's.
  • The proposal is for billiard to send the parent's numbers to the child in Worker.__reduce__, so the child does not infer them. The child then reliably reports the numbers the parent expects: inqW_fd in READY messages and synqW_fd in ACK messages.

Child creation, once per child

sequenceDiagram
    participant CE as Parent (Celery)
    participant BP as Parent (Billiard)
    participant BC as Child (Billiard)

    Note over BP: creates inq pipe, write end is fd 4
    BP->>CE: new worker, identifier 4
    BP->>BC: pipe sent over Unix socket
    Note over BC: same pipe arrives as fd 10
    BP->>BC: inqW_fd = 4 sent with the worker
Loading

Running a task, repeated for every task

sequenceDiagram
    participant CE as Parent (Celery)
    participant BP as Parent (Billiard)
    participant BC as Child (Billiard)

    Note over BC: holds inqW_fd = 4 from creation
    CE->>BC: task A, Celery marks 4 busy
    BC->>BP: READY with inqW_fd = 4
    BP->>CE: worker 4 is ready
    Note over CE: 4 removed from busy set, child is free
Loading

Recovering from fork server death

  • The proposal is to port CPython’s existing on-demand recovery into billiard, rather than introduce a separate monitoring mechanism.
  • Before creating a child, billiard's ForkServer.ensure_running will check whether the forkserver process is still alive.
  • If it is, the existing server will be reused. If the server has exited, billiard will reap it, close stale descriptors and clear the cached server state before launching a replacement.
  • If fork server recovery fails, the parent will continue serving tasks through any surviving healthy children. Failed child creation will be cleaned up and retried during subsequent pool maintenance.
sequenceDiagram
    participant CE as Parent (Celery)
    participant BP as Parent (Billiard)
    participant FS as Fork server (Billiard)

    Note over FS: fork server dies
    Note over CE: surviving children keep serving tasks

    Note over CE,FS: Next time a child is needed
    CE->>BP: maintain the pool
    Note over BP: checks the server, finds it dead
    Note over BP: reaps it, closes stale descriptors, clears cached state
    BP->>FS: launches a replacement server
    alt launch succeeds
        BP->>FS: requests a child
    else launch fails
        Note over BP: cleans up, retries at next pool maintenance
    end
Loading

Preloading modules into the fork server

  • Today, Celery has no way to tell the fork server which modules to load, so each child imports the application itself, which is about as slow as spawn.
  • The proposal is for Celery to pass the modules listed in worker_forkserver_preload to billiard's existing set_forkserver_preload, from TaskPool.on_start, where the start method is set today. The fork server imports them once, before it creates any children, and every child inherits them.

Reloading code with pool restarts

  • With fork and spawn, a pool restart reloads task modules in the parent and replaces the children, so new children run the new code. Pool restarts are opt-in through worker_pool_restarts.
  • The proposal is for a pool restart, in billiard's Pool.restart, to also replace the fork server.
sequenceDiagram
    participant CE as Parent (Celery)
    participant BP as Parent (Billiard)
    participant FS as Fork server (Billiard)
    participant CH as Child (Billiard)

    Note over CE,CH: User sends pool_restart with reload
    Note over CE: reloads task modules, parent has new code
    Note over FS: still has old code from startup
    CE->>BP: restart the pool
    BP->>FS: stops the old fork server
    BP->>FS: starts a new fork server
    Note over FS: imports preload modules again, now new code
    BP->>FS: request a replacement child
    FS->>CH: fork
    Note over CH: inherits the new code
Loading

Alternatives

Fixing the worker identifiers in Celery instead of billiard

  • Celery could override billiard's worker packing to send the parent's numbers itself. This works, but the packing logic lives in billiard, so a Celery override would depend on billiard's internals and could silently break whenever billiard changes them.

Monitoring the fork server continuously

  • A background thread or event-loop timer could watch the fork server and restart it as soon as it dies. Not proposed, because checking on demand is simpler, needs no extra thread or timer, and follows the approach CPython already uses.

Shutting the worker down when fork server recovery fails

  • The worker could stop with a clear error and rely on a process manager to restart it.
  • Not proposed, because the surviving children are still healthy and can keep serving tasks. The trade-off is that if recovery keeps failing, the pool shrinks each time a child is recycled.

Activity

  1. auvipy commented on Nov 14, 2026

    @auvipy
    Member

    here is already a open issue for this celery/billiard#200 may be you should start contributing

  2. tzifudzi commented on Nov 14, 2026

    @tzifudzi
    Author

    here is already a open issue for this celery/billiard#200

    @auvipy On Python 3, billiard already has forkserver support. celery/billiard#200 is for Python 2.

    may be you should start contributing

    Good idea thanks, I read contribution guidelines and will get started on this and propose a design and prototype for review.

  3. tzifudzi commented on Nov 22, 2026

    @tzifudzi
    Author

    I tested the proposed billiard fix locally by applying it as an override in a reproduction script, so it can be tried without changing billiard.

    Worker.__reduce__ is how billiard sends the worker to the child. Returning the parent's identifiers as state makes the child use them, instead of the numbers it works out from its own fd table:

    from billiard.pool import Worker
    
    _reduce = Worker.__reduce__
    
    def __reduce__(self):
        cls, args = _reduce(self)[:2]
        return cls, args, {"inqW_fd": self.inqW_fd, "synqW_fd": self.synqW_fd}
    
    Worker.__reduce__ = __reduce__
    # forkserver, without the fix
    forkserver completed: 2 / 8
      parent-side inqW fds:     [4, 8]
      fds reported by children: [10]
      still marked busy:        [4, 8]
    
    # forkserver, with the fix
    forkserver completed: 8 / 8
      parent-side inqW fds:     [4, 8]
      fds reported by children: [4, 8]
      still marked busy:        []
    
    Start method Without fix With fix
    forkserver 2 / 8 8 / 8
    forkserver, synack=True 7 / 8 8 / 8
    fork 8 / 8 8 / 8
    spawn 8 / 8 8 / 8

    fork and spawn are unaffected.

    Tested with Celery 5.7.0 and unmodified billiard 4.3.2 on macOS arm64, Python 3.14.6.

    Full script
    import os, time
    import billiard
    from billiard.pool import Worker
    from kombu.asynchronous import Hub, set_event_loop
    from celery.concurrency.asynpool import AsynPool
    
    if os.environ.get("FIX"):
        _reduce = Worker.__reduce__
    
        def __reduce__(self):
            cls, args = _reduce(self)[:2]
            return cls, args, {"inqW_fd": self.inqW_fd, "synqW_fd": self.synqW_fd}
    
        Worker.__reduce__ = __reduce__
    
    reported = set()
    
    class Pool(AsynPool):
        def on_job_ready(self, job, i, obj, inqW_fd):
            reported.add(inqW_fd)  # the fd number the child sent back
            super().on_job_ready(job, i, obj, inqW_fd)
    
    def main():
        billiard.set_start_method(os.environ.get("METHOD", "forkserver"), force=True)
        hub = Hub()
        set_event_loop(hub)
        pool = Pool(processes=2, synack=bool(os.environ.get("SYNACK")), threads=False, putlocks=False)
        pool.register_with_event_loop(hub)
        loop = hub.create_loop()
    
        results = [pool.apply_async(time.sleep, (0.1,)) for _ in range(8)]
        deadline = time.time() + 20
        while not all(r.ready() for r in results) and time.time() < deadline:
            next(loop)
    
        print(billiard.get_start_method(), "completed:", sum(r.ready() for r in results), "/ 8")
        print("  parent-side inqW fds:    ", sorted(p.inqW_fd for p in pool._pool))
        print("  fds reported by children:", sorted(reported))
        print("  still marked busy:       ", sorted(pool._busy_workers))
        pool.terminate()
    
    if __name__ == "__main__":  # spawn and forkserver re-import this file in each child
        main()

    Run with METHOD=forkserver python repro.py, then add FIX=1 and optionally SYNACK=1.

  4. tzifudzi commented on Nov 22, 2026

    @tzifudzi
    Author

    I read contribution guidelines and will get started on this and propose a design...

    @auvipy Following up on this, I've updated the description with the proposed design, and posted local test results in above comment. Could you take a look and let me know if you agree with the direction before I start implementing?

  5. auvipy commented on Nov 22, 2026

    @auvipy
    Member

    come with a pr and mention me

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions