Skip to content

Repository files navigation

backEndChat

A high-performance Node.js/Express backend server for a real-time, location-aware chat application. It features user authentication, geo-based nearby user discovery, persistent messaging, real-time WebSocket communication via Socket.IO, media uploads to AWS S3 with on-the-fly FFmpeg video compression/transcoding, and push notifications through the Expo push service.


Features

  • User Registration & Authentication — Register with location data; log in with 30-minute access tokens and 7-day refresh tokens.
  • Real-Time Messaging — Bidirectional, instant messaging over WebSocket (Socket.IO) with sub-millisecond delivery, delivered to both sender and receiver rooms.
  • REST Messaging API — HTTP endpoints to send and retrieve conversation history.
  • Media & Video Processing — Video upload pipeline with automatic FFmpeg H.264/AAC transcoding, 720:1280 aspect ratio scaling/cropping, and streaming upload to AWS S3.
  • Nearby User Discovery — Find other users within a configurable radius (km) using the Haversine formula with offset-based pagination.
  • Location Management — Store and update each user's latitude/longitude coordinates.
  • Expo Push Notifications — Sends a push notification to a recipient's device whenever a new message is received.
  • Password Security — Passwords hashed with bcrypt (cost factor 10).
  • CORS Enabled — Configurable origins via CORS_ORIGINS.

Tech Stack

Layer Technology
Runtime Node.js (v18+)
Framework Express 4
Real-Time WebSockets Socket.IO 4
Database PostgreSQL (via Prisma ORM 6)
Cloud Storage AWS S3 (@aws-sdk/client-s3, @aws-sdk/lib-storage)
Media Transcoding FFmpeg (fluent-ffmpeg)
Auth & Security JSON Web Tokens (jsonwebtoken), bcrypt
Push Notifications Expo Server SDK
Cache & Message Broker Redis
Testing & Benchmarks Jest, Supertest, Autocannon, Socket.io-Client

Data Models

User

Field Type Notes
id Int Auto-increment primary key
username String Unique, max 255 chars
email String Unique, max 255 chars
password String bcrypt hash, max 255 chars
age Int? Optional age (18–120)
gender String? Gender identifier
sexuality String? Sexuality preference
description String? Profile bio / description
videoUrl String? AWS S3 URL for user video
latitude Float? Optional GPS latitude
longitude Float? Optional GPS longitude
expoPushToken String? Expo device push token
tokenVersion Int Token rotation version counter
createdAt DateTime Auto-set on creation

Message

Field Type Notes
id Int Auto-increment primary key
content String Message body
senderId Int Foreign key → User
receiverId Int Foreign key → User
createdAt DateTime Auto-set on creation

API Reference

Authentication

Method Endpoint Description
POST /register Register a new user
POST /login Log in and receive JWT pair (access + refresh)
POST /refresh Rotate and issue new access & refresh tokens

POST /register

Body: { username, email, password, age?, latitude?, longitude? }
Response: { user, accessToken, refreshToken, userId }

POST /login

Body: { email, password }
Response: { user, accessToken, refreshToken, userId }

POST /refresh

Body: { refreshToken }
Response: { accessToken, refreshToken }


Users & Profiles

Method Endpoint Description
GET /nearby-users Get nearby users within radius (km) with pagination
GET /users/connections Get user friendships / connections
GET /users/requests Get incoming friend requests
POST /send-friend-request Send a friend request
POST /accept-friend-request Accept a pending friend request
PUT /users/video Upload and transcode user profile video to S3
PUT /users/location Update user GPS coordinates
PUT /users/profile Update age, gender, or sexuality
PUT /update-description Update user bio / description
PUT /update-push-token Register Expo push token
DELETE /users Delete user account and associated data

PUT /users/video

Headers: Authorization: Bearer <accessToken>, Content-Type: multipart/form-data
Body: video (file up to 25MB)
Process: Automatically transcodes video to 720x1280 H.264/AAC with faststart, uploads to AWS S3, and links to user profile.


Messages

Method Endpoint Description
POST /messages Send message (saves to DB and emits over Socket.IO)
GET /messages Retrieve conversation history between users

WebSocket Events (Socket.IO)

Connect with Socket.IO client using JWT authentication in the handshake:

const socket = io("http://localhost:4000", {
  auth: { token: "<accessToken>" }
});
Event (client → server) Payload Description
sendMessage { receiverId, content } Send a message; triggers real-time delivery and push notification
Event (server → client) Payload Description
receiveMessage Message object Delivered in real-time to both sender and receiver rooms

⚡ Performance Benchmarks & Metrics

Comprehensive performance tests were conducted across all architectural layers of the backend:

1. Executive Summary

Subsystem Metric Result Rating
Express.js HTTP Auth GET Throughput 3,970.6 req/s (Peak: 4,150 req/s) 🟢 Excellent
Express.js Latency Fast-path Auth (P95) 18.0 ms (Avg: 12.14 ms) 🟢 Low Latency
Socket.IO Real-Time Message Throughput 3,167.6 msg/s 🟢 High Throughput
Socket.IO Latency Round-trip delivery 0.31 ms avg (P99: 1.03 ms) 🟢 Sub-millisecond
FFmpeg Transcoding Video Encoding Speed 5.77x Realtime (15s video in 2.6s) 🟢 Fast
FFmpeg Compression Size Reduction 34.30% Size Reduction 🟢 Optimized
AWS S3 Pipeline 25 MB Multipart Upload 93.13 ms (268.45 MB/s) 🟢 High Bandwidth
Event Loop Utilization Active Load Ratio 27.05% (72.95% idle headroom) 🟢 Healthy

2. Express.js HTTP Load Testing (Autocannon)

Endpoint Concurrency Req / Sec (Avg) Req / Sec (Peak) Avg Latency P50 P90 P95 P99 Throughput
GET /users/requests (Auth Guard) 50 3,970.6 4,150 12.14 ms 12 ms 13 ms 18 ms 22 ms 1.75 MB/s
POST /register (400 Rejection) 50 6,570.8 7,100 7.11 ms 7 ms 8 ms 11 ms 12 ms 1.95 MB/s
POST /refresh (Token Rotation) 20 2,317.0 2,380 8.17 ms 8 ms 10 ms 12 ms 15 ms 1.46 MB/s
GET /nearby-users (Haversine Geo) 30 3,403.0 3,540 8.33 ms 8 ms 10 ms 11 ms 13 ms 4.77 MB/s
POST /login (Bcrypt Cost 10) 10 66.4 68 148.52 ms 140 ms 173 ms 179 ms 188 ms 0.04 MB/s

Error rate across all tests: 0.00% (0 errors, 0 timeouts).


3. Socket.IO Real-Time Messaging Metrics

  • Connection Rate: 265.44 handshakes/sec
  • Connection Latency: Avg 3.76 ms (P50: 2.31 ms, P95: 3.69 ms)
  • Message Throughput: 3,167.64 messages/sec
  • Round-Trip Delivery Latency (sendMessage $\rightarrow$ server $\rightarrow$ receiveMessage room delivery):
    • Min: 0.21 ms
    • Average: 0.31 ms
    • P50 (Median): 0.28 ms
    • P95: 0.46 ms
    • P99: 1.03 ms
  • Disconnect Handling: 0.09 ms per client.

4. FFmpeg Video Transcoding Pipeline

Measured with the active transcoding configuration (-c:v libx264 -preset veryfast -crf 23 -vf scale=720:1280 ...):

Video Clip Input (1080p) Output (720x1280) Compression Disk Write Transcode Time Total Time Speed Factor
3 Seconds 105.7 KB 72.4 KB 31.46% 1.82 ms 1,076.82 ms 1,081.08 ms 2.79x realtime
7 Seconds 231.4 KB 161.2 KB 30.32% 0.81 ms 1,365.85 ms 1,368.14 ms 5.13x realtime
15 Seconds 493.5 KB 324.2 KB 34.30% 1.81 ms 2,598.93 ms 2,602.80 ms 5.77x realtime

5. AWS S3 Multipart Upload Pipeline

File Size Stream Time Stream Throughput In-Memory Buffer Time Buffer Throughput
1 MB 37.07 ms 26.98 MB/s 27.00 ms 37.04 MB/s
5 MB 39.11 ms 127.84 MB/s 15.18 ms 329.37 MB/s
15 MB 77.61 ms 193.28 MB/s 61.78 ms 242.78 MB/s
25 MB (Limit) 93.13 ms 268.45 MB/s 92.27 ms 270.94 MB/s
  • Concurrent Upload Capacity: 5 simultaneous 5 MB uploads ($25\text{ MB}$ total) completed in 14.00 ms (1,785.57 MB/s aggregate).

6. Cryptography & Runtime Profile

  • Bcrypt (Cost 10): 57.80 ms/hash, 57.70 ms/compare.
  • JWT Access Sign: 0.0429 ms/op (23,295 ops/s).
  • JWT Access Verify: 0.0479 ms/op (20,885 ops/s).
  • Event Loop Lag: P50 = 27.67 ms, P99 = 34.57 ms under heavy load.
  • Memory Consumption: Base RSS = 90.15 MB, V8 Heap Used = 29.03 MB.

🛠️ Performance Optimization Recommendations

  1. Video Storage Stream Ingestion: Transition from multer.memoryStorage() to multer.diskStorage() to prevent allocating 25 MB buffers directly in the V8 heap during video uploads.
  2. Threadpool Scaling: Configure UV_THREADPOOL_SIZE=16 in production to prevent CPU-bound bcrypt password verifications from saturating default worker threads.
  3. Spatial Indexing: Add a PostgreSQL B-Tree bounding box filter or PostGIS GiST index on (latitude, longitude) for /nearby-users to avoid table scans on high user counts.
  4. Push Notification Offloading: Delegate Expo push notifications to a background worker queue (e.g. BullMQ / Redis) so external network calls do not block WebSocket event acknowledgments.

Environment Variables

Create a .env file in the project root:

# PostgreSQL connection strings
DATABASE_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"
DIRECT_URL="postgresql://USER:PASSWORD@HOST:PORT/DATABASE"

# JWT & Security
JWT_SECRET="your-strong-secret-here"
PORT=4000
CORS_ORIGINS="http://localhost:8081"

# AWS S3 Configuration
AWS_REGION="us-east-1"
AWS_ACCESS_KEY="your-aws-access-key"
AWS_SECRET_KEY="your-aws-secret-key"
S3_BUCKET_NAME="your-s3-bucket-name"

# Redis
REDIS_URL="redis://localhost:6379"

Getting Started

Prerequisites

  • Node.js v18 or later
  • npm v9 or later
  • FFmpeg installed and accessible on system PATH
  • A running PostgreSQL instance

Installation & Benchmarking

# Clone the repository
git clone git@github.com:UzumakiODZ/backEndChat.git
cd backEndChat

# Install dependencies
npm install

# Run database migrations
npx prisma migrate deploy

# Run performance benchmark suite
node benchmarks/run_all_benchmarks.js

# Start server
npm start

License

ISC

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages