Project Overview
Spotify Clone is a comprehensive full-stack music streaming platform that replicates and extends core Spotify functionality with advanced features including real-time synchronized playback, AI-powered playlist generation, and subscription management. As the Backend Developer, I architected and implemented a robust Django REST API backend supporting 30+ endpoints, real-time WebSocket communication, payment processing, and AI integration.
The platform enables artists to upload and manage their music, provides users with subscription-based premium features, supports real-time collaborative listening rooms, and generates intelligent playlists using OpenAI GPT-4. The backend processes 3,724+ lines of production code across multiple Django apps, handling everything from audio analysis to payment webhooks.
Key Achievements & Impact
3,724+
Lines of Backend Code
Technical Stack
Django 5.2.11
Django REST Framework
Python 3.11
PostgreSQL
Redis
Celery
Django Channels
WebSocket
Stripe API
OpenAI GPT-4
Librosa
RESTful APIs
JWT Authentication
Docker
Backend Development Responsibilities
-
RESTful API Architecture: Designed and developed 30+ REST API endpoints using Django REST Framework ViewSets with custom actions. Implemented advanced filtering, search, pagination, and nested routing for music, payments, and user management.
-
Real-Time WebSocket Implementation: Built Django Channels-based WebSocket consumer for synchronized listening rooms, enabling real-time playback synchronization across multiple users with host controls and participant management.
-
Stripe Payment Integration: Implemented complete subscription management system with Stripe Checkout, webhook processing, plan switching, trial periods, and student verification. Created reusable `StripeBaseMixin` eliminating 86+ lines of code duplication.
-
AI-Powered Playlist Generation: Integrated OpenAI GPT-4 API to generate intelligent playlists from natural language prompts, analyzing user preferences and matching songs by audio features (valence, energy, acousticness) with tolerance-based filtering.
-
Audio Analysis Pipeline: Developed Celery background tasks using Librosa to extract audio features (BPM, valence, energy, acousticness) and automatically classify song mood, processing uploads asynchronously without blocking API responses.
-
Database Architecture: Designed 15+ database models with optimized relationships, UUID primary keys, strategic indexing, and proper foreign key constraints. Implemented many-to-many relationships for playlists, genres, and user interactions.
-
Background Task Processing: Configured Celery with Redis broker for async task processing including audio analysis, metadata enrichment, and AI playlist generation, ensuring non-blocking API operations.
-
Code Refactoring & Optimization: Created `StripeBaseMixin` base class pattern with 9 reusable methods, eliminating code redundancy and establishing single source of truth for common Stripe operations across payment endpoints.
-
Security & Authentication: Implemented token-based authentication, role-based access control (User, Artist, Admin), custom permission classes, and comprehensive input validation for secure API access.
-
Performance Optimization: Optimized database queries using `select_related()` and `prefetch_related()`, implemented query filtering at database level, and designed caching strategies with Redis integration.
Key Features Implemented
🎵 Music Management System
- Song CRUD Operations: Complete song management with upload, update, delete, and retrieval endpoints with advanced filtering by genre, artist, date, and visibility
- Album Management: Album creation, cover image uploads, and song association with favorite functionality
- Playlist System: User-created playlists with song reordering, add/remove operations, and playlist sharing
- Like & Favorite System: Song and album like/favorite functionality with user-specific tracking
- Recently Played: Automatic tracking of user listening history with timestamp management
- Trending Algorithm: Time-based trending songs calculation based on play counts and engagement
- Search & Recommendations: Multi-field search (title, artist, album, genre) and AI-powered song recommendations
💳 Subscription Management
- Multiple Plan Types: Free, Individual, Student, Duo, and Family plans with feature differentiation
- Stripe Checkout Integration: Secure payment processing with redirect-based checkout flow
- Webhook Processing: Event-driven subscription updates handling checkout completion, subscription changes, and payment events
- Trial Periods: Automatic 30-day trial management for Individual and Student plans
- Plan Switching: Upgrade/downgrade functionality with Stripe proration support
- Student Verification: Document-based verification system for student discount eligibility
🤖 AI-Powered Features
- Natural Language Playlist Generation: Users describe desired playlist in natural language, GPT-4 extracts parameters, system matches songs by audio features
- Audio Feature Matching: Tolerance-based matching (20% variance) on valence, energy, and acousticness for flexible playlist creation
- User Preference Analysis: Analyzes favorite genres and recently played songs to inform recommendations
⚡ Real-Time Collaboration
- Synchronized Listening Rooms: WebSocket-based rooms where multiple users listen together in real-time
- Host Controls: Only room host can control playback (play, pause, seek) with state broadcast to all listeners
- Participant Management: Join/leave notifications, listener capacity limits, and room state persistence
Technical Challenges & Solutions
Challenge: Real-Time Synchronized Playback
Problem: Implementing synchronized music playback across multiple users in real-time requires low-latency bidirectional communication, state management, and host control mechanisms.
Solution: Implemented Django Channels with WebSocket consumer (`ListeningRoomConsumer`) for full-duplex communication. Created room state management system tracking current song, playback position, and play state. Host controls are enforced at the WebSocket level, with all state changes broadcast to all participants via Redis channel layers. Implemented automatic reconnection handling and graceful degradation for connection issues.
Challenge: Code Duplication in Payment Operations
Problem: Multiple payment endpoints shared common Stripe operations (customer creation, subscription retrieval, error handling), leading to 86+ lines of duplicated code across different views.
Solution: Created `StripeBaseMixin` base class with 9 reusable methods including `get_or_create_stripe_customer()`, `get_stripe_subscription_id()`, `handle_stripe_error()`, and `check_student_verification()`. All payment views inherit from this mixin, establishing single source of truth and reducing maintenance overhead. This pattern improved code consistency and made error handling uniform across all payment operations.
Challenge: Audio Processing Performance
Problem: Audio feature extraction using Librosa is CPU-intensive and can block API responses, causing poor user experience when artists upload songs.
Solution: Implemented Celery background tasks (`analyze_audio_features`) that process audio files asynchronously. Songs are immediately available after upload, with audio analysis (BPM, valence, energy, acousticness, mood classification) happening in the background. Redis serves as the message broker, and task status can be tracked via Celery monitoring. This ensures API responsiveness while maintaining comprehensive audio metadata.
Challenge: AI Playlist Generation with Audio Feature Matching
Problem: Converting natural language playlist requests into actual song selections requires understanding user intent, matching songs by audio characteristics, and handling cases where no perfect matches exist.
Solution: Integrated OpenAI GPT-4 to parse natural language prompts and extract playlist parameters (mood, energy level, genre preferences). Implemented tolerance-based audio feature matching (20% variance) on valence, energy, and acousticness values. Created fallback mechanisms that analyze user's favorite genres and recently played songs if exact matches aren't found. The system combines AI understanding with audio analysis data to create personalized playlists.
Challenge: Stripe Webhook Reliability
Problem: Payment webhooks must be processed reliably to keep subscription status synchronized, but network issues, duplicate events, and processing failures can cause inconsistencies.
Solution: Implemented idempotent webhook handlers that check for duplicate event processing using Stripe event IDs. Created comprehensive error handling with logging and retry mechanisms. Webhook handlers update user profiles atomically, ensuring subscription status, plan features, and trial periods are always accurate. Used Stripe signature verification for security and implemented separate handlers for different event types (checkout completion, subscription updates, payment success/failure).
Architecture Highlights
Django Apps Structure
- Music App: 885+ lines in viewsets, 292+ lines in models, 369+ lines in Celery tasks, 347+ lines in WebSocket consumer
- Payments App: 491+ lines in subscription views, 226+ lines in base Stripe mixin, 237+ lines in webhook handlers
- Users App: 408+ lines in user/profile models, authentication views, and artist follow system
Database Design
- 15+ Models: Song, Album, Genre, Playlist, PlaylistSong, SongLike, FavoriteSong, RecentlyPlayed, ListeningRoom, RoomListener, SongAnalytics, User, UserProfile, SubscriptionPlan, StudentVerification
- Optimized Relationships: Foreign keys, many-to-many with through models, UUID primary keys for security
- Query Optimization: Strategic use of `select_related()` and `prefetch_related()` to minimize database queries
Project Statistics
- Total Backend Code: 3,724+ lines across multiple Django apps
- API Endpoints: 30+ REST endpoints with custom actions
- Database Models: 15+ models with optimized relationships
- Background Tasks: 5 Celery tasks for async processing
- WebSocket Consumers: 1 real-time consumer for listening rooms
- Webhook Handlers: 6 Stripe event handlers
- Code Refactoring: Eliminated 86+ lines of duplication
- External Integrations: Stripe, OpenAI, Redis, Celery
Technical Skills Demonstrated
This project showcased expertise in building enterprise-scale backend systems with:
- Django REST Framework: Advanced ViewSet patterns, custom actions, nested routing, serializer validation
- Real-Time Systems: Django Channels, WebSocket programming, async consumers, channel layers
- Payment Processing: Stripe API integration, webhook handling, subscription management, idempotent operations
- AI Integration: OpenAI GPT-4 API, natural language processing, intelligent feature matching
- Audio Processing: Librosa for feature extraction, audio analysis, mood classification
- Background Processing: Celery task queues, Redis message broker, async task management
- Database Design: Complex relationships, query optimization, indexing strategies
- Code Architecture: Base class inheritance, DRY principles, design patterns, code refactoring
Project Details
Project: Spotify Clone - Full-Stack Music Streaming Platform
Role: Backend Developer
Repository: GitHub - Spotify_Clone
Tech Stack: Django 5.2.11, DRF 3.16.1, Python 3.11, Celery, Redis, Channels, Stripe, OpenAI, Librosa
Type: Full-Stack Application, Personal Project
Status: Production-Ready Backend
Key Achievement
Successfully architected and implemented a production-ready backend supporting real-time collaboration,
AI-powered features, and payment processing. The codebase demonstrates advanced Django patterns,
efficient database design, and scalable architecture suitable for enterprise applications.
Explore Code on GitHub