Skip to content

🔥 feat: optimize CORS origin lookup from O(n) to O(1) using map #4362

@pageton

Description

@pageton

Problem

File: middleware/cors/cors.go:144

The CORS middleware uses slices.Contains(allowOrigins, originHeader) which performs an O(n) linear scan over the configured allowed origins list. This runs on every CORS request (every request with an Origin header).

if slices.Contains(allowOrigins, originHeader) {
    allowOrigin = originHeaderRaw
}

Impact

  • O(n) per request where n = number of configured origins.
  • With many allowed origins (common in multi-tenant SaaS), this becomes a measurable per-request cost.
  • The origin matching also iterates allowSubOrigins linearly (line 150-155).

Proposed fix

Convert allowOrigins from []string to map[string]struct{} at middleware creation time:

allowOriginSet := make(map[string]struct{}, len(cfg.AllowOrigins))
for _, origin := range cfg.AllowOrigins {
    // ... normalize ...
    allowOriginSet[normalizedOrigin] = struct{}{}
}

// In handler:
if _, ok := allowOriginSet[originHeader]; ok {
    allowOrigin = originHeaderRaw
}

This changes lookup from O(n) to O(1). The allowSubOrigins linear scan is harder to optimize but is typically small.

Priority

P1 — Simple fix, measurable improvement for apps with many configured origins.


Identified during a full performance architecture review of the Fiber codebase.

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions