Cursor Rules TemplatesCursor Rules Template

Cursor Rules Template: IoT Water Monitoring with FastAPI & PostgreSQL

Cursor Rules Template for an IoT water monitoring stack using Python FastAPI and PostgreSQL/TimescaleDB, covering MQTT ingestion, anomaly detection, alerts, and conservation recommendations. Copyable .cursorrules block included.

.cursorrules templatecursor rules templatecursor-rules-templatesIoTwater monitoringFastAPIPostgreSQLTimescaleDBMQTTanomaly detectionalertsconservation recommendations

Target User

Developers building an IoT water usage monitoring system with Python FastAPI and PostgreSQL/TimescaleDB

Use Cases

  • Ingest MQTT data from water meters and sensors
  • Store and query time-series readings in PostgreSQL/TimescaleDB
  • Detect anomalies in flow, usage, and pressure
  • Trigger alerts for threshold breaches
  • Generate conservation recommendations based on usage patterns

Markdown Template

Cursor Rules Template: IoT Water Monitoring with FastAPI & PostgreSQL

# Cursor Rules for IoT Water Monitoring Stack (Python FastAPI + PostgreSQL/TimescaleDB + MQTT)
# Section: Framework Role & Context
framework: "python-fastapi-postgres-timescale-mqtt"
role_context:
  - "You are an AI assistant that outputs Cursor-compatible rules to build an IoT water usage monitor."
  - "Stack: Python 3.11+, FastAPI, PostgreSQL with TimescaleDB, MQTT ingestion, SQLAlchemy ORM, JWT auth, and pytest-based tests."
  - "Produce concrete code structure, data models, and safe AI interactions for production systems."

# Section: Code Style and Style Guides
style:
  - pep8
  - black
  - mypy
  - docstring: google

# Section: Architecture & Directory Rules
directories:
  - app/
  - app/api/
  - app/core/
  - app/db/
  - app/ingestion/
  - app/anomalies/
  - app/alerts/
  - app/recommendations/
  - tests/

# Section: Authentication & Security Rules
security:
  auth: jwt
  token_lifetime_minutes: 60
  secret_management: environment_variables
  audience_and_issuer_validation: true

# Section: Database and ORM patterns
database:
  orm: sqlalchemy
  url: "postgresql+psycopg2://USER:PASSWORD@HOST:PORT/DATABASE"
  timescale: true
  models:
    - WaterMeter
    - SensorReading
    - Anomaly
    - Alert
    - Recommendation
  migrations_dir: migrations/

# Section: Testing & Linting Workflows
testing:
  unit: true
  integration: true
  lint: true
  commands:
    - pytest tests/
    - flake8 .

# Section: Prohibited Actions and Anti-patterns for the AI
prohibited:
  - do_not_read_or_write_secret_values_in-code
  - do_not_connect_to_production_systems_without_review
  - avoid_shell=True constructions with unsanitized input
  - do_not skip migrations or bypass tests in CI
  - do_not perform arbitrary network calls in code samples

# Section: Architecture & Patterns (Guidance for implementation)
patterns:
  - ingestion: MQTT for sensor data
  - storage: time-series readings in PostgreSQL/TimescaleDB
  - processing: async task queue for anomaly scoring
  - alerting: condition-based alerts via alerts service
  - recommendations: generation of conservation guidance

Overview

Direct answer: This Cursor Rules Template configures Cursor AI to guide the implementation of an IoT water usage monitoring system built on Python FastAPI with PostgreSQL/TimescaleDB, MQTT ingestion, anomaly detection, alerts, and conservation recommendations. It enforces stack-specific structure, security, testing, and safe AI usage throughout the project.

The Cursor rules configuration template covers the end-to-end stack: ingest MQTT data from water meters and sensors, persist time-series readings in PostgreSQL/TimescaleDB, detect anomalies, raise alerts, and generate actionable conservation recommendations. It specifies architecture constraints, coding standards, and guardrails for robust, auditable development with Cursor AI.

When to Use These Cursor Rules

  • Starting a new IoT water monitoring project with a Python FastAPI backend and PostgreSQL/TimescaleDB storage.
  • Enforcing consistent project structure, naming, and data access patterns across ingestion, processing, and alerting services.
  • Ensuring secure authentication (JWT), auditable data access, and safe AI-assisted coding practices.
  • Documenting testing, linting, and deployment workflows to enable reliable CI/CD for production-grade systems.

Copyable .cursorrules Configuration

# Cursor Rules for IoT Water Monitoring Stack (Python FastAPI + PostgreSQL/TimescaleDB + MQTT)
# Section: Framework Role & Context
framework: "python-fastapi-postgres-timescale-mqtt"
role_context:
  - "You are an AI assistant that outputs Cursor-compatible rules to build an IoT water usage monitor."
  - "Stack: Python 3.11+, FastAPI, PostgreSQL with TimescaleDB, MQTT ingestion, SQLAlchemy ORM, JWT auth, and pytest-based tests."
  - "Produce concrete code structure, data models, and safe AI interactions for production systems."

# Section: Code Style and Style Guides
style:
  - pep8
  - black
  - mypy
  - docstring: google

# Section: Architecture & Directory Rules
directories:
  - app/
  - app/api/
  - app/core/
  - app/db/
  - app/ingestion/
  - app/anomalies/
  - app/alerts/
  - app/recommendations/
  - tests/

# Section: Authentication & Security Rules
security:
  auth: jwt
  token_lifetime_minutes: 60
  secret_management: environment_variables
  audience_and_issuer_validation: true

# Section: Database and ORM patterns
database:
  orm: sqlalchemy
  url: "postgresql+psycopg2://USER:PASSWORD@HOST:PORT/DATABASE"
  timescale: true
  models:
    - WaterMeter
    - SensorReading
    - Anomaly
    - Alert
    - Recommendation
  migrations_dir: migrations/

# Section: Testing & Linting Workflows
testing:
  unit: true
  integration: true
  lint: true
  commands:
    - pytest tests/
    - flake8 .

# Section: Prohibited Actions and Anti-patterns for the AI
prohibited:
  - do_not_read_or_write_secret_values_in-code
  - do_not_connect_to_production_systems_without_review
  - avoid_shell=True constructions with unsanitized input
  - do_not skip migrations or bypass tests in CI
  - do_not perform arbitrary network calls in code samples

# Section: Architecture & Patterns (Guidance for implementation)
patterns:
  - ingestion: MQTT for sensor data
  - storage: time-series readings in PostgreSQL/TimescaleDB
  - processing: async task queue for anomaly scoring
  - alerting: condition-based alerts via alerts service
  - recommendations: generation of conservation guidance

Recommended Project Structure

iot_water_monitor/
├── app/
│   ├── api/
│   │   └── v1/
│   │       ├── routers/
│   │       │   └── endpoints.py
│   │       └── dependencies.py
│   ├── core/
│   │   └── config.py
│   ├── db/
│   │   ├── models.py
│   │   ├── repositories.py
│   │   └── migrations/
│   ├── ingestion/
│   │   ├── mqtt_client.py
│   │   └── ingestion_service.py
│   ├── anomalies/
│   │   ├── detector.py
│   │   └── analysis.py
│   ├── alerts/
│   │   ├── notifier.py
│   │   └── delivery.py
│   └── recommendations/
│       ├── generator.py
│       └── rules.py
├── tests/
│   ├── unit/
│   └── integration/
├── docker/
│   └── Dockerfile
├── migrations/
└── docker-compose.yml

Core Engineering Principles

  • Single source of truth for sensor readings and derived metrics.
  • Explicit time-series schema with partitioning compatible with TimescaleDB.
  • Idempotent ingestion and replay-safe processing for MQTT data streams.
  • Secure by default: encrypted secrets, TLS, and JWT with short-lived tokens.
  • Observability through structured logs, metrics, and traceable events.
  • Testable architecture with clear separation between API, domain, and data layers.

Code Construction Rules

  • API endpoints under app/api/v1/routers must be versioned (v1).
  • DTOs and domain models must be defined with Pydantic for input validation.
  • Use SQLAlchemy ORM with explicit session scopes and context managers.
  • Ingestion should be async-safe; prefer bulk insert patterns with parameterized queries.
  • All secrets must be read from environment variables, not hard-coded.
  • Logging must include correlation IDs for traceability across services.
  • Do not embed real credentials in code samples; use placeholders.

Security and Production Rules

  • Use TLS for all external communications; verify certificates.
  • Rotate JWT keys and enforce audience/issuer checks.
  • Segregate MQTT brokers, API gateways, and DB access with network policies.
  • Enable secrets management and audit trails for data access.
  • Run container image scans and update dependencies regularly.

Testing Checklist

  • Unit tests for data models, validation, and small services.
  • Integration tests for ingestion, anomaly scoring, and alerting flows.
  • End-to-end tests simulating MQTT data, storage, and downstream recommendations.
  • Static analysis (lint) and type checks (mypy) in CI.
  • Performance checks on time-series queries and anomaly pipelines.

Common Mistakes to Avoid

  • Assuming MQTT delivery guarantees exactly-once in all brokers; implement idempotent processing.
  • Storing raw secrets in code or logs; prefer environment vars and secret managers.
  • Overloading API with heavy processing; use asynchronous tasks for anomaly computation.
  • Skipping migrations or skipping tests before deployment.
  • Hard-coding database URLs or credentials in sample code.

Related Cursor rules templates

Explore adjacent Cursor rules templates for similar stacks, workflows, and production constraints.

FAQ

What is the purpose of this Cursor Rules Template?

This Cursor Rules Template defines precise guidelines for building an IoT water monitoring stack with Cursor AI. It constrains architecture, security, testing, and data handling to deliver a reliable, auditable implementation using Python FastAPI and PostgreSQL/TimescaleDB.

Which stack is covered by this template?

The template targets Python FastAPI for the API layer, PostgreSQL with TimescaleDB for time-series data, MQTT for IoT data ingestion, SQLAlchemy for ORM, and JWT for authentication, with pytest-based testing and linting integrated into CI.

How do I customize the .cursorrules for my deployment?

Modify the database URL, environment-based secrets, and routing paths to reflect your environment. Extend the directory rules to match your service layout, and adjust anomaly thresholds and alert rules based on your domain knowledge and data.

How are anomalies and alerts integrated into the workflow?

Anomalies are computed in a dedicated service and persisted with references to readings. Alerts are triggered when thresholds are breached and routed to notification channels, while recommendations are generated from anomaly context and usage patterns to support conservation actions.

What tests and checks should run before deployment?

Run unit tests for data models and utilities, integration tests for ingestion and alerting, and end-to-end tests simulating real MQTT feeds. Ensure linting, type checks, and migrations are executed in CI before production deployment.