Skip to content

⚡ Bolt: [performance improvement] Pre-serialized JSON caching for utility endpoints#616

Merged
RohanExploit merged 3 commits into
mainfrom
bolt-serialization-caching-568603064269904002
Mar 30, 2026
Merged

⚡ Bolt: [performance improvement] Pre-serialized JSON caching for utility endpoints#616
RohanExploit merged 3 commits into
mainfrom
bolt-serialization-caching-568603064269904002

Conversation

@RohanExploit
Copy link
Copy Markdown
Owner

@RohanExploit RohanExploit commented Mar 30, 2026

💡 What: Optimized the caching logic in get_leaderboard and get_stats within backend/routers/utility.py to store pre-serialized JSON strings rather than Python dictionaries. It now returns a base fastapi.Response instead of a JSONResponse.
🎯 Why: Storing raw dictionaries in the cache still required FastAPI/Pydantic to incur validation and serialization overhead on every cache hit. By caching the serialized string, we completely bypass this overhead.
📊 Impact: Expected performance improvement is significant for cache hits. Synthetic benchmarks show returning a raw response with pre-serialized JSON is approximately ~50x faster than passing dictionaries to JSONResponse (0.0312s vs 1.5152s for 10000 iterations).
🔬 Measurement: Verify by monitoring response latencies for the /api/leaderboard and /api/stats endpoints, or by running the associated backend test suite.


PR created automatically by Jules for task 568603064269904002 started by @RohanExploit


Summary by cubic

Optimized /api/leaderboard and /api/stats by caching pre-serialized JSON and returning a raw fastapi.Response. This removes Pydantic/JSONResponse overhead and lowers latency.

  • Refactors
    • Cache JSON strings via json.dumps and return Response(content=..., media_type="application/json") instead of JSONResponse for both endpoints (hits and misses).
    • Added backend/tests/benchmark_serialization.py; shows ~50x speedup on 10k iterations (~1.5152s vs ~0.0312s).

Written for commit 583c95d. Summary will update on new commits.

Summary by CodeRabbit

  • Refactor

    • /stats and /leaderboard now return JSON payloads as application/json responses using pre-serialized JSON content.
  • Tests

    • Added a benchmark script that compares response serialization approaches and reports elapsed times.

Implemented serialization caching in `get_leaderboard` and `get_stats` to improve response times. By serializing the output dictionaries to JSON strings before caching them, and returning a raw `fastapi.Response` with `media_type="application/json"`, we bypass the repetitive validation and JSON serialization overhead associated with `JSONResponse` on cache hits.

Benchmark:
- JSONResponse: ~1.5152s (10000 iterations)
- Raw Response with pre-serialized JSON: ~0.0312s (10000 iterations)
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Copilot AI review requested due to automatic review settings March 30, 2026 14:25
@netlify
Copy link
Copy Markdown

netlify Bot commented Mar 30, 2026

Deploy Preview for fixmybharat canceled.

Name Link
🔨 Latest commit 8332071
🔍 Latest deploy log https://app.netlify.com/projects/fixmybharat/deploys/69caa480a4a38400089b3816

@github-actions
Copy link
Copy Markdown

🙏 Thank you for your contribution, @RohanExploit!

PR Details:

Quality Checklist:
Please ensure your PR meets the following criteria:

  • Code follows the project's style guidelines
  • Self-review of code completed
  • Code is commented where necessary
  • Documentation updated (if applicable)
  • No new warnings generated
  • Tests added/updated (if applicable)
  • All tests passing locally
  • No breaking changes to existing functionality

Review Process:

  1. Automated checks will run on your code
  2. A maintainer will review your changes
  3. Address any requested changes promptly
  4. Once approved, your PR will be merged! 🎉

Note: The maintainers will monitor code quality and ensure the overall project flow isn't broken.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 30, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a79d5632-32b1-427a-8ba3-d07ea06a225c

📥 Commits

Reviewing files that changed from the base of the PR and between 1e2e34f and 8332071.

📒 Files selected for processing (2)
  • backend/routers/utility.py
  • backend/tests/benchmark_serialization.py

📝 Walkthrough

Walkthrough

The PR changes /stats and /leaderboard to store and return pre-serialized JSON strings via fastapi.Response(media_type="application/json") instead of JSONResponse/Pydantic objects, and adds a benchmark script comparing JSONResponse vs pre-serialized Response serialization performance.

Changes

Cohort / File(s) Summary
Response Serialization Optimization
backend/routers/utility.py
Replaced JSONResponse/direct Pydantic returns with fastapi.Response(content=json_string, media_type="application/json"); added json.dumps() when caching responses and adjusted cache reads to return raw JSON strings.
Benchmark Testing
backend/tests/benchmark_serialization.py
New benchmark script that compares creating JSONResponse(content=data) (forcing serialization via resp.body) vs Response(content=json_data, media_type="application/json") over repeated iterations and prints elapsed times.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

🐰 I nibbled bytes beneath the moonlit key,

Pre-dumped JSON snug as can be.
Cache a string, hop—no extra round,
Faster replies with a joyful bound.
Hooray, our endpoints skip the millisecond sea!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning PR description lacks required template structure with missing Type of Change, Related Issue, Testing Done, and Checklist sections. Add all required template sections including Type of Change checkbox, Related Issue link, Testing Done verification, and Checklist items with completion status.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: pre-serialized JSON caching for utility endpoints as a performance improvement.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt-serialization-caching-568603064269904002

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
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

No issues found across 2 files

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Optimizes FastAPI utility endpoints by caching and returning pre-serialized JSON payloads to reduce per-request serialization overhead on cache hits.

Changes:

  • Updated /stats and /leaderboard to cache JSON strings and return fastapi.Response with application/json.
  • Added a small benchmark script comparing JSONResponse vs raw Response with pre-serialized JSON.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
backend/routers/utility.py Switches cached utility endpoints to return pre-serialized JSON via Response.
backend/tests/benchmark_serialization.py Adds a benchmark script to measure serialization overhead differences.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/routers/utility.py Outdated
Comment thread backend/tests/benchmark_serialization.py Outdated
Comment thread backend/tests/benchmark_serialization.py
Comment thread backend/tests/benchmark_serialization.py
Copy link
Copy Markdown

@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)
backend/routers/utility.py (1)

51-52: Add response-contract tests for /stats and /leaderboard endpoints.

Both endpoints return Response directly (lines 55, 91, 121, 158), bypassing FastAPI's response-model validation. While the optimization is valid, contract tests should be added to lock and prevent regression of response shape and types (StatsResponse and LeaderboardResponse).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/routers/utility.py` around lines 51 - 52, Add response-contract tests
that call the /stats and /leaderboard endpoints and validate the actual JSON
response shape/types against the StatsResponse and LeaderboardResponse Pydantic
models (e.g., by importing StatsResponse and LeaderboardResponse and using
.parse_obj or model(**resp.json())). Specifically, write tests that exercise the
get_stats (router path "/stats") and the leaderboard handler (router path
"/leaderboard") which currently return fastapi.Response directly, fetch the
endpoint JSON, and assert model parsing succeeds and required fields/types
match; include negative/test-failure cases if keys are missing or types differ
to lock the contract and prevent regressions. Ensure tests run in CI and mock
DB/fixtures as needed so get_db-dependent handlers return stable predictable
data.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/routers/utility.py`:
- Around line 55-56: Cached cache hits from recent_issues_cache may be
non-string values causing malformed application/json responses; in the endpoints
that read cached_stats (and the other cached value around the referenced lines),
defensively check the cached value's type: if it's a str or bytes return it
directly, otherwise serialize the value to a JSON string (e.g., json.dumps)
before passing to Response with media_type="application/json"; update the code
paths that read from recent_issues_cache and the second cache read to perform
this type check/serialization so non-string Any values are handled safely.

In `@backend/tests/benchmark_serialization.py`:
- Around line 9-25: Rename the pytest-discovered functions test_jsonresponse and
test_rawresponse to names that won't be auto-collected (e.g., bench_jsonresponse
and bench_rawresponse or similar) and move the two print(...) calls so they only
run when the file is executed directly by wrapping them in an if __name__ ==
"__main__": guard; update any internal references to the renamed functions
accordingly so the benchmarks still run when invoked directly but are ignored by
pytest collection.

---

Nitpick comments:
In `@backend/routers/utility.py`:
- Around line 51-52: Add response-contract tests that call the /stats and
/leaderboard endpoints and validate the actual JSON response shape/types against
the StatsResponse and LeaderboardResponse Pydantic models (e.g., by importing
StatsResponse and LeaderboardResponse and using .parse_obj or
model(**resp.json())). Specifically, write tests that exercise the get_stats
(router path "/stats") and the leaderboard handler (router path "/leaderboard")
which currently return fastapi.Response directly, fetch the endpoint JSON, and
assert model parsing succeeds and required fields/types match; include
negative/test-failure cases if keys are missing or types differ to lock the
contract and prevent regressions. Ensure tests run in CI and mock DB/fixtures as
needed so get_db-dependent handlers return stable predictable data.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7d6096d2-da6a-45fb-9379-a3d30d9c02a2

📥 Commits

Reviewing files that changed from the base of the PR and between cf5ed76 and 1e2e34f.

📒 Files selected for processing (2)
  • backend/routers/utility.py
  • backend/tests/benchmark_serialization.py

Comment thread backend/routers/utility.py
Comment thread backend/tests/benchmark_serialization.py Outdated
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown

🔍 Quality Reminder

Thanks for the updates! Please ensure:
- Your changes don't break existing functionality
- All tests still pass
- Code quality standards are maintained

*The maintainers will verify that the overall project flow remains intact.*

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.

2 participants