Skip to content

ShivamMathtech/Enterprise-Realtime-Chat-API

Repository files navigation

Enterprise Realtime Chat API

A production-oriented FastAPI backend for direct messaging, groups, channels and real-time collaboration. The project combines a full identity service with REST APIs, WebSockets, Redis fan-out, PostgreSQL persistence, moderation, notifications, audit logs and deployment assets. image

Major capabilities

Identity and security

  • Registration, email verification, login and password recovery
  • Argon2 password hashing
  • Short-lived JWT access tokens
  • Rotating refresh-token families with reuse detection
  • TOTP MFA and one-time recovery codes
  • Device/session listing and revocation
  • Account lockout and rate limiting
  • Scoped API keys
  • Multi-tenant organizations
  • Global and organization RBAC
  • Request IDs, security headers and audit logs

Messaging

  • Direct conversations with duplicate-thread prevention
  • Groups and broadcast-style channels
  • Owner, admin, moderator and member roles
  • Membership lifecycle, mute, remove, ban and leave
  • Invite links with expiry and usage limits
  • Cursor-style message history
  • Idempotent messages using client_message_id
  • Replies, edits, soft deletion and system messages
  • Emoji reactions
  • Delivered/read receipts and per-conversation read position
  • Pinned messages
  • Full-text-like message search using SQL filters
  • Message notifications and mention-aware notification levels

Realtime WebSocket events

  • Authenticated /ws connection
  • Automatic subscription to active conversations
  • message.send
  • typing.start and typing.stop
  • receipt.read
  • reaction.add and reaction.remove
  • presence.update
  • conversation.subscribe and conversation.unsubscribe
  • ping / pong
  • Multi-device delivery
  • Optional Redis pub/sub fan-out for multiple API replicas

Files and operations

  • Upload-ticket workflow
  • Local multipart upload implementation for development
  • Cloud-object-storage compatible completion endpoint
  • SHA-256 checksum validation
  • File metadata attached to messages
  • User blocking
  • Presence and custom status
  • Notification inbox and preferences
  • Message reports and moderator resolution
  • Platform chat dashboard
  • Durable event-outbox records and Redis outbox worker

Architecture

Web / Mobile / Desktop clients
        | REST + WebSocket
        v
FastAPI API replicas
  |-- Identity and RBAC
  |-- Conversation service
  |-- Message service
  |-- Presence and notifications
  |-- Moderation
  |-- Upload metadata
        |
        +--> PostgreSQL / SQLite
        +--> Redis pub/sub and rate limiting
        +--> Local storage or S3-compatible object storage
        +--> Event outbox worker -> downstream consumers

Quick start with Docker

cp .env.example .env
docker compose up --build

Seed demo users and a sample group:

docker compose exec api python -m scripts.seed

Open:

  • Swagger: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc
  • WebSocket: ws://localhost:8000/ws?token=<ACCESS_TOKEN>

Local Windows setup

py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
Copy-Item .env.example .env

For simple local development, change .env:

DATABASE_URL=sqlite:///./realtime_chat.db
REDIS_URL=
TRUSTED_HOSTS=localhost,127.0.0.1,testserver
UPLOAD_DIR=./uploads
PUBLIC_MEDIA_BASE_URL=http://127.0.0.1:8000/media

Run:

alembic upgrade head
python -m scripts.seed
uvicorn app.main:app --reload

Demo accounts

All demo accounts use Password@123.

Role Email
Super administrator admin@chat.example.com
Chat moderator moderator@chat.example.com
Auditor auditor@chat.example.com
User Alice alice@chat.example.com
User Bob bob@chat.example.com

Basic REST flow

  1. Log in at POST /api/v1/auth/login.
  2. Search users with GET /api/v1/chat/users?q=bob.
  3. Create a direct conversation using POST /api/v1/chat/conversations.
  4. Send a message with POST /api/v1/chat/conversations/{id}/messages.
  5. Read history using GET /api/v1/chat/conversations/{id}/messages.
  6. Mark a read position using POST /api/v1/chat/conversations/{id}/read.

Basic WebSocket flow

Connect:

ws://localhost:8000/ws?token=<JWT_ACCESS_TOKEN>

Send:

{
  "type": "message.send",
  "request_id": "client-request-101",
  "conversation_id": "CONVERSATION_UUID",
  "data": {
    "content": "Hello from WebSocket",
    "type": "text",
    "client_message_id": "device-42-message-1001"
  }
}

Receive:

{
  "type": "message.created",
  "request_id": "client-request-101",
  "conversation_id": "CONVERSATION_UUID",
  "data": {
    "id": "MESSAGE_UUID",
    "sequence": 18,
    "content": "Hello from WebSocket",
    "status": "sent"
  }
}

See docs/WEBSOCKET_PROTOCOL.md for the complete event reference.

Testing

pytest -q

The included tests cover:

  • JWT login
  • Authenticated WebSocket connections
  • Live message delivery between two users
  • Typing indicators
  • Read receipts
  • Reactions
  • Uploads and attachments
  • Group invitations
  • Pins and blocks
  • Moderation reports and mute actions
  • Admin analytics
  • Retry-safe idempotent message creation

Production notes

  • Replace development secrets before deployment.
  • Set EXPOSE_DEBUG_TOKENS=false in production.
  • Put the API behind TLS and a WebSocket-capable reverse proxy.
  • Use PostgreSQL, Redis and object storage rather than local files.
  • Add malware scanning before marking uploads ready.
  • Configure Redis persistence or a managed Redis service.
  • Run multiple API replicas behind a load balancer; Redis handles cross-replica events.
  • Process the event outbox with the included worker or connect it to Kafka/RabbitMQ.
  • Apply retention, legal-hold and privacy policies appropriate to your product.

Documentation

  • docs/API_ENDPOINTS.md
  • docs/WEBSOCKET_PROTOCOL.md
  • docs/ARCHITECTURE.md
  • docs/INTEGRATION_GUIDE.md
  • SECURITY.md
  • WINDOWS_SETUP.md

About

A production-oriented FastAPI backend for direct messaging, groups, channels and real-time collaboration. The project combines a full identity service with REST APIs, WebSockets, Redis fan-out, PostgreSQL persistence, moderation, notifications, audit logs and deployment assets.

Topics

Resources

License

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages