Portable Django Health Monitoring App

Building a Portable Django Health Monitoring App

By Mousam | technology-trends | 18 Apr 2025


 

A Guide to /health and /metrics Endpoints

 

In today’s fast-paced, distributed systems world, ensuring the reliability and performance of your applications is critical. Monitoring tools like Prometheus and health check endpoints have become indispensable for maintaining system health and catching issues before they escalate. In this article, I’ll walk you through my open-source project, django-health-metrics, a portable Django application that provides /health and /metrics endpoints for comprehensive system monitoring. I’ll also guide you on how to build a similar portable Django app, explain why these endpoints are essential, and share how you can use this package via PyPI.

Why /health and /metrics Endpoints Matter

Modern applications often rely on multiple services — databases, caches, message queues, and external APIs. A failure in any of these components can cascade, leading to downtime or degraded performance. The /health endpoint provides a snapshot of your application’s dependencies, such as Redis, PostgreSQL, or Celery, helping you quickly identify issues. The /metrics endpoint, compatible with Prometheus, exposes quantitative data like CPU usage, memory consumption, and request latencies, enabling you to visualize trends and set up alerts.

These endpoints are crucial for:

  • Proactive Monitoring: Detect issues before they impact users.
  • Scalability: Ensure your app performs well under load.
  • DevOps Integration: Seamlessly integrate with tools like Kubernetes, Prometheus, and Grafana.
  • Microservices: Verify the health of interconnected services in a distributed architecture.

By open-sourcing django-health-metrics and publishing it on PyPI, I aim to make it easy for developers to add robust monitoring to their Django projects.

Introducing django-health-metrics

django-health-metrics is a Django app that provides two key endpoints:

  • /health: Returns a JSON response with the status of configured services (e.g., Redis, database, memory, CPU, custom URLs).
  • /metrics: Exposes Prometheus-compatible metrics for integration with monitoring tools.

The app supports health checks for:

  • Redis, PostgreSQL, MongoDB, Elasticsearch, RabbitMQ, Celery, and Django cache.
  • System resources (memory, CPU, threads).
  • Custom URLs for monitoring external services.

It’s designed to be portable, lightweight, and easy to integrate into any Django project. The project is open-source on GitHub and available on PyPI for easy installation.

Installing django-health-metrics

To use the package, install it via pip:

pip install django-health-metrics

For specific features (e.g., Redis or Elasticsearch checks), install optional dependencies:

pip install django-health-metrics[redis,elasticsearch]

Add django_health_metrics to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
# ... other apps ...
'django_health_metrics',
]

Include the app’s URLs in your project’s urls.py:

from django.urls import path, include
urlpatterns = [
# ... other URLs ...
path('monitoring/', include('django_health_metrics.urls')),
]

Configure health checks in settings.py:

ENABLE_REDIS_CHECK = True
ENABLE_DB_CHECK = True
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
CUSTOM_URLS_TO_CHECK = ['http://example.com/health']

Run your Django server and access:

How It Works: A Look Under the Hood

Let’s dive into the key components of django-health-metrics to understand how it delivers robust monitoring.

Health Endpoint (/health)

The /health endpoint, implemented in views.py, uses a HealthChecker class to perform checks on various services. Each check (e.g., check_redis, check_database) returns a dictionary with a status (healthy, unhealthy, or not_connected) and additional details like response time.

Key features:

  • Parallel Execution: Uses ThreadPoolExecutor to run checks concurrently, reducing latency.
  • Configurability: Checks are enabled/disabled via settings (e.g., ENABLE_REDIS_CHECK).
  • Extensibility: Supports custom URL checks for external services.
  • Error Handling: Catches exceptions and logs errors to ensure the endpoint remains responsive.

Example response:

{
"redis": {"status": "healthy", "response_time_ms": 10},
"database": {"status": "healthy", "response_time_ms": 15},
"memory": {"total": 16777216, "available": 8388608, "percent": 50},
"custom_urls": {
"http://example.com/health": {"status": "healthy", "response_time_ms": 50}
}
}

Metrics Endpoint (/metrics)

The /metrics endpoint leverages the prometheus-client library to expose metrics in a format compatible with Prometheus. It includes:

  • Default Python runtime metrics (e.g., garbage collection stats).
  • Custom metrics like health_check_latency_seconds (if PROMETHEUS_HISOGRAM_ENABLED is True).

These metrics can be scraped by Prometheus and visualized in Grafana dashboards.

Portability and Modularity

The app is designed to be portable:

  • Minimal Dependencies: Core dependencies include Django, prometheus-client, and psutil.
  • Optional Dependencies: Install only what you need (e.g., redis for Redis checks).
  • Settings-Driven: All configurations are managed via Django’s settings.py, making it easy to adapt to different environments.
  • PyPI Distribution: Available via pip install, ensuring seamless integration.

Building Your Own Portable Django App

Inspired by django-health-metrics? Here’s a step-by-step guide to building a portable Django app with health and metrics endpoints.

Step 1: Project Structure

Create a clean project structure:

my_django_app/
├── my_django_app/
│ ├── __init__.py
│ ├── apps.py
│ ├── urls.py
│ ├── views.py
├── tests/
│ ├── __init__.py
│ ├── test_views.py
├── docs/
│ ├── installation.md
│ ├── usage.md
├── example/
│ ├── manage.py
│ ├── example_project/
│ ├── settings.py
├── README.md
├── setup.py
├── requirements.txt
├── MANIFEST.in
  • my_django_app/: Core app code.
  • tests/: Unit tests.
  • docs/: Documentation for installation and usage.
  • example/: A sample Django project to demonstrate usage.
  • setup.py: For PyPI distribution.
  • MANIFEST.in: Ensures non-code files (e.g., README) are included in the package.

Step 2: Implement Core Functionality

In views.py, create endpoints for health and metrics:

from django.http import JsonResponse, HttpResponse
from prometheus_client import generate_latest, REGISTRY
import psutil

def health_view(request):
memory = psutil.virtual_memory()
health_data = {
"memory": {
"status": "healthy",
"total": memory.total,
"available": memory.available,
"percent": memory.percent
}
}
return JsonResponse(health_data)
def metrics_view(request):
return HttpResponse(generate_latest(REGISTRY), content_type='text/plain')

In urls.py, map the endpoints:

from django.urls import path
from .views import health_view, metrics_view

urlpatterns = [
path('health/', health_view, name='health'),
path('metrics/', metrics_view, name='metrics'),
]

Step 3: Add Configuration

Allow users to enable/disable features via settings.py. Example:

ENABLE_MEMORY_CHECK = getattr(settings, 'ENABLE_MEMORY_CHECK', True)

Use this in views.py to conditionally include checks.

Step 4: Write Tests

In tests/test_views.py, add unit tests:

from django.test import TestCase, Client
from django.urls import reverse

class HealthViewTests(TestCase):
def setUp(self):
self.client = Client()
def test_health_view(self):
response = self.client.get(reverse('health'))
self.assertEqual(response.status_code, 200)
self.assertIn('memory', response.json())

Run tests with pytest.

Step 5: Package for PyPI

In setup.py, define the package metadata:

from setuptools import setup, find_packages

setup(
name='my-django-app',
version='1.0.0',
description='A Django app for health and metrics monitoring',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
author='Your Name',
author_email='[email protected]',
url='https://github.com/yourusername/my-django-app',
packages=find_packages(),
install_requires=['Django>=3.2', 'prometheus-client', 'psutil'],
classifiers=[
'Framework :: Django',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
],
python_requires='>=3.6',
)

In MANIFEST.in, include non-code files:

include README.md
include LICENSE
recursive-include docs *.md

Build and upload to PyPI:

python setup.py sdist bdist_wheel
twine upload dist/*

Step 6: Document and Open-Source

Write a README.md with installation and usage instructions. Include a docs/ folder with detailed guides. Host the project on GitHub and add a CONTRIBUTING.md file to encourage contributions.

Why Open-Sourcing Matters

By open-sourcing django-health-metrics, I’m inviting the community to contribute, report issues, and extend the project. Open-source projects thrive on collaboration, and sharing this app on PyPI makes it accessible to developers worldwide. I encourage you to open-source your projects too — it’s a great way to learn, give back, and build a portfolio.

Conclusion

django-health-metrics is a powerful tool for adding health and metrics monitoring to your Django applications. Its portable design, comprehensive health checks, and Prometheus integration make it a valuable addition to any project. By following the steps outlined above, you can build your own portable Django app and contribute to the open-source community.

Try it out today:

pip install django-health-metrics

Check out the project on GitHub and contribute to making it even better. Let’s build more reliable systems together!

Github : https://github.com/leodahal4/django-monitoring-tool

How do you rate this article?

5


Mousam
Mousam

I am a software developer and an cyber enthusiastic. I love to write articles related to technology.


technology-trends
technology-trends

Learn and stay updated with technology trends.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.