Torque

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

Installation

Add to your mix.exs:

def deps do
[
{:torque, "~> 0.4.1"}
]
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 reads the document in a single pass, building values only where a path ends and skipping everything else, without building an intermediate document. On a 1.2 KB bid request with 26 fields that is ~1.35× the previous fused parse; with 3 paths and validate: false (below) it is ~2.6×.

# Once, at startup (e.g. into :persistent_term or application state; the
# handle is a NIF resource, so it cannot live in a module attribute):
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).

By default a malformed document is reported wherever the fault is, as parse/2 would report it, even in a region no path selects. validate: false skips unselected regions with a structural bracket scan instead of tokenizing them, but a malformed number, literal, or separator inside one of them goes unreported, and so does anything after the document, which is therefore not UTF-8 checked either. Truncated input, invalid UTF-8 in any byte the walk consumed, and errors in selected values are still rejected. Use it only with trusted input.

It is not a free speed-up. A bracket scan over 64-byte blocks beats tokenizing a large subtree and loses to it on the few-byte scalars a dense path set leaves behind, so the win tracks how little of the document the paths select. Three paths out of a 2 KB request run ~3.6× faster unvalidated; 146 fields of the same request run ~1.2× slower. Measure your own path set.

pointers = Torque.compile_pointers(paths, unique_keys: true, validate: false)

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}]})

Structs are rejected with {:error, :unhandled_struct} unless they implement Torque.Encoder. Implement the protocol for custom types, or derive it to encode a subset of fields:

defimpl Torque.Encoder, for: Decimal do
def encode(decimal), do: Decimal.to_string(decimal)
end
# or, on the struct itself:
@derive {Torque.Encoder, only: [:id, :name]}
defstruct [:id, :name, :secret]

Date, Time, NaiveDateTime, and DateTime ship with implementations and encode as ISO 8601 strings.

Breaking change in 0.4.0. Structs previously encoded as raw maps, leaking the struct marker into the output: ~D[2026-09-14] produced {"calendar":"Elixir.Calendar.ISO","month":9,"__struct__":"Elixir.Date",...}. They now error unless the protocol is implemented.

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
struct implementing Torque.Encoderwhatever encode/1 returns

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
:unhandled_structencode/1Struct has no Torque.Encoder implementation
:encoder_expansion_too_deepencode/1A Torque.Encoder implementation expands the same struct again, or structs nest past 128 levels

Benchmarks

Per-commit trends and the full cross-library comparison are published at lpgauth.github.io/torque/dev/bench.

Apple M1 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 make -C deps/glazer/c_src PGO=generate, the workload in bench/glazer_pgo_workload.exs, then PGO=use). Glazer's Makefile writes that flow for GCC; under clang the raw counters need an explicit llvm-profdata merge -o obj/pgo/default.profdata obj/pgo/*.profraw between those two steps. Every table below comes from one run of bench/torque_bench.exs.

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
torque411.0K2.43 μs2.33 μs2.96 μs1.56 KB
glazer348.4K2.87 μs2.79 μs3.42 μs1.56 KB
jiffy201.5K4.96 μs4.63 μs9.79 μs1.55 KB
otp json124.4K8.04 μs7.08 μs19.96 μs7.73 KB
jason102.3K9.78 μs9.25 μs17.50 μs9.54 KB

Decode (750 KB Twitter)

Libraryipsmeanmedianp99memory
torque710.61.41 ms1.28 ms1.85 ms1.57 KB
glazer581.61.72 ms1.63 ms2.16 ms1.58 KB
jiffy295.63.38 ms3.49 ms3.82 ms2.30 MB
otp json202.14.95 ms5.01 ms5.63 ms2.48 MB
jason139.27.18 ms7.08 ms8.32 ms3.54 MB

Encode (1.2 KB OpenRTB)

Libraryipsmeanmedianp99memory
torque [proplist() :: iodata()]1400K0.71 μs0.67 μs0.79 μs64 B
torque [proplist() :: binary()]1360K0.73 μs0.67 μs0.79 μs88 B
torque [map() :: binary()]1200K0.84 μs0.75 μs1.00 μs88 B
torque [map() :: iodata()]1190K0.84 μs0.75 μs0.96 μs64 B
otp json [map() :: iodata()]1110K0.90 μs0.83 μs1.17 μs3928 B
glazer [map() :: binary()]1070K0.93 μs0.83 μs1.17 μs64 B
jiffy [proplist() :: iodata()]850K1.18 μs1.04 μs1.29 μs120 B
jiffy [map() :: iodata()]680K1.47 μs1.33 μs1.58 μs632 B
jason [map() :: iodata()]590K1.70 μs1.63 μs2.63 μs3848 B
jason [map() :: binary()]370K2.71 μs2.54 μs4.67 μs3912 B

Encode (750 KB Twitter)

Libraryipsmeanmedianp99memory
torque [proplist() :: binary()]1604.80.62 ms0.61 ms0.73 ms88 B
torque [proplist() :: iodata()]1533.60.65 ms0.61 ms0.79 ms64 B
torque [map() :: iodata()]1421.50.70 ms0.69 ms0.82 ms64 B
torque [map() :: binary()]1420.40.70 ms0.69 ms0.84 ms88 B
glazer [map() :: binary()]872.61.15 ms1.14 ms1.34 ms64 B
jiffy [proplist() :: iodata()]607.81.65 ms1.63 ms1.86 ms2.97 KB
jiffy [map() :: iodata()]439.42.28 ms2.16 ms2.81 ms803 KB
otp json [map() :: iodata()]256.93.89 ms4.03 ms5.20 ms5.40 MB
jason [map() :: iodata()]243.54.11 ms3.79 ms6.72 ms4.96 MB
jason [map() :: binary()]128.37.79 ms7.56 ms9.57 ms4.96 MB

Parse (1.2 KB OpenRTB)

Libraryipsmeanmedianp99
torque parse585.5K1.71 μs1.38 μs3.50 μs
torque parse(unique_keys)578.9K1.73 μs1.38 μs2.96 μ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.

parse_get_many_nil goes further. Given a handle compiled once at startup (like glazer's compiled jq paths), it walks the document a single time and builds a value only where a path ends, so no document is built at all. validate: false also skips validating the regions no path selects, which on a document this small is most of what is left.

Libraryipsmeanmedianp99
torque parse_get_many_nil unique_keys validate: false1363K0.73 μs0.71 μs0.83 μs
torque parse_get_many_nil unique_keys705.8K1.42 μs1.38 μs1.58 μs
torque parse_get_many_nil699.3K1.43 μs1.38 μs1.58 μs
torque parse(unique_keys) + get_many486.0K2.06 μs1.79 μs4.13 μs
torque parse + get_many468.6K2.13 μs1.75 μs3.88 μs
torque parse + get x5464.0K2.16 μs1.92 μs4.04 μs
glazer decode + find x5312.4K3.20 μs3.08 μs4.38 μs

Run benchmarks locally:

MIX_ENV=bench mix run bench/torque_bench.exs

Limitations

License

MIT