Skip to main content

Castana

PyPI version Python versions License

Health check library for Python that handles async and sync probes together.

Features

  • Runs async and sync probes in the same health check
  • Auto-detects database drivers (SQLAlchemy, asyncpg, psycopg, redis-py)
  • IETF-compliant JSON responses
  • No dependencies for core library
  • Thread pool isolation for health checks

Installation

pip install castana

Optional extras:

pip install "castana[http]"      # httpx for HTTP probes
pip install "castana[system]"    # psutil for memory checks
pip install "castana[redis]"     # redis-py
pip install "castana[postgres]"  # asyncpg/psycopg
pip install "castana[all]"       # all extras

Basic Usage

from castana import HealthCheck
from castana.probes import PostgresProbe, RedisProbe, DiskProbe

health = HealthCheck(name="my-service", version="1.0.0")

health.add_probe(PostgresProbe(conn=db_pool, name="db"))
health.add_probe(RedisProbe(client=redis_client, name="cache"))
health.add_probe(DiskProbe(warning_mb=500))

FastAPI

from fastapi import FastAPI
from castana.adapters.fastapi import create_health_router, create_health_lifespan

app = FastAPI(lifespan=create_health_lifespan(health))
app.include_router(create_health_router(health))

Flask

from flask import Flask
from castana.adapters.flask import FlaskHealth

app = Flask(__name__)
FlaskHealth(app, health_check=health)

Django

urls.py:

from django.urls import path
from castana.adapters.django import DjangoHealthView

urlpatterns = [
    path('health/', DjangoHealthView.as_view(health_check=health)),
]

apps.py:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        from castana.adapters.django import register_shutdown
        register_shutdown(health)

Response Format

{
  "status": "pass",
  "version": "1.0.0",
  "checks": {
    "db": [{
      "status": "pass",
      "componentType": "datastore",
      "observedValue": 1,
      "time": "2026-01-05T14:32:07+00:00",
      "metadata": {"latency_ms": 2.34}
    }]
  },
  "metrics": {
    "duration_ms": 2.5,
    "probe_count": 1
  }
}

HTTP status codes:

  • 200 - status is pass or warn
  • 503 - status is fail

Available Probes

Probe Description Dependencies
DiskProbe Disk space check None
MemoryProbe Memory usage check psutil
HttpProbe HTTP endpoint check httpx
RedisProbe Redis ping check redis-py
PostgresProbe PostgreSQL check asyncpg/psycopg/SQLAlchemy

Configuration

health = HealthCheck(
    name="my-api",
    version="1.0.0",
    global_timeout=30.0,
    max_workers=4,
    cache_ttl=5.0,
)

Options:

  • name: Service identifier
  • version: Service version string
  • global_timeout: Maximum time for entire health check suite
  • max_workers: Dedicated thread pool size
  • cache_ttl: Cache results for N seconds

Caching

Set cache_ttl to cache results and reduce probe execution frequency:

health = HealthCheck(cache_ttl=5.0)

Concurrent requests wait for the first result instead of all running probes.

Critical Probes

By default, probe failures cause global fail status. Mark non-critical probes:

health.add_probe(RedisProbe(client=redis, name="cache"))  # Critical
health.add_probe(DiskProbe(name="backup-disk", critical=False))  # Optional

Kubernetes Probes

Separate liveness and readiness checks:

health = HealthCheck()
health.add_probe(DiskProbe(name="disk"), groups=["liveness", "readiness"])
health.add_probe(PostgresProbe(conn=db_pool, name="db"), groups=["readiness"])

Enable separate endpoints:

# FastAPI
app.include_router(create_health_router(health, include_live_ready=True))

# Flask
FlaskHealth(app, health_check=health, include_live_ready=True)

# Django
urlpatterns = get_health_urlpatterns(health, include_live_ready=True)

Endpoints:

  • /health - All probes
  • /health/live - Liveness group only
  • /health/ready - Readiness group only

Retry Logic

health.add_probe(HttpProbe(
    name="external-api",
    url="https://api.example.com/health",
    retry_attempts=2,
    retry_delay=0.3,
))

Global defaults:

health = HealthCheck(
    default_retry_attempts=3,
    default_retry_delay=1.0,
)

Failures and timeouts trigger retries. WarnCondition does not retry.

Custom Probes

Decorator

from castana import HealthCheck, WarnCondition

health = HealthCheck()

@health.probe(name="config-check", timeout=1.0)
def check_config():
    if not config.IS_LOADED:
        raise ValueError("Config not loaded")
    return {"env": "production"}

@health.probe(name="db-ping")
async def check_database():
    return await db.ping()

Class-based

from castana import BaseProbe, WarnCondition

class QueueProbe(BaseProbe):
    def __init__(self, queue):
        super().__init__(name="queue-depth", timeout=5.0)
        self.queue = queue

    async def check(self):
        depth = await self.queue.get_depth()
        if depth > 1000:
            raise WarnCondition(f"Queue depth: {depth}")
        return depth

class DiskSpaceProbe(BaseProbe):
    def check(self):
        return "OK"

License

MIT

Metadata

Release files for castana 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for castana 1.0.0
File Size Uploaded Provenance Actions
castana-1.0.0.tar.gz 28.0 kB Without provenance Details for castana-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for castana 1.0.0
File Interpreter ABI Platform Actions
castana-1.0.0-py3-none-any.whl Python 3 none any Details for castana-1.0.0-py3-none-any.whl

Total release size: 52.7 kB

Release files / castana-1.0.0.tar.gz

Download URL castana-1.0.0.tar.gz
Size 28.0 kB
Tags Source
SHA-256 checksum
How to use checksums
b83781346370347097a721a4c5363a669dc315533486f02fc5a525093e16c35f
BLAKE2b-256 checksum
How to use checksums
3de876562e235bc3e6fca680c05b95fe8a1642a6fa7b430b5e11489eeaf40715
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.2

Release files / castana-1.0.0-py3-none-any.whl

Download URL castana-1.0.0-py3-none-any.whl
Size 24.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
79637ab145b7ede05eee2e3aa48d2e2c0816b22092dca011097c1a6dccb172d3
BLAKE2b-256 checksum
How to use checksums
baa03ff2370082224fe26ee160d9a3cd4e2aadb8df185e3fc94d3b1357a0ef61
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.2

Security for castana 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page