# samyakshrma/proctoring-backend architecture

> Architecture diagram of the GitHub repository samyakshrma/proctoring-backend, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-08-27). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/samyakshrma/proctoring-backend
- Repository: https://github.com/samyakshrma/proctoring-backend

## Overview

#### Purpose and Entry Points
This monorepo implements a distributed video-proctoring frame pipeline: authenticated clients upload frames to S3-compatible storage, workers infer results asynchronously, and PostgreSQL retains frame metadata/results. Runnable service entry points are:
- API: `services/api/app/main.py`
- ML worker: `services/ml_worker/app/main.py`
- Result worker: `services/result_worker/app/main.py`
- Cleanup worker: `services/cleanup_worker/app/main.py`

#### API Ingestion and Upload Authorization
FastAPI is the synchronous control-plane boundary. It validates JWT identity, applies Redis-backed per-user frame-rate limits, allocates the end-to-end `event_id`, and issues short-lived presigned blob-upload URLs. Clients upload bytes directly to storage; API completion verifies the blob then publishes the raw-frame event.
- Routes/auth: `services/api/app/api/frames.py`, `services/api/app/api/auth.py`
- Domain orchestration: `services/api/app/services/frame_service.py`, `services/api/app/services/upload_service.py`
- Rate limiting and Kafka publication: `services/api/app/services/rate_limit_service.py`, `services/api/app/services/kafka_service.py`

#### Shared Contracts and Infrastructure Adapters
`shared/` is the consistency boundary across independently deployed services. Typed frame, event, and result schemas carry `event_id` through the pipeline. Shared clients isolate Kafka, blob storage, SQLAlchemy sessions, and persistence models from service-specific orchestration.
- Event/data contracts: `shared/schemas/frame.py`, `shared/schemas/kafka_events.py`, `shared/schemas/results.py`
- External adapters: `shared/kafka/client.py`, `shared/storage/blob_client.py`
- Database foundation: `shared/database/models.py`, `shared/database/session.py`

#### Asynchronous ML Processing
The ML worker consumes `frames.raw` as a Kafka consumer group, retrieves the referenced blob, executes the replaceable model abstraction, and emits `frames.processed`. Missing blobs or irrecoverable processing errors go to the configured DLQ, allowing offsets to advance rather than blocking a partition. Horizontal scaling is partition/lag driven.
- Consumer lifecycle: `services/ml_worker/app/consumer.py`, `services/ml_worker/app/main.py`
- Processing and model boundary: `services/ml_worker/app/processor.py`, `services/ml_worker/app/model.py`
- KEDA scaling: `infrastructure/keda/ml-worker-scaler.yaml`

#### Result Persistence and Idempotency
The result worker consumes processed events and writes/upserts frame records in PostgreSQL. `event_id` is the cross-service idempotency key: duplicate Kafka delivery or recovery after a crash overwrites the existing result instead of creating conflicting rows. Database schema evolution is managed with Alembic.
- Consumer and persistence orchestration: `services/result_worker/app/consumer.py`, `services/result_worker/app/repository.py`
- Initial frames schema: `migrations/versions/20240520_0001_create_frames.py`
- Migration runtime: `migrations/env.py`

#### Retention and Lifecycle Management
The cleanup worker periodically finds benign frames beyond retention, deletes associated blob objects, and nulls their blob reference while preserving metadata and inference records. Operations tolerate absent objects and are restart-safe.
- Cleanup loop and policy: `services/cleanup_worker/app/cleanup.py`, `services/cleanup_worker/app/config.py`
- Shared persistence/blob boundaries: `shared/database/repositories.py`, `shared/storage/blob_client.py`

#### Runtime, Deployment, and Observability
Services run on Python 3.12 in separate containers, with FastAPI, Kafka, PostgreSQL, Redis, and S3/MinIO as material dependencies. Docker Compose provides the local full stack; Kubernetes deploys API and each worker separately. The API exposes health/readiness and Prometheus metrics; shared JSON logging supports correlation by event/user.
- Local composition: `infrastructure/docker/docker-compose.yml`
- Kubernetes workloads: `infrastructure/kubernetes/api/deployment.yaml`, `infrastructure/kubernetes/ml-worker/deployment.yaml`, `infrastructure/kubernetes/result-worker/deployment.yaml`
- API health/metrics: `services/api/app/api/health.py`, `services/api/app/metrics.py`

Main entry points: [`services/ml_worker/app/processor.py`](https://github.com/samyakshrma/proctoring-backend/blob/main/services/ml_worker/app/processor.py) (ML consumer and processor), [`services/api/app/api/frames.py`](https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/api/frames.py) (API routes and auth), [`services/api/app/services/frame_service.py`](https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/services/frame_service.py) (Frame upload orchestration), [`shared/storage/blob_client.py`](https://github.com/samyakshrma/proctoring-backend/blob/main/shared/storage/blob_client.py) (Blob storage adapter)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["API control plane"]
  node_api_routes["API routes and auth<br/>FastAPI boundary<br/>[frames.py]"]
  node_api_orchestration["Frame upload orchestration<br/>domain service<br/>[frame_service.py]"]
  node_rate_limit["Per-user rate limiter<br/>Redis service"]
  node_api_observability["Health and metrics<br/>Prometheus endpoint<br/>[health.py]"]
end

subgraph group_pipeline["Async pipeline"]
  node_ml_worker["ML consumer and processor<br/>worker service<br/>[processor.py]"]
  node_model["Model abstraction<br/>inference boundary<br/>[model.py]"]
  node_result_worker["Result persistence worker<br/>worker service<br/>[repository.py]"]
  node_cleanup_worker["Retention cleanup worker<br/>periodic worker<br/>[cleanup.py]"]
end

subgraph group_shared["Shared boundaries"]
  node_contracts["Frame event contracts<br/>shared schemas<br/>[kafka_events.py]"]
  node_blob_adapter["Blob storage adapter<br/>shared client<br/>[blob_client.py]"]
  node_db_foundation["Database models and sessions<br/>shared persistence<br/>[models.py]"]
  node_migrations["Alembic migrations<br/>schema evolution<br/>[env.py]"]
end

subgraph group_infra["Infrastructure"]
  node_kafka_raw["frames.raw<br/>Kafka topic"]
  node_kafka_processed["frames.processed<br/>Kafka topic"]
  node_kafka_dlq["Processing DLQ<br/>Kafka topic"]
  node_blob_storage[("S3 / MinIO blobs<br/>object storage")]
  node_redis[("Redis<br/>rate-limit store")]
  node_postgres[("PostgreSQL frames<br/>result database")]
  node_ml_scaler{{"KEDA ML scaler<br/>autoscaling policy"}}
  node_deployment["Container deployments<br/>runtime deployment<br/>[docker-compose.yml]"]
end

node_client(("Authenticated client"))

node_client -->|"authenticated requests"| node_api_routes
node_api_routes -->|"frame commands"| node_api_orchestration
node_api_routes -->|"check quota"| node_rate_limit
node_rate_limit -->|"counter state"| node_redis
node_api_orchestration -->|"create event"| node_contracts
node_api_orchestration -->|"presign and verify"| node_blob_adapter
node_client -->|"direct presigned upload"| node_blob_storage
node_blob_adapter -->|"blob operations"| node_blob_storage
node_api_orchestration -->|"publish after verification"| node_kafka_raw
node_kafka_raw -->|"consume"| node_ml_worker
node_ml_worker -->|"retrieve frame"| node_blob_adapter
node_ml_worker -->|"infer"| node_model
node_ml_worker -->|"publish result"| node_kafka_processed
node_ml_worker -.->|"missing blob / fatal error"| node_kafka_dlq
node_kafka_processed -->|"consume"| node_result_worker
node_result_worker -->|"idempotent upsert"| node_db_foundation
node_db_foundation -->|"sessions and models"| node_postgres
node_migrations -->|"evolve schema"| node_postgres
node_cleanup_worker -->|"find retained frames"| node_postgres
node_cleanup_worker -->|"delete expired blobs"| node_blob_adapter
node_ml_scaler -.->|"scale on lag"| node_ml_worker
node_deployment -.->|"deploy"| node_api_routes
node_deployment -.->|"deploy"| node_ml_worker
node_deployment -.->|"deploy"| node_result_worker
node_api_routes -->|"health and metrics"| node_api_observability

click node_api_routes "https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/api/frames.py"
click node_api_orchestration "https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/services/frame_service.py"
click node_rate_limit "https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/services/rate_limit_service.py"
click node_api_observability "https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/api/health.py"
click node_contracts "https://github.com/samyakshrma/proctoring-backend/blob/main/shared/schemas/kafka_events.py"
click node_blob_adapter "https://github.com/samyakshrma/proctoring-backend/blob/main/shared/storage/blob_client.py"
click node_db_foundation "https://github.com/samyakshrma/proctoring-backend/blob/main/shared/database/models.py"
click node_ml_worker "https://github.com/samyakshrma/proctoring-backend/blob/main/services/ml_worker/app/processor.py"
click node_model "https://github.com/samyakshrma/proctoring-backend/blob/main/services/ml_worker/app/model.py"
click node_result_worker "https://github.com/samyakshrma/proctoring-backend/blob/main/services/result_worker/app/repository.py"
click node_migrations "https://github.com/samyakshrma/proctoring-backend/blob/main/migrations/env.py"
click node_cleanup_worker "https://github.com/samyakshrma/proctoring-backend/blob/main/services/cleanup_worker/app/cleanup.py"
click node_ml_scaler "https://github.com/samyakshrma/proctoring-backend/blob/main/infrastructure/keda/ml-worker-scaler.yaml"
click node_deployment "https://github.com/samyakshrma/proctoring-backend/blob/main/infrastructure/docker/docker-compose.yml"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_api_routes,node_api_orchestration,node_rate_limit,node_api_observability toneBlue
class node_ml_worker,node_model,node_result_worker,node_cleanup_worker toneAmber
class node_contracts,node_blob_adapter,node_db_foundation,node_migrations toneMint
class node_kafka_raw,node_kafka_processed,node_kafka_dlq,node_blob_storage,node_redis,node_postgres,node_ml_scaler,node_deployment toneRose
class node_client toneNeutral
```

## Components

### API control plane

- [API routes and auth](https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/api/frames.py): FastAPI boundary · `services/api/app/api/frames.py`
- [Frame upload orchestration](https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/services/frame_service.py): domain service · Allocates event IDs, verifies uploads, and publishes raw-frame events. · `services/api/app/services/frame_service.py`
- [Per-user rate limiter](https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/services/rate_limit_service.py): Redis service · `services/api/app/services/rate_limit_service.py`
- [Health and metrics](https://github.com/samyakshrma/proctoring-backend/blob/main/services/api/app/api/health.py): Prometheus endpoint · `services/api/app/api/health.py`

### Async pipeline

- [ML consumer and processor](https://github.com/samyakshrma/proctoring-backend/blob/main/services/ml_worker/app/processor.py): worker service · Fetches frame blobs, invokes the replaceable model, and emits processed events. · `services/ml_worker/app/processor.py`
- [Model abstraction](https://github.com/samyakshrma/proctoring-backend/blob/main/services/ml_worker/app/model.py): inference boundary · `services/ml_worker/app/model.py`
- [Result persistence worker](https://github.com/samyakshrma/proctoring-backend/blob/main/services/result_worker/app/repository.py): worker service · Upserts results by event_id for idempotent Kafka recovery. · `services/result_worker/app/repository.py`
- [Retention cleanup worker](https://github.com/samyakshrma/proctoring-backend/blob/main/services/cleanup_worker/app/cleanup.py): periodic worker · Deletes expired benign blobs and clears their references restart-safely. · `services/cleanup_worker/app/cleanup.py`

### Shared boundaries

- [Frame event contracts](https://github.com/samyakshrma/proctoring-backend/blob/main/shared/schemas/kafka_events.py): shared schemas · Carries event_id across service boundaries. · `shared/schemas/kafka_events.py`
- [Blob storage adapter](https://github.com/samyakshrma/proctoring-backend/blob/main/shared/storage/blob_client.py): shared client · `shared/storage/blob_client.py`
- [Database models and sessions](https://github.com/samyakshrma/proctoring-backend/blob/main/shared/database/models.py): shared persistence · `shared/database/models.py`
- [Alembic migrations](https://github.com/samyakshrma/proctoring-backend/blob/main/migrations/env.py): schema evolution · `migrations/env.py`

### Infrastructure

- **frames.raw**: Kafka topic
- **frames.processed**: Kafka topic
- **Processing DLQ**: Kafka topic · Irrecoverable ML failures are diverted without blocking partitions.
- **S3 / MinIO blobs**: object storage
- **Redis**: rate-limit store
- **PostgreSQL frames**: result database · Preserves frame metadata and inference records.
- [KEDA ML scaler](https://github.com/samyakshrma/proctoring-backend/blob/main/infrastructure/keda/ml-worker-scaler.yaml): autoscaling policy · Scales ML workers from Kafka partition lag. · `infrastructure/keda/ml-worker-scaler.yaml`
- [Container deployments](https://github.com/samyakshrma/proctoring-backend/blob/main/infrastructure/docker/docker-compose.yml): runtime deployment · Compose supplies local stack; Kubernetes deploys API and workers separately. · `infrastructure/docker/docker-compose.yml`

### Other components

- **Authenticated client**: client

## Connections

- Authenticated client → API routes and auth: authenticated requests
- API routes and auth → Frame upload orchestration: frame commands
- API routes and auth → Per-user rate limiter: check quota
- Per-user rate limiter → Redis: counter state
- Frame upload orchestration → Frame event contracts: create event
- Frame upload orchestration → Blob storage adapter: presign and verify
- Authenticated client → S3 / MinIO blobs: direct presigned upload
- Blob storage adapter → S3 / MinIO blobs: blob operations
- Frame upload orchestration → frames.raw: publish after verification
- frames.raw → ML consumer and processor: consume
- ML consumer and processor → Blob storage adapter: retrieve frame
- ML consumer and processor → Model abstraction: infer
- ML consumer and processor → frames.processed: publish result
- ML consumer and processor → Processing DLQ: missing blob / fatal error
- frames.processed → Result persistence worker: consume
- Result persistence worker → Database models and sessions: idempotent upsert
- Database models and sessions → PostgreSQL frames: sessions and models
- Alembic migrations → PostgreSQL frames: evolve schema
- Retention cleanup worker → PostgreSQL frames: find retained frames
- Retention cleanup worker → Blob storage adapter: delete expired blobs
- KEDA ML scaler → ML consumer and processor: scale on lag
- Container deployments → API routes and auth: deploy
- Container deployments → ML consumer and processor: deploy
- Container deployments → Result persistence worker: deploy
- API routes and auth → Health and metrics: health and metrics
