GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat: add metrics middleware · IDTS-LAB/python-codebase@c1759fe

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .env.example
  • README.md
  • docker-compose.yml
  • docker
    • otel-collector
      • config.yaml
    • prometheus
      • prometheus.yml
  • poetry.lock
  • pyproject.toml
  • src
    • core
      • bootstrap
        • middleware.py
      • config
        • setting.py
      • lifespan.py
      • middleware
        • metrics.py
      • routers
        • admin.py
      • telemetry
        • __init__.py
        • metrics.py
        • tracing.py
    • main.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.env.example‎

Copy file name to clipboardExpand all lines: .env.example
+7Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ ACCOUNT_LOCKOUT_DURATION_MINUTES=15
5454
# Logging output format for application logs.
5555
LOG_FORMAT=json
5656

57+
# OpenTelemetry distributed tracing configuration.
58+
# Set OTEL_ENABLED=true and point OTEL_EXPORTER_OTLP_ENDPOINT at a collector to enable tracing.
59+
OTEL_ENABLED=false
60+
OTEL_SERVICE_NAME=fastapi-modulith
61+
OTEL_EXPORTER_OTLP_ENDPOINT=
62+
OTEL_EXPORTER_OTLP_HEADERS=
63+
5764
# Email provider selection. Options: ses, sendgrid, smtp.
5865
EMAIL_PROVIDER=ses
5966

Collapse file

‎README.md‎

Copy file name to clipboardExpand all lines: README.md
+41-3Lines changed: 41 additions & 3 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ The API is currently versioned under `/api/v1`.
4848
- Redis-backed rate limiting.
4949
- Request ID, structured logging, audit logging, and security headers.
5050
- Request size limiting and idempotency support.
51-
- Health, liveness, and readiness endpoints.
51+
- Health, liveness, and readiness endpoints with structured RFC-style responses.
52+
- Prometheus metrics at `/metrics`.
53+
- OpenTelemetry distributed tracing (FastAPI, SQLAlchemy, Redis instrumentations).
5254
- API route grouping under `/api/v1`.
5355
- Async SQLAlchemy persistence.
5456
- Alembic database migrations.
@@ -70,6 +72,8 @@ The API is currently versioned under `/api/v1`.
7072
- Passlib for password hashing
7173
- Casbin for authorization policies
7274
- Redis and fastapi-limiter for rate limiting and token revocation
75+
- Prometheus for metrics collection
76+
- OpenTelemetry for distributed tracing
7377
- Pytest
7478
- Ruff
7579
- Poetry
@@ -94,6 +98,7 @@ The API is currently versioned under `/api/v1`.
9498
│ │ ├── schemas/ # Shared response schemas
9599
│ │ ├── security/ # JWT, password, revocation, audit helpers
96100
│ │ ├── seed/ # Database seeding orchestration
101+
│ │ ├── telemetry/ # Prometheus metrics and OpenTelemetry tracing setup
97102
│ │ └── lifespan.py # FastAPI lifespan hook
98103
│ ├── modules/
99104
│ │ ├── authorization/
@@ -123,7 +128,10 @@ The API is currently versioned under `/api/v1`.
123128
├── poetry.lock # Poetry lock file
124129
├── alembic.ini # Alembic configuration
125130
├── Dockerfile # Docker image definition
126-
└── docker-compose.yml # Local API, PostgreSQL, and Redis services
131+
├── docker-compose.yml # Local API, PostgreSQL, Redis, Prometheus, and OTEL collector services
132+
└── docker/
133+
├── prometheus/prometheus.yml # Prometheus scrape configuration
134+
└── otel-collector/config.yaml # OpenTelemetry collector configuration
127135
```
128136

129137
## Architecture
@@ -235,13 +243,15 @@ DELETE /api/v1/permissions/{permission_id}
235243
GET /health
236244
GET /live
237245
GET /ready
246+
GET /metrics
238247
```
239248

240249
Public routes:
241250

242251
- `/health`
243252
- `/live`
244253
- `/ready`
254+
- `/metrics`
245255
- `/docs`
246256
- `/redoc`
247257
- `/openapi.json`
@@ -307,6 +317,10 @@ ACCOUNT_LOCKOUT_MAX_ATTEMPTS=5
307317
ACCOUNT_LOCKOUT_WINDOW_MINUTES=15
308318
ACCOUNT_LOCKOUT_DURATION_MINUTES=15
309319
LOG_FORMAT=json
320+
OTEL_ENABLED=false
321+
OTEL_SERVICE_NAME=fastapi-modulith
322+
OTEL_EXPORTER_OTLP_ENDPOINT=
323+
OTEL_EXPORTER_OTLP_HEADERS=
310324
EMAIL_PROVIDER=ses
311325
AWS_REGION=us-east-1
312326
AWS_ACCESS_KEY_ID=
@@ -339,6 +353,10 @@ REDIS_URL=redis://127.0.0.1:6379/0
339353

340354
Production mode requires a non-default `SECRET_KEY`, non-empty database and Redis URLs, JWT issuer and audience values, positive token lifetimes, and explicit CORS origins.
341355

356+
OpenTelemetry tracing is off by default. To enable it, set `OTEL_ENABLED=true` and point `OTEL_EXPORTER_OTLP_ENDPOINT` at an OTLP HTTP collector endpoint.
357+
358+
Metrics from Prometheus are always available at `/metrics` and require no additional setup.
359+
342360
## Local Setup
343361

344362
The Makefile expects Poetry to create `.venv` inside the repository. Configure that once, then install dependencies:
@@ -389,6 +407,12 @@ Operational checks:
389407
```text
390408
http://localhost:8000/live
391409
http://localhost:8000/ready
410+
411+
Metrics:
412+
413+
```text
414+
http://localhost:8000/metrics
415+
```
392416
```
393417
394418
## Database and Migrations
@@ -536,14 +560,26 @@ make clean
536560

537561
Before starting Docker Compose, set non-empty `POSTGRES_PASSWORD`, `REDIS_PASSWORD`, and `SECRET_KEY` in `.env`. Compose intentionally fails fast when database or Redis passwords are missing.
538562

539-
Run API, PostgreSQL, and Redis services:
563+
Run all services (API, PostgreSQL, Redis, Prometheus, and OpenTelemetry Collector):
540564

541565
```bash
542566
make db-up
543567
```
544568

545569
The API container applies Alembic migrations before starting Uvicorn. Database seeding remains an explicit `make seed` step.
546570

571+
### Docker Services
572+
573+
| Service | Image | Port | Purpose |
574+
| --- | --- | --- | --- |
575+
| `api` | `fastapi-modulith:local` | 8000 | FastAPI application |
576+
| `db` | `postgres:17-alpine` | — | PostgreSQL database |
577+
| `redis` | `redis:8-alpine` | — | Redis for rate limiting and token revocation |
578+
| `prometheus` | `prom/prometheus:latest` | 9090 | Metrics scraping and storage |
579+
| `otel-collector` | `otel/opentelemetry-collector-contrib:latest` | 4318 | OTLP trace ingestion and export |
580+
581+
Tracing is automatically enabled in Docker Compose — the API sends spans to the `otel-collector` service via OTLP HTTP. Prometheus scrapes `/metrics` from the API every 15 seconds.
582+
547583
Stop services:
548584

549585
```bash
@@ -663,6 +699,8 @@ Legend: `Implemented` means code exists in the repository. `Partial` means code
663699
| OpenAPI Authentication | Required | Implemented | Swagger OAuth2 auth is configured, and docs/OpenAPI endpoints are disabled when `APP_ENV=production`. |
664700
| Health Check Endpoint | Required | Implemented | `/health` endpoint returns service health. |
665701
| Readiness/Liveness Endpoints | Required | Implemented | Adds `/live` and `/ready` operational endpoints. |
702+
| Prometheus Metrics | Recommended | Implemented | Request count, latency histogram, active requests at `/metrics`. |
703+
| Distributed Tracing (OpenTelemetry) | Recommended | Implemented | FastAPI, SQLAlchemy, and Redis instrumentations with OTLP HTTP export. Configurable via `OTEL_ENABLED`. |
666704
| Request Size Limiting | Required | Implemented | `LimitRequestSizeMiddleware` rejects oversized write requests. |
667705
| Idempotency Support (for applicable POST endpoints) | Optional but valuable | Implemented | Supports `Idempotency-Key` replay caching for POST responses. |
668706
| Database Migrations | Required | Implemented | Alembic is configured with migration commands in the README and Makefile. |
Collapse file

‎docker-compose.yml‎

Copy file name to clipboardExpand all lines: docker-compose.yml
+31Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ services:
1313
APP_ENV: production
1414
DATABASE_URL: postgresql+asyncpg://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}@db:5432/${POSTGRES_DB:-todo_db}
1515
REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}@redis:6379/0
16+
OTEL_ENABLED: "true"
17+
OTEL_SERVICE_NAME: "fastapi-modulith"
18+
OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4318/v1/traces"
1619
depends_on:
1720
db:
1821
condition: service_healthy
@@ -72,6 +75,34 @@ services:
7275
timeout: 5s
7376
retries: 5
7477

78+
prometheus:
79+
image: prom/prometheus:latest
80+
restart: unless-stopped
81+
ports:
82+
- "${PROMETHEUS_PORT:-9090}:9090"
83+
volumes:
84+
- ./docker/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
85+
- prometheus_data:/prometheus
86+
command:
87+
- "--config.file=/etc/prometheus/prometheus.yml"
88+
- "--storage.tsdb.path=/prometheus"
89+
- "--storage.tsdb.retention.time=30d"
90+
depends_on:
91+
api:
92+
condition: service_healthy
93+
94+
otel-collector:
95+
image: otel/opentelemetry-collector-contrib:latest
96+
restart: unless-stopped
97+
ports:
98+
- "${OTEL_COLLECTOR_PORT:-4318}:4318"
99+
volumes:
100+
- ./docker/otel-collector/config.yaml:/etc/otelcol-contrib/config.yaml:ro
101+
depends_on:
102+
api:
103+
condition: service_healthy
104+
75105
volumes:
76106
postgres_data:
77107
redis_data:
108+
prometheus_data:
Collapse file

‎docker/otel-collector/config.yaml‎

Copy file name to clipboard
+14Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
receivers:
2+
otlp:
3+
protocols:
4+
http:
5+
6+
exporters:
7+
debug:
8+
verbosity: detailed
9+
10+
service:
11+
pipelines:
12+
traces:
13+
receivers: [otlp]
14+
exporters: [debug]
Collapse file

‎docker/prometheus/prometheus.yml‎

Copy file name to clipboard
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
global:
2+
scrape_interval: 15s
3+
evaluation_interval: 15s
4+
5+
scrape_configs:
6+
- job_name: "fastapi-modulith"
7+
static_configs:
8+
- targets: ["api:8000"]
9+
metrics_path: /metrics

0 commit comments

Comments
0 (0)
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.