Building Harmony AI: An AI Music Generation SaaS

Building Harmony AI: An AI Music Generation SaaS
Turning an AI model into a product people pay for is a different challenge than calling an API from a script. When I built Harmony AI, the goal was a full subscription SaaS: users sign up, buy credits, generate music from text prompts, and manage their library — all with low-latency responses and a billing system that scales.
This post breaks down the architecture, the business model, and the engineering decisions behind Harmony AI.


What Is Harmony AI?
Harmony AI is a web-based AI music generation platform. Users describe the mood, genre, or style they want — and the system generates original audio using AI models.
Unlike a demo or API playground, Harmony AI is built as a production SaaS:
- User accounts with secure authentication
- Stripe-powered subscriptions and one-time credit packs
- Credit-based usage metering — each generation costs credits
- Edge Functions for low-latency AI processing
- Optimized API routes for fast server responses
Source: github.com/ganeshkasture95/Harmony_AI_Music_Gen
High-Level Architecture
flowchart LR
User["User Browser"] --> WebApp["Next.js Web App"]
WebApp --> Auth["Auth Provider"]
WebApp --> API["API Routes"]
API --> Edge["Edge Functions"]
Edge --> AIModel["AI Music Model"]
API --> DB["Database"]
Stripe["Stripe"] --> Webhook["Webhook Handler"]
Webhook --> DB
WebApp --> Stripe
The stack separates concerns cleanly:
| Component | Role |
|---|---|
| Frontend | Prompt input, audio player, library, billing UI |
| Auth | Secure sign-up/login, session management |
| API Routes | Business logic, credit checks, generation requests |
| Edge Functions | Proximity to users + model endpoints for speed |
| Database | Users, credits, generation history, subscriptions |
| Stripe | Payments, subscriptions, webhooks |
The Credit System
AI inference costs money. A flat "unlimited" plan doesn't work at scale — you need usage-based metering.
Harmony AI uses a credit wallet model:
- User purchases credits (one-time) or receives monthly credits via subscription
- Each music generation deducts N credits based on length/complexity
- Insufficient credits → prompt to upgrade or buy more
// Simplified credit check before generation
async function canGenerate(userId: string, cost: number): Promise<boolean> {
const user = await db.users.find(userId);
return user.credits >= cost;
}
async function deductCredits(userId: string, cost: number) {
await db.users.update(userId, {
credits: { decrement: cost },
});
}
This pattern is standard across AI SaaS products (image gen, voice, code assistants) because it aligns user cost with your inference cost.
Stripe Integration
Harmony AI supports both subscriptions and one-time credit purchases.
Subscription flow
- User selects a plan (e.g. Basic, Pro)
- Redirected to Stripe Checkout
- On success, Stripe fires a
checkout.session.completedwebhook - Backend provisions monthly credits and stores
stripe_customer_id
Webhook handling (critical)
Never trust the client for payment confirmation. Always verify via Stripe webhooks:
// Stripe webhook — verify signature, then update DB
const event = stripe.webhooks.constructEvent(
rawBody,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
if (event.type === "checkout.session.completed") {
const session = event.data.object;
await provisionCredits(session.metadata.userId, session.metadata.plan);
}
Why Stripe?
- Handles PCI compliance (you never touch card numbers)
- Built-in subscription lifecycle (renewals, cancellations, failed payments)
- Customer portal for self-service billing management
- Global payment methods
Authentication & Security
Harmony AI implements secure user authentication so:
- Generation history is private per user
- Credits can't be manipulated from the client
- API routes validate session tokens server-side
Key security practices:
- Server-side credit validation — never trust client-reported balance
- Rate limiting on generation endpoints
- Webhook signature verification for Stripe events
- Environment secrets for API keys (never committed to git)
Edge Functions for Low Latency
AI music generation involves multiple hops: user → server → model → storage → user. Latency kills UX.
Harmony AI uses Edge Functions to:
- Run lightweight auth and routing close to the user
- Proxy requests to AI inference endpoints with minimal cold-start overhead
- Stream status updates during long-running generations
Edge deployment reduces round-trip time, especially for users far from your primary server region.
Optimized API routes
Beyond edge placement, API routes are structured for speed:
- Async job pattern — return a job ID immediately, poll or websocket for completion
- Pre-signed URLs — serve generated audio from object storage without proxying bytes through your server
- Caching — store generation metadata, not re-fetch on every page load
The Generation Pipeline
A typical user flow:
- User enters prompt: "Upbeat lo-fi beat with soft piano, 90 BPM"
- Frontend sends request to
/api/generate - Server validates auth + credits
- Credits deducted atomically
- Job queued to AI model
- Audio file stored (S3/Supabase Storage/similar)
- User receives playback URL + saved to library
// Simplified generation endpoint
export async function POST(req: Request) {
const { userId, prompt, duration } = await req.json();
const cost = calculateCost(duration);
if (!(await canGenerate(userId, cost))) {
return Response.json({ error: "Insufficient credits" }, { status: 402 });
}
await deductCredits(userId, cost);
const job = await queueGeneration({ userId, prompt, duration });
return Response.json({ jobId: job.id });
}
Frontend UX Considerations
AI SaaS lives or dies on UX. Harmony AI focuses on:
- Instant feedback — loading states, progress indicators during generation
- Audio player — inline playback with download option
- Generation history — users can revisit and re-download past tracks
- Credit balance visibility — always show remaining credits in the header
- Upgrade prompts — contextual, not aggressive; shown when credits run low
Monetization Model
Harmony AI uses a hybrid model:
| Tier | Model |
|---|---|
| Free | Limited trial credits on signup |
| Subscription | Monthly credits + rollover (optional) |
| Pay-as-you-go | One-time credit packs for casual users |
This covers both power users (subscriptions) and occasional users (credit packs) without forcing everyone into a monthly plan.
Challenges & Solutions
Challenge 1: Inference cost vs. pricing
Problem: AI generation is expensive; underpricing kills margins.
Solution: Credit costs scale with duration/quality. Monitor cost-per-generation and adjust pricing quarterly.
Challenge 2: Generation latency
Problem: Users expect results in seconds; models can take 30–60s.
Solution: Async jobs + progress UI + edge routing. Set expectations with honest loading states.
Challenge 3: Failed generations
Problem: Model timeouts or bad outputs frustrate users.
Solution: Refund credits automatically on failure. Log errors for debugging.
Tech Lessons from Building Harmony AI
- Billing first — design credits and Stripe webhooks before the AI integration; payments are harder to retrofit
- Edge matters for AI SaaS — users won't wait 10 seconds for a server round-trip before generation even starts
- Meter everything — track generations, costs, failures, and conversion from free → paid
- Ship a narrow v1 — text-to-music with credits and Stripe beats a feature-rich demo with no revenue
What's Next
Potential Harmony AI roadmap items:
- Style transfer (upload a reference track)
- Stem separation (vocals, drums, bass)
- Collaboration — shared workspaces for teams
- API access for developers (B2B tier)
Explore the Project
Harmony AI is open source on GitHub:
github.com/ganeshkasture95/Harmony_AI_Music_Gen
Building an AI SaaS isn't just about the model — it's about auth, billing, metering, latency, and UX. Harmony AI was my attempt to wire all of those pieces together into something users can actually pay for and use daily.