Skip to content

Comments

feat: make request body size configurable via MAX_REQUEST_BODY_MB#128

Open
Omkarop0808 wants to merge 3 commits intoAnkanMisra:mainfrom
Omkarop0808:feat/configurable-request-body-size
Open

feat: make request body size configurable via MAX_REQUEST_BODY_MB#128
Omkarop0808 wants to merge 3 commits intoAnkanMisra:mainfrom
Omkarop0808:feat/configurable-request-body-size

Conversation

@Omkarop0808
Copy link
Contributor

@Omkarop0808 Omkarop0808 commented Feb 21, 2026

🎯 Description

This PR makes the request body size limit configurable via the MAX_REQUEST_BODY_MB environment variable, replacing the hardcoded 10MB limit in the Gateway service.

Fixes #116

🔧 Changes Made

1. Added Configuration Helper (gateway/config.go)

  • Implemented getMaxBodySize() function that reads MAX_REQUEST_BODY_MB from environment
  • Returns size in bytes (MB × 1024 × 1024)
  • Defaults to 10MB if not set

2. Updated Request Handler (gateway/main.go)

  • Removed hardcoded const maxBodySize = 10 * 1024 * 1024
  • Replaced with dynamic call to getMaxBodySize()
  • Updated error response to show actual configured limit in max_size_mb field

3. Added Documentation (.env.example)

  • Added MAX_REQUEST_BODY_MB=10 with clear comments
  • Placed in Request Configuration section for easy discovery

4. Added Tests (gateway/config_test.go)

  • Comprehensive unit tests for getMaxBodySize()
  • Tests default value (10MB)
  • Tests custom values (1MB, 50MB, 100MB)
  • Follows existing test patterns

📊 Impact

  • Backward Compatible: Default remains 10MB
  • Production Ready: Allows different deployments to configure limits based on needs
  • DoS Protection: Enables restricting payload sizes to prevent memory attacks
  • Large Documents: Supports increasing limits for summarization of larger texts

✅ Testing

  • Added unit tests for getMaxBodySize()
  • All tests follow existing patterns
  • Default behavior unchanged (10MB)
  • Configuration properly documented

📝 Usage Example

# Set 1MB limit for testing
MAX_REQUEST_BODY_MB=1

# Set 50MB limit for large documents
MAX_REQUEST_BODY_MB=50

🔍 Code Quality
Follows Go idioms and project conventions
Consistent with existing timeout configuration helpers
Clear comments and documentation
Minimal, focused changes
📦 Files Changed
.env.example - Added configuration variable
config.go
 - Added helper function
config_test.go
 - Added unit tests
main.go
 - Updated handler to use dynamic configuration

Ready for review!

Summary by CodeRabbit

  • New Features

    • Request body size limit is now configurable via an environment variable (default: 10 MB).
  • Chores

    • Error responses for oversized payloads use a clearer field name indicating the limit in MB.
  • Tests

    • Added unit tests covering default, custom, zero and negative configuration scenarios.
  • Documentation

    • Example environment file updated with the new configuration option and comments.

Greptile Summary

This PR makes request body size configurable via MAX_REQUEST_BODY_MB, but critically, it only updates main.go and misses cache.go, which still has a hardcoded 10MB limit. This creates inconsistent behavior where cached requests ignore the configuration.

Critical Issues:

  • gateway/cache.go lines 50, 52, 62, 54, 69 still use hardcoded 10 * 1024 * 1024 and "10MB" strings
  • When caching is enabled, the configurable limit is completely bypassed
  • getMaxBodySize() lacks validation for non-positive values (unlike other timeout helpers)

Minor Issues:

  • Error response on line 377 duplicates logic by calling getEnvAsInt() again instead of reusing maxBodySize
  • Tests missing edge cases for zero/negative values

Confidence Score: 1/5

  • This PR has a critical bug that breaks the feature when caching is enabled
  • The implementation is incomplete - cache.go still has hardcoded 10MB limits in multiple places (lines 50, 52, 62, 54, 69), which means the configurable body size only works when caching is disabled. Additionally, missing validation allows invalid values like 0 or negative numbers.
  • gateway/cache.go must be updated to use getMaxBodySize() instead of hardcoded limits, and gateway/config.go needs validation for non-positive values

Important Files Changed

Filename Overview
gateway/config.go Added getMaxBodySize() helper but missing validation for non-positive values
gateway/config_test.go Added tests for getMaxBodySize() but missing edge cases for zero/negative values
gateway/main.go Updated to use getMaxBodySize() but incomplete - cache.go still has hardcoded 10MB limit causing inconsistent behavior, and error response duplicates logic
.env.example Added MAX_REQUEST_BODY_MB configuration with clear documentation

Last reviewed commit: 4e494c3

(5/5) You can turn off certain types of comments like style here!

- Add getMaxBodySize() helper in gateway/config.go

- Replace hardcoded 10MB limit with dynamic configuration

- Add MAX_REQUEST_BODY_MB to .env.example with default 10MB

- Add comprehensive unit tests for getMaxBodySize()

- Update error response to show actual configured limit

Fixes AnkanMisra#116
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 21, 2026

Warning

Rate limit exceeded

@Omkarop0808 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 18 minutes and 15 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

The PR makes the gateway's request body size configurable via a new MAX_REQUEST_BODY_MB env var, adds getMaxBodySize() in gateway/config.go with tests, updates .env.example, and replaces hardcoded 10MB limits in handlers and cache checks with the dynamic value (also changing error payload field to max_size_mb).

Changes

Cohort / File(s) Summary
Environment
.env.example
Added MAX_REQUEST_BODY_MB with default value 10 and documentation under Request Body Size Configuration.
Config Helper & Tests
gateway/config.go, gateway/config_test.go
Added getMaxBodySize() int64 which reads MAX_REQUEST_BODY_MB, clamps non-positive values to default 10, and returns bytes. Added table-driven tests for defaults and various values (including zero/negative fallback).
Runtime Usage
gateway/main.go, gateway/cache.go
Replaced hardcoded 10MB limit with getMaxBodySize() for http.MaxBytesReader and Content-Length checks. Updated error payload key from max_size to max_size_mb and included size value in MB.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client as Client
  participant Gateway as Gateway Handler
  participant Config as Config (getMaxBodySize)
  participant Reader as http.MaxBytesReader

  Client->>Gateway: POST /api/ai/summarize (body)
  Gateway->>Config: getMaxBodySize()
  Config-->>Gateway: maxBodySize (bytes)
  Gateway->>Reader: wrap Request.Body with MaxBytesReader(maxBodySize)
  Gateway->>Gateway: read body -> if exceeds -> 413 error with max_size_mb
  Gateway-->>Client: 200/413 response
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Suggested labels

Medium, SWoC26

Suggested reviewers

  • AnkanMisra

Poem

🐰 I sniffed the env and gave a hop,
No more hardcoded mountaintop.
Now limits bend by config's light —
Bytes dance softly, all is right! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Changes in gateway/cache.go extend beyond the original issue scope by replacing additional hardcoded 10MB usages and changing error field names from max_size to max_size_mb. Document or create separate issue for cache.go changes, or clarify if these are necessary follow-up fixes to ensure consistency across all body size limit enforcement points.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: making request body size configurable via an environment variable instead of hardcoded.
Linked Issues check ✅ Passed All requirements from issue #116 are met: MAX_REQUEST_BODY_MB environment variable added, getMaxBodySize() implemented in gateway/config.go, hardcoded limit replaced with dynamic value, and .env.example updated.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

4 files reviewed, 4 comments

Edit Code Review Agent Settings | Greptile

Comment on lines 25 to 28
func getMaxBodySize() int64 {
mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10)
return int64(mb) * 1024 * 1024
}
Copy link

Choose a reason for hiding this comment

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

Missing validation for non-positive values - allows MAX_REQUEST_BODY_MB=0 or negative values, unlike getPositiveTimeout() which validates positive values

Suggested change
func getMaxBodySize() int64 {
mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10)
return int64(mb) * 1024 * 1024
}
func getMaxBodySize() int64 {
mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10)
if mb <= 0 {
mb = 10
}
return int64(mb) * 1024 * 1024
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: gateway/config.go
Line: 25-28

Comment:
Missing validation for non-positive values - allows `MAX_REQUEST_BODY_MB=0` or negative values, unlike `getPositiveTimeout()` which validates positive values

```suggestion
func getMaxBodySize() int64 {
	mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10)
	if mb <= 0 {
		mb = 10
	}
	return int64(mb) * 1024 * 1024
}
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 261 to 300
func TestGetMaxBodySize(t *testing.T) {
tests := []struct {
name string
envValue string
expected int64
}{
{
name: "default 10MB",
envValue: "",
expected: 10 * 1024 * 1024,
},
{
name: "custom 1MB",
envValue: "1",
expected: 1 * 1024 * 1024,
},
{
name: "custom 50MB",
envValue: "50",
expected: 50 * 1024 * 1024,
},
{
name: "custom 100MB",
envValue: "100",
expected: 100 * 1024 * 1024,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.envValue != "" {
t.Setenv("MAX_REQUEST_BODY_MB", tt.envValue)
}
result := getMaxBodySize()
if result != tt.expected {
t.Errorf("expected %d bytes, got %d bytes", tt.expected, result)
}
})
}
}
Copy link

Choose a reason for hiding this comment

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

Missing test cases for invalid values (zero, negative) - all timeout helpers test non-positive fallback behavior (see line 255-258)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Prompt To Fix With AI
This is a comment left during a code review.
Path: gateway/config_test.go
Line: 261-300

Comment:
Missing test cases for invalid values (zero, negative) - all timeout helpers test non-positive fallback behavior (see line 255-258)

<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>

How can I resolve this? If you propose a fix, please make it concise.

gateway/main.go Outdated
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
c.JSON(413, gin.H{"error": "Payload too large", "max_size": "10MB"})
c.JSON(413, gin.H{"error": "Payload too large", "max_size_mb": getEnvAsInt("MAX_REQUEST_BODY_MB", 10)})
Copy link

Choose a reason for hiding this comment

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

Calling getEnvAsInt() directly here duplicates the logic from getMaxBodySize() - should reuse the same value from line 371

Suggested change
c.JSON(413, gin.H{"error": "Payload too large", "max_size_mb": getEnvAsInt("MAX_REQUEST_BODY_MB", 10)})
c.JSON(413, gin.H{"error": "Payload too large", "max_size_mb": maxBodySize / (1024 * 1024)})
Prompt To Fix With AI
This is a comment left during a code review.
Path: gateway/main.go
Line: 377

Comment:
Calling `getEnvAsInt()` directly here duplicates the logic from `getMaxBodySize()` - should reuse the same value from line 371

```suggestion
				c.JSON(413, gin.H{"error": "Payload too large", "max_size_mb": maxBodySize / (1024 * 1024)})
```

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 23 to 28
// getMaxBodySize returns the maximum request body size in bytes.
// Configurable via MAX_REQUEST_BODY_MB environment variable (default: 10MB).
func getMaxBodySize() int64 {
mb := getEnvAsInt("MAX_REQUEST_BODY_MB", 10)
return int64(mb) * 1024 * 1024
}
Copy link

Choose a reason for hiding this comment

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

Critical: gateway/cache.go lines 50, 52, 62, 54, 69 still use hardcoded const maxBodySize = 10 * 1024 * 1024 - when caching is enabled, requests will be limited to 10MB regardless of this configuration

Prompt To Fix With AI
This is a comment left during a code review.
Path: gateway/config.go
Line: 23-28

Comment:
**Critical**: `gateway/cache.go` lines 50, 52, 62, 54, 69 still use hardcoded `const maxBodySize = 10 * 1024 * 1024` - when caching is enabled, requests will be limited to 10MB regardless of this configuration

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
gateway/main.go (1)

371-377: Derive max_size_mb from the already-computed maxBodySize instead of a second env read.

Line 377 calls getEnvAsInt("MAX_REQUEST_BODY_MB", 10) independently. The value it reports could theoretically differ from what was passed to MaxBytesReader on line 372 if the env var changes between the two reads. Using integer division from the in-scope maxBodySize is both simpler and guaranteed consistent.

♻️ Proposed fix
-			c.JSON(413, gin.H{"error": "Payload too large", "max_size_mb": getEnvAsInt("MAX_REQUEST_BODY_MB", 10)})
+			c.JSON(413, gin.H{"error": "Payload too large", "max_size_mb": maxBodySize / (1024 * 1024)})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@gateway/main.go` around lines 371 - 377, The 413 error response currently
calls getEnvAsInt("MAX_REQUEST_BODY_MB", 10) again instead of using the
already-computed maxBodySize; update the error branch in the handler to derive
max_size_mb from maxBodySize (e.g., divide maxBodySize by (1024*1024) with
appropriate integer rounding) and pass that value to c.JSON so the reported
limit matches the value used with http.MaxBytesReader; adjust references in the
request-reading block around maxBodySize, http.MaxBytesReader, and the
c.JSON(413, ...) call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@gateway/config_test.go`:
- Around line 289-299: The default subtest does not clear the environment so
MAX_REQUEST_BODY_MB may leak into tests; unconditionally call
t.Setenv("MAX_REQUEST_BODY_MB", tt.envValue) in the table-driven loop (pass ""
for the default case) so getMaxBodySize() sees an absent value as intended, and
add two edge-case table entries where envValue is "0" and "-1" and expected is
the default 10*1024*1024 to verify the non-positive guard in
getMaxBodySize()/getEnvAsInt; update the tests loop and test cases referencing
getMaxBodySize and MAX_REQUEST_BODY_MB accordingly.

In `@gateway/config.go`:
- Around line 25-28: The getMaxBodySize function should guard against
non-positive environment values: read mb via getEnvAsInt("MAX_REQUEST_BODY_MB",
10), and if mb <= 0 set mb = 10 (mirroring getPositiveTimeout) before converting
to int64 and multiplying by 1024*1024 so http.MaxBytesReader never receives n ≤
0; update getMaxBodySize to enforce this default behavior using the existing
symbols getMaxBodySize and getEnvAsInt.

---

Nitpick comments:
In `@gateway/main.go`:
- Around line 371-377: The 413 error response currently calls
getEnvAsInt("MAX_REQUEST_BODY_MB", 10) again instead of using the
already-computed maxBodySize; update the error branch in the handler to derive
max_size_mb from maxBodySize (e.g., divide maxBodySize by (1024*1024) with
appropriate integer rounding) and pass that value to c.JSON so the reported
limit matches the value used with http.MaxBytesReader; adjust references in the
request-reading block around maxBodySize, http.MaxBytesReader, and the
c.JSON(413, ...) call.

- Add validation for non-positive values in getMaxBodySize()

- Add test cases for zero and negative values

- Reuse maxBodySize value instead of calling getEnvAsInt() multiple times

- Fix cache.go to use calculated maxBodySize value consistently
- Always call t.Setenv() to prevent MAX_REQUEST_BODY_MB leakage between tests

- Ensures default test case properly clears environment
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@gateway/config_test.go`:
- Around line 299-309: The "default" subtest can inherit an existing
MAX_REQUEST_BODY_MB from the environment because t.Setenv is only called when
tt.envValue != ""—fix by unconditionally calling t.Setenv("MAX_REQUEST_BODY_MB",
tt.envValue) inside the test loop so an empty tt.envValue clears the env for
that subtest; update the loop around the table-driven tests that call
getMaxBodySize() (referencing tt.envValue and getMaxBodySize) to always invoke
t.Setenv before calling getMaxBodySize().

@AnkanMisra
Copy link
Owner

@greptile give the confidence score and point out where the bugs are in this pr

@greptile-apps
Copy link

greptile-apps bot commented Feb 22, 2026

Confidence Score: 1/5

This is a very low score indicating critical issues that make the PR unsuitable for merging.

Critical Bugs

1. Incomplete Implementation - Cache Handler Ignored

Location: gateway/cache.go (lines 50, 52, 54, 62, 69)

The PR updates main.go to use the configurable limit, but completely misses cache.go which still has hardcoded values:

  • Hardcoded 10 * 1024 * 1024 bytes
  • Hardcoded "10MB" strings in error messages

Impact: When caching is enabled, requests will still be limited to 10MB regardless of the MAX_REQUEST_BODY_MB configuration. This breaks the entire feature for cached requests.

2. Missing Input Validation

Location: gateway/config.go - getMaxBodySize() function

The function lacks validation for non-positive values (0, negative numbers). Other timeout helpers in the codebase validate their inputs, but this one doesn't.

Impact: Setting MAX_REQUEST_BODY_MB=0 or negative values could cause undefined behavior or bypass size limits entirely.

Minor Issues

3. Duplicated Logic in Error Response

Location: gateway/main.go line 377

The error response calls getEnvAsInt("MAX_REQUEST_BODY_MB", 10) again instead of reusing the already-computed maxBodySize variable.

4. Incomplete Test Coverage

Location: gateway/config_test.go

Tests are missing edge cases for:

  • Zero value (MAX_REQUEST_BODY_MB=0)
  • Negative values (MAX_REQUEST_BODY_MB=-1)

Bottom Line: The feature appears to work but has a critical blind spot in the cache handler, making it only partially functional. The PR needs updates to cache.go and proper validation before it's safe to merge.

Copy link
Owner

@AnkanMisra AnkanMisra left a comment

Choose a reason for hiding this comment

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

@Omkarop0808 Follow and do the changes that greptile said

@Omkarop0808
Copy link
Contributor Author

Omkarop0808 commented Feb 22, 2026

Hi! All the issues mentioned have already been addressed in commits 0e04eb3 and 7625ff8:
✅ Cache handler now uses getMaxBodySize() (no hardcoded values)
✅ Input validation added for zero/negative values
✅ Removed duplicated getEnvAsInt() call in error response
✅ Added test cases for edge cases (zero and negative values)
The bot might be reviewing cached data. All fixes are pushed and ready for review. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make Request Body Size Configurable

2 participants