fix(apijson): replace O(n^2) array encoding with O(n) bytes.Buffer - #4346
Merged
Conversation
newArrayTypeEncoder built JSON arrays by calling sjson.SetRawBytes in a loop, which re-parses and reallocates the entire buffer on each iteration. For a 30,000-element array this allocates ~6.2 GB and causes OOM kills. Replace with single-pass bytes.Buffer concatenation. Output is byte-identical to the previous implementation. Includes benchmark and correctness tests as a regression guard. Fixes #4315 Ref: https://jira.cfdata.org/browse/APIX-1066
rotem-cloud
approved these changes
Jun 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
newArrayTypeEncoderbuilds JSON arrays by callingsjson.SetRawBytes(json, "-1", item)in a loop.sjsonre-parses and reallocates the entire accumulated buffer on each call, giving O(n^2) time and memory complexity. For a 30,000-element IP list update viaRules.Lists.Items.Update, this allocates ~6.2 GB and OOM-kills the process.This replaces the
sjsonloop with a single-passbytes.Bufferconcatenation, restoring O(n). Output is byte-identical to the previous implementation.Context
Benchmarks (from #4316)
Tests
All existing
internal/apijsontests pass. Addedarray_bench_test.gowith correctness verification againstencoding/jsonand benchmarks at N=100..30,000 as a regression guard.Fixes #4315