Skip to content

perf: cache compiled path regexes and cut request validation allocations - #340

Open
emilien-puget wants to merge 1 commit into
pb33f:mainfrom
emilien-puget:path-regex-cache
Open

emilien-puget wants to merge 1 commit into
pb33f:mainfrom
emilien-puget:path-regex-cache

Conversation

@emilien-puget

@emilien-puget emilien-puget commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Goal

Request validation called helpers.GetRegexForPath for every path template on every request and recompiled the same regex each time, and the rest of the request hot path rebuilt per-request state it could reuse. This PR caches compiled regexes per validator, then applies the same discipline to the request and response hot path: stop rebuilding per-request state, hoist per-call allocations out of loops, and reuse what the validator already built.

It also fixes operation resolution gaps this work surfaced: ExtractParamsForOperation disagreed with ExtractOperation and the router for HEAD fallback, OpenAPI 3.2 query operations, and additionalOperations methods.

It closes the gap with libopenapi, which caches its compiled JSONPath expressions the same way.

What changed

  • GetRegexForPath compiles and returns; the state is gone from helpers. Each validator gets its own regex cache by default (NewValidatorFromV3Model seeds ValidationOptions.RegexCache with a fresh sync.Map), shared with the sub-validators through WithExistingOpts. ValidationOptions.Release() empties an owned cache, so a service can load a spec, validate and get its memory back. A cache set through config.WithRegexCache stays shared. paramValidator keeps a per-validator brace-index map with the same lifetime.
  • ExtractOperation resolves QUERY (OpenAPI 3.2) and additionalOperations methods, and keeps its HEAD fallback to get. ExtractParamsForOperation delegates to it, so request-level method resolution and parameter extraction can no longer disagree. Before this, a HEAD request on a get-only path skipped GET's required query and header parameters, and 3.2 query and custom methods were rejected with a false "no '' method found in the spec" error.
  • ValidateRequestSchema, ValidateResponseSchema and ValidateResponseHeaders accept pre-built options through an unexported core; internal callers stop building config.NewValidationOptions per request. Exported signatures are unchanged.
  • ExtractParamsForOperation returns the model slices untouched when one side is empty and merges into an exact-size slice otherwise: appending to item.Parameters could write into the model backing array, which is shared across validators and requests. Its result is documented read-only.
  • nonEmptyPathSegments walks the path once with strings.SplitSeq; ExtractRawQueryValues returns nil for an empty query; GetRenderedSchema returns the cached ReferenceSchema string; compilePathRegex assembles patterns with strings.Builder.

Evidence

Paired runs, 10 samples per side, compared with benchstat (i7-1265U, Go 1.26). Every commit was measured back-to-back; the table compares main against the final branch across 12 gateway scenarios. Allocation counts are exact (±0%); time is p<0.001 for the shapes this PR touches (the urlencoded shape shows ~ with allocation improvements of −12%).

Scenario allocs/op sec/op Δ sec/op
Plain GET (1 uuid path param) 96 → 35 8.0 → 3.8 µs −52%
Param-heavy GET (2 path, query, header) 320 → 94 26.0 → 11.2 µs −57%
POST, JSON body 77 → 65 6.9 → 6.5 µs −5.8%
Response 200 + header 44 → 37 3.9 → 3.6 µs −9.3%
Query-heavy GET (4 query + enum header) 122 → 111 11.5 → 11.1 µs ~
Invalid request (error path) 322 → 96 27.0 → 11.1 µs −59%
Concurrent GET, 12 goroutines 96 → 35 4.2 → 1.4 µs −67%
Format assertions on 97 → 36 13.4 → 4.1 µs −69%
Strict server matching 98 → 37 10.1 → 4.7 µs −53%
Form-urlencoded body 99 → 87 9.8 → 11.1 µs ~ (drift)
JSON response body 57 → 48 7.7 → 8.0 µs ~
Large route table (200 paths) 113 → 35 11.7 → 3.8 µs −68%
geomean 107.5 → 53.7 (−50%) 9.9 → 5.7 µs −42.6%

Reproduce:

go test -run='^$' -bench='BenchmarkValidateHttpRequestSync|BenchmarkValidateHttpResponse' \
  -count=10 -benchmem -benchtime=50000x ./ .

Mechanism and memory

Each validator owns its regex cache: NewValidatorFromV3Model defaults ValidationOptions.RegexCache to a fresh sync.Map, the validators built with WithExistingOpts share it, and Release() empties an owned cache, so compiled regexes die with the validator instead of living for the process lifetime. A custom cache set through config.WithRegexCache keeps working and stays shared. GetRegexForPath itself is stateless again. The default cache is a *sync.Map and the hot paths call it concretely, so the template key does not box per lookup; the per-segment brace indices live in a per-validator map on the parameter validator with the same lifetime.

One candidate was measured and rejected, recorded in the commit history: hoisting the per-segment regex out of the parameter loop cost +9% sec/op on the single-parameter shape (three precompute slices, nothing to dedupe), so it was reverted.

Verification

  • go test -race -count=1 ./... — 21/21 packages PASS (run after every change).
  • make lint (golangci-lint, repo config) — 0 issues.
  • New tests: cache identity, errors stay uncached, ClearRegexCache semantics at the options level, cached brace indices, the exact-size merge with model-slice safety, the unbraced-segment skip, and six tests pinning the HEAD/QUERY/additionalOperations resolution gaps (each flipped by the fix in this PR).
  • 12 benchmark scenarios in validator_request_bench_test.go and validator_scenario_bench_test.go cover query-heavy, invalid-request, concurrent, format-assertions, strict-server, urlencoded, JSON-response-body and 200-route shapes.

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.82%. Comparing base (754a5b7) to head (cf51e42).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #340      +/-   ##
==========================================
+ Coverage   98.74%   98.82%   +0.07%     
==========================================
  Files          94       95       +1     
  Lines       12310    12451     +141     
==========================================
+ Hits        12156    12305     +149     
+ Misses        129      125       -4     
+ Partials       25       21       -4     
Flag Coverage Δ
unittests 98.82% <100.00%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@daveshanley daveshanley left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @emilien-puget, this is a seriously good PR. Half the allocations, a 42% geomean drop, and benchmarks that cover the shapes people actually run. That's the kind of thing I love seeing land.

The ExtractParamsForOperation change also fixes a real race that I don't think anyone had spotted. Nice work.

The one thing I'd like changed before merging is the global regex cache, because nothing ever frees it. Details inline. The HEAD and QUERY comments are older bugs that you happened to walk past, so follow-ups are fine for those.

Comment thread helpers/regex_maker.go Outdated
//
// ClearRegexCache empties the cache. Call it between document lifecycles in
// long-running processes to bound memory.
var regexCache sync.Map // map[string]*regexp.Regexp

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the one I'd like to change before we merge. The cache lives for the life of the process, and nothing ever calls ClearRegexCache. validator.Release() and ValidationOptions.Release() exist so a service can load a spec, validate, throw it away and get its memory back. This cache skips that contract.

Some of our own tools load a lot of specs in one long-running process, so every template from every spec stays here forever. At your measured 4.3 KB an entry, that adds up fast.

GetRegexForPath is also exported. Anyone passing it strings that aren't templates now grows this map without limit, where it used to hold no state at all.

What do you think about defaulting RegexCache to a per-validator sync.Map in NewValidatorFromV3Model instead? Same hit rate, and Release() cleans it up for free.

Comment thread helpers/parameter_utilities.go Outdated
func ExtractParamsForOperation(request *http.Request, item *v3.PathItem) []*v3.Parameter {
params := item.Parameters
var operationParams []*v3.Parameter
switch request.Method {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same family as the HEAD comment below, and also older than this PR. There's no case for QUERY or for AdditionalOperations, and the router resolves both. So a 3.2 query operation with its own required params gets matched, and then only the path level params are validated. Fine for a follow-up.

Comment thread helpers/parameter_utilities.go Outdated
params = append(params, item.Options.Parameters...)
operationParams = item.Options.Parameters
}
case http.MethodHead:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one predates you, but you're in here so I'll flag it. For a HEAD request on a path with no head operation, ExtractOperation and the router both fall back to get. This function doesn't, so it returns only the path level params.

So HEAD /reports is validated as the GET operation, but GET's required query and header params are never checked. Falling back to item.Get here, the same way ExtractOperation does, closes it. Happy for that to go in here or in a follow-up, your call.

return item.Parameters
}
if len(item.Parameters) == 0 {
return operationParams

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now hands back the operation's own Parameters slice when there are no path level params. Everything in the repo only reads the result, so we're fine internally. It's exported though, so I'd add a line to the doc comment saying the result is read-only. Otherwise someone appends to it and writes straight into the shared model.

require.Equal(t, []*v3.Parameter{operationOnly}, got)
})

t.Run("both sides merge without writing into the model slice", func(t *testing.T) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch on the backing array. Concurrent GET and POST requests on the same path item could stomp on each other's parameter lists, which is a properly sneaky bug.

The test can't see it though. item.Parameters here has len == cap, so the old append reallocates and passes too. Revert the fix and this test stays green. Build it with spare capacity, something like make([]*v3.Parameter, 1, 4), then check the slot past len is untouched.

Comment thread helpers/regex_maker.go
@@ -1,10 +1,10 @@
package helpers

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tiny one: this file is missing the standard copyright header. Worth adding while you're in here.

Comment thread helpers/regex_maker.go Outdated
// The function ensures that the template is well-formed, with balanced and properly
// nested braces. If the template is invalid, an error is returned.
//
// Compiled regexes are cached by template string. The first call for a template

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this in, path segments get cached twice: once here, and again in the user's config.RegexCache in path_parameters.go and paths.comparePaths. WithRegexCache still says it enables regex caching, which is now always on. If the per-validator default from my other comment works out, we're back to one cache and the option means something again.

Comment thread helpers/regex_maker.go Outdated
// the same values BraceIndices computes. The indices come from the compile
// cache, so repeated calls for one template do not re-scan it. Callers must
// treat the returned slice as read-only. An invalid template returns an error.
func GetBraceIndicesForPath(tpl string) ([]int, error) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The doc says this returns the same values BraceIndices computes, but on a cache miss it runs the whole regex compile. So {id:(abc)} gets indices from BraceIndices and an error from this.

Today that's mostly hidden because GetRegexForPath runs first. In ValidatePathParamsWithPathItem though, when the regex came out of a user supplied RegexCache, this error hits the continue and the segment's params are skipped without a peep. I'd compute the indices separately from the compile, or at least fix the doc.

Comment thread helpers/regex_maker_test.go Outdated
before, errBefore := GetRegexForPath("/cache-clear/{id}")
assert.NoError(t, errBefore)

ClearRegexCache()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests share the process-wide cache, and this one clears it while the identity tests next door assert on pointers from that same cache. Works today because nothing here calls t.Parallel(). The day someone adds it, these go flaky. One more nudge toward a cache that isn't global.

// The schema will be stored and reused from cache if available, otherwise it will be compiled on each call.
func ValidateRequestSchema(input *ValidateRequestSchemaInput) (bool, []*liberrors.ValidationError) {
validationOptions := config.NewValidationOptions(input.Options...)
validationOptions := input.ValidationOptions

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If someone sets both ValidationOptions and Options, the Options vanish without a word. These input structs are public, so I can see someone passing the validator's options plus config.WithFormatAssertions() for one call and wondering why formats aren't checked. Either document that they're mutually exclusive, or apply Options on top of a copy. Same thing in responses/validate_response.go.

@emilien-puget

Copy link
Copy Markdown
Contributor Author

thanks for the review @daveshanley , i had other ideas for performances improvments but first i wanted some parity with some previous work done in the main openapi library, i'm taking a look at your comment and might open follow ups

@emilien-puget

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @daveshanley — all findings are addressed in the pushed commits.

The merge blocker — the global regex cache (regex_maker.go): gone, done the way you proposed. NewValidatorFromV3Model now defaults ValidationOptions.RegexCache to a per-validator sync.Map, shared with the sub-validators through WithExistingOpts, and ValidationOptions.Release() empties an owned cache, so the Release() contract holds: entries die with the validator. GetRegexForPath is stateless again, ClearRegexCache and the package-level map are deleted (both were introduced by this PR, so no public surface changed). WithRegexCache means what it says again: supply or share a cache, otherwise you get the per-validator default. Hot-path parity is measured, not assumed: paired n=10 against the global-cache build, allocs/op identical on every shape (35 plain, 94 param-heavy, 96 invalid, 35 large-routes — all samples equal). The brace indices moved onto a per-validator map inside the parameter validator (braceIdxCache), so the index lookup is also per-validator and dies with it.

The two bugs we walked past — fixed with tests. ExtractOperation now resolves QUERY, additionalOperations and falls back to get for HEAD (matching the router), and ExtractParamsForOperation delegates to it so the two can't drift again. The claim tests you saw earlier in the thread flipped from pinning the bug to asserting the fix: a 3.2 query operation and a custom method now enforce their required params instead of failing with the false "no method found" error, and HEAD /reports enforces GET's required query params.

The smaller findings:

  • ExtractParamsForOperation doc now states the result may alias the model's slices and is read-only.
  • The merge-safety test is rebuilt: item.Parameters has spare capacity (len 1, cap 4) and the test asserts the capacity slot past the length stays empty — reverting the fix makes it fail. The untouched-slice cases assert slice identity, the duplicated subtest is gone.
  • compilePathRegexEntry assembles patterns with strings.Builder: buffer writes can't fail, so the unreachable error branch is deleted rather than left uncovered (also −3 allocs/op on the compile path).
  • The copyright header is in.
  • GetBraceIndicesForPath is deleted; indices come from helpers.BraceIndices (or the per-validator cache), so the doc/behavior mismatch and the silent-skip path you flagged disappear with it.
  • ValidationOptions vs Options: documented as mutually exclusive (Options ignored when both set) in both input structs.

The tests that share the process-wide regex cache are gone with it — the cache tests now seed the per-validator options.RegexCache directly, so there is no shared process state left for t.Parallel() to trip over. CI is green (build, lint, Codecov 100% patch).

…ation allocations

Request validation called helpers.GetRegexForPath for every path
template on every request and recompiled the same regex each time, and
the rest of the request hot path rebuilt per-request state it could
reuse. This closes the gap with libopenapi, which caches compiled
JSONPath expressions the same way.

Changes:

- Each validator owns its regex cache: NewValidatorFromV3Model defaults
  ValidationOptions.RegexCache to a fresh sync.Map, shared with the sub
  validators through WithExistingOpts, and ValidationOptions.Release
  empties an owned cache, so compiled regexes die with the validator.
  GetRegexForPath stays stateless: it compiles and returns. A cache set
  through config.WithRegexCache keeps the interface contract and stays
  shared. The default cache is called through its concrete *sync.Map
  type, so the template key does not box per lookup; custom caches keep
  the interface path.
- The brace indices of path templates are cached on a per-validator map
  inside the parameter validator, so repeated segment scans allocate
  once per validator lifetime.
- ExtractOperation resolves OpenAPI 3.2 query operations, methods
  declared under additionalOperations, and falls back to get for HEAD,
  matching the router. ExtractParamsForOperation delegates to it, so
  request-level method resolution and parameter extraction cannot
  drift. Previously a HEAD request on a get-only path skipped GET's
  required query and header parameters, and 3.2 query operations and
  custom methods were rejected with a false "no '<METHOD>' method
  found in the spec" error although the router had resolved them.
- ExtractParamsForOperation returns the model slices untouched when one
  side is empty and merges into an exact-size slice otherwise: appending
  to item.Parameters can write into the model backing array, and the
  model stays shared across validators and requests. Its result may
  alias the model's slices, so the doc comment states it is read-only.
- ValidateRequestSchema, ValidateResponseSchema and
  ValidateResponseHeaders accept pre-built options through an unexported
  core; internal callers stop building config.NewValidationOptions per
  request. Exported signatures are unchanged, and the input structs
  document that ValidationOptions and Options are mutually exclusive.
- nonEmptyPathSegments walks the path once with strings.SplitSeq.
- ExtractRawQueryValues returns nil for an empty query.
- GetRenderedSchema returns the cached ReferenceSchema string instead of
  copying bytes per call.
- compilePathRegexEntry assembles patterns with strings.Builder:
  bytes.Buffer writes cannot fail, so the unreachable error branch and
  the fmt call with its interface boxing are gone.

Evidence: paired runs, 10 samples per side, benchstat (i7-1265U, Go
1.26), measured back-to-back main vs branch across 12 gateway scenarios
including query-heavy, invalid-request, concurrent, format-assertions,
strict-server, urlencoded, JSON-response-body and 200-route shapes:

- plain GET: 96 -> 35 allocs/op (-64%), 8.0 -> 3.8 us (-52%)
- param-heavy GET: 320 -> 94 allocs/op (-71%), 26.0 -> 11.2 us (-57%)
- invalid request: 322 -> 96 allocs/op (-70%), 27.0 -> 11.1 us (-59%)
- concurrent GET, 12 goroutines: 96 -> 35 allocs/op, 4.2 -> 1.4 us
- large route table (200 paths): 113 -> 35 allocs/op (-69%), -68%
- format assertions: 97 -> 36 allocs/op; strict server: 98 -> 37
- urlencoded body: 99 -> 87; JSON response body: 57 -> 48
- geomean: -42.6% sec/op, -53.9% B/op, -50.1% allocs/op

Memory: an entry holds a few KB (measured 4.3 KB: key string plus
compiled regex), so a 1,000-route API costs about 4 MB, and
validator.Release drops it with the validator.

One candidate was measured and rejected, recorded here: hoisting the
per-segment regex out of the parameter loop cost +9% sec/op on the
single-parameter shape (three precompute slices, nothing to dedupe).

Verification: go test -race -count=1 ./... (21/21 packages), make lint
(0 issues), CI green (build, lint, Codecov 100% patch coverage), new
tests for the per-validator cache flow, brace indices, the exact-size
merge with model-slice safety (verified to fail against the old append),
the unbraced-segment skip, the operation resolution fixes, and 12
benchmark scenarios in validator_request_bench_test.go and
validator_scenario_bench_test.go.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants