A production-ready web application for tracking daily habits, sleep patterns, and mood with intelligent visualizations and performance-optimized backend.
The application is deployed on Railway:
Note: This is a demo environment. Data may be reset periodically. For production use, deploy your own instance.
Rivio is a full-stack web application designed for individuals who want to monitor and improve their daily routines. Built with Django and modern web technologies, it offers:
- Multi-dimensional tracking: habits, sleep quality, and mood in one unified platform
- Flexible visualizations: day, week, and month views with color-coded progress indicators
- Production-grade security: JWT authentication, rate limiting, CSRF protection, and secure headers
- Performance-optimized: N+1 query elimination, batch operations, and connection pooling
- Timezone-aware architecture: consistent UTC storage with local timezone display
- RESTful API: comprehensive API for integrations and mobile apps
- Custom Habit Tracking - Create unlimited habits, track daily completion with visual feedback
- Sleep Quality Logging - Record sleep periods (start/end times), visualize patterns, detect overlaps automatically
- Mood Tracking - Daily mood logging (0-10 scale) with trend visualization
- Multi-Period Views - Day, week, and month views for each tracking category
- Dynamic UI - Color-coded blocks (green=complete, gray=incomplete), gradient backgrounds, dark mode support
- JWT Authentication - Secure API access with token rotation and blacklisting (15-min access tokens, 7-day refresh)
- Performance Optimized - 94%+ query reduction through select_related/prefetch_related and batch operations
- Timezone-Aware - All timestamps stored in UTC, converted to user's local timezone for display
- Security-First - Rate limiting (5 auth attempts/min), CSRF protection, HSTS, secure cookies
- High Test Coverage - 148 tests with 85% code coverage (models, views, serializers, services, security, API)
- Docker-Ready - Multi-stage Dockerfile, Docker Compose orchestration for dev and production
- RESTful API v1: All endpoints under
/api/v1/prefix for future versioning - Interactive Documentation:
- Swagger UI at
/api/docs/- Test endpoints in browser - ReDoc at
/api/redoc/- Beautiful API reference - OpenAPI schema at
/api/schema/- Machine-readable spec
- Swagger UI at
- JWT Authentication: Register, login, refresh, logout with token blacklisting
- Rate Limiting: 20 req/min (anonymous), 200 req/hour (authenticated)
- Comprehensive Validation: Clear error messages and field-level feedback
- Pagination: 100 items per page with next/previous links
- Framework: Django 5.2.11
- API: Django REST Framework with JWT authentication (djangorestframework-simplejwt 5.5.1)
- Database: PostgreSQL 15 (production), SQLite (development)
- Server: Gunicorn 23.0.0 (WSGI)
- Authentication: JWT (access + refresh tokens with rotation and blacklist)
- Rate Limiting: django-ratelimit 4.1.0 + DRF throttling
- CORS: django-cors-headers 4.3.1
- CSP: django-csp 3.8 (Content Security Policy)
- Environment: django-environ 0.11.2 (
.envfile support)
- Templates: Django templating engine with custom template tags
- CSS: Custom CSS with CSS variables for theming (dark mode support)
- JavaScript: Vanilla JS for dynamic interactions (habit toggling, theme switching)
- Static Files: WhiteNoise 6.6.0 (compression and caching)
- Containerization: Docker with multi-stage builds (optimized production images)
- Orchestration: Docker Compose (dev and prod configurations)
- CI/CD: GitHub Actions (tests, linting, security scanning with Trivy + Bandit, Docker build verification)
- Deployment: Railway (PaaS) with automatic deployments from GitHub
- Monitoring: Sentry SDK 2.8.0 (optional, error tracking)
- Backups: Automated PostgreSQL backup scripts with S3/R2 cloud upload support
- Debugging: django-debug-toolbar 4.2.0 (query profiling, SQL inspection)
- Testing: Django TestCase + DRF APIClient (148 tests, 85% coverage)
-
Service Layer Pattern
- Business logic extracted to
base/services/sleep_service.py - Handles complex operations: overlap detection, batch queries, date range filtering
- Benefits: Testable in isolation (98% coverage), reusable across views and API
- Example:
SleepService.detect_overlaps()used by both HTML views and API
- Business logic extracted to
-
Timezone-First Design
- Global setting:
TIME_ZONE='UTC',USE_TZ=True - Database: All timestamps stored in UTC (prevents timezone bugs)
- Display: Converted to user's local timezone via JavaScript
Dateobjects and Django utilities - Utilities: Centralized helpers in
base/utils.py:get_today()→timezone.localdate()(replacesdate.today())get_now()→timezone.now()(replacesdatetime.now())parse_date_param()→ safe date parsing from query params
- Global setting:
-
N+1 Query Elimination
- Problem: Original implementation had 50+ queries for week view
- Solution:
select_related('habit')for HabitLog FK traversal- Batch queries in SleepService (
date__infilters) - Prefetch logs in single query, build dict in memory
- Benchmarks:
- Habits week (7 habits, 7 days): 50 queries → 3 queries
- Sleep week: 30 queries → 1 query
- Mood month (30 days): 32 queries → 2 queries
-
JWT vs Session Auth
- API endpoints (
/api/*): JWT authentication only- Short-lived access tokens (15 minutes) for security
- Refresh tokens (7 days) for convenience
- Token rotation on refresh (generates new refresh token)
- Blacklist on logout (prevents token reuse)
- HTML views (
/): Session authentication (Django's built-in)- Secure cookies in production (
SESSION_COOKIE_SECURE=True) - CSRF protection for all POST forms
- Secure cookies in production (
- Why separate? API and web UI have different security requirements; JWT is stateless (no DB lookup per request), sessions are familiar for HTML forms
- API endpoints (
-
Defense in Depth (Validation)
- 3 layers of validation for data integrity:
- Database constraints:
CheckConstraint(end > start)for SleepLog - Model validation:
clean()methods check duration (30min - 24h) - Serializer validation: API-level checks with user-friendly error messages
- Database constraints:
- Why? Catches errors at multiple levels, prevents invalid data from edge cases
- 3 layers of validation for data integrity:
-
Authentication & Authorization
- JWT with token rotation and blacklisting (prevents stolen token reuse)
- Access tokens expire after 15 minutes (short window for compromise)
- Refresh tokens expire after 7 days (balance security and UX)
- Secure password hashing (Django's PBKDF2 with SHA256)
- Password validation (length, similarity, common passwords, numeric-only checks)
-
Rate Limiting
- Auth endpoints: 5 attempts per minute per IP (prevents brute force)
- Anonymous API: 20 requests per minute (prevents DoS)
- Authenticated API: 200 requests per hour (generous for normal use)
- Implementation: django-ratelimit + DRF throttling with cache backend
-
HTTPS & Secure Headers
SECURE_SSL_REDIRECT=Truein production (HTTP → HTTPS redirect)HSTSenabled (1 year, includeSubdomains, preload)SECURE_BROWSER_XSS_FILTER=True(XSS protection)X_FRAME_OPTIONS='DENY'(prevents clickjacking)SECURE_CONTENT_TYPE_NOSNIFF=True(MIME sniffing protection)- Secure cookies:
SESSION_COOKIE_SECURE=True,CSRF_COOKIE_SECURE=True
-
CSRF & CORS
- CSRF tokens required for all POST/PUT/DELETE forms
- CORS strict whitelist in production (
CORS_ALLOW_ALL_ORIGINS=False) CORS_ALLOWED_ORIGINSexplicitly configured via environment variable
-
Secrets Management
SECRET_KEYrequired via environment variable (fail-fast if missing)- No hardcoded secrets in codebase
.envfile support for local development (excluded from git)- Database credentials via
DATABASE_URLor separate env vars
-
Input Validation
- Django's built-in SQL injection protection (parameterized queries)
- XSS prevention (template auto-escaping)
- Serializer validation for API inputs (max length, range checks)
- Model-level validation (duration bounds, date constraints)