Skip to content

feat(health): ping database and Redis, return 503 on failure #126

Open
Janeeshareddy wants to merge 4 commits into
rishabh0510rishabh:mainfrom
Janeeshareddy:feat/health-endpoint-db-redis-78
Open

feat(health): ping database and Redis, return 503 on failure #126
Janeeshareddy wants to merge 4 commits into
rishabh0510rishabh:mainfrom
Janeeshareddy:feat/health-endpoint-db-redis-78

Conversation

@Janeeshareddy
Copy link
Copy Markdown
Contributor

@Janeeshareddy Janeeshareddy commented May 22, 2026

Closes #78

Changes

  • backend/app/cache.py — new Redis client manager (singleton, optional if redis_url not set)
  • backend/app/main.py — updated /health to async-ping PostgreSQL and Redis with 2s timeout
  • backend/tests/unit/test_health.py — 5 tests covering all scenarios

Behavior

Scenario Status Code Response
Both healthy 200 "status": "healthy"
DB down 503 "status": "degraded"
Redis down 503 "status": "degraded"
Both down 503 "status": "degraded"
Redis not configured 200 "redis": "not_configured"

Summary by CodeRabbit

  • New Features

    • Enhanced health status monitoring: The health check now validates database and Redis availability, reporting service health as either healthy or degraded.
    • Added optional Redis support for caching, with graceful fallback if not configured.
  • Tests

    • Improved health check test coverage to verify correct status reporting when database or Redis services are unavailable.

Review Change Stack

@vercel
Copy link
Copy Markdown

vercel Bot commented May 22, 2026

@Janeeshareddy is attempting to deploy a commit to the rishabhmishra0510-5147's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 22, 2026

Warning

Rate limit exceeded

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

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 91532f61-663a-4d8e-bee3-17647b4c3643

📥 Commits

Reviewing files that changed from the base of the PR and between 6db4575 and d5b6323.

📒 Files selected for processing (3)
  • backend/app/cache.py
  • backend/app/main.py
  • backend/tests/unit/test_health.py
📝 Walkthrough

Walkthrough

This PR adds a Redis client singleton module and replaces the static /health endpoint with a service-dependent health check that verifies database and Redis connectivity, returning 200 when healthy and 503 when any critical service is unavailable, along with comprehensive test coverage for all health scenarios.

Changes

Health Endpoint Enhancement

Layer / File(s) Summary
Redis client singleton management
backend/app/cache.py
New module provides async Redis client singleton via get_redis_client() that lazily initializes on first call and returns None if redis_url is not configured, making Redis an optional dependency.
Enhanced health endpoint implementation
backend/app/main.py
Adds imports for asyncio, JSONResponse, and sqlalchemy.text; includes the compatibility router under /api/v1; replaces /health handler with a dependency-checking implementation that verifies database and Redis connectivity using short timeouts, returning JSONResponse with 200 and status "healthy" when all services are reachable, or 503 and status "degraded" when any dependency fails, plus per-service status entries and app version.
Health endpoint test coverage
backend/tests/unit/test_health.py
Replaces old tests with comprehensive mock-based suite using TestClient that validates all health scenarios: all services healthy (200, status "healthy"), database unavailable (503, status "degraded", database "unavailable"), Redis unavailable (503, status "degraded", redis "unavailable"), both unavailable (503, both "unavailable"), and Redis not configured (200, redis "not_configured").

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

type:feature

Suggested reviewers

  • rishabh0510rishabh

Poem

🐰 A health check that's truly alive,
Pings the database and Redis alike,
When services thrive, we reply "OK",
But when they stumble, we signal dismay—
Now load balancers can trust what we say! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly summarizes the main objective: enhancing the health endpoint to ping database and Redis dependencies and return 503 on failure.
Linked Issues check ✅ Passed The pull request implements all core objectives from issue #78: active dependency verification via async pings to PostgreSQL and Redis, dependency status in JSON response, and HTTP 503 return on failure.
Out of Scope Changes check ✅ Passed All changes are directly scoped to issue #78. New cache.py module supports optional Redis dependency management; main.py and test_health.py changes focus exclusively on health endpoint enhancement.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@Janeeshareddy
Copy link
Copy Markdown
Contributor Author

Hey @rishabh0510rishabh, fixed the main.py content issue. PR is ready for review!

Copy link
Copy Markdown
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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/app/cache.py`:
- Line 1: Remove the shell heredoc wrapper lines from backend/app/cache.py:
delete the leading "cat > backend/app/cache.py << 'EOF'" line and the trailing
"EOF" line so the file contains only valid Python code; then verify the module
(cache.py) imports cleanly and contains the intended Python definitions
(functions/classes) without the heredoc tokens.

In `@backend/tests/unit/test_health.py`:
- Line 35: The tests are patching the wrong symbol: AsyncSessionLocal is
imported inside the /health route handler, so patching
app.main.AsyncSessionLocal has no effect; update the tests to patch the symbol
where the handler imports it (patch "app.routes.health.AsyncSessionLocal" or the
module that defines the health endpoint) so the mock returned by
AsyncSessionLocal is used during the request, and adjust the existing patch(...)
calls in the test_health tests to reference AsyncSessionLocal in the health
route module.
- Line 1: Remove the accidental heredoc wrapper lines from the test file so it
contains only valid Python test code (delete the leading "cat > ... << 'EOF'"
and trailing "EOF"), and update the patch target used in the test from
patch("app.main.AsyncSessionLocal", ...) to
patch("app.database.AsyncSessionLocal", ...) while leaving
patch("app.cache.get_redis_client", ...) unchanged; ensure imports and any
patched fixtures reference AsyncSessionLocal and get_redis_client accordingly.
🪄 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: 99c95adb-8d3f-473f-87a0-70616f308240

📥 Commits

Reviewing files that changed from the base of the PR and between b7ddb2b and 6db4575.

📒 Files selected for processing (3)
  • backend/app/cache.py
  • backend/app/main.py
  • backend/tests/unit/test_health.py

Comment thread backend/app/cache.py Outdated
Comment thread backend/tests/unit/test_health.py Outdated
Comment thread backend/tests/unit/test_health.py Outdated
@rishabh0510rishabh
Copy link
Copy Markdown
Owner

hey @Janeeshareddy address all coderabbit review and fix test fails
if you need any help feel free to reach out

@rishabh0510rishabh
Copy link
Copy Markdown
Owner

some checks still failed, please review them and make updates accordingly

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.

[Enhancement] Enhance /health endpoint to verify database and Redis connectivity

2 participants