Skip to content

Is JSON::Coder intended to be thread safe ? #1064

Description

@daveferrykami

In JRuby we hit a race condition: ActiveSupport uses a single shared JSON::Coder
instance and calls #dump on it from multiple threads.

ActiveSupport creates one shared Coder:
https://github.com/rails/rails/blob/v8.1.3.1/activesupport/lib/active_support/json/encoding.rb#L152

…and reuses it on every encode:
https://github.com/rails/rails/blob/v8.1.3.1/activesupport/lib/active_support/json/encoding.rb#L188

The error we got, on a flat object was

JSON::NestingError: nesting of 100 is too deep. Did you try to serialize objects with circular references?

Question: is a single JSON::Coder instance intended to be safe to call
concurrently from multiple threads (i.e. is #dump/#generate on one Coder
intended to be thread-safe)?

Versions: json 2.21.2 (java), JRuby 10.0.5.0, activesupport 8.1.3.1.

I have a small threaded reproduction I can add if useful.

Activity

  1. headius commented on Aug 26, 2026

    @headius
    Contributor

    I also looked into this a little bit and could find no documentation one way or another about using a single Coder instance concurrently across threads.

    I believe this issue affects both the Java code and the C code, but the C code might only expose it if some object implements part of its dumping in Ruby.

  2. byroot commented on Aug 27, 2026

    @byroot
    Member

    Is JSON::Coder intended to be thread safe ?

    Yes, one of the goal of JSON::Coder is to not have to reparse options on every call,hence it needs to be shareable between threads and e able to be used concurrently.

    I some how can't find the commit anymore but we had one such bug in the past that we fixed.

    The struct/object that holds the current_nesting should be duped at the start of parse and generate (or be kept in a separate object.

  3. byroot commented on Aug 27, 2026

    @byroot
    Member

    I some how can't find the commit anymore

    Ah I think it was: #911

  4. headius commented on Sep 10, 2026

    @headius
    Contributor

    @byroot Thanks for the background info. We'll look into fixing the JRuby Coder to be thread-safe.

    FWIW I tihnk there's still an issue in CRuby if dumping requires a call back into Ruby, since that could trigger a context switch and parallel updating of the Coder depth.

  5. chaadow commented on Sep 11, 2026

    @chaadow

    yeah I originally encountered this issue about a year ago #874

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