NuestroNido - Backend API
Backend API for NuestroNido, a family organization platform engineered for task management, shopping lists, shared notes, gamified progression (XP & levels), and push notifications.
System Architecture
The application is structured following Clean Layered Architecture principles, enforcing strict separation of concerns and dependency inversion.
graph TD
subgraph ClientLayer["Client Applications"]
WebClient["Frontend SPA (Next.js / React)"]
end
subgraph TransportLayer["API Transport Layer (src/api/)"]
Router["FastAPI Routers"]
Middleware["Middlewares (CSRF, CORS, Rate Limit, Sessions)"]
Deps["Dependency Injection (get_db, services)"]
end
subgraph BusinessLayer["Service Layer (src/services/)"]
AuthSvc["AuthService (Supabase Auth)"]
FamilySvc["FamilyService"]
MemberSvc["FamilyMemberService"]
TaskSvc["TaskService"]
ListSvc["ListService"]
NoteSvc["NoteService"]
UserSvc["UserService"]
PushSvc["PushNotificationService (WebPush)"]
end
subgraph DataLayer["Repository Layer (src/repositories/)"]
BaseRepo["BaseRepository (CRUD & Flush)"]
UserRepo["UserRepository"]
FamilyRepo["FamilyRepository"]
TaskRepo["TaskRepository"]
ListRepo["ListItemRepository"]
NoteRepo["NoteRepository"]
PushRepo["PushSubscriptionRepository"]
end
subgraph StorageLayer["Infrastructure & Storage"]
Postgres[(PostgreSQL + pgvector / UUID)]
Redis[(Redis Cache)]
SupabaseAuth["Supabase Auth / JWKS"]
end
WebClient -->|HTTP / Cookies| Middleware
Middleware --> Router
Router --> Deps
Deps --> BusinessLayer
BusinessLayer --> DataLayer
DataLayer -->|Async SQLAlchemy 2.0| Postgres
BusinessLayer -.->|Read/Write Cache| Redis
AuthSvc -.->|OAuth / Token Exchange| SupabaseAuth
Key Architectural Highlights
1. Robust Unit of Work & Transaction Boundary
- No Premature Commits: Repositories only issue queries and execute
await db.flush()within the active transaction to evaluate constraints and generate entity IDs. - Automatic Request Lifecycle Management: The
get_dbdependency encapsulates the entire HTTP request in a transactional boundary—automatically committing upon successful execution or performing a fullROLLBACKon unhandled exceptions.
sequenceDiagram
autonumber
actor Client as Frontend Client
participant FastAPI as FastAPI Route
participant DB as get_db (Session Scope)
participant Service as Business Service
participant Repo as Repository
participant PG as PostgreSQL
Client->>FastAPI: HTTP Request (e.g. Create Family)
FastAPI->>DB: Open AsyncSession
FastAPI->>Service: Execute Use Case
Service->>Repo: Create Family Record
Repo->>PG: INSERT ... + flush() (Generates family_id)
Service->>Repo: Create Admin Member Record
Repo->>PG: INSERT ... + flush() (Links family_id)
alt Success
Service-->>FastAPI: Result
FastAPI->>DB: Request Complete
DB->>PG: COMMIT
FastAPI-->>Client: 201 Created (JSON + Cookies)
else Any Exception
Service-->>FastAPI: Exception Raised
FastAPI->>DB: Error Captured
DB->>PG: ROLLBACK (Atomic Undo)
FastAPI-->>Client: Error Response (4xx / 5xx)
end
2. High-Performance Database Cascades
- Foreign key constraints utilize PostgreSQL's native
ON DELETE CASCADE. - Deleting a family or user instantly cleans up all dependent entities (
family_members,tasks,notes,list_items,family_invitations) atomically at the engine level without requiring multiple sequential round-trips from Python.
3. Enterprise-Grade Authentication & Security
- HttpOnly Cookies: Authentication tokens (
access_tokenandrefresh_token) are transported viaHttpOnly,Secure, andSameSitecookies to protect against XSS. - CSRF Mitigation: Cookie-authenticated requests require the custom
X-Requested-Withheader or CSRF tokens. - Idempotent User Provisioning: The authentication middleware synchronizes users using atomic
INSERT ... ON CONFLICT DO NOTHINGoperations, eliminating race conditions during initial concurrent logins. - JWKS Caching: Supabase JWT tokens are verified using cached public keys (RS256/ES256) with automatic key rotation and fallback to HS256.
4. Comprehensive Observability & Reliability
- Prometheus Metrics: Integrated with
prometheus-fastapi-instrumentatorexposing real-time HTTP duration, throughput, and status counters at/metrics. - Sentry APM: Configured for error tracking, distributed tracing, and database performance profiling.
- Background Scheduler: APScheduler runs autonomous maintenance jobs (task reminders, shopping reminders, invitation expiration cleanup) in dedicated session scopes.
Project Structure
nuestronido-back/
├── alembic/ # Database migrations
│ └── versions/ # Migration versions
├── src/
│ ├── api/ # FastAPI routers and HTTP dependencies
│ ├── core/ # Configuration, security, middleware, scheduler, exceptions
│ ├── db/ # SQLAlchemy engine, sessions, and Supabase client
│ ├── models/ # SQLAlchemy 2.0 ORM models
│ ├── repositories/ # Data access layer (BaseRepository & specialized repos)
│ ├── schemas/ # Pydantic validation schemas (DTOs)
│ ├── services/ # Business logic layer (Auth, Task, Family, List, etc.)
│ └── utils/ # Shared utilities (date formatting, helpers)
├── tests/ # Automated test suite (pytest-asyncio)
├── pyproject.toml # Dependencies & tooling configurations (ruff, pytest, mypy)
├── alembic.ini # Alembic configuration
└── README.md
Configuration & Development
Prerequisites
- Python: 3.11+ (Python 3.12 recommended)
- PostgreSQL: 15+
- Redis: 7+
- uv: Fast Python package installer and resolver
Environment Variables
Create a .env file in the root directory:
# ==================== Server ====================
APP_NAME=NuestroNido
ENVIRONMENT=development
SECRET_KEY=your-secure-32-character-secret-key-for-sessions
FRONTEND_URL=https://nuestronido.vercel.app/
# ==================== Database ====================
DATABASE_URL=postgresql+asyncpg://postgres:password@localhost:5432/postgres
# ==================== Supabase Auth ====================
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your-supabase-service-key
SUPABASE_JWT_SECRET=your-supabase-jwt-secret
# ==================== Redis Cache ====================
REDIS_URL=redis://localhost:6379
# ==================== Web Push (VAPID) ====================
VAPID_PUBLIC_KEY=your-vapid-public-key
VAPID_PRIVATE_KEY=your-vapid-private-key
VAPID_CLAIMS_EMAIL=mailto:admin@nuestronido.com
# ==================== Observability ====================
SENTRY_DSN=https://your-sentry-dsn
LOG_LEVEL=INFO
Running the Application
1. Install Dependencies
uv sync
2. Run Database Migrations
uv run alembic upgrade head
3. Start Development Server
uv run uvicorn src.main:app --reload --host 127.0.0.1 --port 8000
Interactive OpenAPI documentation will be accessible at http://localhost:8000/docs.
Testing & Code Quality
Running the Test Suite
uv run pytest
Static Type Checking (mypy)
uv run mypy src
Linting & Formatting (ruff)
uv run ruff check src
uv run ruff format src --check
License
Private repository. All rights reserved by NuestroNido.