Skip to content

Non-forking implementation #679

Closed
Closed

Description

@headius

Hello! I would like to offer my help making modifications to Solid Queue to support executing in-process using threads rather than out-of-process as a fork.

There's many issues with using fork:

  • Impossible to support on JRuby and TruffleRuby, as well as on Windows
  • Wastes system resources on CRuby by creating additional processes with their own working sets, GCs, and JITs.

The primary reason for using forks here is to get parallelism, which can be achieved easily by using threads on JRuby and TruffleRuby. The logic you have for starting up, managing, and terminating forked processes can be modified to do the same with threads, and no additional processes would be needed.

I have started playing with patches locally that swap calls to fork for calls to Thread.new with appropriate thread management code, and there's not really even that many places that would need to be changed. The bulk of the logic is all signals and waitpid, which map pretty easily to Thread#kill, Thread#raise, and Thread#join (or just let it die quietly).

Could we collaborate on this? I could start hacking on a branch this week.

Activity

  1. headius commented on Nov 4, 2025

    @headius
    Author

    I have not actually gotten Solid Queue to start up under JRuby, since I'm not a Rails guy and I don't know how to set that up. But the patch below is a ham-fisted attempt to swap forks for threads, and may be illustrative.

    diff --git a/lib/puma/plugin/solid_queue.rb b/lib/puma/plugin/solid_queue.rb
    index 434b8f6..6c8d547 100644
    --- a/lib/puma/plugin/solid_queue.rb
    +++ b/lib/puma/plugin/solid_queue.rb
    @@ -13,20 +13,20 @@ Puma::Plugin.create do
     
         if Gem::Version.new(Puma::Const::VERSION) < Gem::Version.new("7")
           launcher.events.on_booted do
    -        @solid_queue_pid = fork do
    -          Thread.new { monitor_puma }
    -          SolidQueue::Supervisor.start
    -        end
    +        @solid_queue_pid = #fork do
    +          # Thread.new { monitor_puma }
    +          Thread.new { SolidQueue::Supervisor.start }
    +        # end
           end
     
           launcher.events.on_stopped { stop_solid_queue }
           launcher.events.on_restart { stop_solid_queue }
         else
           launcher.events.after_booted do
    -        @solid_queue_pid = fork do
    -          Thread.new { monitor_puma }
    -          SolidQueue::Supervisor.start
    -        end
    +        @solid_queue_pid = #fork do
    +          # Thread.new { monitor_puma }
    +          Thread.new { SolidQueue::Supervisor.start }
    +        # end
           end
     
           launcher.events.after_stopped { stop_solid_queue }
    @@ -36,10 +36,12 @@ Puma::Plugin.create do
     
       private
         def stop_solid_queue
    -      Process.waitpid(solid_queue_pid, Process::WNOHANG)
    +      # Process.waitpid(solid_queue_pid, Process::WNOHANG)
           log "Stopping Solid Queue..."
    -      Process.kill(:INT, solid_queue_pid) if solid_queue_pid
    -      Process.wait(solid_queue_pid)
    +      solid_queue_pid.kill
    +      solid_queue_pid.join
    +      # Process.kill(:INT, solid_queue_pid) if solid_queue_pid
    +      # Process.wait(solid_queue_pid)
         rescue Errno::ECHILD, Errno::ESRCH
         end
     
    diff --git a/lib/solid_queue/supervisor.rb b/lib/solid_queue/supervisor.rb
    index ef9c79d..89fdfe5 100644
    --- a/lib/solid_queue/supervisor.rb
    +++ b/lib/solid_queue/supervisor.rb
    @@ -80,7 +80,7 @@ module SolidQueue
               instance.mode = :fork
             end
     
    -        pid = fork do
    +        pid = Thread.new do
               process_instance.start
             end
     
    @@ -130,20 +130,22 @@ module SolidQueue
           end
     
           def term_forks
    -        signal_processes(forks.keys, :TERM)
    +        forks.each(&:kill)
    +        # signal_processes(forks.keys, :TERM)
           end
     
           def quit_forks
    -        signal_processes(forks.keys, :QUIT)
    +        forks.each(&:kill)
    +        # signal_processes(forks.keys, :QUIT)
           end
     
           def reap_and_replace_terminated_forks
    -        loop do
    -          pid, status = ::Process.waitpid2(-1, ::Process::WNOHANG)
    -          break unless pid
    -
    -          replace_fork(pid, status)
    -        end
    +        # loop do
    +        #   pid, status = ::Process.waitpid2(-1, ::Process::WNOHANG)
    +        #   break unless pid
    +        #
    +        #   replace_fork(pid, status)
    +        # end
           end
     
           def reap_terminated_forks

    I suspect that the thread-based version will end up being quite a bit simpler than the fork-based version, since there's less hassle monitoring the supervisor and the lifecycle of the single process will apply to all worker threads (so no monitoring of a parent puma process).

  2. dhh commented on Nov 5, 2025

    @dhh
    Member

    Don't see how a thread based version is going to give us the throughput we need. Just like running puma on threads alone wouldn't. GVL is going to be a big factor here. But possible that a Ractor-based solution might work. Feel free to explore that and open a PR with benchmarks if you get somewhere with it.

  3. headius commented on Nov 5, 2025

    @headius
    Author

    @dhh My interest is for users of parallel-threaded implementations of Ruby like JRuby. We have had users and potential users asking what it would take for Solid Queue to work on JRuby.

    I think the answer is "not very much", and the threaded version would likely have less overhead than the forked version via shared memory and shared VM resources. A thread-based version would give you all the throughput you need in the same JRuby process without forking any additional processes.

  4. eregon commented on Nov 5, 2025

    @eregon

    From reading the issue, I think there is some misunderstanding here: Solid Queue would need to keep a fork-based implementation for CRuby, to get parallelism on CRuby (or use Ractor instead of fork, though that probably limits quite a bit what can run inside a job).

    And this issue as I understand it is about adding a Thread-based implementation, which would be used where Process.respond_to?(:fork) is false (JRuby, TruffleRuby, Windows, etc). I think that would be valuable.

  5. dhh commented on Nov 5, 2025

    @dhh
    Member

    Happy to accommodate JRuby, if we can make minimal incisions into the code to do so. But it's not a project that we as maintainers of Solid Queue will be taking on, as it's not a platform that we use. So whatever solution is proposed has to have no impact on CRuby running and be minimally invasive. If anyone is interested in pursuing that, please do open a PR 👍

  6. seuros commented on Nov 5, 2025

    @seuros
    Member

    Changing from Unix fork to threads will make it compatible with Java and Windows, but that totally changes the architecture. It will be a breaking change.

    JVM Rubies have real parallel threads with no GVL and correct isolation. CRuby doesn't have that privilege.

    The GVL means all threads are on one CPU core for Ruby execution, and if one thread crashes badly enough, the whole process is gone terminating the other jobs.

    I think the correct approach is to have a monkey patcher gem, that will give every engine solution. CRuby stays vanilla, Jruby use java executors, and Truffle can use threads.

    Windows ? They can install Omarchy/Omakub or test in production.

    Full implementation here , i had it working for jruby, just added truffleruby.

    The gem can be transferred to jruby org.

  7. eregon commented on Nov 5, 2025

    @eregon

    I think the correct approach is to have a monkey patcher gem, that will give every engine solution.

    That's nice to prototype but it's far from convenient for users, they have to discover that gem and by default it just doesn't work and errors.
    Having it integrated in this gem would make things just work, and ensure better testing by running all tests.
    It's also more reliable by not relying on monkey-patching.

    @seuros Would you be up to open a PR with your Executor from https://github.com/seuros/solid_queue-java/blob/master/lib/solid_queue/java/executor.rb here (used unless Process.respond_to?(:fork))? I think you could simplify to just the (Ruby) Thread-based executor, since that works fine on JRuby too, and is more familiar for Rubyists in general.

    Another option would be to use a concurrent-ruby thread pool, since concurrent-ruby is already a dependency of solid_queue. That's a more complete and well-tested thread pool implementation.

  8. rosa commented on Nov 5, 2025

    @rosa
    Member

    Hey! There's already some preliminary work on this in #644, which was from a previous attempt I made myself, but before this was made Rails's default, and so way before version 1.0.0. It needs some work (the PR reinstitutes that former feature). The idea is that it'd be completely orthogonal to the fork-based version (the default). We could also make it conditional on Process.respond_to?(:fork).

  9. seuros commented on Nov 5, 2025

    @seuros
    Member

    @eregon I could do that!

    But here’s my reasoning: this gem probably belongs in the JRuby org, alongside the other JDBC gems.

    Rails isn’t exactly plug-and-play on JRuby: every ActiveRecord adapter has its own JDBC Wrapper.

    The Java-based implementation I had works quite well for my use case, while the thread-based version comes from @headius in this PR.

    Adding multiple (or worse, triple) implementations inside this gem would just add complexity.

    Maintainers would then have to test against several JRuby and Java versions.

    If @rosa thinks it’s better to keep it here, that is fine too.

    The other gem isnt even released yet, it is just an extraction for now. Headius can decide its fate.

  10. rosa commented on Nov 5, 2025

    @rosa
    Member

    I think a version that uses threads instead of processes could be included here as per #644. My initial motivation to do it was to have a lighter version to use in development and in memory-contrained environments, but it could also support JRuby, even if that wasn't the original motivation. I think that'd be a matter of finishing #644, that still needs some work. If anyone is willing to do that work, I'd be happy to review!

  11. headius commented on Nov 5, 2025

    @headius
    Author

    I'm willing to assist with either firming up the prototype from @seuros or helping to finish #644 If I knew that it would be accepted into the project. I was a bit discouraged that my issue was summarily closed without any discussion of the actual benefits and seemingly without actually reading my description.

    Reopening this issue would help give me confidence that my work would not be ignored or discarded.

  12. rosa commented on Nov 5, 2025

    @rosa
    Member

    I'd say, from those two, only #644 would have a solid chance of being included. It's an open PR, and I generally close all PRs that I'm not willing to consider. Would that give you some more confidence?

  13. headius commented on Nov 5, 2025

    @headius
    Author

    @rosa It does seem that #644 has momentum, and I'm glad to see there are additional reasons for a non-forking version even when only considering CRuby.

    @seuros With JRuby-specific code I think your version would be unlikely to get merged as-is. Perhaps we can take what you have created and use that work to finish #644 on top of something like concurrent-ruby (already a Rails dependency)?

  14. CufeHaco commented on Nov 5, 2025

    @CufeHaco

    @headius I've been working on Unix domain socket support for JRuby (JEP-380)
    which I believe can help here in two ways:

    Approach 1: Thread-based (what you proposed)

    I can help modify Solid Queue to use Thread.new instead of fork.
    The signal handling → thread management mapping is straightforward:

    • fork { } → Thread.new { }
    • Process.kill → thread.kill / thread.raise
    • Process.waitpid → thread.join

    This works on JRuby/TruffleRuby/Windows and uses less memory.

    Approach 2: IPC-based (complementary)

    For production deployments wanting process isolation, workers can run as
    separate processes communicating via Unix sockets + MessagePack.

    This gives:

    • True process isolation (crashes don't affect dispatcher)
    • Language-agnostic workers (Ruby, Python, Rust, etc)
    • Better for multi-machine deployments
    • Works on both CRuby (fork) and JRuby (threads within worker)

    I have the Unix socket implementation ready and can demo both approaches.
    The socket layer enables distributed workers even in the thread-based version.

    Would you prefer I focus on:

    1. Thread-based Solid Queue modifications (pure Ruby changes)
    2. Unix socket PR + IPC architecture demo (infrastructure layer)
    3. Both (thread-based with optional IPC distribution)

    I can have working code ready by tomorrow morning.

  15. headius commented on Nov 5, 2025

    @headius
    Author

    @seuros Approach 2 is probably a better long-term approach, but may not be what Solid Queue is going for. I would definitely recommend focusing on a minimal change to Solid Queue that allows either forked processes or threads.

  16. seuros commented on Nov 5, 2025

    @seuros
    Member

    @headius I wasn't expecting it to get merged into this gem, otherwise I would have commented with the solution.

    The monkey-patch gem pattern gives JRuby team total flexibility and ownership of the adapter. If any bug arises or API change is needed, you just patch it and release. You don't have to request @rosa for an unscheduled release.

    Btw you are free to use the code.


    My main concern with a universal threading implementation: it's well-known that threading is problematic on CRuby due to the GVL. JRuby would get an edge with real parallelism, while CRuby would turn into a single-CPU serialized queue competing with Sidekiq/GoodJob. Observability also becomes harder with threads, we lose per worker process metrics, cant track individual worker memory usage.

    On CRuby, people would have to spin up multiple worker processes just to use multiple cores, essentialy reimplementing what fork already does already. Meanwhile, JRuby will gets native multi-core threading in a single process.

  17. CufeHaco commented on Nov 5, 2025

    @CufeHaco

    @seuross You've articulated exactly why I've been building the Unix socket + IPC approach!

    Your concerns about the pure threading implementation are spot-on:

    The Problems You Identified:

    1. CRuby GVL - Threading doesn't give real parallelism
    2. Observability - Can't track per-worker metrics with threads
    3. Memory tracking - Lose per-worker memory visibility
    4. Multi-core on CRuby - Would need multiple processes anyway

    How Unix Sockets Solve This:

    Architecture:
    Dispatcher (any Ruby)
    ↓ Unix Socket + MessagePack
    Worker Process 1 (CRuby fork, 1 core)
    Worker Process 2 (CRuby fork, 1 core)
    Worker Process 3 (JRuby, 10 threads, 10 cores)
    Worker Process 4 (Python/Rust/Go/etc)

    Benefits:

    • Process isolation (observability, crash resistance)
    • Per-process metrics (CPU, memory, jobs)
    • CRuby uses fork (what it's good at)
    • JRuby uses threads (what it's good at)
    • Language-agnostic workers
    • Horizontal scaling (multiple machines)

    The Implementation:

    I have the JRuby Unix socket layer (JEP-380) ready, which enables:

    CRuby workers:

    # Worker process (forked)
    server = UNIXServer.new('/tmp/worker_1.sock')
    loop do
      client = server.accept
      job = MessagePack.unpack(client.read)
      result = process_job(job)
      client.write(MessagePack.pack(result))
    end
    
    
    JRuby workers:
    # Worker process (threaded internally)
    server = UNIXServer.new('/tmp/worker_jruby.sock')
    loop do
      client = server.accept
      Thread.new do  # Real parallelism on JRuby!
        job = MessagePack.unpack(client.read)
        result = process_job(job)
        client.write(MessagePack.pack(result))
        client.close
      end
    end
    Observability Maintained:
    # Full process metrics
    $ ps aux | grep worker
    5678  worker_1  15%  500MB
    5679  worker_2  80%  1.2GB
    
    # Per-worker monitoring
    $ cat /var/run/solid_queue/worker_1.meta
    {"pid": 5678, "jobs": 142, "memory": 500}
    
    # Kill/restart individual workers
    $ kill -TERM 5679
    This gives us:
    The monkey-patch gem pattern you mentioned (JRuby team controls adapter)
    Process isolation (metrics, crashes, memory tracking)
    Runtime flexibility (fork on CRuby, threads on JRuby)
    Production-grade architecture (what companies actually need)
    @headius This also addresses your needs - workers run in processes with
    threads internally (JRuby), communicating via sockets. No fork required.
    
    Im also not using TCP/IP.  Im treating directories as the IP 
  18. headius commented on Nov 5, 2025

    @headius
    Author

    The monkey-patch gem pattern gives JRuby team total flexibility and ownership of the adapter.

    @seuros I agree! But I don't think we're in such a critical situation that we need to release a monkey-patch gem right this second. It is good that we have this as a fallback position, and perhaps we could release something in the short term, but the ultimate goal should be to make Solid Queue work with either forked processes or threaded workers, which would mean all Ruby implementations can benefit.

    I have the JRuby Unix socket layer (JEP-380) ready,

    @CufeHaco And I also agree that the IPC approach would be a more robust long-term option, but a standalone IPC-based approach seems further from what Solid Queue is designed for than just patching what we have now for in-process threading.

    That's not to say the IPC approach has anything wrong with it... I just think it might be too big of a change for @rosa et al to consider right now, and I am keen to get something in here to support non-forking usage.

  19. CufeHaco commented on Nov 5, 2025

    @CufeHaco

    @headius Got it. Let me do a but more of a deep dive into Solid Queue. I'll put JEP-380 on the back burner for this evening and see what I can do to have a proposed solution for Solid Queue without invasive overhaul.

    Give me about an hour so I can get caught up.

  20. seuros commented on Nov 5, 2025

    @seuros
    Member

    @CufeHaco What you're describing is a working prototype, but it totally changes the direction of the gem.

    You are building a distributed job broker, which is the opposite of what "Solid" means.

    I wrote a similar architecture for Lapssos to track errors. It worked on my machine until I deployed it at scale.

    Such patterns have to be tested in every deployment mechanism in existence.

    Your local machine can use socket bypass for the TCP stack, but 2 pods in k8s or docker swarm wont have a shared sockets.

    With solid they shared a single database, now you added extra point of possible failure.

    @headius I'm concerned about #644. Giving the ability to toggle between thread/fork will generate observability headaches. Once you open a thread, you cannot see what's inside it, limit it, or kill it cleanly. You control the process, not the thread - unless you spin up a supervisor pattern inside your process to manage your threads, which adds complexity.

    If you're okay with a big refactoring to merge #644, why not do a breaking change and create an adapter pattern?

    JRuby, TruffleRuby, CRuby every implementation will load one file based on the runtime. The end users will not see this change, but concern will follow the Matryoshka pattern, where were have multiple gems inside a singe gem.

    The breaking change will be just for extensions or monkeypatchers, not the API.

    graph TD
        A[Solid Queue] --> B{Runtime Detection}
        B -->|CRuby| C[Fork Executor]
        B -->|JRuby| D[Thread Executor]
        B -->|TruffleRuby| E[Thread Executor]
        
        C --> F[Process Supervisor]
        D --> G[ThreadPool Manager]
        E --> G
    
    Loading
  21. CufeHaco commented on Nov 6, 2025

    @CufeHaco

    @Seros, close but not quite. Im only replacing forks with sockets localy. No tcp/ip. This exactly what I needed to build my Kernel. I just wanted to be clear on that front so theres not miscommunication. The worker process is only a part of that. To really fix ruby's fragmentation relys on the system admin and kernel level of things. Symblinks, ffi's, and static file paths are what breaks systems. This kind of system would even solve your concerns with communication with threads and forks.

    But that's future and what ive been doing personally.

    A few ideas for #644

    1. Thread local variables + thread state.
    2. Queue based communication
    3. Actor model with Concurrent ruby.
    4. Fiber based lightweight concurrency
    5. Ractor based parallelism

    Each one has pros and cons of course, but they dont require a socket, which would be the best method to go over all.

  22. CufeHaco commented on Nov 6, 2025

    @CufeHaco

    @seuros @headius i had an epiphany last night while reading up on this

    Using your gem pattern, we can let ruby understand its enviroment at runtime. Instead of manual config, we let Ruby do it via the kernel, os, and ruby interpreter enviroments. If we do it this way, the gem can automatically configure itself to the user runtime env when required.

    Solid Queue would then be able to act accordingly from there.

    If jruby do this
    If ruby do this
    If truffleruby do this.

    If this OS and this Ruby env, do this.

    We can still have manual control, but doing something like this would cut back on the time to setup. Plug an play. It should just work without having to play config roulette.

  23. seuros commented on Nov 6, 2025

    @seuros
    Member

    @CufeHaco This is like adding AI to Rails generators...... We are not doing Kubernetes.

    The solution is primitive

    In your gemfile

    gem 'solid_queue' #<- Load everywhere
    gem 'solid_queue-java', platform: :java   #<- Load and monkey patch if jruby/truffle is present
    

    That it.

    This project will work in the 3 engines.

  24. CufeHaco commented on Nov 6, 2025

    @CufeHaco

    @seuros With respect, this isn't AI or Kubernetes complexity. This is basic kernel-level engineering.

    You're approaching this as a web developer problem (two gems, platform-specific).
    I'm approaching this as a systems problem (one runtime, environment-aware).

    The issue:

    # Your proposal:
    gem 'solid_queue'
    gem 'solid_queue-java', platform: :jruby
    This pushes the responsibility to the user. They need to know:
    What Ruby they're running
    Which gem to add
    How to configure it
    Systems approach:
    # Runtime introspection (built into Ruby):
    RUBY_ENGINE        # "ruby", "jruby", "truffleruby"
    RUBY_PLATFORM      # "x86_64-linux", "java", "x86_64-darwin"

    The kernel already knows what it's running on. Why make the user tell us?
    This is how operating systems work:
    Linux doesn't ask "are you on x86 or ARM?" - it detects
    macOS doesn't ask "are you on Intel or Apple Silicon?" - it detects
    Ruby provides these constants for exactly this purpose

    The code is 5 lines:
    def self.executor
      return :thread if RUBY_ENGINE == 'jruby'
      return :fork if RUBY_PLATFORM !~ /mswin|mingw/
      :spawn
    end

    That's not complexity. That's using the information the system already provides.
    Two gems means:
    Two codebases to maintain
    Two release cycles
    Two sets of bugs
    Users have to read docs to figure out which gem they need
    One gem with detection means:
    One codebase
    User does gem install solid_queue and it works
    Zero configuration
    Zero documentation needed
    This is basic systems engineering: inspect the environment, adapt accordingly.
    Not magic. Not AI. Just reading what Ruby tells us.

  25. seuros commented on Nov 6, 2025

    @seuros
    Member

    This pushes the responsibility to the user. They need to know:
    What Ruby they're running
    Which gem to add

    Ok, Claude since that was clearly Claude Haiku hallucinating on me.
    Yes that exactly the point. The user HAS TO know the ruby type and gem they are adding. Rails is a framework, we are not building SolidVibe Gem here.

    the monkey patcher gem, just swap the executor methods with Java compatible one, if there are bugs, it will be either in Jruby or SolidQueue.


    @CufeHaco Give this back to Claude, see if he still side with you. Also switch to Sonnet 4.5 with thinking on.

    P.S : I have nothing against using AI, but at least have your own arguments. AI doesn't even believe Rails 8 exists.

  26. CufeHaco commented on Nov 6, 2025

    @CufeHaco

    Sir I use my tools correctly. And the code is mine. Not claudes.just because I use an llm to proofread while im away from my workstation doesnt mean anything.

    You've been gatekeeping and defensive this whole conversation. And this last response proves thst you ran out of any arguing points and rebuttals.

  27. CufeHaco commented on Nov 6, 2025

    @CufeHaco

    I will also add that rails it self uses runtime detection everywhere. The very same thing im discussing here. Your want raw me? Best get used to reading typos everywhere.

  28. rosa commented on Nov 7, 2025

    @rosa
    Member

    Ok, since #644 would be the approach that we'll consider here, and the relevant conversation is happening over there, while the conversation here is derailing and not being productive, I'm going to lock the comments here.

    Thanks everyone!

  29. locked as off topic and limited conversation to collaborators on Nov 7, 2025
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