High-performance JSON library for Elixir via Rustler NIFs, powered by sonic-rs (SIMD-accelerated).

Torque provides the fastest JSON encoding and decoding available in the BEAM ecosystem, with a selective field extraction API for workloads that only need a subset of fields from each document.

Features

  • SIMD-accelerated decoding (AVX2 on x86, NEON on ARM)
  • Ultra-low memory encoder (64 B per encode vs ~4 KB for OTP json/jason)
  • Parse-then-get API for selective field extraction via JSON Pointer (RFC 6901)
  • Batch field extraction (get_many/2) with single NIF call
  • Pre-compiled pointers with fused parse + extract (parse_get_many_nil/2)
  • Automatic dirty CPU scheduler dispatch for decode/parse inputs larger than 20 KB (opt-in dirty: true for encode)
  • jiffy-compatible {proplist} encoding

Installation

Add to your mix.exs:

def deps do
  [
    {:torque, "~> 0.2.6"}
  ]
end

Precompiled binaries are available for common targets. To compile from source, install a stable Rust toolchain and set TORQUE_BUILD=true.

CPU-optimized variants

On x86_64, precompiled binaries are available for three CPU feature levels:

VariantCPU featurestarget-cpu
baselineSSE2x86-64
v2SSE4.2, SSSE3, POPCNTx86-64-v2
v3AVX2, AVX, BMI1, BMI2, FMAx86-64-v3

At compile time, Torque auto-detects the host CPU and downloads the best matching variant. To override detection (e.g., when cross-compiling for a different target):

TORQUE_CPU_VARIANT=v2 mix compile  # force SSE4.2 variant
TORQUE_CPU_VARIANT=v3 mix compile  # force AVX2 variant
TORQUE_CPU_VARIANT=base mix compile  # force baseline

Usage

Decoding

{:ok, data} = Torque.decode(~s({"name":"Alice","age":30}))
# %{"name" => "Alice", "age" => 30}

data = Torque.decode!(json)

Selective Field Extraction

Parse once, extract many fields without building the full Elixir term tree:

{:ok, doc} = Torque.parse(json)

{:ok, "example.com"} = Torque.get(doc, "/site/domain")
nil = Torque.get(doc, "/missing/field", nil)

# Batch extraction (single NIF call, fastest path)
results = Torque.get_many(doc, ["/id", "/site/domain", "/device/ip"])
# [{:ok, "req-1"}, {:ok, "example.com"}, {:ok, "1.2.3.4"}]

When your JSON is known to have no duplicate object keys, pass unique_keys: true for faster field lookups (uses sonic-rs internal indexing instead of linear scan):

{:ok, doc} = Torque.parse(json, unique_keys: true)

Compiled Pointers

When the same fixed set of paths is extracted from every document, compile the pointers once and reuse the handle. parse_get_many_nil/2 then fuses the parse and extraction into a single NIF call, skipping all per-request path parsing — roughly 1.5× faster end-to-end than parse/2 + get_many_nil/2.

# Once, at startup (e.g. a module attribute or :persistent_term):
pointers = Torque.compile_pointers(["/id", "/site/domain", "/imp/0/banner/w"], unique_keys: true)

# Per document — parse + extract in one call:
{:ok, ["req-1", "example.com", 300]} = Torque.parse_get_many_nil(json, pointers)

Missing fields and JSON null both become nil. The handle also works with an already-parsed document via Torque.get_many_nil(doc, pointers).

Encoding

# Maps with atom or binary keys
{:ok, json} = Torque.encode(%{id: "abc", price: 1.5})
# "{\"id\":\"abc\",\"price\":1.5}"

# Integer keys are stringified — JSON object names must be strings
{:ok, json} = Torque.encode(%{0 => "a", 1 => "b"})
# "{\"0\":\"a\",\"1\":\"b\"}"

# Bang variant
json = Torque.encode!(%{id: "abc"})

# iodata variant (fastest, no {:ok, ...} tuple wrapping)
json = Torque.encode_to_iodata(%{id: "abc"})

# jiffy-compatible proplist format
{:ok, json} = Torque.encode({[{:id, "abc"}, {:price, 1.5}]})

Unlike decoding, encoding cannot cheaply predict its output size, so dirty scheduler dispatch is opt-in. Pass dirty: true (accepted by encode/2, encode!/2, encode_to_iodata/2, and encode_to_iodata!/2) when terms are expected to encode to large output (more than roughly 20 KB):

{:ok, json} = Torque.encode(big_term, dirty: true)

API

FunctionDescription
Torque.compile_pointers(paths, opts)Pre-compile a fixed path set into a reusable handle
Torque.decode(binary)Decode JSON to Elixir terms
Torque.decode!(binary)Decode JSON, raising on error
Torque.encode(term, opts)Encode term to JSON binary
Torque.encode!(term, opts)Encode term, raising on error
Torque.encode_to_iodata(term, opts)Encode term, returns binary directly (fastest)
Torque.encode_to_iodata!(term, opts)Alias for encode_to_iodata/2 (Phoenix :json_library)
Torque.get(doc, path)Extract field by JSON Pointer path
Torque.get(doc, path, default)Extract field with default for missing paths
Torque.get_many(doc, paths)Extract multiple fields in one NIF call
Torque.get_many_nil(doc, paths)Extract multiple fields, nil for missing
Torque.length(doc, path)Return length of array at path
Torque.parse(binary, opts)Parse JSON into opaque document reference
Torque.parse_get_many_nil(binary, pointers)Fused parse + extract of compiled pointers in one NIF call

Type Conversion

JSON to Elixir

JSONElixir
objectmap (binary keys)
arraylist
stringbinary
integerinteger
floatfloat
true, falsetrue, false
nullnil

For objects with duplicate keys, the last value wins (unless unique_keys: true is passed to parse/2).

Integers outside the signed/unsigned 64-bit range decode as exact arbitrary-precision integers (Erlang bignums) via decode/1, rather than degrading to lossy floats. The parse/2 + get/2 path returns them as floats, since the parsed document cannot hold a bignum.

Elixir to JSON

ElixirJSON
map (atom/binary/integer keys)object
listarray
binarystring
integernumber
floatnumber
true, falsetrue, false
nilnull
atomstring
{keyword_list}object

Errors

Functions return {:error, reason} tuples (or raise ArgumentError for bang/iodata variants). Possible reason atoms:

Decode / Parse

AtomReturned byMeaning
:nesting_too_deepdecode/1, parse/1, get/2, get_many/2, parse_get_many_nil/2Document exceeds 128 nesting levels

parse/1, decode/1, and parse_get_many_nil/2 also return {:error, binary} with a message from sonic-rs for malformed JSON.

Encode

AtomReturned byMeaning
:unsupported_typeencode/1Term has no JSON representation (PID, reference, port, …)
:invalid_utf8encode/1Binary string or map key is not valid UTF-8
:invalid_keyencode/1Map key is not an atom, binary, or integer (e.g. float or tuple key)
:malformed_proplistencode/1{proplist} contains a non-{key, value} element
:non_finite_floatencode/1Float is infinity or NaN (unreachable from normal BEAM code)
:nesting_too_deepencode/1Term exceeds 128 nesting levels

Benchmarks

Apple M2 Pro, OTP 29, Elixir 1.20. Both libraries are profile-guided optimised (PGO) builds: Torque PGO (via scripts/pgo-build.sh) and Glazer PGO (via OPTIMIZE=1).

glazer is benchmarked with UTF-8 validation enabled (validate_utf8 on decode, force_utf8 on encode — both off by default in glazer) so every library provides the same guarantee Torque always does: JSON strings are valid UTF-8.

Decode (1.2 KB OpenRTB)

Libraryipsmeanmedianp99memory
torque412.8K2.42 μs2.29 μs4.67 μs1.56 KB
glazer355.5K2.81 μs2.67 μs5.00 μs1.56 KB
jiffy200.0K5.00 μs4.50 μs11.00 μs1.55 KB
otp json143.8K6.95 μs6.71 μs12.54 μs7.73 KB
jason109.0K9.17 μs8.54 μs20.58 μs9.54 KB

Decode (750 KB Twitter)

Libraryipsmeanmedianp99memory
torque659.41.52 ms1.32 ms2.14 ms1.57 KB
glazer597.01.68 ms1.59 ms2.26 ms1.58 KB
jiffy298.83.35 ms3.37 ms4.52 ms2.30 MB
otp json211.34.73 ms4.77 ms5.57 ms2.48 MB
jason150.26.66 ms6.59 ms8.21 ms3.54 MB

Encode (1.2 KB OpenRTB)

Libraryipsmeanmedianp99memory
otp json [map() :: iodata()]1174K0.85 μs0.79 μs1.21 μs3928 B
torque [proplist() :: iodata()]1084K0.92 μs0.88 μs1.08 μs64 B
torque [proplist() :: binary()]1048K0.95 μs0.88 μs1.21 μs88 B
torque [map() :: iodata()]957K1.04 μs1.00 μs1.25 μs64 B
torque [map() :: binary()]953K1.05 μs1.00 μs1.21 μs88 B
glazer [map() :: binary()]932K1.07 μs1.00 μs1.21 μs64 B
jiffy [proplist() :: iodata()]654K1.53 μs1.33 μs1.88 μs120 B
jason [map() :: iodata()]598K1.67 μs1.54 μs3.21 μs3848 B
jiffy [map() :: iodata()]526K1.90 μs1.75 μs2.17 μs824 B
jason [map() :: binary()]401K2.49 μs2.33 μs4.63 μs3912 B

Encode (750 KB Twitter)

Libraryipsmeanmedianp99memory
torque [proplist() :: iodata()]1163.70.86 ms0.84 ms1.08 ms64 B
torque [proplist() :: binary()]1143.30.87 ms0.84 ms1.44 ms88 B
torque [map() :: binary()]1056.00.95 ms0.93 ms1.15 ms88 B
torque [map() :: iodata()]1019.00.98 ms0.96 ms1.21 ms64 B
glazer [map() :: binary()]843.91.19 ms1.17 ms1.38 ms64 B
jiffy [proplist() :: iodata()]473.82.11 ms2.09 ms2.31 ms37.7 KB
jiffy [map() :: iodata()]357.12.80 ms2.95 ms3.26 ms1.06 MB
otp json [map() :: iodata()]270.53.70 ms3.93 ms4.77 ms5.40 MB
jason [map() :: iodata()]261.03.83 ms3.54 ms5.86 ms4.96 MB
jason [map() :: binary()]138.57.22 ms7.18 ms8.09 ms4.96 MB

Parse (1.2 KB OpenRTB)

Libraryipsmeanmedianp99
torque parse(unique_keys)556.8K1.80 μs1.46 μs5.21 μs
torque parse555.4K1.80 μs1.42 μs5.21 μs

Extract 5 fields from raw JSON (1.2 KB OpenRTB)

End-to-end cost of pulling 5 fields out of a JSON blob: parse + get (torque) vs decode + find (glazer has no lazy handle, so it must fully decode first). This is the apples-to-apples version of "get" — torque's selective extraction skips materializing the whole document.

Libraryipsmeanmedianp99
torque parse(unique_keys) + get_many467.3K2.14 μs1.79 μs4.79 μs
torque parse + get_many455.1K2.20 μs1.79 μs5.46 μs
torque parse + get x5420.1K2.38 μs1.96 μs6.08 μs
glazer decode + find x5315.1K3.17 μs3.04 μs4.88 μs

Run benchmarks locally:

MIX_ENV=bench mix run bench/torque_bench.exs

Limitations

  • Integer map keys are lossy: JSON object names must be strings (RFC 8259 §4), so encode/1 stringifies integer keys and decode/1 gives them back as binaries — %{1 => "a"} round-trips to %{"1" => "a"}. A map mixing both forms, like %{1 => "a", "1" => "b"}, encodes to duplicate names ({"1":"a","1":"b"}); RFC 8259 says names should be unique, and decoders resolve the collision however they choose. Jason behaves identically.
  • Nesting depth: JSON documents nested deeper than 128 levels return {:error, :nesting_too_deep} from decode/1, parse/1, get/2, get_many/2, and encode/1 rather than crashing the VM. Real-world documents are never this deep; the limit exists to prevent stack overflow in the NIF (the dirty CPU scheduler, used for inputs over 20 KB, has a small stack).

License

MIT